echarts.simple.js 996 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982
  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. /**
  529. * @memberOf module:zrender/core/util
  530. * @param {Function} func
  531. * @param {*} context
  532. * @return {Function}
  533. */
  534. function bind(func, context) {
  535. var args = nativeSlice.call(arguments, 2);
  536. return function () {
  537. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  538. };
  539. }
  540. /**
  541. * @memberOf module:zrender/core/util
  542. * @param {Function} func
  543. * @return {Function}
  544. */
  545. function curry(func) {
  546. var args = nativeSlice.call(arguments, 1);
  547. return function () {
  548. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  549. };
  550. }
  551. /**
  552. * @memberOf module:zrender/core/util
  553. * @param {*} value
  554. * @return {boolean}
  555. */
  556. function isArray(value) {
  557. return objToString.call(value) === '[object Array]';
  558. }
  559. /**
  560. * @memberOf module:zrender/core/util
  561. * @param {*} value
  562. * @return {boolean}
  563. */
  564. function isFunction$1(value) {
  565. return typeof value === 'function';
  566. }
  567. /**
  568. * @memberOf module:zrender/core/util
  569. * @param {*} value
  570. * @return {boolean}
  571. */
  572. function isString(value) {
  573. return objToString.call(value) === '[object String]';
  574. }
  575. /**
  576. * @memberOf module:zrender/core/util
  577. * @param {*} value
  578. * @return {boolean}
  579. */
  580. function isObject$1(value) {
  581. // Avoid a V8 JIT bug in Chrome 19-20.
  582. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  583. var type = typeof value;
  584. return type === 'function' || (!!value && type == 'object');
  585. }
  586. /**
  587. * @memberOf module:zrender/core/util
  588. * @param {*} value
  589. * @return {boolean}
  590. */
  591. function isBuiltInObject(value) {
  592. return !!BUILTIN_OBJECT[objToString.call(value)];
  593. }
  594. /**
  595. * @memberOf module:zrender/core/util
  596. * @param {*} value
  597. * @return {boolean}
  598. */
  599. function isTypedArray(value) {
  600. return !!TYPED_ARRAY[objToString.call(value)];
  601. }
  602. /**
  603. * @memberOf module:zrender/core/util
  604. * @param {*} value
  605. * @return {boolean}
  606. */
  607. function isDom(value) {
  608. return typeof value === 'object'
  609. && typeof value.nodeType === 'number'
  610. && typeof value.ownerDocument === 'object';
  611. }
  612. /**
  613. * Whether is exactly NaN. Notice isNaN('a') returns true.
  614. * @param {*} value
  615. * @return {boolean}
  616. */
  617. function eqNaN(value) {
  618. return value !== value;
  619. }
  620. /**
  621. * If value1 is not null, then return value1, otherwise judget rest of values.
  622. * Low performance.
  623. * @memberOf module:zrender/core/util
  624. * @return {*} Final value
  625. */
  626. function retrieve(values) {
  627. for (var i = 0, len = arguments.length; i < len; i++) {
  628. if (arguments[i] != null) {
  629. return arguments[i];
  630. }
  631. }
  632. }
  633. function retrieve2(value0, value1) {
  634. return value0 != null
  635. ? value0
  636. : value1;
  637. }
  638. function retrieve3(value0, value1, value2) {
  639. return value0 != null
  640. ? value0
  641. : value1 != null
  642. ? value1
  643. : value2;
  644. }
  645. /**
  646. * @memberOf module:zrender/core/util
  647. * @param {Array} arr
  648. * @param {number} startIndex
  649. * @param {number} endIndex
  650. * @return {Array}
  651. */
  652. function slice() {
  653. return Function.call.apply(nativeSlice, arguments);
  654. }
  655. /**
  656. * Normalize css liked array configuration
  657. * e.g.
  658. * 3 => [3, 3, 3, 3]
  659. * [4, 2] => [4, 2, 4, 2]
  660. * [4, 3, 2] => [4, 3, 2, 3]
  661. * @param {number|Array.<number>} val
  662. * @return {Array.<number>}
  663. */
  664. function normalizeCssArray(val) {
  665. if (typeof (val) === 'number') {
  666. return [val, val, val, val];
  667. }
  668. var len = val.length;
  669. if (len === 2) {
  670. // vertical | horizontal
  671. return [val[0], val[1], val[0], val[1]];
  672. }
  673. else if (len === 3) {
  674. // top | horizontal | bottom
  675. return [val[0], val[1], val[2], val[1]];
  676. }
  677. return val;
  678. }
  679. /**
  680. * @memberOf module:zrender/core/util
  681. * @param {boolean} condition
  682. * @param {string} message
  683. */
  684. function assert$1(condition, message) {
  685. if (!condition) {
  686. throw new Error(message);
  687. }
  688. }
  689. /**
  690. * @memberOf module:zrender/core/util
  691. * @param {string} str string to be trimed
  692. * @return {string} trimed string
  693. */
  694. function trim(str) {
  695. if (str == null) {
  696. return null;
  697. }
  698. else if (typeof str.trim === 'function') {
  699. return str.trim();
  700. }
  701. else {
  702. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  703. }
  704. }
  705. var primitiveKey = '__ec_primitive__';
  706. /**
  707. * Set an object as primitive to be ignored traversing children in clone or merge
  708. */
  709. function setAsPrimitive(obj) {
  710. obj[primitiveKey] = true;
  711. }
  712. function isPrimitive(obj) {
  713. return obj[primitiveKey];
  714. }
  715. /**
  716. * @constructor
  717. * @param {Object} obj Only apply `ownProperty`.
  718. */
  719. function HashMap(obj) {
  720. var isArr = isArray(obj);
  721. var thisMap = this;
  722. (obj instanceof HashMap)
  723. ? obj.each(visit)
  724. : (obj && each$1(obj, visit));
  725. function visit(value, key) {
  726. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  727. }
  728. }
  729. // Add prefix to avoid conflict with Object.prototype.
  730. HashMap.prototype = {
  731. constructor: HashMap,
  732. // Do not provide `has` method to avoid defining what is `has`.
  733. // (We usually treat `null` and `undefined` as the same, different
  734. // from ES6 Map).
  735. get: function (key) {
  736. return this.hasOwnProperty(key) ? this[key] : null;
  737. },
  738. set: function (key, value) {
  739. // Comparing with invocation chaining, `return value` is more commonly
  740. // used in this case: `var someVal = map.set('a', genVal());`
  741. return (this[key] = value);
  742. },
  743. // Although util.each can be performed on this hashMap directly, user
  744. // should not use the exposed keys, who are prefixed.
  745. each: function (cb, context) {
  746. context !== void 0 && (cb = bind(cb, context));
  747. for (var key in this) {
  748. this.hasOwnProperty(key) && cb(this[key], key);
  749. }
  750. },
  751. // Do not use this method if performance sensitive.
  752. removeKey: function (key) {
  753. delete this[key];
  754. }
  755. };
  756. function createHashMap(obj) {
  757. return new HashMap(obj);
  758. }
  759. function noop() {}
  760. var ArrayCtor = typeof Float32Array === 'undefined'
  761. ? Array
  762. : Float32Array;
  763. /**
  764. * 创建一个向量
  765. * @param {number} [x=0]
  766. * @param {number} [y=0]
  767. * @return {Vector2}
  768. */
  769. function create(x, y) {
  770. var out = new ArrayCtor(2);
  771. if (x == null) {
  772. x = 0;
  773. }
  774. if (y == null) {
  775. y = 0;
  776. }
  777. out[0] = x;
  778. out[1] = y;
  779. return out;
  780. }
  781. /**
  782. * 复制向量数据
  783. * @param {Vector2} out
  784. * @param {Vector2} v
  785. * @return {Vector2}
  786. */
  787. function copy(out, v) {
  788. out[0] = v[0];
  789. out[1] = v[1];
  790. return out;
  791. }
  792. /**
  793. * 克隆一个向量
  794. * @param {Vector2} v
  795. * @return {Vector2}
  796. */
  797. function clone$1(v) {
  798. var out = new ArrayCtor(2);
  799. out[0] = v[0];
  800. out[1] = v[1];
  801. return out;
  802. }
  803. /**
  804. * 设置向量的两个项
  805. * @param {Vector2} out
  806. * @param {number} a
  807. * @param {number} b
  808. * @return {Vector2} 结果
  809. */
  810. /**
  811. * 向量相加
  812. * @param {Vector2} out
  813. * @param {Vector2} v1
  814. * @param {Vector2} v2
  815. */
  816. function add(out, v1, v2) {
  817. out[0] = v1[0] + v2[0];
  818. out[1] = v1[1] + v2[1];
  819. return out;
  820. }
  821. /**
  822. * 向量缩放后相加
  823. * @param {Vector2} out
  824. * @param {Vector2} v1
  825. * @param {Vector2} v2
  826. * @param {number} a
  827. */
  828. function scaleAndAdd(out, v1, v2, a) {
  829. out[0] = v1[0] + v2[0] * a;
  830. out[1] = v1[1] + v2[1] * a;
  831. return out;
  832. }
  833. /**
  834. * 向量相减
  835. * @param {Vector2} out
  836. * @param {Vector2} v1
  837. * @param {Vector2} v2
  838. */
  839. function sub(out, v1, v2) {
  840. out[0] = v1[0] - v2[0];
  841. out[1] = v1[1] - v2[1];
  842. return out;
  843. }
  844. /**
  845. * 向量长度
  846. * @param {Vector2} v
  847. * @return {number}
  848. */
  849. function len(v) {
  850. return Math.sqrt(lenSquare(v));
  851. }
  852. // jshint ignore:line
  853. /**
  854. * 向量长度平方
  855. * @param {Vector2} v
  856. * @return {number}
  857. */
  858. function lenSquare(v) {
  859. return v[0] * v[0] + v[1] * v[1];
  860. }
  861. /**
  862. * 向量乘法
  863. * @param {Vector2} out
  864. * @param {Vector2} v1
  865. * @param {Vector2} v2
  866. */
  867. /**
  868. * 向量除法
  869. * @param {Vector2} out
  870. * @param {Vector2} v1
  871. * @param {Vector2} v2
  872. */
  873. /**
  874. * 向量点乘
  875. * @param {Vector2} v1
  876. * @param {Vector2} v2
  877. * @return {number}
  878. */
  879. /**
  880. * 向量缩放
  881. * @param {Vector2} out
  882. * @param {Vector2} v
  883. * @param {number} s
  884. */
  885. function scale(out, v, s) {
  886. out[0] = v[0] * s;
  887. out[1] = v[1] * s;
  888. return out;
  889. }
  890. /**
  891. * 向量归一化
  892. * @param {Vector2} out
  893. * @param {Vector2} v
  894. */
  895. function normalize(out, v) {
  896. var d = len(v);
  897. if (d === 0) {
  898. out[0] = 0;
  899. out[1] = 0;
  900. }
  901. else {
  902. out[0] = v[0] / d;
  903. out[1] = v[1] / d;
  904. }
  905. return out;
  906. }
  907. /**
  908. * 计算向量间距离
  909. * @param {Vector2} v1
  910. * @param {Vector2} v2
  911. * @return {number}
  912. */
  913. function distance(v1, v2) {
  914. return Math.sqrt(
  915. (v1[0] - v2[0]) * (v1[0] - v2[0])
  916. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  917. );
  918. }
  919. var dist = distance;
  920. /**
  921. * 向量距离平方
  922. * @param {Vector2} v1
  923. * @param {Vector2} v2
  924. * @return {number}
  925. */
  926. function distanceSquare(v1, v2) {
  927. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  928. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  929. }
  930. var distSquare = distanceSquare;
  931. /**
  932. * 求负向量
  933. * @param {Vector2} out
  934. * @param {Vector2} v
  935. */
  936. /**
  937. * 插值两个点
  938. * @param {Vector2} out
  939. * @param {Vector2} v1
  940. * @param {Vector2} v2
  941. * @param {number} t
  942. */
  943. /**
  944. * 矩阵左乘向量
  945. * @param {Vector2} out
  946. * @param {Vector2} v
  947. * @param {Vector2} m
  948. */
  949. function applyTransform(out, v, m) {
  950. var x = v[0];
  951. var y = v[1];
  952. out[0] = m[0] * x + m[2] * y + m[4];
  953. out[1] = m[1] * x + m[3] * y + m[5];
  954. return out;
  955. }
  956. /**
  957. * 求两个向量最小值
  958. * @param {Vector2} out
  959. * @param {Vector2} v1
  960. * @param {Vector2} v2
  961. */
  962. function min(out, v1, v2) {
  963. out[0] = Math.min(v1[0], v2[0]);
  964. out[1] = Math.min(v1[1], v2[1]);
  965. return out;
  966. }
  967. /**
  968. * 求两个向量最大值
  969. * @param {Vector2} out
  970. * @param {Vector2} v1
  971. * @param {Vector2} v2
  972. */
  973. function max(out, v1, v2) {
  974. out[0] = Math.max(v1[0], v2[0]);
  975. out[1] = Math.max(v1[1], v2[1]);
  976. return out;
  977. }
  978. // TODO Draggable for group
  979. // FIXME Draggable on element which has parent rotation or scale
  980. function Draggable() {
  981. this.on('mousedown', this._dragStart, this);
  982. this.on('mousemove', this._drag, this);
  983. this.on('mouseup', this._dragEnd, this);
  984. this.on('globalout', this._dragEnd, this);
  985. // this._dropTarget = null;
  986. // this._draggingTarget = null;
  987. // this._x = 0;
  988. // this._y = 0;
  989. }
  990. Draggable.prototype = {
  991. constructor: Draggable,
  992. _dragStart: function (e) {
  993. var draggingTarget = e.target;
  994. if (draggingTarget && draggingTarget.draggable) {
  995. this._draggingTarget = draggingTarget;
  996. draggingTarget.dragging = true;
  997. this._x = e.offsetX;
  998. this._y = e.offsetY;
  999. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1000. }
  1001. },
  1002. _drag: function (e) {
  1003. var draggingTarget = this._draggingTarget;
  1004. if (draggingTarget) {
  1005. var x = e.offsetX;
  1006. var y = e.offsetY;
  1007. var dx = x - this._x;
  1008. var dy = y - this._y;
  1009. this._x = x;
  1010. this._y = y;
  1011. draggingTarget.drift(dx, dy, e);
  1012. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1013. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1014. var lastDropTarget = this._dropTarget;
  1015. this._dropTarget = dropTarget;
  1016. if (draggingTarget !== dropTarget) {
  1017. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1018. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1019. }
  1020. if (dropTarget && dropTarget !== lastDropTarget) {
  1021. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1022. }
  1023. }
  1024. }
  1025. },
  1026. _dragEnd: function (e) {
  1027. var draggingTarget = this._draggingTarget;
  1028. if (draggingTarget) {
  1029. draggingTarget.dragging = false;
  1030. }
  1031. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1032. if (this._dropTarget) {
  1033. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1034. }
  1035. this._draggingTarget = null;
  1036. this._dropTarget = null;
  1037. }
  1038. };
  1039. function param(target, e) {
  1040. return {target: target, topTarget: e && e.topTarget};
  1041. }
  1042. /**
  1043. * 事件扩展
  1044. * @module zrender/mixin/Eventful
  1045. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1046. * pissang (https://www.github.com/pissang)
  1047. */
  1048. var arrySlice = Array.prototype.slice;
  1049. /**
  1050. * 事件分发器
  1051. * @alias module:zrender/mixin/Eventful
  1052. * @constructor
  1053. */
  1054. var Eventful = function () {
  1055. this._$handlers = {};
  1056. };
  1057. Eventful.prototype = {
  1058. constructor: Eventful,
  1059. /**
  1060. * 单次触发绑定,trigger后销毁
  1061. *
  1062. * @param {string} event 事件名
  1063. * @param {Function} handler 响应函数
  1064. * @param {Object} context
  1065. */
  1066. one: function (event, handler, context) {
  1067. var _h = this._$handlers;
  1068. if (!handler || !event) {
  1069. return this;
  1070. }
  1071. if (!_h[event]) {
  1072. _h[event] = [];
  1073. }
  1074. for (var i = 0; i < _h[event].length; i++) {
  1075. if (_h[event][i].h === handler) {
  1076. return this;
  1077. }
  1078. }
  1079. _h[event].push({
  1080. h: handler,
  1081. one: true,
  1082. ctx: context || this
  1083. });
  1084. return this;
  1085. },
  1086. /**
  1087. * 绑定事件
  1088. * @param {string} event 事件名
  1089. * @param {Function} handler 事件处理函数
  1090. * @param {Object} [context]
  1091. */
  1092. on: function (event, handler, context) {
  1093. var _h = this._$handlers;
  1094. if (!handler || !event) {
  1095. return this;
  1096. }
  1097. if (!_h[event]) {
  1098. _h[event] = [];
  1099. }
  1100. for (var i = 0; i < _h[event].length; i++) {
  1101. if (_h[event][i].h === handler) {
  1102. return this;
  1103. }
  1104. }
  1105. _h[event].push({
  1106. h: handler,
  1107. one: false,
  1108. ctx: context || this
  1109. });
  1110. return this;
  1111. },
  1112. /**
  1113. * 是否绑定了事件
  1114. * @param {string} event
  1115. * @return {boolean}
  1116. */
  1117. isSilent: function (event) {
  1118. var _h = this._$handlers;
  1119. return _h[event] && _h[event].length;
  1120. },
  1121. /**
  1122. * 解绑事件
  1123. * @param {string} event 事件名
  1124. * @param {Function} [handler] 事件处理函数
  1125. */
  1126. off: function (event, handler) {
  1127. var _h = this._$handlers;
  1128. if (!event) {
  1129. this._$handlers = {};
  1130. return this;
  1131. }
  1132. if (handler) {
  1133. if (_h[event]) {
  1134. var newList = [];
  1135. for (var i = 0, l = _h[event].length; i < l; i++) {
  1136. if (_h[event][i]['h'] != handler) {
  1137. newList.push(_h[event][i]);
  1138. }
  1139. }
  1140. _h[event] = newList;
  1141. }
  1142. if (_h[event] && _h[event].length === 0) {
  1143. delete _h[event];
  1144. }
  1145. }
  1146. else {
  1147. delete _h[event];
  1148. }
  1149. return this;
  1150. },
  1151. /**
  1152. * 事件分发
  1153. *
  1154. * @param {string} type 事件类型
  1155. */
  1156. trigger: function (type) {
  1157. if (this._$handlers[type]) {
  1158. var args = arguments;
  1159. var argLen = args.length;
  1160. if (argLen > 3) {
  1161. args = arrySlice.call(args, 1);
  1162. }
  1163. var _h = this._$handlers[type];
  1164. var len = _h.length;
  1165. for (var i = 0; i < len;) {
  1166. // Optimize advise from backbone
  1167. switch (argLen) {
  1168. case 1:
  1169. _h[i]['h'].call(_h[i]['ctx']);
  1170. break;
  1171. case 2:
  1172. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1173. break;
  1174. case 3:
  1175. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1176. break;
  1177. default:
  1178. // have more than 2 given arguments
  1179. _h[i]['h'].apply(_h[i]['ctx'], args);
  1180. break;
  1181. }
  1182. if (_h[i]['one']) {
  1183. _h.splice(i, 1);
  1184. len--;
  1185. }
  1186. else {
  1187. i++;
  1188. }
  1189. }
  1190. }
  1191. return this;
  1192. },
  1193. /**
  1194. * 带有context的事件分发, 最后一个参数是事件回调的context
  1195. * @param {string} type 事件类型
  1196. */
  1197. triggerWithContext: function (type) {
  1198. if (this._$handlers[type]) {
  1199. var args = arguments;
  1200. var argLen = args.length;
  1201. if (argLen > 4) {
  1202. args = arrySlice.call(args, 1, args.length - 1);
  1203. }
  1204. var ctx = args[args.length - 1];
  1205. var _h = this._$handlers[type];
  1206. var len = _h.length;
  1207. for (var i = 0; i < len;) {
  1208. // Optimize advise from backbone
  1209. switch (argLen) {
  1210. case 1:
  1211. _h[i]['h'].call(ctx);
  1212. break;
  1213. case 2:
  1214. _h[i]['h'].call(ctx, args[1]);
  1215. break;
  1216. case 3:
  1217. _h[i]['h'].call(ctx, args[1], args[2]);
  1218. break;
  1219. default:
  1220. // have more than 2 given arguments
  1221. _h[i]['h'].apply(ctx, args);
  1222. break;
  1223. }
  1224. if (_h[i]['one']) {
  1225. _h.splice(i, 1);
  1226. len--;
  1227. }
  1228. else {
  1229. i++;
  1230. }
  1231. }
  1232. }
  1233. return this;
  1234. }
  1235. };
  1236. var SILENT = 'silent';
  1237. function makeEventPacket(eveType, targetInfo, event) {
  1238. return {
  1239. type: eveType,
  1240. event: event,
  1241. // target can only be an element that is not silent.
  1242. target: targetInfo.target,
  1243. // topTarget can be a silent element.
  1244. topTarget: targetInfo.topTarget,
  1245. cancelBubble: false,
  1246. offsetX: event.zrX,
  1247. offsetY: event.zrY,
  1248. gestureEvent: event.gestureEvent,
  1249. pinchX: event.pinchX,
  1250. pinchY: event.pinchY,
  1251. pinchScale: event.pinchScale,
  1252. wheelDelta: event.zrDelta,
  1253. zrByTouch: event.zrByTouch,
  1254. which: event.which
  1255. };
  1256. }
  1257. function EmptyProxy () {}
  1258. EmptyProxy.prototype.dispose = function () {};
  1259. var handlerNames = [
  1260. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1261. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1262. ];
  1263. /**
  1264. * @alias module:zrender/Handler
  1265. * @constructor
  1266. * @extends module:zrender/mixin/Eventful
  1267. * @param {module:zrender/Storage} storage Storage instance.
  1268. * @param {module:zrender/Painter} painter Painter instance.
  1269. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1270. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1271. */
  1272. var Handler = function(storage, painter, proxy, painterRoot) {
  1273. Eventful.call(this);
  1274. this.storage = storage;
  1275. this.painter = painter;
  1276. this.painterRoot = painterRoot;
  1277. proxy = proxy || new EmptyProxy();
  1278. /**
  1279. * Proxy of event. can be Dom, WebGLSurface, etc.
  1280. */
  1281. this.proxy = null;
  1282. /**
  1283. * {target, topTarget, x, y}
  1284. * @private
  1285. * @type {Object}
  1286. */
  1287. this._hovered = {};
  1288. /**
  1289. * @private
  1290. * @type {Date}
  1291. */
  1292. this._lastTouchMoment;
  1293. /**
  1294. * @private
  1295. * @type {number}
  1296. */
  1297. this._lastX;
  1298. /**
  1299. * @private
  1300. * @type {number}
  1301. */
  1302. this._lastY;
  1303. Draggable.call(this);
  1304. this.setHandlerProxy(proxy);
  1305. };
  1306. Handler.prototype = {
  1307. constructor: Handler,
  1308. setHandlerProxy: function (proxy) {
  1309. if (this.proxy) {
  1310. this.proxy.dispose();
  1311. }
  1312. if (proxy) {
  1313. each$1(handlerNames, function (name) {
  1314. proxy.on && proxy.on(name, this[name], this);
  1315. }, this);
  1316. // Attach handler
  1317. proxy.handler = this;
  1318. }
  1319. this.proxy = proxy;
  1320. },
  1321. mousemove: function (event) {
  1322. var x = event.zrX;
  1323. var y = event.zrY;
  1324. var lastHovered = this._hovered;
  1325. var lastHoveredTarget = lastHovered.target;
  1326. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1327. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1328. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1329. // See #6198.
  1330. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1331. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1332. lastHoveredTarget = lastHovered.target;
  1333. }
  1334. var hovered = this._hovered = this.findHover(x, y);
  1335. var hoveredTarget = hovered.target;
  1336. var proxy = this.proxy;
  1337. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1338. // Mouse out on previous hovered element
  1339. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1340. this.dispatchToElement(lastHovered, 'mouseout', event);
  1341. }
  1342. // Mouse moving on one element
  1343. this.dispatchToElement(hovered, 'mousemove', event);
  1344. // Mouse over on a new element
  1345. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1346. this.dispatchToElement(hovered, 'mouseover', event);
  1347. }
  1348. },
  1349. mouseout: function (event) {
  1350. this.dispatchToElement(this._hovered, 'mouseout', event);
  1351. // There might be some doms created by upper layer application
  1352. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1353. // dom created by echarts), where 'globalout' event should not
  1354. // be triggered when mouse enters these doms. (But 'mouseout'
  1355. // should be triggered at the original hovered element as usual).
  1356. var element = event.toElement || event.relatedTarget;
  1357. var innerDom;
  1358. do {
  1359. element = element && element.parentNode;
  1360. }
  1361. while (element && element.nodeType != 9 && !(
  1362. innerDom = element === this.painterRoot
  1363. ));
  1364. !innerDom && this.trigger('globalout', {event: event});
  1365. },
  1366. /**
  1367. * Resize
  1368. */
  1369. resize: function (event) {
  1370. this._hovered = {};
  1371. },
  1372. /**
  1373. * Dispatch event
  1374. * @param {string} eventName
  1375. * @param {event=} eventArgs
  1376. */
  1377. dispatch: function (eventName, eventArgs) {
  1378. var handler = this[eventName];
  1379. handler && handler.call(this, eventArgs);
  1380. },
  1381. /**
  1382. * Dispose
  1383. */
  1384. dispose: function () {
  1385. this.proxy.dispose();
  1386. this.storage =
  1387. this.proxy =
  1388. this.painter = null;
  1389. },
  1390. /**
  1391. * 设置默认的cursor style
  1392. * @param {string} [cursorStyle='default'] 例如 crosshair
  1393. */
  1394. setCursorStyle: function (cursorStyle) {
  1395. var proxy = this.proxy;
  1396. proxy.setCursor && proxy.setCursor(cursorStyle);
  1397. },
  1398. /**
  1399. * 事件分发代理
  1400. *
  1401. * @private
  1402. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1403. * @param {string} eventName 事件名称
  1404. * @param {Object} event 事件对象
  1405. */
  1406. dispatchToElement: function (targetInfo, eventName, event) {
  1407. targetInfo = targetInfo || {};
  1408. var el = targetInfo.target;
  1409. if (el && el.silent) {
  1410. return;
  1411. }
  1412. var eventHandler = 'on' + eventName;
  1413. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1414. while (el) {
  1415. el[eventHandler]
  1416. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1417. el.trigger(eventName, eventPacket);
  1418. el = el.parent;
  1419. if (eventPacket.cancelBubble) {
  1420. break;
  1421. }
  1422. }
  1423. if (!eventPacket.cancelBubble) {
  1424. // 冒泡到顶级 zrender 对象
  1425. this.trigger(eventName, eventPacket);
  1426. // 分发事件到用户自定义层
  1427. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1428. this.painter && this.painter.eachOtherLayer(function (layer) {
  1429. if (typeof(layer[eventHandler]) == 'function') {
  1430. layer[eventHandler].call(layer, eventPacket);
  1431. }
  1432. if (layer.trigger) {
  1433. layer.trigger(eventName, eventPacket);
  1434. }
  1435. });
  1436. }
  1437. },
  1438. /**
  1439. * @private
  1440. * @param {number} x
  1441. * @param {number} y
  1442. * @param {module:zrender/graphic/Displayable} exclude
  1443. * @return {model:zrender/Element}
  1444. * @method
  1445. */
  1446. findHover: function(x, y, exclude) {
  1447. var list = this.storage.getDisplayList();
  1448. var out = {x: x, y: y};
  1449. for (var i = list.length - 1; i >= 0 ; i--) {
  1450. var hoverCheckResult;
  1451. if (list[i] !== exclude
  1452. // getDisplayList may include ignored item in VML mode
  1453. && !list[i].ignore
  1454. && (hoverCheckResult = isHover(list[i], x, y))
  1455. ) {
  1456. !out.topTarget && (out.topTarget = list[i]);
  1457. if (hoverCheckResult !== SILENT) {
  1458. out.target = list[i];
  1459. break;
  1460. }
  1461. }
  1462. }
  1463. return out;
  1464. }
  1465. };
  1466. // Common handlers
  1467. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1468. Handler.prototype[name] = function (event) {
  1469. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1470. var hovered = this.findHover(event.zrX, event.zrY);
  1471. var hoveredTarget = hovered.target;
  1472. if (name === 'mousedown') {
  1473. this._downEl = hoveredTarget;
  1474. this._downPoint = [event.zrX, event.zrY];
  1475. // In case click triggered before mouseup
  1476. this._upEl = hoveredTarget;
  1477. }
  1478. else if (name === 'mouseup') {
  1479. this._upEl = hoveredTarget;
  1480. }
  1481. else if (name === 'click') {
  1482. if (this._downEl !== this._upEl
  1483. // Original click event is triggered on the whole canvas element,
  1484. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1485. // which should be filtered, otherwise it will bring trouble to
  1486. // pan and zoom.
  1487. || !this._downPoint
  1488. // Arbitrary value
  1489. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1490. ) {
  1491. return;
  1492. }
  1493. this._downPoint = null;
  1494. }
  1495. this.dispatchToElement(hovered, name, event);
  1496. };
  1497. });
  1498. function isHover(displayable, x, y) {
  1499. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1500. var el = displayable;
  1501. var isSilent;
  1502. while (el) {
  1503. // If clipped by ancestor.
  1504. // FIXME: If clipPath has neither stroke nor fill,
  1505. // el.clipPath.contain(x, y) will always return false.
  1506. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1507. return false;
  1508. }
  1509. if (el.silent) {
  1510. isSilent = true;
  1511. }
  1512. el = el.parent;
  1513. }
  1514. return isSilent ? SILENT : true;
  1515. }
  1516. return false;
  1517. }
  1518. mixin(Handler, Eventful);
  1519. mixin(Handler, Draggable);
  1520. /**
  1521. * 3x2矩阵操作类
  1522. * @exports zrender/tool/matrix
  1523. */
  1524. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1525. ? Array
  1526. : Float32Array;
  1527. /**
  1528. * Create a identity matrix.
  1529. * @return {Float32Array|Array.<number>}
  1530. */
  1531. function create$1() {
  1532. var out = new ArrayCtor$1(6);
  1533. identity(out);
  1534. return out;
  1535. }
  1536. /**
  1537. * 设置矩阵为单位矩阵
  1538. * @param {Float32Array|Array.<number>} out
  1539. */
  1540. function identity(out) {
  1541. out[0] = 1;
  1542. out[1] = 0;
  1543. out[2] = 0;
  1544. out[3] = 1;
  1545. out[4] = 0;
  1546. out[5] = 0;
  1547. return out;
  1548. }
  1549. /**
  1550. * 复制矩阵
  1551. * @param {Float32Array|Array.<number>} out
  1552. * @param {Float32Array|Array.<number>} m
  1553. */
  1554. function copy$1(out, m) {
  1555. out[0] = m[0];
  1556. out[1] = m[1];
  1557. out[2] = m[2];
  1558. out[3] = m[3];
  1559. out[4] = m[4];
  1560. out[5] = m[5];
  1561. return out;
  1562. }
  1563. /**
  1564. * 矩阵相乘
  1565. * @param {Float32Array|Array.<number>} out
  1566. * @param {Float32Array|Array.<number>} m1
  1567. * @param {Float32Array|Array.<number>} m2
  1568. */
  1569. function mul$1(out, m1, m2) {
  1570. // Consider matrix.mul(m, m2, m);
  1571. // where out is the same as m2.
  1572. // So use temp variable to escape error.
  1573. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1574. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1575. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1576. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1577. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1578. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1579. out[0] = out0;
  1580. out[1] = out1;
  1581. out[2] = out2;
  1582. out[3] = out3;
  1583. out[4] = out4;
  1584. out[5] = out5;
  1585. return out;
  1586. }
  1587. /**
  1588. * 平移变换
  1589. * @param {Float32Array|Array.<number>} out
  1590. * @param {Float32Array|Array.<number>} a
  1591. * @param {Float32Array|Array.<number>} v
  1592. */
  1593. function translate(out, a, v) {
  1594. out[0] = a[0];
  1595. out[1] = a[1];
  1596. out[2] = a[2];
  1597. out[3] = a[3];
  1598. out[4] = a[4] + v[0];
  1599. out[5] = a[5] + v[1];
  1600. return out;
  1601. }
  1602. /**
  1603. * 旋转变换
  1604. * @param {Float32Array|Array.<number>} out
  1605. * @param {Float32Array|Array.<number>} a
  1606. * @param {number} rad
  1607. */
  1608. function rotate(out, a, rad) {
  1609. var aa = a[0];
  1610. var ac = a[2];
  1611. var atx = a[4];
  1612. var ab = a[1];
  1613. var ad = a[3];
  1614. var aty = a[5];
  1615. var st = Math.sin(rad);
  1616. var ct = Math.cos(rad);
  1617. out[0] = aa * ct + ab * st;
  1618. out[1] = -aa * st + ab * ct;
  1619. out[2] = ac * ct + ad * st;
  1620. out[3] = -ac * st + ct * ad;
  1621. out[4] = ct * atx + st * aty;
  1622. out[5] = ct * aty - st * atx;
  1623. return out;
  1624. }
  1625. /**
  1626. * 缩放变换
  1627. * @param {Float32Array|Array.<number>} out
  1628. * @param {Float32Array|Array.<number>} a
  1629. * @param {Float32Array|Array.<number>} v
  1630. */
  1631. function scale$1(out, a, v) {
  1632. var vx = v[0];
  1633. var vy = v[1];
  1634. out[0] = a[0] * vx;
  1635. out[1] = a[1] * vy;
  1636. out[2] = a[2] * vx;
  1637. out[3] = a[3] * vy;
  1638. out[4] = a[4] * vx;
  1639. out[5] = a[5] * vy;
  1640. return out;
  1641. }
  1642. /**
  1643. * 求逆矩阵
  1644. * @param {Float32Array|Array.<number>} out
  1645. * @param {Float32Array|Array.<number>} a
  1646. */
  1647. function invert(out, a) {
  1648. var aa = a[0];
  1649. var ac = a[2];
  1650. var atx = a[4];
  1651. var ab = a[1];
  1652. var ad = a[3];
  1653. var aty = a[5];
  1654. var det = aa * ad - ab * ac;
  1655. if (!det) {
  1656. return null;
  1657. }
  1658. det = 1.0 / det;
  1659. out[0] = ad * det;
  1660. out[1] = -ab * det;
  1661. out[2] = -ac * det;
  1662. out[3] = aa * det;
  1663. out[4] = (ac * aty - ad * atx) * det;
  1664. out[5] = (ab * atx - aa * aty) * det;
  1665. return out;
  1666. }
  1667. /**
  1668. * Clone a new matrix.
  1669. * @param {Float32Array|Array.<number>} a
  1670. */
  1671. /**
  1672. * 提供变换扩展
  1673. * @module zrender/mixin/Transformable
  1674. * @author pissang (https://www.github.com/pissang)
  1675. */
  1676. var mIdentity = identity;
  1677. var EPSILON = 5e-5;
  1678. function isNotAroundZero(val) {
  1679. return val > EPSILON || val < -EPSILON;
  1680. }
  1681. /**
  1682. * @alias module:zrender/mixin/Transformable
  1683. * @constructor
  1684. */
  1685. var Transformable = function (opts) {
  1686. opts = opts || {};
  1687. // If there are no given position, rotation, scale
  1688. if (!opts.position) {
  1689. /**
  1690. * 平移
  1691. * @type {Array.<number>}
  1692. * @default [0, 0]
  1693. */
  1694. this.position = [0, 0];
  1695. }
  1696. if (opts.rotation == null) {
  1697. /**
  1698. * 旋转
  1699. * @type {Array.<number>}
  1700. * @default 0
  1701. */
  1702. this.rotation = 0;
  1703. }
  1704. if (!opts.scale) {
  1705. /**
  1706. * 缩放
  1707. * @type {Array.<number>}
  1708. * @default [1, 1]
  1709. */
  1710. this.scale = [1, 1];
  1711. }
  1712. /**
  1713. * 旋转和缩放的原点
  1714. * @type {Array.<number>}
  1715. * @default null
  1716. */
  1717. this.origin = this.origin || null;
  1718. };
  1719. var transformableProto = Transformable.prototype;
  1720. transformableProto.transform = null;
  1721. /**
  1722. * 判断是否需要有坐标变换
  1723. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1724. */
  1725. transformableProto.needLocalTransform = function () {
  1726. return isNotAroundZero(this.rotation)
  1727. || isNotAroundZero(this.position[0])
  1728. || isNotAroundZero(this.position[1])
  1729. || isNotAroundZero(this.scale[0] - 1)
  1730. || isNotAroundZero(this.scale[1] - 1);
  1731. };
  1732. transformableProto.updateTransform = function () {
  1733. var parent = this.parent;
  1734. var parentHasTransform = parent && parent.transform;
  1735. var needLocalTransform = this.needLocalTransform();
  1736. var m = this.transform;
  1737. if (!(needLocalTransform || parentHasTransform)) {
  1738. m && mIdentity(m);
  1739. return;
  1740. }
  1741. m = m || create$1();
  1742. if (needLocalTransform) {
  1743. this.getLocalTransform(m);
  1744. }
  1745. else {
  1746. mIdentity(m);
  1747. }
  1748. // 应用父节点变换
  1749. if (parentHasTransform) {
  1750. if (needLocalTransform) {
  1751. mul$1(m, parent.transform, m);
  1752. }
  1753. else {
  1754. copy$1(m, parent.transform);
  1755. }
  1756. }
  1757. // 保存这个变换矩阵
  1758. this.transform = m;
  1759. this.invTransform = this.invTransform || create$1();
  1760. invert(this.invTransform, m);
  1761. };
  1762. transformableProto.getLocalTransform = function (m) {
  1763. return Transformable.getLocalTransform(this, m);
  1764. };
  1765. /**
  1766. * 将自己的transform应用到context上
  1767. * @param {CanvasRenderingContext2D} ctx
  1768. */
  1769. transformableProto.setTransform = function (ctx) {
  1770. var m = this.transform;
  1771. var dpr = ctx.dpr || 1;
  1772. if (m) {
  1773. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1774. }
  1775. else {
  1776. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1777. }
  1778. };
  1779. transformableProto.restoreTransform = function (ctx) {
  1780. var dpr = ctx.dpr || 1;
  1781. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1782. };
  1783. var tmpTransform = [];
  1784. /**
  1785. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1786. */
  1787. transformableProto.decomposeTransform = function () {
  1788. if (!this.transform) {
  1789. return;
  1790. }
  1791. var parent = this.parent;
  1792. var m = this.transform;
  1793. if (parent && parent.transform) {
  1794. // Get local transform and decompose them to position, scale, rotation
  1795. mul$1(tmpTransform, parent.invTransform, m);
  1796. m = tmpTransform;
  1797. }
  1798. var sx = m[0] * m[0] + m[1] * m[1];
  1799. var sy = m[2] * m[2] + m[3] * m[3];
  1800. var position = this.position;
  1801. var scale$$1 = this.scale;
  1802. if (isNotAroundZero(sx - 1)) {
  1803. sx = Math.sqrt(sx);
  1804. }
  1805. if (isNotAroundZero(sy - 1)) {
  1806. sy = Math.sqrt(sy);
  1807. }
  1808. if (m[0] < 0) {
  1809. sx = -sx;
  1810. }
  1811. if (m[3] < 0) {
  1812. sy = -sy;
  1813. }
  1814. position[0] = m[4];
  1815. position[1] = m[5];
  1816. scale$$1[0] = sx;
  1817. scale$$1[1] = sy;
  1818. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1819. };
  1820. /**
  1821. * Get global scale
  1822. * @return {Array.<number>}
  1823. */
  1824. transformableProto.getGlobalScale = function () {
  1825. var m = this.transform;
  1826. if (!m) {
  1827. return [1, 1];
  1828. }
  1829. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1830. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1831. if (m[0] < 0) {
  1832. sx = -sx;
  1833. }
  1834. if (m[3] < 0) {
  1835. sy = -sy;
  1836. }
  1837. return [sx, sy];
  1838. };
  1839. /**
  1840. * 变换坐标位置到 shape 的局部坐标空间
  1841. * @method
  1842. * @param {number} x
  1843. * @param {number} y
  1844. * @return {Array.<number>}
  1845. */
  1846. transformableProto.transformCoordToLocal = function (x, y) {
  1847. var v2 = [x, y];
  1848. var invTransform = this.invTransform;
  1849. if (invTransform) {
  1850. applyTransform(v2, v2, invTransform);
  1851. }
  1852. return v2;
  1853. };
  1854. /**
  1855. * 变换局部坐标位置到全局坐标空间
  1856. * @method
  1857. * @param {number} x
  1858. * @param {number} y
  1859. * @return {Array.<number>}
  1860. */
  1861. transformableProto.transformCoordToGlobal = function (x, y) {
  1862. var v2 = [x, y];
  1863. var transform = this.transform;
  1864. if (transform) {
  1865. applyTransform(v2, v2, transform);
  1866. }
  1867. return v2;
  1868. };
  1869. /**
  1870. * @static
  1871. * @param {Object} target
  1872. * @param {Array.<number>} target.origin
  1873. * @param {number} target.rotation
  1874. * @param {Array.<number>} target.position
  1875. * @param {Array.<number>} [m]
  1876. */
  1877. Transformable.getLocalTransform = function (target, m) {
  1878. m = m || [];
  1879. mIdentity(m);
  1880. var origin = target.origin;
  1881. var scale$$1 = target.scale || [1, 1];
  1882. var rotation = target.rotation || 0;
  1883. var position = target.position || [0, 0];
  1884. if (origin) {
  1885. // Translate to origin
  1886. m[4] -= origin[0];
  1887. m[5] -= origin[1];
  1888. }
  1889. scale$1(m, m, scale$$1);
  1890. if (rotation) {
  1891. rotate(m, m, rotation);
  1892. }
  1893. if (origin) {
  1894. // Translate back from origin
  1895. m[4] += origin[0];
  1896. m[5] += origin[1];
  1897. }
  1898. m[4] += position[0];
  1899. m[5] += position[1];
  1900. return m;
  1901. };
  1902. /**
  1903. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  1904. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  1905. * @exports zrender/animation/easing
  1906. */
  1907. var easing = {
  1908. /**
  1909. * @param {number} k
  1910. * @return {number}
  1911. */
  1912. linear: function (k) {
  1913. return k;
  1914. },
  1915. /**
  1916. * @param {number} k
  1917. * @return {number}
  1918. */
  1919. quadraticIn: function (k) {
  1920. return k * k;
  1921. },
  1922. /**
  1923. * @param {number} k
  1924. * @return {number}
  1925. */
  1926. quadraticOut: function (k) {
  1927. return k * (2 - k);
  1928. },
  1929. /**
  1930. * @param {number} k
  1931. * @return {number}
  1932. */
  1933. quadraticInOut: function (k) {
  1934. if ((k *= 2) < 1) {
  1935. return 0.5 * k * k;
  1936. }
  1937. return -0.5 * (--k * (k - 2) - 1);
  1938. },
  1939. // 三次方的缓动(t^3)
  1940. /**
  1941. * @param {number} k
  1942. * @return {number}
  1943. */
  1944. cubicIn: function (k) {
  1945. return k * k * k;
  1946. },
  1947. /**
  1948. * @param {number} k
  1949. * @return {number}
  1950. */
  1951. cubicOut: function (k) {
  1952. return --k * k * k + 1;
  1953. },
  1954. /**
  1955. * @param {number} k
  1956. * @return {number}
  1957. */
  1958. cubicInOut: function (k) {
  1959. if ((k *= 2) < 1) {
  1960. return 0.5 * k * k * k;
  1961. }
  1962. return 0.5 * ((k -= 2) * k * k + 2);
  1963. },
  1964. // 四次方的缓动(t^4)
  1965. /**
  1966. * @param {number} k
  1967. * @return {number}
  1968. */
  1969. quarticIn: function (k) {
  1970. return k * k * k * k;
  1971. },
  1972. /**
  1973. * @param {number} k
  1974. * @return {number}
  1975. */
  1976. quarticOut: function (k) {
  1977. return 1 - (--k * k * k * k);
  1978. },
  1979. /**
  1980. * @param {number} k
  1981. * @return {number}
  1982. */
  1983. quarticInOut: function (k) {
  1984. if ((k *= 2) < 1) {
  1985. return 0.5 * k * k * k * k;
  1986. }
  1987. return -0.5 * ((k -= 2) * k * k * k - 2);
  1988. },
  1989. // 五次方的缓动(t^5)
  1990. /**
  1991. * @param {number} k
  1992. * @return {number}
  1993. */
  1994. quinticIn: function (k) {
  1995. return k * k * k * k * k;
  1996. },
  1997. /**
  1998. * @param {number} k
  1999. * @return {number}
  2000. */
  2001. quinticOut: function (k) {
  2002. return --k * k * k * k * k + 1;
  2003. },
  2004. /**
  2005. * @param {number} k
  2006. * @return {number}
  2007. */
  2008. quinticInOut: function (k) {
  2009. if ((k *= 2) < 1) {
  2010. return 0.5 * k * k * k * k * k;
  2011. }
  2012. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2013. },
  2014. // 正弦曲线的缓动(sin(t))
  2015. /**
  2016. * @param {number} k
  2017. * @return {number}
  2018. */
  2019. sinusoidalIn: function (k) {
  2020. return 1 - Math.cos(k * Math.PI / 2);
  2021. },
  2022. /**
  2023. * @param {number} k
  2024. * @return {number}
  2025. */
  2026. sinusoidalOut: function (k) {
  2027. return Math.sin(k * Math.PI / 2);
  2028. },
  2029. /**
  2030. * @param {number} k
  2031. * @return {number}
  2032. */
  2033. sinusoidalInOut: function (k) {
  2034. return 0.5 * (1 - Math.cos(Math.PI * k));
  2035. },
  2036. // 指数曲线的缓动(2^t)
  2037. /**
  2038. * @param {number} k
  2039. * @return {number}
  2040. */
  2041. exponentialIn: function (k) {
  2042. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2043. },
  2044. /**
  2045. * @param {number} k
  2046. * @return {number}
  2047. */
  2048. exponentialOut: function (k) {
  2049. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2050. },
  2051. /**
  2052. * @param {number} k
  2053. * @return {number}
  2054. */
  2055. exponentialInOut: function (k) {
  2056. if (k === 0) {
  2057. return 0;
  2058. }
  2059. if (k === 1) {
  2060. return 1;
  2061. }
  2062. if ((k *= 2) < 1) {
  2063. return 0.5 * Math.pow(1024, k - 1);
  2064. }
  2065. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2066. },
  2067. // 圆形曲线的缓动(sqrt(1-t^2))
  2068. /**
  2069. * @param {number} k
  2070. * @return {number}
  2071. */
  2072. circularIn: function (k) {
  2073. return 1 - Math.sqrt(1 - k * k);
  2074. },
  2075. /**
  2076. * @param {number} k
  2077. * @return {number}
  2078. */
  2079. circularOut: function (k) {
  2080. return Math.sqrt(1 - (--k * k));
  2081. },
  2082. /**
  2083. * @param {number} k
  2084. * @return {number}
  2085. */
  2086. circularInOut: function (k) {
  2087. if ((k *= 2) < 1) {
  2088. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2089. }
  2090. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2091. },
  2092. // 创建类似于弹簧在停止前来回振荡的动画
  2093. /**
  2094. * @param {number} k
  2095. * @return {number}
  2096. */
  2097. elasticIn: function (k) {
  2098. var s;
  2099. var a = 0.1;
  2100. var p = 0.4;
  2101. if (k === 0) {
  2102. return 0;
  2103. }
  2104. if (k === 1) {
  2105. return 1;
  2106. }
  2107. if (!a || a < 1) {
  2108. a = 1; s = p / 4;
  2109. }
  2110. else {
  2111. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2112. }
  2113. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2114. Math.sin((k - s) * (2 * Math.PI) / p));
  2115. },
  2116. /**
  2117. * @param {number} k
  2118. * @return {number}
  2119. */
  2120. elasticOut: function (k) {
  2121. var s;
  2122. var a = 0.1;
  2123. var p = 0.4;
  2124. if (k === 0) {
  2125. return 0;
  2126. }
  2127. if (k === 1) {
  2128. return 1;
  2129. }
  2130. if (!a || a < 1) {
  2131. a = 1; s = p / 4;
  2132. }
  2133. else {
  2134. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2135. }
  2136. return (a * Math.pow(2, -10 * k) *
  2137. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2138. },
  2139. /**
  2140. * @param {number} k
  2141. * @return {number}
  2142. */
  2143. elasticInOut: function (k) {
  2144. var s;
  2145. var a = 0.1;
  2146. var p = 0.4;
  2147. if (k === 0) {
  2148. return 0;
  2149. }
  2150. if (k === 1) {
  2151. return 1;
  2152. }
  2153. if (!a || a < 1) {
  2154. a = 1; s = p / 4;
  2155. }
  2156. else {
  2157. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2158. }
  2159. if ((k *= 2) < 1) {
  2160. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2161. * Math.sin((k - s) * (2 * Math.PI) / p));
  2162. }
  2163. return a * Math.pow(2, -10 * (k -= 1))
  2164. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2165. },
  2166. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2167. /**
  2168. * @param {number} k
  2169. * @return {number}
  2170. */
  2171. backIn: function (k) {
  2172. var s = 1.70158;
  2173. return k * k * ((s + 1) * k - s);
  2174. },
  2175. /**
  2176. * @param {number} k
  2177. * @return {number}
  2178. */
  2179. backOut: function (k) {
  2180. var s = 1.70158;
  2181. return --k * k * ((s + 1) * k + s) + 1;
  2182. },
  2183. /**
  2184. * @param {number} k
  2185. * @return {number}
  2186. */
  2187. backInOut: function (k) {
  2188. var s = 1.70158 * 1.525;
  2189. if ((k *= 2) < 1) {
  2190. return 0.5 * (k * k * ((s + 1) * k - s));
  2191. }
  2192. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2193. },
  2194. // 创建弹跳效果
  2195. /**
  2196. * @param {number} k
  2197. * @return {number}
  2198. */
  2199. bounceIn: function (k) {
  2200. return 1 - easing.bounceOut(1 - k);
  2201. },
  2202. /**
  2203. * @param {number} k
  2204. * @return {number}
  2205. */
  2206. bounceOut: function (k) {
  2207. if (k < (1 / 2.75)) {
  2208. return 7.5625 * k * k;
  2209. }
  2210. else if (k < (2 / 2.75)) {
  2211. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2212. }
  2213. else if (k < (2.5 / 2.75)) {
  2214. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2215. }
  2216. else {
  2217. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2218. }
  2219. },
  2220. /**
  2221. * @param {number} k
  2222. * @return {number}
  2223. */
  2224. bounceInOut: function (k) {
  2225. if (k < 0.5) {
  2226. return easing.bounceIn(k * 2) * 0.5;
  2227. }
  2228. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2229. }
  2230. };
  2231. /**
  2232. * 动画主控制器
  2233. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2234. * @config life(1000) 动画时长
  2235. * @config delay(0) 动画延迟时间
  2236. * @config loop(true)
  2237. * @config gap(0) 循环的间隔时间
  2238. * @config onframe
  2239. * @config easing(optional)
  2240. * @config ondestroy(optional)
  2241. * @config onrestart(optional)
  2242. *
  2243. * TODO pause
  2244. */
  2245. function Clip(options) {
  2246. this._target = options.target;
  2247. // 生命周期
  2248. this._life = options.life || 1000;
  2249. // 延时
  2250. this._delay = options.delay || 0;
  2251. // 开始时间
  2252. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2253. this._initialized = false;
  2254. // 是否循环
  2255. this.loop = options.loop == null ? false : options.loop;
  2256. this.gap = options.gap || 0;
  2257. this.easing = options.easing || 'Linear';
  2258. this.onframe = options.onframe;
  2259. this.ondestroy = options.ondestroy;
  2260. this.onrestart = options.onrestart;
  2261. this._pausedTime = 0;
  2262. this._paused = false;
  2263. }
  2264. Clip.prototype = {
  2265. constructor: Clip,
  2266. step: function (globalTime, deltaTime) {
  2267. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2268. // PENDING
  2269. if (!this._initialized) {
  2270. this._startTime = globalTime + this._delay;
  2271. this._initialized = true;
  2272. }
  2273. if (this._paused) {
  2274. this._pausedTime += deltaTime;
  2275. return;
  2276. }
  2277. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2278. // 还没开始
  2279. if (percent < 0) {
  2280. return;
  2281. }
  2282. percent = Math.min(percent, 1);
  2283. var easing$$1 = this.easing;
  2284. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2285. var schedule = typeof easingFunc === 'function'
  2286. ? easingFunc(percent)
  2287. : percent;
  2288. this.fire('frame', schedule);
  2289. // 结束
  2290. if (percent == 1) {
  2291. if (this.loop) {
  2292. this.restart (globalTime);
  2293. // 重新开始周期
  2294. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2295. return 'restart';
  2296. }
  2297. // 动画完成将这个控制器标识为待删除
  2298. // 在Animation.update中进行批量删除
  2299. this._needsRemove = true;
  2300. return 'destroy';
  2301. }
  2302. return null;
  2303. },
  2304. restart: function (globalTime) {
  2305. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2306. this._startTime = globalTime - remainder + this.gap;
  2307. this._pausedTime = 0;
  2308. this._needsRemove = false;
  2309. },
  2310. fire: function (eventType, arg) {
  2311. eventType = 'on' + eventType;
  2312. if (this[eventType]) {
  2313. this[eventType](this._target, arg);
  2314. }
  2315. },
  2316. pause: function () {
  2317. this._paused = true;
  2318. },
  2319. resume: function () {
  2320. this._paused = false;
  2321. }
  2322. };
  2323. // Simple LRU cache use doubly linked list
  2324. // @module zrender/core/LRU
  2325. /**
  2326. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2327. * @constructor
  2328. */
  2329. var LinkedList = function () {
  2330. /**
  2331. * @type {module:zrender/core/LRU~Entry}
  2332. */
  2333. this.head = null;
  2334. /**
  2335. * @type {module:zrender/core/LRU~Entry}
  2336. */
  2337. this.tail = null;
  2338. this._len = 0;
  2339. };
  2340. var linkedListProto = LinkedList.prototype;
  2341. /**
  2342. * Insert a new value at the tail
  2343. * @param {} val
  2344. * @return {module:zrender/core/LRU~Entry}
  2345. */
  2346. linkedListProto.insert = function (val) {
  2347. var entry = new Entry(val);
  2348. this.insertEntry(entry);
  2349. return entry;
  2350. };
  2351. /**
  2352. * Insert an entry at the tail
  2353. * @param {module:zrender/core/LRU~Entry} entry
  2354. */
  2355. linkedListProto.insertEntry = function (entry) {
  2356. if (!this.head) {
  2357. this.head = this.tail = entry;
  2358. }
  2359. else {
  2360. this.tail.next = entry;
  2361. entry.prev = this.tail;
  2362. entry.next = null;
  2363. this.tail = entry;
  2364. }
  2365. this._len++;
  2366. };
  2367. /**
  2368. * Remove entry.
  2369. * @param {module:zrender/core/LRU~Entry} entry
  2370. */
  2371. linkedListProto.remove = function (entry) {
  2372. var prev = entry.prev;
  2373. var next = entry.next;
  2374. if (prev) {
  2375. prev.next = next;
  2376. }
  2377. else {
  2378. // Is head
  2379. this.head = next;
  2380. }
  2381. if (next) {
  2382. next.prev = prev;
  2383. }
  2384. else {
  2385. // Is tail
  2386. this.tail = prev;
  2387. }
  2388. entry.next = entry.prev = null;
  2389. this._len--;
  2390. };
  2391. /**
  2392. * @return {number}
  2393. */
  2394. linkedListProto.len = function () {
  2395. return this._len;
  2396. };
  2397. /**
  2398. * Clear list
  2399. */
  2400. linkedListProto.clear = function () {
  2401. this.head = this.tail = null;
  2402. this._len = 0;
  2403. };
  2404. /**
  2405. * @constructor
  2406. * @param {} val
  2407. */
  2408. var Entry = function (val) {
  2409. /**
  2410. * @type {}
  2411. */
  2412. this.value = val;
  2413. /**
  2414. * @type {module:zrender/core/LRU~Entry}
  2415. */
  2416. this.next;
  2417. /**
  2418. * @type {module:zrender/core/LRU~Entry}
  2419. */
  2420. this.prev;
  2421. };
  2422. /**
  2423. * LRU Cache
  2424. * @constructor
  2425. * @alias module:zrender/core/LRU
  2426. */
  2427. var LRU = function (maxSize) {
  2428. this._list = new LinkedList();
  2429. this._map = {};
  2430. this._maxSize = maxSize || 10;
  2431. this._lastRemovedEntry = null;
  2432. };
  2433. var LRUProto = LRU.prototype;
  2434. /**
  2435. * @param {string} key
  2436. * @param {} value
  2437. * @return {} Removed value
  2438. */
  2439. LRUProto.put = function (key, value) {
  2440. var list = this._list;
  2441. var map = this._map;
  2442. var removed = null;
  2443. if (map[key] == null) {
  2444. var len = list.len();
  2445. // Reuse last removed entry
  2446. var entry = this._lastRemovedEntry;
  2447. if (len >= this._maxSize && len > 0) {
  2448. // Remove the least recently used
  2449. var leastUsedEntry = list.head;
  2450. list.remove(leastUsedEntry);
  2451. delete map[leastUsedEntry.key];
  2452. removed = leastUsedEntry.value;
  2453. this._lastRemovedEntry = leastUsedEntry;
  2454. }
  2455. if (entry) {
  2456. entry.value = value;
  2457. }
  2458. else {
  2459. entry = new Entry(value);
  2460. }
  2461. entry.key = key;
  2462. list.insertEntry(entry);
  2463. map[key] = entry;
  2464. }
  2465. return removed;
  2466. };
  2467. /**
  2468. * @param {string} key
  2469. * @return {}
  2470. */
  2471. LRUProto.get = function (key) {
  2472. var entry = this._map[key];
  2473. var list = this._list;
  2474. if (entry != null) {
  2475. // Put the latest used entry in the tail
  2476. if (entry !== list.tail) {
  2477. list.remove(entry);
  2478. list.insertEntry(entry);
  2479. }
  2480. return entry.value;
  2481. }
  2482. };
  2483. /**
  2484. * Clear the cache
  2485. */
  2486. LRUProto.clear = function () {
  2487. this._list.clear();
  2488. this._map = {};
  2489. };
  2490. var kCSSColorTable = {
  2491. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2492. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2493. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2494. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2495. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2496. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2497. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2498. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2499. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2500. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2501. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2502. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2503. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2504. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2505. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2506. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2507. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2508. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2509. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2510. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2511. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2512. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2513. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2514. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2515. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2516. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2517. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2518. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2519. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2520. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2521. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2522. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2523. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2524. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2525. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2526. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2527. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2528. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2529. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2530. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2531. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2532. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2533. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2534. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2535. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2536. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2537. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2538. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2539. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2540. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2541. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2542. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2543. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2544. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2545. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2546. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2547. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2548. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2549. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2550. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2551. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2552. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2553. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2554. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2555. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2556. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2557. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2558. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2559. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2560. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2561. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2562. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2563. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2564. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2565. };
  2566. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2567. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2568. return i < 0 ? 0 : i > 255 ? 255 : i;
  2569. }
  2570. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2571. return f < 0 ? 0 : f > 1 ? 1 : f;
  2572. }
  2573. function parseCssInt(str) { // int or percentage.
  2574. if (str.length && str.charAt(str.length - 1) === '%') {
  2575. return clampCssByte(parseFloat(str) / 100 * 255);
  2576. }
  2577. return clampCssByte(parseInt(str, 10));
  2578. }
  2579. function parseCssFloat(str) { // float or percentage.
  2580. if (str.length && str.charAt(str.length - 1) === '%') {
  2581. return clampCssFloat(parseFloat(str) / 100);
  2582. }
  2583. return clampCssFloat(parseFloat(str));
  2584. }
  2585. function cssHueToRgb(m1, m2, h) {
  2586. if (h < 0) {
  2587. h += 1;
  2588. }
  2589. else if (h > 1) {
  2590. h -= 1;
  2591. }
  2592. if (h * 6 < 1) {
  2593. return m1 + (m2 - m1) * h * 6;
  2594. }
  2595. if (h * 2 < 1) {
  2596. return m2;
  2597. }
  2598. if (h * 3 < 2) {
  2599. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2600. }
  2601. return m1;
  2602. }
  2603. function setRgba(out, r, g, b, a) {
  2604. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2605. return out;
  2606. }
  2607. function copyRgba(out, a) {
  2608. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2609. return out;
  2610. }
  2611. var colorCache = new LRU(20);
  2612. var lastRemovedArr = null;
  2613. function putToCache(colorStr, rgbaArr) {
  2614. // Reuse removed array
  2615. if (lastRemovedArr) {
  2616. copyRgba(lastRemovedArr, rgbaArr);
  2617. }
  2618. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2619. }
  2620. /**
  2621. * @param {string} colorStr
  2622. * @param {Array.<number>} out
  2623. * @return {Array.<number>}
  2624. * @memberOf module:zrender/util/color
  2625. */
  2626. function parse(colorStr, rgbaArr) {
  2627. if (!colorStr) {
  2628. return;
  2629. }
  2630. rgbaArr = rgbaArr || [];
  2631. var cached = colorCache.get(colorStr);
  2632. if (cached) {
  2633. return copyRgba(rgbaArr, cached);
  2634. }
  2635. // colorStr may be not string
  2636. colorStr = colorStr + '';
  2637. // Remove all whitespace, not compliant, but should just be more accepting.
  2638. var str = colorStr.replace(/ /g, '').toLowerCase();
  2639. // Color keywords (and transparent) lookup.
  2640. if (str in kCSSColorTable) {
  2641. copyRgba(rgbaArr, kCSSColorTable[str]);
  2642. putToCache(colorStr, rgbaArr);
  2643. return rgbaArr;
  2644. }
  2645. // #abc and #abc123 syntax.
  2646. if (str.charAt(0) === '#') {
  2647. if (str.length === 4) {
  2648. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2649. if (!(iv >= 0 && iv <= 0xfff)) {
  2650. setRgba(rgbaArr, 0, 0, 0, 1);
  2651. return; // Covers NaN.
  2652. }
  2653. setRgba(rgbaArr,
  2654. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2655. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2656. (iv & 0xf) | ((iv & 0xf) << 4),
  2657. 1
  2658. );
  2659. putToCache(colorStr, rgbaArr);
  2660. return rgbaArr;
  2661. }
  2662. else if (str.length === 7) {
  2663. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2664. if (!(iv >= 0 && iv <= 0xffffff)) {
  2665. setRgba(rgbaArr, 0, 0, 0, 1);
  2666. return; // Covers NaN.
  2667. }
  2668. setRgba(rgbaArr,
  2669. (iv & 0xff0000) >> 16,
  2670. (iv & 0xff00) >> 8,
  2671. iv & 0xff,
  2672. 1
  2673. );
  2674. putToCache(colorStr, rgbaArr);
  2675. return rgbaArr;
  2676. }
  2677. return;
  2678. }
  2679. var op = str.indexOf('('), ep = str.indexOf(')');
  2680. if (op !== -1 && ep + 1 === str.length) {
  2681. var fname = str.substr(0, op);
  2682. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2683. var alpha = 1; // To allow case fallthrough.
  2684. switch (fname) {
  2685. case 'rgba':
  2686. if (params.length !== 4) {
  2687. setRgba(rgbaArr, 0, 0, 0, 1);
  2688. return;
  2689. }
  2690. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2691. // Fall through.
  2692. case 'rgb':
  2693. if (params.length !== 3) {
  2694. setRgba(rgbaArr, 0, 0, 0, 1);
  2695. return;
  2696. }
  2697. setRgba(rgbaArr,
  2698. parseCssInt(params[0]),
  2699. parseCssInt(params[1]),
  2700. parseCssInt(params[2]),
  2701. alpha
  2702. );
  2703. putToCache(colorStr, rgbaArr);
  2704. return rgbaArr;
  2705. case 'hsla':
  2706. if (params.length !== 4) {
  2707. setRgba(rgbaArr, 0, 0, 0, 1);
  2708. return;
  2709. }
  2710. params[3] = parseCssFloat(params[3]);
  2711. hsla2rgba(params, rgbaArr);
  2712. putToCache(colorStr, rgbaArr);
  2713. return rgbaArr;
  2714. case 'hsl':
  2715. if (params.length !== 3) {
  2716. setRgba(rgbaArr, 0, 0, 0, 1);
  2717. return;
  2718. }
  2719. hsla2rgba(params, rgbaArr);
  2720. putToCache(colorStr, rgbaArr);
  2721. return rgbaArr;
  2722. default:
  2723. return;
  2724. }
  2725. }
  2726. setRgba(rgbaArr, 0, 0, 0, 1);
  2727. return;
  2728. }
  2729. /**
  2730. * @param {Array.<number>} hsla
  2731. * @param {Array.<number>} rgba
  2732. * @return {Array.<number>} rgba
  2733. */
  2734. function hsla2rgba(hsla, rgba) {
  2735. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2736. // NOTE(deanm): According to the CSS spec s/l should only be
  2737. // percentages, but we don't bother and let float or percentage.
  2738. var s = parseCssFloat(hsla[1]);
  2739. var l = parseCssFloat(hsla[2]);
  2740. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2741. var m1 = l * 2 - m2;
  2742. rgba = rgba || [];
  2743. setRgba(rgba,
  2744. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2745. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2746. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2747. 1
  2748. );
  2749. if (hsla.length === 4) {
  2750. rgba[3] = hsla[3];
  2751. }
  2752. return rgba;
  2753. }
  2754. /**
  2755. * @param {string} color
  2756. * @param {number} level
  2757. * @return {string}
  2758. * @memberOf module:zrender/util/color
  2759. */
  2760. function lift(color, level) {
  2761. var colorArr = parse(color);
  2762. if (colorArr) {
  2763. for (var i = 0; i < 3; i++) {
  2764. if (level < 0) {
  2765. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2766. }
  2767. else {
  2768. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2769. }
  2770. }
  2771. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2772. }
  2773. }
  2774. /**
  2775. * @param {string} color
  2776. * @return {string}
  2777. * @memberOf module:zrender/util/color
  2778. */
  2779. /**
  2780. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  2781. * @param {number} normalizedValue A float between 0 and 1.
  2782. * @param {Array.<Array.<number>>} colors List of rgba color array
  2783. * @param {Array.<number>} [out] Mapped gba color array
  2784. * @return {Array.<number>} will be null/undefined if input illegal.
  2785. */
  2786. /**
  2787. * @deprecated
  2788. */
  2789. /**
  2790. * @param {number} normalizedValue A float between 0 and 1.
  2791. * @param {Array.<string>} colors Color list.
  2792. * @param {boolean=} fullOutput Default false.
  2793. * @return {(string|Object)} Result color. If fullOutput,
  2794. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  2795. * @memberOf module:zrender/util/color
  2796. */
  2797. /**
  2798. * @deprecated
  2799. */
  2800. /**
  2801. * @param {string} color
  2802. * @param {number=} h 0 ~ 360, ignore when null.
  2803. * @param {number=} s 0 ~ 1, ignore when null.
  2804. * @param {number=} l 0 ~ 1, ignore when null.
  2805. * @return {string} Color string in rgba format.
  2806. * @memberOf module:zrender/util/color
  2807. */
  2808. /**
  2809. * @param {string} color
  2810. * @param {number=} alpha 0 ~ 1
  2811. * @return {string} Color string in rgba format.
  2812. * @memberOf module:zrender/util/color
  2813. */
  2814. /**
  2815. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  2816. * @param {string} type 'rgba', 'hsva', ...
  2817. * @return {string} Result color. (If input illegal, return undefined).
  2818. */
  2819. function stringify(arrColor, type) {
  2820. if (!arrColor || !arrColor.length) {
  2821. return;
  2822. }
  2823. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  2824. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  2825. colorStr += ',' + arrColor[3];
  2826. }
  2827. return type + '(' + colorStr + ')';
  2828. }
  2829. /**
  2830. * @module echarts/animation/Animator
  2831. */
  2832. var arraySlice = Array.prototype.slice;
  2833. function defaultGetter(target, key) {
  2834. return target[key];
  2835. }
  2836. function defaultSetter(target, key, value) {
  2837. target[key] = value;
  2838. }
  2839. /**
  2840. * @param {number} p0
  2841. * @param {number} p1
  2842. * @param {number} percent
  2843. * @return {number}
  2844. */
  2845. function interpolateNumber(p0, p1, percent) {
  2846. return (p1 - p0) * percent + p0;
  2847. }
  2848. /**
  2849. * @param {string} p0
  2850. * @param {string} p1
  2851. * @param {number} percent
  2852. * @return {string}
  2853. */
  2854. function interpolateString(p0, p1, percent) {
  2855. return percent > 0.5 ? p1 : p0;
  2856. }
  2857. /**
  2858. * @param {Array} p0
  2859. * @param {Array} p1
  2860. * @param {number} percent
  2861. * @param {Array} out
  2862. * @param {number} arrDim
  2863. */
  2864. function interpolateArray(p0, p1, percent, out, arrDim) {
  2865. var len = p0.length;
  2866. if (arrDim == 1) {
  2867. for (var i = 0; i < len; i++) {
  2868. out[i] = interpolateNumber(p0[i], p1[i], percent);
  2869. }
  2870. }
  2871. else {
  2872. var len2 = len && p0[0].length;
  2873. for (var i = 0; i < len; i++) {
  2874. for (var j = 0; j < len2; j++) {
  2875. out[i][j] = interpolateNumber(
  2876. p0[i][j], p1[i][j], percent
  2877. );
  2878. }
  2879. }
  2880. }
  2881. }
  2882. // arr0 is source array, arr1 is target array.
  2883. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  2884. function fillArr(arr0, arr1, arrDim) {
  2885. var arr0Len = arr0.length;
  2886. var arr1Len = arr1.length;
  2887. if (arr0Len !== arr1Len) {
  2888. // FIXME Not work for TypedArray
  2889. var isPreviousLarger = arr0Len > arr1Len;
  2890. if (isPreviousLarger) {
  2891. // Cut the previous
  2892. arr0.length = arr1Len;
  2893. }
  2894. else {
  2895. // Fill the previous
  2896. for (var i = arr0Len; i < arr1Len; i++) {
  2897. arr0.push(
  2898. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  2899. );
  2900. }
  2901. }
  2902. }
  2903. // Handling NaN value
  2904. var len2 = arr0[0] && arr0[0].length;
  2905. for (var i = 0; i < arr0.length; i++) {
  2906. if (arrDim === 1) {
  2907. if (isNaN(arr0[i])) {
  2908. arr0[i] = arr1[i];
  2909. }
  2910. }
  2911. else {
  2912. for (var j = 0; j < len2; j++) {
  2913. if (isNaN(arr0[i][j])) {
  2914. arr0[i][j] = arr1[i][j];
  2915. }
  2916. }
  2917. }
  2918. }
  2919. }
  2920. /**
  2921. * @param {Array} arr0
  2922. * @param {Array} arr1
  2923. * @param {number} arrDim
  2924. * @return {boolean}
  2925. */
  2926. function isArraySame(arr0, arr1, arrDim) {
  2927. if (arr0 === arr1) {
  2928. return true;
  2929. }
  2930. var len = arr0.length;
  2931. if (len !== arr1.length) {
  2932. return false;
  2933. }
  2934. if (arrDim === 1) {
  2935. for (var i = 0; i < len; i++) {
  2936. if (arr0[i] !== arr1[i]) {
  2937. return false;
  2938. }
  2939. }
  2940. }
  2941. else {
  2942. var len2 = arr0[0].length;
  2943. for (var i = 0; i < len; i++) {
  2944. for (var j = 0; j < len2; j++) {
  2945. if (arr0[i][j] !== arr1[i][j]) {
  2946. return false;
  2947. }
  2948. }
  2949. }
  2950. }
  2951. return true;
  2952. }
  2953. /**
  2954. * Catmull Rom interpolate array
  2955. * @param {Array} p0
  2956. * @param {Array} p1
  2957. * @param {Array} p2
  2958. * @param {Array} p3
  2959. * @param {number} t
  2960. * @param {number} t2
  2961. * @param {number} t3
  2962. * @param {Array} out
  2963. * @param {number} arrDim
  2964. */
  2965. function catmullRomInterpolateArray(
  2966. p0, p1, p2, p3, t, t2, t3, out, arrDim
  2967. ) {
  2968. var len = p0.length;
  2969. if (arrDim == 1) {
  2970. for (var i = 0; i < len; i++) {
  2971. out[i] = catmullRomInterpolate(
  2972. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  2973. );
  2974. }
  2975. }
  2976. else {
  2977. var len2 = p0[0].length;
  2978. for (var i = 0; i < len; i++) {
  2979. for (var j = 0; j < len2; j++) {
  2980. out[i][j] = catmullRomInterpolate(
  2981. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  2982. t, t2, t3
  2983. );
  2984. }
  2985. }
  2986. }
  2987. }
  2988. /**
  2989. * Catmull Rom interpolate number
  2990. * @param {number} p0
  2991. * @param {number} p1
  2992. * @param {number} p2
  2993. * @param {number} p3
  2994. * @param {number} t
  2995. * @param {number} t2
  2996. * @param {number} t3
  2997. * @return {number}
  2998. */
  2999. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3000. var v0 = (p2 - p0) * 0.5;
  3001. var v1 = (p3 - p1) * 0.5;
  3002. return (2 * (p1 - p2) + v0 + v1) * t3
  3003. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3004. + v0 * t + p1;
  3005. }
  3006. function cloneValue(value) {
  3007. if (isArrayLike(value)) {
  3008. var len = value.length;
  3009. if (isArrayLike(value[0])) {
  3010. var ret = [];
  3011. for (var i = 0; i < len; i++) {
  3012. ret.push(arraySlice.call(value[i]));
  3013. }
  3014. return ret;
  3015. }
  3016. return arraySlice.call(value);
  3017. }
  3018. return value;
  3019. }
  3020. function rgba2String(rgba) {
  3021. rgba[0] = Math.floor(rgba[0]);
  3022. rgba[1] = Math.floor(rgba[1]);
  3023. rgba[2] = Math.floor(rgba[2]);
  3024. return 'rgba(' + rgba.join(',') + ')';
  3025. }
  3026. function getArrayDim(keyframes) {
  3027. var lastValue = keyframes[keyframes.length - 1].value;
  3028. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3029. }
  3030. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3031. var getter = animator._getter;
  3032. var setter = animator._setter;
  3033. var useSpline = easing === 'spline';
  3034. var trackLen = keyframes.length;
  3035. if (!trackLen) {
  3036. return;
  3037. }
  3038. // Guess data type
  3039. var firstVal = keyframes[0].value;
  3040. var isValueArray = isArrayLike(firstVal);
  3041. var isValueColor = false;
  3042. var isValueString = false;
  3043. // For vertices morphing
  3044. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3045. var trackMaxTime;
  3046. // Sort keyframe as ascending
  3047. keyframes.sort(function(a, b) {
  3048. return a.time - b.time;
  3049. });
  3050. trackMaxTime = keyframes[trackLen - 1].time;
  3051. // Percents of each keyframe
  3052. var kfPercents = [];
  3053. // Value of each keyframe
  3054. var kfValues = [];
  3055. var prevValue = keyframes[0].value;
  3056. var isAllValueEqual = true;
  3057. for (var i = 0; i < trackLen; i++) {
  3058. kfPercents.push(keyframes[i].time / trackMaxTime);
  3059. // Assume value is a color when it is a string
  3060. var value = keyframes[i].value;
  3061. // Check if value is equal, deep check if value is array
  3062. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3063. || (!isValueArray && value === prevValue))) {
  3064. isAllValueEqual = false;
  3065. }
  3066. prevValue = value;
  3067. // Try converting a string to a color array
  3068. if (typeof value == 'string') {
  3069. var colorArray = parse(value);
  3070. if (colorArray) {
  3071. value = colorArray;
  3072. isValueColor = true;
  3073. }
  3074. else {
  3075. isValueString = true;
  3076. }
  3077. }
  3078. kfValues.push(value);
  3079. }
  3080. if (!forceAnimate && isAllValueEqual) {
  3081. return;
  3082. }
  3083. var lastValue = kfValues[trackLen - 1];
  3084. // Polyfill array and NaN value
  3085. for (var i = 0; i < trackLen - 1; i++) {
  3086. if (isValueArray) {
  3087. fillArr(kfValues[i], lastValue, arrDim);
  3088. }
  3089. else {
  3090. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3091. kfValues[i] = lastValue;
  3092. }
  3093. }
  3094. }
  3095. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3096. // Cache the key of last frame to speed up when
  3097. // animation playback is sequency
  3098. var lastFrame = 0;
  3099. var lastFramePercent = 0;
  3100. var start;
  3101. var w;
  3102. var p0;
  3103. var p1;
  3104. var p2;
  3105. var p3;
  3106. if (isValueColor) {
  3107. var rgba = [0, 0, 0, 0];
  3108. }
  3109. var onframe = function (target, percent) {
  3110. // Find the range keyframes
  3111. // kf1-----kf2---------current--------kf3
  3112. // find kf2 and kf3 and do interpolation
  3113. var frame;
  3114. // In the easing function like elasticOut, percent may less than 0
  3115. if (percent < 0) {
  3116. frame = 0;
  3117. }
  3118. else if (percent < lastFramePercent) {
  3119. // Start from next key
  3120. // PENDING start from lastFrame ?
  3121. start = Math.min(lastFrame + 1, trackLen - 1);
  3122. for (frame = start; frame >= 0; frame--) {
  3123. if (kfPercents[frame] <= percent) {
  3124. break;
  3125. }
  3126. }
  3127. // PENDING really need to do this ?
  3128. frame = Math.min(frame, trackLen - 2);
  3129. }
  3130. else {
  3131. for (frame = lastFrame; frame < trackLen; frame++) {
  3132. if (kfPercents[frame] > percent) {
  3133. break;
  3134. }
  3135. }
  3136. frame = Math.min(frame - 1, trackLen - 2);
  3137. }
  3138. lastFrame = frame;
  3139. lastFramePercent = percent;
  3140. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3141. if (range === 0) {
  3142. return;
  3143. }
  3144. else {
  3145. w = (percent - kfPercents[frame]) / range;
  3146. }
  3147. if (useSpline) {
  3148. p1 = kfValues[frame];
  3149. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3150. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3151. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3152. if (isValueArray) {
  3153. catmullRomInterpolateArray(
  3154. p0, p1, p2, p3, w, w * w, w * w * w,
  3155. getter(target, propName),
  3156. arrDim
  3157. );
  3158. }
  3159. else {
  3160. var value;
  3161. if (isValueColor) {
  3162. value = catmullRomInterpolateArray(
  3163. p0, p1, p2, p3, w, w * w, w * w * w,
  3164. rgba, 1
  3165. );
  3166. value = rgba2String(rgba);
  3167. }
  3168. else if (isValueString) {
  3169. // String is step(0.5)
  3170. return interpolateString(p1, p2, w);
  3171. }
  3172. else {
  3173. value = catmullRomInterpolate(
  3174. p0, p1, p2, p3, w, w * w, w * w * w
  3175. );
  3176. }
  3177. setter(
  3178. target,
  3179. propName,
  3180. value
  3181. );
  3182. }
  3183. }
  3184. else {
  3185. if (isValueArray) {
  3186. interpolateArray(
  3187. kfValues[frame], kfValues[frame + 1], w,
  3188. getter(target, propName),
  3189. arrDim
  3190. );
  3191. }
  3192. else {
  3193. var value;
  3194. if (isValueColor) {
  3195. interpolateArray(
  3196. kfValues[frame], kfValues[frame + 1], w,
  3197. rgba, 1
  3198. );
  3199. value = rgba2String(rgba);
  3200. }
  3201. else if (isValueString) {
  3202. // String is step(0.5)
  3203. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3204. }
  3205. else {
  3206. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3207. }
  3208. setter(
  3209. target,
  3210. propName,
  3211. value
  3212. );
  3213. }
  3214. }
  3215. };
  3216. var clip = new Clip({
  3217. target: animator._target,
  3218. life: trackMaxTime,
  3219. loop: animator._loop,
  3220. delay: animator._delay,
  3221. onframe: onframe,
  3222. ondestroy: oneTrackDone
  3223. });
  3224. if (easing && easing !== 'spline') {
  3225. clip.easing = easing;
  3226. }
  3227. return clip;
  3228. }
  3229. /**
  3230. * @alias module:zrender/animation/Animator
  3231. * @constructor
  3232. * @param {Object} target
  3233. * @param {boolean} loop
  3234. * @param {Function} getter
  3235. * @param {Function} setter
  3236. */
  3237. var Animator = function(target, loop, getter, setter) {
  3238. this._tracks = {};
  3239. this._target = target;
  3240. this._loop = loop || false;
  3241. this._getter = getter || defaultGetter;
  3242. this._setter = setter || defaultSetter;
  3243. this._clipCount = 0;
  3244. this._delay = 0;
  3245. this._doneList = [];
  3246. this._onframeList = [];
  3247. this._clipList = [];
  3248. };
  3249. Animator.prototype = {
  3250. /**
  3251. * 设置动画关键帧
  3252. * @param {number} time 关键帧时间,单位是ms
  3253. * @param {Object} props 关键帧的属性值,key-value表示
  3254. * @return {module:zrender/animation/Animator}
  3255. */
  3256. when: function(time /* ms */, props) {
  3257. var tracks = this._tracks;
  3258. for (var propName in props) {
  3259. if (!props.hasOwnProperty(propName)) {
  3260. continue;
  3261. }
  3262. if (!tracks[propName]) {
  3263. tracks[propName] = [];
  3264. // Invalid value
  3265. var value = this._getter(this._target, propName);
  3266. if (value == null) {
  3267. // zrLog('Invalid property ' + propName);
  3268. continue;
  3269. }
  3270. // If time is 0
  3271. // Then props is given initialize value
  3272. // Else
  3273. // Initialize value from current prop value
  3274. if (time !== 0) {
  3275. tracks[propName].push({
  3276. time: 0,
  3277. value: cloneValue(value)
  3278. });
  3279. }
  3280. }
  3281. tracks[propName].push({
  3282. time: time,
  3283. value: props[propName]
  3284. });
  3285. }
  3286. return this;
  3287. },
  3288. /**
  3289. * 添加动画每一帧的回调函数
  3290. * @param {Function} callback
  3291. * @return {module:zrender/animation/Animator}
  3292. */
  3293. during: function (callback) {
  3294. this._onframeList.push(callback);
  3295. return this;
  3296. },
  3297. pause: function () {
  3298. for (var i = 0; i < this._clipList.length; i++) {
  3299. this._clipList[i].pause();
  3300. }
  3301. this._paused = true;
  3302. },
  3303. resume: function () {
  3304. for (var i = 0; i < this._clipList.length; i++) {
  3305. this._clipList[i].resume();
  3306. }
  3307. this._paused = false;
  3308. },
  3309. isPaused: function () {
  3310. return !!this._paused;
  3311. },
  3312. _doneCallback: function () {
  3313. // Clear all tracks
  3314. this._tracks = {};
  3315. // Clear all clips
  3316. this._clipList.length = 0;
  3317. var doneList = this._doneList;
  3318. var len = doneList.length;
  3319. for (var i = 0; i < len; i++) {
  3320. doneList[i].call(this);
  3321. }
  3322. },
  3323. /**
  3324. * 开始执行动画
  3325. * @param {string|Function} [easing]
  3326. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3327. * @param {boolean} forceAnimate
  3328. * @return {module:zrender/animation/Animator}
  3329. */
  3330. start: function (easing, forceAnimate) {
  3331. var self = this;
  3332. var clipCount = 0;
  3333. var oneTrackDone = function() {
  3334. clipCount--;
  3335. if (!clipCount) {
  3336. self._doneCallback();
  3337. }
  3338. };
  3339. var lastClip;
  3340. for (var propName in this._tracks) {
  3341. if (!this._tracks.hasOwnProperty(propName)) {
  3342. continue;
  3343. }
  3344. var clip = createTrackClip(
  3345. this, easing, oneTrackDone,
  3346. this._tracks[propName], propName, forceAnimate
  3347. );
  3348. if (clip) {
  3349. this._clipList.push(clip);
  3350. clipCount++;
  3351. // If start after added to animation
  3352. if (this.animation) {
  3353. this.animation.addClip(clip);
  3354. }
  3355. lastClip = clip;
  3356. }
  3357. }
  3358. // Add during callback on the last clip
  3359. if (lastClip) {
  3360. var oldOnFrame = lastClip.onframe;
  3361. lastClip.onframe = function (target, percent) {
  3362. oldOnFrame(target, percent);
  3363. for (var i = 0; i < self._onframeList.length; i++) {
  3364. self._onframeList[i](target, percent);
  3365. }
  3366. };
  3367. }
  3368. // This optimization will help the case that in the upper application
  3369. // the view may be refreshed frequently, where animation will be
  3370. // called repeatly but nothing changed.
  3371. if (!clipCount) {
  3372. this._doneCallback();
  3373. }
  3374. return this;
  3375. },
  3376. /**
  3377. * 停止动画
  3378. * @param {boolean} forwardToLast If move to last frame before stop
  3379. */
  3380. stop: function (forwardToLast) {
  3381. var clipList = this._clipList;
  3382. var animation = this.animation;
  3383. for (var i = 0; i < clipList.length; i++) {
  3384. var clip = clipList[i];
  3385. if (forwardToLast) {
  3386. // Move to last frame before stop
  3387. clip.onframe(this._target, 1);
  3388. }
  3389. animation && animation.removeClip(clip);
  3390. }
  3391. clipList.length = 0;
  3392. },
  3393. /**
  3394. * 设置动画延迟开始的时间
  3395. * @param {number} time 单位ms
  3396. * @return {module:zrender/animation/Animator}
  3397. */
  3398. delay: function (time) {
  3399. this._delay = time;
  3400. return this;
  3401. },
  3402. /**
  3403. * 添加动画结束的回调
  3404. * @param {Function} cb
  3405. * @return {module:zrender/animation/Animator}
  3406. */
  3407. done: function(cb) {
  3408. if (cb) {
  3409. this._doneList.push(cb);
  3410. }
  3411. return this;
  3412. },
  3413. /**
  3414. * @return {Array.<module:zrender/animation/Clip>}
  3415. */
  3416. getClips: function () {
  3417. return this._clipList;
  3418. }
  3419. };
  3420. var dpr = 1;
  3421. // If in browser environment
  3422. if (typeof window !== 'undefined') {
  3423. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3424. }
  3425. /**
  3426. * config默认配置项
  3427. * @exports zrender/config
  3428. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3429. */
  3430. /**
  3431. * debug日志选项:catchBrushException为true下有效
  3432. * 0 : 不生成debug数据,发布用
  3433. * 1 : 异常抛出,调试用
  3434. * 2 : 控制台输出,调试用
  3435. */
  3436. var debugMode = 0;
  3437. // retina 屏幕优化
  3438. var devicePixelRatio = dpr;
  3439. var log = function () {
  3440. };
  3441. if (debugMode === 1) {
  3442. log = function () {
  3443. for (var k in arguments) {
  3444. throw new Error(arguments[k]);
  3445. }
  3446. };
  3447. }
  3448. else if (debugMode > 1) {
  3449. log = function () {
  3450. for (var k in arguments) {
  3451. console.log(arguments[k]);
  3452. }
  3453. };
  3454. }
  3455. var log$1 = log;
  3456. /**
  3457. * @alias modue:zrender/mixin/Animatable
  3458. * @constructor
  3459. */
  3460. var Animatable = function () {
  3461. /**
  3462. * @type {Array.<module:zrender/animation/Animator>}
  3463. * @readOnly
  3464. */
  3465. this.animators = [];
  3466. };
  3467. Animatable.prototype = {
  3468. constructor: Animatable,
  3469. /**
  3470. * 动画
  3471. *
  3472. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3473. * @param {boolean} [loop] Whether to loop animation.
  3474. * @return {module:zrender/animation/Animator}
  3475. * @example:
  3476. * el.animate('style', false)
  3477. * .when(1000, {x: 10} )
  3478. * .done(function(){ // Animation done })
  3479. * .start()
  3480. */
  3481. animate: function (path, loop) {
  3482. var target;
  3483. var animatingShape = false;
  3484. var el = this;
  3485. var zr = this.__zr;
  3486. if (path) {
  3487. var pathSplitted = path.split('.');
  3488. var prop = el;
  3489. // If animating shape
  3490. animatingShape = pathSplitted[0] === 'shape';
  3491. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3492. if (!prop) {
  3493. continue;
  3494. }
  3495. prop = prop[pathSplitted[i]];
  3496. }
  3497. if (prop) {
  3498. target = prop;
  3499. }
  3500. }
  3501. else {
  3502. target = el;
  3503. }
  3504. if (!target) {
  3505. log$1(
  3506. 'Property "'
  3507. + path
  3508. + '" is not existed in element '
  3509. + el.id
  3510. );
  3511. return;
  3512. }
  3513. var animators = el.animators;
  3514. var animator = new Animator(target, loop);
  3515. animator.during(function (target) {
  3516. el.dirty(animatingShape);
  3517. })
  3518. .done(function () {
  3519. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3520. animators.splice(indexOf(animators, animator), 1);
  3521. });
  3522. animators.push(animator);
  3523. // If animate after added to the zrender
  3524. if (zr) {
  3525. zr.animation.addAnimator(animator);
  3526. }
  3527. return animator;
  3528. },
  3529. /**
  3530. * 停止动画
  3531. * @param {boolean} forwardToLast If move to last frame before stop
  3532. */
  3533. stopAnimation: function (forwardToLast) {
  3534. var animators = this.animators;
  3535. var len = animators.length;
  3536. for (var i = 0; i < len; i++) {
  3537. animators[i].stop(forwardToLast);
  3538. }
  3539. animators.length = 0;
  3540. return this;
  3541. },
  3542. /**
  3543. * Caution: this method will stop previous animation.
  3544. * So do not use this method to one element twice before
  3545. * animation starts, unless you know what you are doing.
  3546. * @param {Object} target
  3547. * @param {number} [time=500] Time in ms
  3548. * @param {string} [easing='linear']
  3549. * @param {number} [delay=0]
  3550. * @param {Function} [callback]
  3551. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3552. * immediently when target values are the same as current values.
  3553. *
  3554. * @example
  3555. * // Animate position
  3556. * el.animateTo({
  3557. * position: [10, 10]
  3558. * }, function () { // done })
  3559. *
  3560. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3561. * el.animateTo({
  3562. * shape: {
  3563. * width: 500
  3564. * },
  3565. * style: {
  3566. * fill: 'red'
  3567. * }
  3568. * position: [10, 10]
  3569. * }, 100, 100, 'cubicOut', function () { // done })
  3570. */
  3571. // TODO Return animation key
  3572. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3573. // animateTo(target, time, easing, callback);
  3574. if (isString(delay)) {
  3575. callback = easing;
  3576. easing = delay;
  3577. delay = 0;
  3578. }
  3579. // animateTo(target, time, delay, callback);
  3580. else if (isFunction$1(easing)) {
  3581. callback = easing;
  3582. easing = 'linear';
  3583. delay = 0;
  3584. }
  3585. // animateTo(target, time, callback);
  3586. else if (isFunction$1(delay)) {
  3587. callback = delay;
  3588. delay = 0;
  3589. }
  3590. // animateTo(target, callback)
  3591. else if (isFunction$1(time)) {
  3592. callback = time;
  3593. time = 500;
  3594. }
  3595. // animateTo(target)
  3596. else if (!time) {
  3597. time = 500;
  3598. }
  3599. // Stop all previous animations
  3600. this.stopAnimation();
  3601. this._animateToShallow('', this, target, time, delay);
  3602. // Animators may be removed immediately after start
  3603. // if there is nothing to animate
  3604. var animators = this.animators.slice();
  3605. var count = animators.length;
  3606. function done() {
  3607. count--;
  3608. if (!count) {
  3609. callback && callback();
  3610. }
  3611. }
  3612. // No animators. This should be checked before animators[i].start(),
  3613. // because 'done' may be executed immediately if no need to animate.
  3614. if (!count) {
  3615. callback && callback();
  3616. }
  3617. // Start after all animators created
  3618. // Incase any animator is done immediately when all animation properties are not changed
  3619. for (var i = 0; i < animators.length; i++) {
  3620. animators[i]
  3621. .done(done)
  3622. .start(easing, forceAnimate);
  3623. }
  3624. },
  3625. /**
  3626. * @private
  3627. * @param {string} path=''
  3628. * @param {Object} source=this
  3629. * @param {Object} target
  3630. * @param {number} [time=500]
  3631. * @param {number} [delay=0]
  3632. *
  3633. * @example
  3634. * // Animate position
  3635. * el._animateToShallow({
  3636. * position: [10, 10]
  3637. * })
  3638. *
  3639. * // Animate shape, style and position in 100ms, delayed 100ms
  3640. * el._animateToShallow({
  3641. * shape: {
  3642. * width: 500
  3643. * },
  3644. * style: {
  3645. * fill: 'red'
  3646. * }
  3647. * position: [10, 10]
  3648. * }, 100, 100)
  3649. */
  3650. _animateToShallow: function (path, source, target, time, delay) {
  3651. var objShallow = {};
  3652. var propertyCount = 0;
  3653. for (var name in target) {
  3654. if (!target.hasOwnProperty(name)) {
  3655. continue;
  3656. }
  3657. if (source[name] != null) {
  3658. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3659. this._animateToShallow(
  3660. path ? path + '.' + name : name,
  3661. source[name],
  3662. target[name],
  3663. time,
  3664. delay
  3665. );
  3666. }
  3667. else {
  3668. objShallow[name] = target[name];
  3669. propertyCount++;
  3670. }
  3671. }
  3672. else if (target[name] != null) {
  3673. // Attr directly if not has property
  3674. // FIXME, if some property not needed for element ?
  3675. if (!path) {
  3676. this.attr(name, target[name]);
  3677. }
  3678. else { // Shape or style
  3679. var props = {};
  3680. props[path] = {};
  3681. props[path][name] = target[name];
  3682. this.attr(props);
  3683. }
  3684. }
  3685. }
  3686. if (propertyCount > 0) {
  3687. this.animate(path, false)
  3688. .when(time == null ? 500 : time, objShallow)
  3689. .delay(delay || 0);
  3690. }
  3691. return this;
  3692. }
  3693. };
  3694. /**
  3695. * @alias module:zrender/Element
  3696. * @constructor
  3697. * @extends {module:zrender/mixin/Animatable}
  3698. * @extends {module:zrender/mixin/Transformable}
  3699. * @extends {module:zrender/mixin/Eventful}
  3700. */
  3701. var Element = function (opts) { // jshint ignore:line
  3702. Transformable.call(this, opts);
  3703. Eventful.call(this, opts);
  3704. Animatable.call(this, opts);
  3705. /**
  3706. * 画布元素ID
  3707. * @type {string}
  3708. */
  3709. this.id = opts.id || guid();
  3710. };
  3711. Element.prototype = {
  3712. /**
  3713. * 元素类型
  3714. * Element type
  3715. * @type {string}
  3716. */
  3717. type: 'element',
  3718. /**
  3719. * 元素名字
  3720. * Element name
  3721. * @type {string}
  3722. */
  3723. name: '',
  3724. /**
  3725. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  3726. * ZRender instance will be assigned when element is associated with zrender
  3727. * @name module:/zrender/Element#__zr
  3728. * @type {module:zrender/ZRender}
  3729. */
  3730. __zr: null,
  3731. /**
  3732. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  3733. * If ignore drawing and events of the element object
  3734. * @name module:/zrender/Element#ignore
  3735. * @type {boolean}
  3736. * @default false
  3737. */
  3738. ignore: false,
  3739. /**
  3740. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  3741. * 该路径会继承被裁减对象的变换
  3742. * @type {module:zrender/graphic/Path}
  3743. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  3744. * @readOnly
  3745. */
  3746. clipPath: null,
  3747. /**
  3748. * 是否是 Group
  3749. * @type {boolean}
  3750. */
  3751. isGroup: false,
  3752. /**
  3753. * Drift element
  3754. * @param {number} dx dx on the global space
  3755. * @param {number} dy dy on the global space
  3756. */
  3757. drift: function (dx, dy) {
  3758. switch (this.draggable) {
  3759. case 'horizontal':
  3760. dy = 0;
  3761. break;
  3762. case 'vertical':
  3763. dx = 0;
  3764. break;
  3765. }
  3766. var m = this.transform;
  3767. if (!m) {
  3768. m = this.transform = [1, 0, 0, 1, 0, 0];
  3769. }
  3770. m[4] += dx;
  3771. m[5] += dy;
  3772. this.decomposeTransform();
  3773. this.dirty(false);
  3774. },
  3775. /**
  3776. * Hook before update
  3777. */
  3778. beforeUpdate: function () {},
  3779. /**
  3780. * Hook after update
  3781. */
  3782. afterUpdate: function () {},
  3783. /**
  3784. * Update each frame
  3785. */
  3786. update: function () {
  3787. this.updateTransform();
  3788. },
  3789. /**
  3790. * @param {Function} cb
  3791. * @param {} context
  3792. */
  3793. traverse: function (cb, context) {},
  3794. /**
  3795. * @protected
  3796. */
  3797. attrKV: function (key, value) {
  3798. if (key === 'position' || key === 'scale' || key === 'origin') {
  3799. // Copy the array
  3800. if (value) {
  3801. var target = this[key];
  3802. if (!target) {
  3803. target = this[key] = [];
  3804. }
  3805. target[0] = value[0];
  3806. target[1] = value[1];
  3807. }
  3808. }
  3809. else {
  3810. this[key] = value;
  3811. }
  3812. },
  3813. /**
  3814. * Hide the element
  3815. */
  3816. hide: function () {
  3817. this.ignore = true;
  3818. this.__zr && this.__zr.refresh();
  3819. },
  3820. /**
  3821. * Show the element
  3822. */
  3823. show: function () {
  3824. this.ignore = false;
  3825. this.__zr && this.__zr.refresh();
  3826. },
  3827. /**
  3828. * @param {string|Object} key
  3829. * @param {*} value
  3830. */
  3831. attr: function (key, value) {
  3832. if (typeof key === 'string') {
  3833. this.attrKV(key, value);
  3834. }
  3835. else if (isObject$1(key)) {
  3836. for (var name in key) {
  3837. if (key.hasOwnProperty(name)) {
  3838. this.attrKV(name, key[name]);
  3839. }
  3840. }
  3841. }
  3842. this.dirty(false);
  3843. return this;
  3844. },
  3845. /**
  3846. * @param {module:zrender/graphic/Path} clipPath
  3847. */
  3848. setClipPath: function (clipPath) {
  3849. var zr = this.__zr;
  3850. if (zr) {
  3851. clipPath.addSelfToZr(zr);
  3852. }
  3853. // Remove previous clip path
  3854. if (this.clipPath && this.clipPath !== clipPath) {
  3855. this.removeClipPath();
  3856. }
  3857. this.clipPath = clipPath;
  3858. clipPath.__zr = zr;
  3859. clipPath.__clipTarget = this;
  3860. this.dirty(false);
  3861. },
  3862. /**
  3863. */
  3864. removeClipPath: function () {
  3865. var clipPath = this.clipPath;
  3866. if (clipPath) {
  3867. if (clipPath.__zr) {
  3868. clipPath.removeSelfFromZr(clipPath.__zr);
  3869. }
  3870. clipPath.__zr = null;
  3871. clipPath.__clipTarget = null;
  3872. this.clipPath = null;
  3873. this.dirty(false);
  3874. }
  3875. },
  3876. /**
  3877. * Add self from zrender instance.
  3878. * Not recursively because it will be invoked when element added to storage.
  3879. * @param {module:zrender/ZRender} zr
  3880. */
  3881. addSelfToZr: function (zr) {
  3882. this.__zr = zr;
  3883. // 添加动画
  3884. var animators = this.animators;
  3885. if (animators) {
  3886. for (var i = 0; i < animators.length; i++) {
  3887. zr.animation.addAnimator(animators[i]);
  3888. }
  3889. }
  3890. if (this.clipPath) {
  3891. this.clipPath.addSelfToZr(zr);
  3892. }
  3893. },
  3894. /**
  3895. * Remove self from zrender instance.
  3896. * Not recursively because it will be invoked when element added to storage.
  3897. * @param {module:zrender/ZRender} zr
  3898. */
  3899. removeSelfFromZr: function (zr) {
  3900. this.__zr = null;
  3901. // 移除动画
  3902. var animators = this.animators;
  3903. if (animators) {
  3904. for (var i = 0; i < animators.length; i++) {
  3905. zr.animation.removeAnimator(animators[i]);
  3906. }
  3907. }
  3908. if (this.clipPath) {
  3909. this.clipPath.removeSelfFromZr(zr);
  3910. }
  3911. }
  3912. };
  3913. mixin(Element, Animatable);
  3914. mixin(Element, Transformable);
  3915. mixin(Element, Eventful);
  3916. /**
  3917. * @module echarts/core/BoundingRect
  3918. */
  3919. var v2ApplyTransform = applyTransform;
  3920. var mathMin = Math.min;
  3921. var mathMax = Math.max;
  3922. /**
  3923. * @alias module:echarts/core/BoundingRect
  3924. */
  3925. function BoundingRect(x, y, width, height) {
  3926. if (width < 0) {
  3927. x = x + width;
  3928. width = -width;
  3929. }
  3930. if (height < 0) {
  3931. y = y + height;
  3932. height = -height;
  3933. }
  3934. /**
  3935. * @type {number}
  3936. */
  3937. this.x = x;
  3938. /**
  3939. * @type {number}
  3940. */
  3941. this.y = y;
  3942. /**
  3943. * @type {number}
  3944. */
  3945. this.width = width;
  3946. /**
  3947. * @type {number}
  3948. */
  3949. this.height = height;
  3950. }
  3951. BoundingRect.prototype = {
  3952. constructor: BoundingRect,
  3953. /**
  3954. * @param {module:echarts/core/BoundingRect} other
  3955. */
  3956. union: function (other) {
  3957. var x = mathMin(other.x, this.x);
  3958. var y = mathMin(other.y, this.y);
  3959. this.width = mathMax(
  3960. other.x + other.width,
  3961. this.x + this.width
  3962. ) - x;
  3963. this.height = mathMax(
  3964. other.y + other.height,
  3965. this.y + this.height
  3966. ) - y;
  3967. this.x = x;
  3968. this.y = y;
  3969. },
  3970. /**
  3971. * @param {Array.<number>} m
  3972. * @methods
  3973. */
  3974. applyTransform: (function () {
  3975. var lt = [];
  3976. var rb = [];
  3977. var lb = [];
  3978. var rt = [];
  3979. return function (m) {
  3980. // In case usage like this
  3981. // el.getBoundingRect().applyTransform(el.transform)
  3982. // And element has no transform
  3983. if (!m) {
  3984. return;
  3985. }
  3986. lt[0] = lb[0] = this.x;
  3987. lt[1] = rt[1] = this.y;
  3988. rb[0] = rt[0] = this.x + this.width;
  3989. rb[1] = lb[1] = this.y + this.height;
  3990. v2ApplyTransform(lt, lt, m);
  3991. v2ApplyTransform(rb, rb, m);
  3992. v2ApplyTransform(lb, lb, m);
  3993. v2ApplyTransform(rt, rt, m);
  3994. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  3995. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  3996. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  3997. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  3998. this.width = maxX - this.x;
  3999. this.height = maxY - this.y;
  4000. };
  4001. })(),
  4002. /**
  4003. * Calculate matrix of transforming from self to target rect
  4004. * @param {module:zrender/core/BoundingRect} b
  4005. * @return {Array.<number>}
  4006. */
  4007. calculateTransform: function (b) {
  4008. var a = this;
  4009. var sx = b.width / a.width;
  4010. var sy = b.height / a.height;
  4011. var m = create$1();
  4012. // 矩阵右乘
  4013. translate(m, m, [-a.x, -a.y]);
  4014. scale$1(m, m, [sx, sy]);
  4015. translate(m, m, [b.x, b.y]);
  4016. return m;
  4017. },
  4018. /**
  4019. * @param {(module:echarts/core/BoundingRect|Object)} b
  4020. * @return {boolean}
  4021. */
  4022. intersect: function (b) {
  4023. if (!b) {
  4024. return false;
  4025. }
  4026. if (!(b instanceof BoundingRect)) {
  4027. // Normalize negative width/height.
  4028. b = BoundingRect.create(b);
  4029. }
  4030. var a = this;
  4031. var ax0 = a.x;
  4032. var ax1 = a.x + a.width;
  4033. var ay0 = a.y;
  4034. var ay1 = a.y + a.height;
  4035. var bx0 = b.x;
  4036. var bx1 = b.x + b.width;
  4037. var by0 = b.y;
  4038. var by1 = b.y + b.height;
  4039. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4040. },
  4041. contain: function (x, y) {
  4042. var rect = this;
  4043. return x >= rect.x
  4044. && x <= (rect.x + rect.width)
  4045. && y >= rect.y
  4046. && y <= (rect.y + rect.height);
  4047. },
  4048. /**
  4049. * @return {module:echarts/core/BoundingRect}
  4050. */
  4051. clone: function () {
  4052. return new BoundingRect(this.x, this.y, this.width, this.height);
  4053. },
  4054. /**
  4055. * Copy from another rect
  4056. */
  4057. copy: function (other) {
  4058. this.x = other.x;
  4059. this.y = other.y;
  4060. this.width = other.width;
  4061. this.height = other.height;
  4062. },
  4063. plain: function () {
  4064. return {
  4065. x: this.x,
  4066. y: this.y,
  4067. width: this.width,
  4068. height: this.height
  4069. };
  4070. }
  4071. };
  4072. /**
  4073. * @param {Object|module:zrender/core/BoundingRect} rect
  4074. * @param {number} rect.x
  4075. * @param {number} rect.y
  4076. * @param {number} rect.width
  4077. * @param {number} rect.height
  4078. * @return {module:zrender/core/BoundingRect}
  4079. */
  4080. BoundingRect.create = function (rect) {
  4081. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4082. };
  4083. /**
  4084. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4085. * @module zrender/graphic/Group
  4086. * @example
  4087. * var Group = require('zrender/container/Group');
  4088. * var Circle = require('zrender/graphic/shape/Circle');
  4089. * var g = new Group();
  4090. * g.position[0] = 100;
  4091. * g.position[1] = 100;
  4092. * g.add(new Circle({
  4093. * style: {
  4094. * x: 100,
  4095. * y: 100,
  4096. * r: 20,
  4097. * }
  4098. * }));
  4099. * zr.add(g);
  4100. */
  4101. /**
  4102. * @alias module:zrender/graphic/Group
  4103. * @constructor
  4104. * @extends module:zrender/mixin/Transformable
  4105. * @extends module:zrender/mixin/Eventful
  4106. */
  4107. var Group = function (opts) {
  4108. opts = opts || {};
  4109. Element.call(this, opts);
  4110. for (var key in opts) {
  4111. if (opts.hasOwnProperty(key)) {
  4112. this[key] = opts[key];
  4113. }
  4114. }
  4115. this._children = [];
  4116. this.__storage = null;
  4117. this.__dirty = true;
  4118. };
  4119. Group.prototype = {
  4120. constructor: Group,
  4121. isGroup: true,
  4122. /**
  4123. * @type {string}
  4124. */
  4125. type: 'group',
  4126. /**
  4127. * 所有子孙元素是否响应鼠标事件
  4128. * @name module:/zrender/container/Group#silent
  4129. * @type {boolean}
  4130. * @default false
  4131. */
  4132. silent: false,
  4133. /**
  4134. * @return {Array.<module:zrender/Element>}
  4135. */
  4136. children: function () {
  4137. return this._children.slice();
  4138. },
  4139. /**
  4140. * 获取指定 index 的儿子节点
  4141. * @param {number} idx
  4142. * @return {module:zrender/Element}
  4143. */
  4144. childAt: function (idx) {
  4145. return this._children[idx];
  4146. },
  4147. /**
  4148. * 获取指定名字的儿子节点
  4149. * @param {string} name
  4150. * @return {module:zrender/Element}
  4151. */
  4152. childOfName: function (name) {
  4153. var children = this._children;
  4154. for (var i = 0; i < children.length; i++) {
  4155. if (children[i].name === name) {
  4156. return children[i];
  4157. }
  4158. }
  4159. },
  4160. /**
  4161. * @return {number}
  4162. */
  4163. childCount: function () {
  4164. return this._children.length;
  4165. },
  4166. /**
  4167. * 添加子节点到最后
  4168. * @param {module:zrender/Element} child
  4169. */
  4170. add: function (child) {
  4171. if (child && child !== this && child.parent !== this) {
  4172. this._children.push(child);
  4173. this._doAdd(child);
  4174. }
  4175. return this;
  4176. },
  4177. /**
  4178. * 添加子节点在 nextSibling 之前
  4179. * @param {module:zrender/Element} child
  4180. * @param {module:zrender/Element} nextSibling
  4181. */
  4182. addBefore: function (child, nextSibling) {
  4183. if (child && child !== this && child.parent !== this
  4184. && nextSibling && nextSibling.parent === this) {
  4185. var children = this._children;
  4186. var idx = children.indexOf(nextSibling);
  4187. if (idx >= 0) {
  4188. children.splice(idx, 0, child);
  4189. this._doAdd(child);
  4190. }
  4191. }
  4192. return this;
  4193. },
  4194. _doAdd: function (child) {
  4195. if (child.parent) {
  4196. child.parent.remove(child);
  4197. }
  4198. child.parent = this;
  4199. var storage = this.__storage;
  4200. var zr = this.__zr;
  4201. if (storage && storage !== child.__storage) {
  4202. storage.addToStorage(child);
  4203. if (child instanceof Group) {
  4204. child.addChildrenToStorage(storage);
  4205. }
  4206. }
  4207. zr && zr.refresh();
  4208. },
  4209. /**
  4210. * 移除子节点
  4211. * @param {module:zrender/Element} child
  4212. */
  4213. remove: function (child) {
  4214. var zr = this.__zr;
  4215. var storage = this.__storage;
  4216. var children = this._children;
  4217. var idx = indexOf(children, child);
  4218. if (idx < 0) {
  4219. return this;
  4220. }
  4221. children.splice(idx, 1);
  4222. child.parent = null;
  4223. if (storage) {
  4224. storage.delFromStorage(child);
  4225. if (child instanceof Group) {
  4226. child.delChildrenFromStorage(storage);
  4227. }
  4228. }
  4229. zr && zr.refresh();
  4230. return this;
  4231. },
  4232. /**
  4233. * 移除所有子节点
  4234. */
  4235. removeAll: function () {
  4236. var children = this._children;
  4237. var storage = this.__storage;
  4238. var child;
  4239. var i;
  4240. for (i = 0; i < children.length; i++) {
  4241. child = children[i];
  4242. if (storage) {
  4243. storage.delFromStorage(child);
  4244. if (child instanceof Group) {
  4245. child.delChildrenFromStorage(storage);
  4246. }
  4247. }
  4248. child.parent = null;
  4249. }
  4250. children.length = 0;
  4251. return this;
  4252. },
  4253. /**
  4254. * 遍历所有子节点
  4255. * @param {Function} cb
  4256. * @param {} context
  4257. */
  4258. eachChild: function (cb, context) {
  4259. var children = this._children;
  4260. for (var i = 0; i < children.length; i++) {
  4261. var child = children[i];
  4262. cb.call(context, child, i);
  4263. }
  4264. return this;
  4265. },
  4266. /**
  4267. * 深度优先遍历所有子孙节点
  4268. * @param {Function} cb
  4269. * @param {} context
  4270. */
  4271. traverse: function (cb, context) {
  4272. for (var i = 0; i < this._children.length; i++) {
  4273. var child = this._children[i];
  4274. cb.call(context, child);
  4275. if (child.type === 'group') {
  4276. child.traverse(cb, context);
  4277. }
  4278. }
  4279. return this;
  4280. },
  4281. addChildrenToStorage: function (storage) {
  4282. for (var i = 0; i < this._children.length; i++) {
  4283. var child = this._children[i];
  4284. storage.addToStorage(child);
  4285. if (child instanceof Group) {
  4286. child.addChildrenToStorage(storage);
  4287. }
  4288. }
  4289. },
  4290. delChildrenFromStorage: function (storage) {
  4291. for (var i = 0; i < this._children.length; i++) {
  4292. var child = this._children[i];
  4293. storage.delFromStorage(child);
  4294. if (child instanceof Group) {
  4295. child.delChildrenFromStorage(storage);
  4296. }
  4297. }
  4298. },
  4299. dirty: function () {
  4300. this.__dirty = true;
  4301. this.__zr && this.__zr.refresh();
  4302. return this;
  4303. },
  4304. /**
  4305. * @return {module:zrender/core/BoundingRect}
  4306. */
  4307. getBoundingRect: function (includeChildren) {
  4308. // TODO Caching
  4309. var rect = null;
  4310. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4311. var children = includeChildren || this._children;
  4312. var tmpMat = [];
  4313. for (var i = 0; i < children.length; i++) {
  4314. var child = children[i];
  4315. if (child.ignore || child.invisible) {
  4316. continue;
  4317. }
  4318. var childRect = child.getBoundingRect();
  4319. var transform = child.getLocalTransform(tmpMat);
  4320. // TODO
  4321. // The boundingRect cacluated by transforming original
  4322. // rect may be bigger than the actual bundingRect when rotation
  4323. // is used. (Consider a circle rotated aginst its center, where
  4324. // the actual boundingRect should be the same as that not be
  4325. // rotated.) But we can not find better approach to calculate
  4326. // actual boundingRect yet, considering performance.
  4327. if (transform) {
  4328. tmpRect.copy(childRect);
  4329. tmpRect.applyTransform(transform);
  4330. rect = rect || tmpRect.clone();
  4331. rect.union(tmpRect);
  4332. }
  4333. else {
  4334. rect = rect || childRect.clone();
  4335. rect.union(childRect);
  4336. }
  4337. }
  4338. return rect || tmpRect;
  4339. }
  4340. };
  4341. inherits(Group, Element);
  4342. // https://github.com/mziccard/node-timsort
  4343. var DEFAULT_MIN_MERGE = 32;
  4344. var DEFAULT_MIN_GALLOPING = 7;
  4345. function minRunLength(n) {
  4346. var r = 0;
  4347. while (n >= DEFAULT_MIN_MERGE) {
  4348. r |= n & 1;
  4349. n >>= 1;
  4350. }
  4351. return n + r;
  4352. }
  4353. function makeAscendingRun(array, lo, hi, compare) {
  4354. var runHi = lo + 1;
  4355. if (runHi === hi) {
  4356. return 1;
  4357. }
  4358. if (compare(array[runHi++], array[lo]) < 0) {
  4359. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4360. runHi++;
  4361. }
  4362. reverseRun(array, lo, runHi);
  4363. }
  4364. else {
  4365. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4366. runHi++;
  4367. }
  4368. }
  4369. return runHi - lo;
  4370. }
  4371. function reverseRun(array, lo, hi) {
  4372. hi--;
  4373. while (lo < hi) {
  4374. var t = array[lo];
  4375. array[lo++] = array[hi];
  4376. array[hi--] = t;
  4377. }
  4378. }
  4379. function binaryInsertionSort(array, lo, hi, start, compare) {
  4380. if (start === lo) {
  4381. start++;
  4382. }
  4383. for (; start < hi; start++) {
  4384. var pivot = array[start];
  4385. var left = lo;
  4386. var right = start;
  4387. var mid;
  4388. while (left < right) {
  4389. mid = left + right >>> 1;
  4390. if (compare(pivot, array[mid]) < 0) {
  4391. right = mid;
  4392. }
  4393. else {
  4394. left = mid + 1;
  4395. }
  4396. }
  4397. var n = start - left;
  4398. switch (n) {
  4399. case 3:
  4400. array[left + 3] = array[left + 2];
  4401. case 2:
  4402. array[left + 2] = array[left + 1];
  4403. case 1:
  4404. array[left + 1] = array[left];
  4405. break;
  4406. default:
  4407. while (n > 0) {
  4408. array[left + n] = array[left + n - 1];
  4409. n--;
  4410. }
  4411. }
  4412. array[left] = pivot;
  4413. }
  4414. }
  4415. function gallopLeft(value, array, start, length, hint, compare) {
  4416. var lastOffset = 0;
  4417. var maxOffset = 0;
  4418. var offset = 1;
  4419. if (compare(value, array[start + hint]) > 0) {
  4420. maxOffset = length - hint;
  4421. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4422. lastOffset = offset;
  4423. offset = (offset << 1) + 1;
  4424. if (offset <= 0) {
  4425. offset = maxOffset;
  4426. }
  4427. }
  4428. if (offset > maxOffset) {
  4429. offset = maxOffset;
  4430. }
  4431. lastOffset += hint;
  4432. offset += hint;
  4433. }
  4434. else {
  4435. maxOffset = hint + 1;
  4436. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4437. lastOffset = offset;
  4438. offset = (offset << 1) + 1;
  4439. if (offset <= 0) {
  4440. offset = maxOffset;
  4441. }
  4442. }
  4443. if (offset > maxOffset) {
  4444. offset = maxOffset;
  4445. }
  4446. var tmp = lastOffset;
  4447. lastOffset = hint - offset;
  4448. offset = hint - tmp;
  4449. }
  4450. lastOffset++;
  4451. while (lastOffset < offset) {
  4452. var m = lastOffset + (offset - lastOffset >>> 1);
  4453. if (compare(value, array[start + m]) > 0) {
  4454. lastOffset = m + 1;
  4455. }
  4456. else {
  4457. offset = m;
  4458. }
  4459. }
  4460. return offset;
  4461. }
  4462. function gallopRight(value, array, start, length, hint, compare) {
  4463. var lastOffset = 0;
  4464. var maxOffset = 0;
  4465. var offset = 1;
  4466. if (compare(value, array[start + hint]) < 0) {
  4467. maxOffset = hint + 1;
  4468. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4469. lastOffset = offset;
  4470. offset = (offset << 1) + 1;
  4471. if (offset <= 0) {
  4472. offset = maxOffset;
  4473. }
  4474. }
  4475. if (offset > maxOffset) {
  4476. offset = maxOffset;
  4477. }
  4478. var tmp = lastOffset;
  4479. lastOffset = hint - offset;
  4480. offset = hint - tmp;
  4481. }
  4482. else {
  4483. maxOffset = length - hint;
  4484. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4485. lastOffset = offset;
  4486. offset = (offset << 1) + 1;
  4487. if (offset <= 0) {
  4488. offset = maxOffset;
  4489. }
  4490. }
  4491. if (offset > maxOffset) {
  4492. offset = maxOffset;
  4493. }
  4494. lastOffset += hint;
  4495. offset += hint;
  4496. }
  4497. lastOffset++;
  4498. while (lastOffset < offset) {
  4499. var m = lastOffset + (offset - lastOffset >>> 1);
  4500. if (compare(value, array[start + m]) < 0) {
  4501. offset = m;
  4502. }
  4503. else {
  4504. lastOffset = m + 1;
  4505. }
  4506. }
  4507. return offset;
  4508. }
  4509. function TimSort(array, compare) {
  4510. var minGallop = DEFAULT_MIN_GALLOPING;
  4511. var runStart;
  4512. var runLength;
  4513. var stackSize = 0;
  4514. var tmp = [];
  4515. runStart = [];
  4516. runLength = [];
  4517. function pushRun(_runStart, _runLength) {
  4518. runStart[stackSize] = _runStart;
  4519. runLength[stackSize] = _runLength;
  4520. stackSize += 1;
  4521. }
  4522. function mergeRuns() {
  4523. while (stackSize > 1) {
  4524. var n = stackSize - 2;
  4525. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4526. if (runLength[n - 1] < runLength[n + 1]) {
  4527. n--;
  4528. }
  4529. }
  4530. else if (runLength[n] > runLength[n + 1]) {
  4531. break;
  4532. }
  4533. mergeAt(n);
  4534. }
  4535. }
  4536. function forceMergeRuns() {
  4537. while (stackSize > 1) {
  4538. var n = stackSize - 2;
  4539. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4540. n--;
  4541. }
  4542. mergeAt(n);
  4543. }
  4544. }
  4545. function mergeAt(i) {
  4546. var start1 = runStart[i];
  4547. var length1 = runLength[i];
  4548. var start2 = runStart[i + 1];
  4549. var length2 = runLength[i + 1];
  4550. runLength[i] = length1 + length2;
  4551. if (i === stackSize - 3) {
  4552. runStart[i + 1] = runStart[i + 2];
  4553. runLength[i + 1] = runLength[i + 2];
  4554. }
  4555. stackSize--;
  4556. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4557. start1 += k;
  4558. length1 -= k;
  4559. if (length1 === 0) {
  4560. return;
  4561. }
  4562. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4563. if (length2 === 0) {
  4564. return;
  4565. }
  4566. if (length1 <= length2) {
  4567. mergeLow(start1, length1, start2, length2);
  4568. }
  4569. else {
  4570. mergeHigh(start1, length1, start2, length2);
  4571. }
  4572. }
  4573. function mergeLow(start1, length1, start2, length2) {
  4574. var i = 0;
  4575. for (i = 0; i < length1; i++) {
  4576. tmp[i] = array[start1 + i];
  4577. }
  4578. var cursor1 = 0;
  4579. var cursor2 = start2;
  4580. var dest = start1;
  4581. array[dest++] = array[cursor2++];
  4582. if (--length2 === 0) {
  4583. for (i = 0; i < length1; i++) {
  4584. array[dest + i] = tmp[cursor1 + i];
  4585. }
  4586. return;
  4587. }
  4588. if (length1 === 1) {
  4589. for (i = 0; i < length2; i++) {
  4590. array[dest + i] = array[cursor2 + i];
  4591. }
  4592. array[dest + length2] = tmp[cursor1];
  4593. return;
  4594. }
  4595. var _minGallop = minGallop;
  4596. var count1, count2, exit;
  4597. while (1) {
  4598. count1 = 0;
  4599. count2 = 0;
  4600. exit = false;
  4601. do {
  4602. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4603. array[dest++] = array[cursor2++];
  4604. count2++;
  4605. count1 = 0;
  4606. if (--length2 === 0) {
  4607. exit = true;
  4608. break;
  4609. }
  4610. }
  4611. else {
  4612. array[dest++] = tmp[cursor1++];
  4613. count1++;
  4614. count2 = 0;
  4615. if (--length1 === 1) {
  4616. exit = true;
  4617. break;
  4618. }
  4619. }
  4620. } while ((count1 | count2) < _minGallop);
  4621. if (exit) {
  4622. break;
  4623. }
  4624. do {
  4625. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4626. if (count1 !== 0) {
  4627. for (i = 0; i < count1; i++) {
  4628. array[dest + i] = tmp[cursor1 + i];
  4629. }
  4630. dest += count1;
  4631. cursor1 += count1;
  4632. length1 -= count1;
  4633. if (length1 <= 1) {
  4634. exit = true;
  4635. break;
  4636. }
  4637. }
  4638. array[dest++] = array[cursor2++];
  4639. if (--length2 === 0) {
  4640. exit = true;
  4641. break;
  4642. }
  4643. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4644. if (count2 !== 0) {
  4645. for (i = 0; i < count2; i++) {
  4646. array[dest + i] = array[cursor2 + i];
  4647. }
  4648. dest += count2;
  4649. cursor2 += count2;
  4650. length2 -= count2;
  4651. if (length2 === 0) {
  4652. exit = true;
  4653. break;
  4654. }
  4655. }
  4656. array[dest++] = tmp[cursor1++];
  4657. if (--length1 === 1) {
  4658. exit = true;
  4659. break;
  4660. }
  4661. _minGallop--;
  4662. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4663. if (exit) {
  4664. break;
  4665. }
  4666. if (_minGallop < 0) {
  4667. _minGallop = 0;
  4668. }
  4669. _minGallop += 2;
  4670. }
  4671. minGallop = _minGallop;
  4672. minGallop < 1 && (minGallop = 1);
  4673. if (length1 === 1) {
  4674. for (i = 0; i < length2; i++) {
  4675. array[dest + i] = array[cursor2 + i];
  4676. }
  4677. array[dest + length2] = tmp[cursor1];
  4678. }
  4679. else if (length1 === 0) {
  4680. throw new Error();
  4681. // throw new Error('mergeLow preconditions were not respected');
  4682. }
  4683. else {
  4684. for (i = 0; i < length1; i++) {
  4685. array[dest + i] = tmp[cursor1 + i];
  4686. }
  4687. }
  4688. }
  4689. function mergeHigh (start1, length1, start2, length2) {
  4690. var i = 0;
  4691. for (i = 0; i < length2; i++) {
  4692. tmp[i] = array[start2 + i];
  4693. }
  4694. var cursor1 = start1 + length1 - 1;
  4695. var cursor2 = length2 - 1;
  4696. var dest = start2 + length2 - 1;
  4697. var customCursor = 0;
  4698. var customDest = 0;
  4699. array[dest--] = array[cursor1--];
  4700. if (--length1 === 0) {
  4701. customCursor = dest - (length2 - 1);
  4702. for (i = 0; i < length2; i++) {
  4703. array[customCursor + i] = tmp[i];
  4704. }
  4705. return;
  4706. }
  4707. if (length2 === 1) {
  4708. dest -= length1;
  4709. cursor1 -= length1;
  4710. customDest = dest + 1;
  4711. customCursor = cursor1 + 1;
  4712. for (i = length1 - 1; i >= 0; i--) {
  4713. array[customDest + i] = array[customCursor + i];
  4714. }
  4715. array[dest] = tmp[cursor2];
  4716. return;
  4717. }
  4718. var _minGallop = minGallop;
  4719. while (true) {
  4720. var count1 = 0;
  4721. var count2 = 0;
  4722. var exit = false;
  4723. do {
  4724. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  4725. array[dest--] = array[cursor1--];
  4726. count1++;
  4727. count2 = 0;
  4728. if (--length1 === 0) {
  4729. exit = true;
  4730. break;
  4731. }
  4732. }
  4733. else {
  4734. array[dest--] = tmp[cursor2--];
  4735. count2++;
  4736. count1 = 0;
  4737. if (--length2 === 1) {
  4738. exit = true;
  4739. break;
  4740. }
  4741. }
  4742. } while ((count1 | count2) < _minGallop);
  4743. if (exit) {
  4744. break;
  4745. }
  4746. do {
  4747. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  4748. if (count1 !== 0) {
  4749. dest -= count1;
  4750. cursor1 -= count1;
  4751. length1 -= count1;
  4752. customDest = dest + 1;
  4753. customCursor = cursor1 + 1;
  4754. for (i = count1 - 1; i >= 0; i--) {
  4755. array[customDest + i] = array[customCursor + i];
  4756. }
  4757. if (length1 === 0) {
  4758. exit = true;
  4759. break;
  4760. }
  4761. }
  4762. array[dest--] = tmp[cursor2--];
  4763. if (--length2 === 1) {
  4764. exit = true;
  4765. break;
  4766. }
  4767. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  4768. if (count2 !== 0) {
  4769. dest -= count2;
  4770. cursor2 -= count2;
  4771. length2 -= count2;
  4772. customDest = dest + 1;
  4773. customCursor = cursor2 + 1;
  4774. for (i = 0; i < count2; i++) {
  4775. array[customDest + i] = tmp[customCursor + i];
  4776. }
  4777. if (length2 <= 1) {
  4778. exit = true;
  4779. break;
  4780. }
  4781. }
  4782. array[dest--] = array[cursor1--];
  4783. if (--length1 === 0) {
  4784. exit = true;
  4785. break;
  4786. }
  4787. _minGallop--;
  4788. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4789. if (exit) {
  4790. break;
  4791. }
  4792. if (_minGallop < 0) {
  4793. _minGallop = 0;
  4794. }
  4795. _minGallop += 2;
  4796. }
  4797. minGallop = _minGallop;
  4798. if (minGallop < 1) {
  4799. minGallop = 1;
  4800. }
  4801. if (length2 === 1) {
  4802. dest -= length1;
  4803. cursor1 -= length1;
  4804. customDest = dest + 1;
  4805. customCursor = cursor1 + 1;
  4806. for (i = length1 - 1; i >= 0; i--) {
  4807. array[customDest + i] = array[customCursor + i];
  4808. }
  4809. array[dest] = tmp[cursor2];
  4810. }
  4811. else if (length2 === 0) {
  4812. throw new Error();
  4813. // throw new Error('mergeHigh preconditions were not respected');
  4814. }
  4815. else {
  4816. customCursor = dest - (length2 - 1);
  4817. for (i = 0; i < length2; i++) {
  4818. array[customCursor + i] = tmp[i];
  4819. }
  4820. }
  4821. }
  4822. this.mergeRuns = mergeRuns;
  4823. this.forceMergeRuns = forceMergeRuns;
  4824. this.pushRun = pushRun;
  4825. }
  4826. function sort(array, compare, lo, hi) {
  4827. if (!lo) {
  4828. lo = 0;
  4829. }
  4830. if (!hi) {
  4831. hi = array.length;
  4832. }
  4833. var remaining = hi - lo;
  4834. if (remaining < 2) {
  4835. return;
  4836. }
  4837. var runLength = 0;
  4838. if (remaining < DEFAULT_MIN_MERGE) {
  4839. runLength = makeAscendingRun(array, lo, hi, compare);
  4840. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  4841. return;
  4842. }
  4843. var ts = new TimSort(array, compare);
  4844. var minRun = minRunLength(remaining);
  4845. do {
  4846. runLength = makeAscendingRun(array, lo, hi, compare);
  4847. if (runLength < minRun) {
  4848. var force = remaining;
  4849. if (force > minRun) {
  4850. force = minRun;
  4851. }
  4852. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  4853. runLength = force;
  4854. }
  4855. ts.pushRun(lo, runLength);
  4856. ts.mergeRuns();
  4857. remaining -= runLength;
  4858. lo += runLength;
  4859. } while (remaining !== 0);
  4860. ts.forceMergeRuns();
  4861. }
  4862. // Use timsort because in most case elements are partially sorted
  4863. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  4864. function shapeCompareFunc(a, b) {
  4865. if (a.zlevel === b.zlevel) {
  4866. if (a.z === b.z) {
  4867. // if (a.z2 === b.z2) {
  4868. // // FIXME Slow has renderidx compare
  4869. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  4870. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  4871. // return a.__renderidx - b.__renderidx;
  4872. // }
  4873. return a.z2 - b.z2;
  4874. }
  4875. return a.z - b.z;
  4876. }
  4877. return a.zlevel - b.zlevel;
  4878. }
  4879. /**
  4880. * 内容仓库 (M)
  4881. * @alias module:zrender/Storage
  4882. * @constructor
  4883. */
  4884. var Storage = function () { // jshint ignore:line
  4885. this._roots = [];
  4886. this._displayList = [];
  4887. this._displayListLen = 0;
  4888. };
  4889. Storage.prototype = {
  4890. constructor: Storage,
  4891. /**
  4892. * @param {Function} cb
  4893. *
  4894. */
  4895. traverse: function (cb, context) {
  4896. for (var i = 0; i < this._roots.length; i++) {
  4897. this._roots[i].traverse(cb, context);
  4898. }
  4899. },
  4900. /**
  4901. * 返回所有图形的绘制队列
  4902. * @param {boolean} [update=false] 是否在返回前更新该数组
  4903. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  4904. *
  4905. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  4906. * @return {Array.<module:zrender/graphic/Displayable>}
  4907. */
  4908. getDisplayList: function (update, includeIgnore) {
  4909. includeIgnore = includeIgnore || false;
  4910. if (update) {
  4911. this.updateDisplayList(includeIgnore);
  4912. }
  4913. return this._displayList;
  4914. },
  4915. /**
  4916. * 更新图形的绘制队列。
  4917. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  4918. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  4919. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  4920. */
  4921. updateDisplayList: function (includeIgnore) {
  4922. this._displayListLen = 0;
  4923. var roots = this._roots;
  4924. var displayList = this._displayList;
  4925. for (var i = 0, len = roots.length; i < len; i++) {
  4926. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  4927. }
  4928. displayList.length = this._displayListLen;
  4929. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  4930. },
  4931. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  4932. if (el.ignore && !includeIgnore) {
  4933. return;
  4934. }
  4935. el.beforeUpdate();
  4936. if (el.__dirty) {
  4937. el.update();
  4938. }
  4939. el.afterUpdate();
  4940. var userSetClipPath = el.clipPath;
  4941. if (userSetClipPath) {
  4942. // FIXME 效率影响
  4943. if (clipPaths) {
  4944. clipPaths = clipPaths.slice();
  4945. }
  4946. else {
  4947. clipPaths = [];
  4948. }
  4949. var currentClipPath = userSetClipPath;
  4950. var parentClipPath = el;
  4951. // Recursively add clip path
  4952. while (currentClipPath) {
  4953. // clipPath 的变换是基于使用这个 clipPath 的元素
  4954. currentClipPath.parent = parentClipPath;
  4955. currentClipPath.updateTransform();
  4956. clipPaths.push(currentClipPath);
  4957. parentClipPath = currentClipPath;
  4958. currentClipPath = currentClipPath.clipPath;
  4959. }
  4960. }
  4961. if (el.isGroup) {
  4962. var children = el._children;
  4963. for (var i = 0; i < children.length; i++) {
  4964. var child = children[i];
  4965. // Force to mark as dirty if group is dirty
  4966. // FIXME __dirtyPath ?
  4967. if (el.__dirty) {
  4968. child.__dirty = true;
  4969. }
  4970. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  4971. }
  4972. // Mark group clean here
  4973. el.__dirty = false;
  4974. }
  4975. else {
  4976. el.__clipPaths = clipPaths;
  4977. this._displayList[this._displayListLen++] = el;
  4978. }
  4979. },
  4980. /**
  4981. * 添加图形(Shape)或者组(Group)到根节点
  4982. * @param {module:zrender/Element} el
  4983. */
  4984. addRoot: function (el) {
  4985. if (el.__storage === this) {
  4986. return;
  4987. }
  4988. if (el instanceof Group) {
  4989. el.addChildrenToStorage(this);
  4990. }
  4991. this.addToStorage(el);
  4992. this._roots.push(el);
  4993. },
  4994. /**
  4995. * 删除指定的图形(Shape)或者组(Group)
  4996. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  4997. */
  4998. delRoot: function (el) {
  4999. if (el == null) {
  5000. // 不指定el清空
  5001. for (var i = 0; i < this._roots.length; i++) {
  5002. var root = this._roots[i];
  5003. if (root instanceof Group) {
  5004. root.delChildrenFromStorage(this);
  5005. }
  5006. }
  5007. this._roots = [];
  5008. this._displayList = [];
  5009. this._displayListLen = 0;
  5010. return;
  5011. }
  5012. if (el instanceof Array) {
  5013. for (var i = 0, l = el.length; i < l; i++) {
  5014. this.delRoot(el[i]);
  5015. }
  5016. return;
  5017. }
  5018. var idx = indexOf(this._roots, el);
  5019. if (idx >= 0) {
  5020. this.delFromStorage(el);
  5021. this._roots.splice(idx, 1);
  5022. if (el instanceof Group) {
  5023. el.delChildrenFromStorage(this);
  5024. }
  5025. }
  5026. },
  5027. addToStorage: function (el) {
  5028. if (el) {
  5029. el.__storage = this;
  5030. el.dirty(false);
  5031. }
  5032. return this;
  5033. },
  5034. delFromStorage: function (el) {
  5035. if (el) {
  5036. el.__storage = null;
  5037. }
  5038. return this;
  5039. },
  5040. /**
  5041. * 清空并且释放Storage
  5042. */
  5043. dispose: function () {
  5044. this._renderList =
  5045. this._roots = null;
  5046. },
  5047. displayableSortFunc: shapeCompareFunc
  5048. };
  5049. var SHADOW_PROPS = {
  5050. 'shadowBlur': 1,
  5051. 'shadowOffsetX': 1,
  5052. 'shadowOffsetY': 1,
  5053. 'textShadowBlur': 1,
  5054. 'textShadowOffsetX': 1,
  5055. 'textShadowOffsetY': 1,
  5056. 'textBoxShadowBlur': 1,
  5057. 'textBoxShadowOffsetX': 1,
  5058. 'textBoxShadowOffsetY': 1
  5059. };
  5060. var fixShadow = function (ctx, propName, value) {
  5061. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5062. return value *= ctx.dpr;
  5063. }
  5064. return value;
  5065. };
  5066. var STYLE_COMMON_PROPS = [
  5067. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5068. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5069. ];
  5070. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5071. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5072. var Style = function (opts, host) {
  5073. this.extendFrom(opts, false);
  5074. this.host = host;
  5075. };
  5076. function createLinearGradient(ctx, obj, rect) {
  5077. var x = obj.x == null ? 0 : obj.x;
  5078. var x2 = obj.x2 == null ? 1 : obj.x2;
  5079. var y = obj.y == null ? 0 : obj.y;
  5080. var y2 = obj.y2 == null ? 0 : obj.y2;
  5081. if (!obj.global) {
  5082. x = x * rect.width + rect.x;
  5083. x2 = x2 * rect.width + rect.x;
  5084. y = y * rect.height + rect.y;
  5085. y2 = y2 * rect.height + rect.y;
  5086. }
  5087. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5088. return canvasGradient;
  5089. }
  5090. function createRadialGradient(ctx, obj, rect) {
  5091. var width = rect.width;
  5092. var height = rect.height;
  5093. var min = Math.min(width, height);
  5094. var x = obj.x == null ? 0.5 : obj.x;
  5095. var y = obj.y == null ? 0.5 : obj.y;
  5096. var r = obj.r == null ? 0.5 : obj.r;
  5097. if (!obj.global) {
  5098. x = x * width + rect.x;
  5099. y = y * height + rect.y;
  5100. r = r * min;
  5101. }
  5102. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5103. return canvasGradient;
  5104. }
  5105. Style.prototype = {
  5106. constructor: Style,
  5107. /**
  5108. * @type {module:zrender/graphic/Displayable}
  5109. */
  5110. host: null,
  5111. /**
  5112. * @type {string}
  5113. */
  5114. fill: '#000',
  5115. /**
  5116. * @type {string}
  5117. */
  5118. stroke: null,
  5119. /**
  5120. * @type {number}
  5121. */
  5122. opacity: 1,
  5123. /**
  5124. * @type {Array.<number>}
  5125. */
  5126. lineDash: null,
  5127. /**
  5128. * @type {number}
  5129. */
  5130. lineDashOffset: 0,
  5131. /**
  5132. * @type {number}
  5133. */
  5134. shadowBlur: 0,
  5135. /**
  5136. * @type {number}
  5137. */
  5138. shadowOffsetX: 0,
  5139. /**
  5140. * @type {number}
  5141. */
  5142. shadowOffsetY: 0,
  5143. /**
  5144. * @type {number}
  5145. */
  5146. lineWidth: 1,
  5147. /**
  5148. * If stroke ignore scale
  5149. * @type {Boolean}
  5150. */
  5151. strokeNoScale: false,
  5152. // Bounding rect text configuration
  5153. // Not affected by element transform
  5154. /**
  5155. * @type {string}
  5156. */
  5157. text: null,
  5158. /**
  5159. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5160. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5161. * So do not visit it directly in upper application (like echarts),
  5162. * but use `contain/text#makeFont` instead.
  5163. * @type {string}
  5164. */
  5165. font: null,
  5166. /**
  5167. * The same as font. Use font please.
  5168. * @deprecated
  5169. * @type {string}
  5170. */
  5171. textFont: null,
  5172. /**
  5173. * It helps merging respectively, rather than parsing an entire font string.
  5174. * @type {string}
  5175. */
  5176. fontStyle: null,
  5177. /**
  5178. * It helps merging respectively, rather than parsing an entire font string.
  5179. * @type {string}
  5180. */
  5181. fontWeight: null,
  5182. /**
  5183. * It helps merging respectively, rather than parsing an entire font string.
  5184. * Should be 12 but not '12px'.
  5185. * @type {number}
  5186. */
  5187. fontSize: null,
  5188. /**
  5189. * It helps merging respectively, rather than parsing an entire font string.
  5190. * @type {string}
  5191. */
  5192. fontFamily: null,
  5193. /**
  5194. * Reserved for special functinality, like 'hr'.
  5195. * @type {string}
  5196. */
  5197. textTag: null,
  5198. /**
  5199. * @type {string}
  5200. */
  5201. textFill: '#000',
  5202. /**
  5203. * @type {string}
  5204. */
  5205. textStroke: null,
  5206. /**
  5207. * @type {number}
  5208. */
  5209. textWidth: null,
  5210. /**
  5211. * Only for textBackground.
  5212. * @type {number}
  5213. */
  5214. textHeight: null,
  5215. /**
  5216. * textStroke may be set as some color as a default
  5217. * value in upper applicaion, where the default value
  5218. * of textStrokeWidth should be 0 to make sure that
  5219. * user can choose to do not use text stroke.
  5220. * @type {number}
  5221. */
  5222. textStrokeWidth: 0,
  5223. /**
  5224. * @type {number}
  5225. */
  5226. textLineHeight: null,
  5227. /**
  5228. * 'inside', 'left', 'right', 'top', 'bottom'
  5229. * [x, y]
  5230. * Based on x, y of rect.
  5231. * @type {string|Array.<number>}
  5232. * @default 'inside'
  5233. */
  5234. textPosition: 'inside',
  5235. /**
  5236. * If not specified, use the boundingRect of a `displayable`.
  5237. * @type {Object}
  5238. */
  5239. textRect: null,
  5240. /**
  5241. * [x, y]
  5242. * @type {Array.<number>}
  5243. */
  5244. textOffset: null,
  5245. /**
  5246. * @type {string}
  5247. */
  5248. textAlign: null,
  5249. /**
  5250. * @type {string}
  5251. */
  5252. textVerticalAlign: null,
  5253. /**
  5254. * @type {number}
  5255. */
  5256. textDistance: 5,
  5257. /**
  5258. * @type {string}
  5259. */
  5260. textShadowColor: 'transparent',
  5261. /**
  5262. * @type {number}
  5263. */
  5264. textShadowBlur: 0,
  5265. /**
  5266. * @type {number}
  5267. */
  5268. textShadowOffsetX: 0,
  5269. /**
  5270. * @type {number}
  5271. */
  5272. textShadowOffsetY: 0,
  5273. /**
  5274. * @type {string}
  5275. */
  5276. textBoxShadowColor: 'transparent',
  5277. /**
  5278. * @type {number}
  5279. */
  5280. textBoxShadowBlur: 0,
  5281. /**
  5282. * @type {number}
  5283. */
  5284. textBoxShadowOffsetX: 0,
  5285. /**
  5286. * @type {number}
  5287. */
  5288. textBoxShadowOffsetY: 0,
  5289. /**
  5290. * Whether transform text.
  5291. * Only useful in Path and Image element
  5292. * @type {boolean}
  5293. */
  5294. transformText: false,
  5295. /**
  5296. * Text rotate around position of Path or Image
  5297. * Only useful in Path and Image element and transformText is false.
  5298. */
  5299. textRotation: 0,
  5300. /**
  5301. * Text origin of text rotation, like [10, 40].
  5302. * Based on x, y of rect.
  5303. * Useful in label rotation of circular symbol.
  5304. * By default, this origin is textPosition.
  5305. * Can be 'center'.
  5306. * @type {string|Array.<number>}
  5307. */
  5308. textOrigin: null,
  5309. /**
  5310. * @type {string}
  5311. */
  5312. textBackgroundColor: null,
  5313. /**
  5314. * @type {string}
  5315. */
  5316. textBorderColor: null,
  5317. /**
  5318. * @type {number}
  5319. */
  5320. textBorderWidth: 0,
  5321. /**
  5322. * @type {number}
  5323. */
  5324. textBorderRadius: 0,
  5325. /**
  5326. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5327. * @type {number|Array.<number>}
  5328. */
  5329. textPadding: null,
  5330. /**
  5331. * Text styles for rich text.
  5332. * @type {Object}
  5333. */
  5334. rich: null,
  5335. /**
  5336. * {outerWidth, outerHeight, ellipsis, placeholder}
  5337. * @type {Object}
  5338. */
  5339. truncate: null,
  5340. /**
  5341. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5342. * @type {string}
  5343. */
  5344. blend: null,
  5345. /**
  5346. * @param {CanvasRenderingContext2D} ctx
  5347. */
  5348. bind: function (ctx, el, prevEl) {
  5349. var style = this;
  5350. var prevStyle = prevEl && prevEl.style;
  5351. var firstDraw = !prevStyle;
  5352. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5353. var prop = STYLE_COMMON_PROPS[i];
  5354. var styleName = prop[0];
  5355. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5356. // FIXME Invalid property value will cause style leak from previous element.
  5357. ctx[styleName] =
  5358. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5359. }
  5360. }
  5361. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5362. ctx.fillStyle = style.fill;
  5363. }
  5364. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5365. ctx.strokeStyle = style.stroke;
  5366. }
  5367. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5368. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5369. }
  5370. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5371. ctx.globalCompositeOperation = style.blend || 'source-over';
  5372. }
  5373. if (this.hasStroke()) {
  5374. var lineWidth = style.lineWidth;
  5375. ctx.lineWidth = lineWidth / (
  5376. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5377. );
  5378. }
  5379. },
  5380. hasFill: function () {
  5381. var fill = this.fill;
  5382. return fill != null && fill !== 'none';
  5383. },
  5384. hasStroke: function () {
  5385. var stroke = this.stroke;
  5386. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5387. },
  5388. /**
  5389. * Extend from other style
  5390. * @param {zrender/graphic/Style} otherStyle
  5391. * @param {boolean} overwrite true: overwrirte any way.
  5392. * false: overwrite only when !target.hasOwnProperty
  5393. * others: overwrite when property is not null/undefined.
  5394. */
  5395. extendFrom: function (otherStyle, overwrite) {
  5396. if (otherStyle) {
  5397. for (var name in otherStyle) {
  5398. if (otherStyle.hasOwnProperty(name)
  5399. && (overwrite === true
  5400. || (
  5401. overwrite === false
  5402. ? !this.hasOwnProperty(name)
  5403. : otherStyle[name] != null
  5404. )
  5405. )
  5406. ) {
  5407. this[name] = otherStyle[name];
  5408. }
  5409. }
  5410. }
  5411. },
  5412. /**
  5413. * Batch setting style with a given object
  5414. * @param {Object|string} obj
  5415. * @param {*} [obj]
  5416. */
  5417. set: function (obj, value) {
  5418. if (typeof obj === 'string') {
  5419. this[obj] = value;
  5420. }
  5421. else {
  5422. this.extendFrom(obj, true);
  5423. }
  5424. },
  5425. /**
  5426. * Clone
  5427. * @return {zrender/graphic/Style} [description]
  5428. */
  5429. clone: function () {
  5430. var newStyle = new this.constructor();
  5431. newStyle.extendFrom(this, true);
  5432. return newStyle;
  5433. },
  5434. getGradient: function (ctx, obj, rect) {
  5435. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5436. var canvasGradient = method(ctx, obj, rect);
  5437. var colorStops = obj.colorStops;
  5438. for (var i = 0; i < colorStops.length; i++) {
  5439. canvasGradient.addColorStop(
  5440. colorStops[i].offset, colorStops[i].color
  5441. );
  5442. }
  5443. return canvasGradient;
  5444. }
  5445. };
  5446. var styleProto = Style.prototype;
  5447. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5448. var prop = STYLE_COMMON_PROPS[i];
  5449. if (!(prop[0] in styleProto)) {
  5450. styleProto[prop[0]] = prop[1];
  5451. }
  5452. }
  5453. // Provide for others
  5454. Style.getGradient = styleProto.getGradient;
  5455. var Pattern = function (image, repeat) {
  5456. // Should do nothing more in this constructor. Because gradient can be
  5457. // declard by `color: {image: ...}`, where this constructor will not be called.
  5458. this.image = image;
  5459. this.repeat = repeat;
  5460. // Can be cloned
  5461. this.type = 'pattern';
  5462. };
  5463. Pattern.prototype.getCanvasPattern = function (ctx) {
  5464. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5465. };
  5466. /**
  5467. * @module zrender/Layer
  5468. * @author pissang(https://www.github.com/pissang)
  5469. */
  5470. function returnFalse() {
  5471. return false;
  5472. }
  5473. /**
  5474. * 创建dom
  5475. *
  5476. * @inner
  5477. * @param {string} id dom id 待用
  5478. * @param {Painter} painter painter instance
  5479. * @param {number} number
  5480. */
  5481. function createDom(id, painter, dpr) {
  5482. var newDom = createCanvas();
  5483. var width = painter.getWidth();
  5484. var height = painter.getHeight();
  5485. var newDomStyle = newDom.style;
  5486. if (newDomStyle) { // In node or some other non-browser environment
  5487. newDomStyle.position = 'absolute';
  5488. newDomStyle.left = 0;
  5489. newDomStyle.top = 0;
  5490. newDomStyle.width = width + 'px';
  5491. newDomStyle.height = height + 'px';
  5492. newDom.setAttribute('data-zr-dom-id', id);
  5493. }
  5494. newDom.width = width * dpr;
  5495. newDom.height = height * dpr;
  5496. return newDom;
  5497. }
  5498. /**
  5499. * @alias module:zrender/Layer
  5500. * @constructor
  5501. * @extends module:zrender/mixin/Transformable
  5502. * @param {string} id
  5503. * @param {module:zrender/Painter} painter
  5504. * @param {number} [dpr]
  5505. */
  5506. var Layer = function(id, painter, dpr) {
  5507. var dom;
  5508. dpr = dpr || devicePixelRatio;
  5509. if (typeof id === 'string') {
  5510. dom = createDom(id, painter, dpr);
  5511. }
  5512. // Not using isDom because in node it will return false
  5513. else if (isObject$1(id)) {
  5514. dom = id;
  5515. id = dom.id;
  5516. }
  5517. this.id = id;
  5518. this.dom = dom;
  5519. var domStyle = dom.style;
  5520. if (domStyle) { // Not in node
  5521. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5522. domStyle['-webkit-user-select'] = 'none';
  5523. domStyle['user-select'] = 'none';
  5524. domStyle['-webkit-touch-callout'] = 'none';
  5525. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5526. domStyle['padding'] = 0;
  5527. domStyle['margin'] = 0;
  5528. domStyle['border-width'] = 0;
  5529. }
  5530. this.domBack = null;
  5531. this.ctxBack = null;
  5532. this.painter = painter;
  5533. this.config = null;
  5534. // Configs
  5535. /**
  5536. * 每次清空画布的颜色
  5537. * @type {string}
  5538. * @default 0
  5539. */
  5540. this.clearColor = 0;
  5541. /**
  5542. * 是否开启动态模糊
  5543. * @type {boolean}
  5544. * @default false
  5545. */
  5546. this.motionBlur = false;
  5547. /**
  5548. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5549. * @type {number}
  5550. * @default 0.7
  5551. */
  5552. this.lastFrameAlpha = 0.7;
  5553. /**
  5554. * Layer dpr
  5555. * @type {number}
  5556. */
  5557. this.dpr = dpr;
  5558. };
  5559. Layer.prototype = {
  5560. constructor: Layer,
  5561. __dirty: true,
  5562. __used: false,
  5563. __drawIndex: 0,
  5564. __startIndex: 0,
  5565. __endIndex: 0,
  5566. incremental: false,
  5567. getElementCount: function () {
  5568. return this.__endIndex - this.__startIndex;
  5569. },
  5570. initContext: function () {
  5571. this.ctx = this.dom.getContext('2d');
  5572. this.ctx.dpr = this.dpr;
  5573. },
  5574. createBackBuffer: function () {
  5575. var dpr = this.dpr;
  5576. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5577. this.ctxBack = this.domBack.getContext('2d');
  5578. if (dpr != 1) {
  5579. this.ctxBack.scale(dpr, dpr);
  5580. }
  5581. },
  5582. /**
  5583. * @param {number} width
  5584. * @param {number} height
  5585. */
  5586. resize: function (width, height) {
  5587. var dpr = this.dpr;
  5588. var dom = this.dom;
  5589. var domStyle = dom.style;
  5590. var domBack = this.domBack;
  5591. domStyle.width = width + 'px';
  5592. domStyle.height = height + 'px';
  5593. dom.width = width * dpr;
  5594. dom.height = height * dpr;
  5595. if (domBack) {
  5596. domBack.width = width * dpr;
  5597. domBack.height = height * dpr;
  5598. if (dpr != 1) {
  5599. this.ctxBack.scale(dpr, dpr);
  5600. }
  5601. }
  5602. },
  5603. /**
  5604. * 清空该层画布
  5605. * @param {boolean} clearAll Clear all with out motion blur
  5606. */
  5607. clear: function (clearAll) {
  5608. var dom = this.dom;
  5609. var ctx = this.ctx;
  5610. var width = dom.width;
  5611. var height = dom.height;
  5612. var clearColor = this.clearColor;
  5613. var haveMotionBLur = this.motionBlur && !clearAll;
  5614. var lastFrameAlpha = this.lastFrameAlpha;
  5615. var dpr = this.dpr;
  5616. if (haveMotionBLur) {
  5617. if (!this.domBack) {
  5618. this.createBackBuffer();
  5619. }
  5620. this.ctxBack.globalCompositeOperation = 'copy';
  5621. this.ctxBack.drawImage(
  5622. dom, 0, 0,
  5623. width / dpr,
  5624. height / dpr
  5625. );
  5626. }
  5627. ctx.clearRect(0, 0, width, height);
  5628. if (clearColor) {
  5629. var clearColorGradientOrPattern;
  5630. // Gradient
  5631. if (clearColor.colorStops) {
  5632. // Cache canvas gradient
  5633. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5634. x: 0,
  5635. y: 0,
  5636. width: width,
  5637. height: height
  5638. });
  5639. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5640. }
  5641. // Pattern
  5642. else if (clearColor.image) {
  5643. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5644. }
  5645. ctx.save();
  5646. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5647. ctx.fillRect(0, 0, width, height);
  5648. ctx.restore();
  5649. }
  5650. if (haveMotionBLur) {
  5651. var domBack = this.domBack;
  5652. ctx.save();
  5653. ctx.globalAlpha = lastFrameAlpha;
  5654. ctx.drawImage(domBack, 0, 0, width, height);
  5655. ctx.restore();
  5656. }
  5657. }
  5658. };
  5659. var requestAnimationFrame = (
  5660. typeof window !== 'undefined'
  5661. && (
  5662. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5663. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5664. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5665. || window.mozRequestAnimationFrame
  5666. || window.webkitRequestAnimationFrame
  5667. )
  5668. ) || function (func) {
  5669. setTimeout(func, 16);
  5670. };
  5671. var globalImageCache = new LRU(50);
  5672. /**
  5673. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5674. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5675. */
  5676. function findExistImage(newImageOrSrc) {
  5677. if (typeof newImageOrSrc === 'string') {
  5678. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5679. return cachedImgObj && cachedImgObj.image;
  5680. }
  5681. else {
  5682. return newImageOrSrc;
  5683. }
  5684. }
  5685. /**
  5686. * Caution: User should cache loaded images, but not just count on LRU.
  5687. * Consider if required images more than LRU size, will dead loop occur?
  5688. *
  5689. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  5690. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  5691. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  5692. * @param {Function} [cb] params: (image, cbPayload)
  5693. * @param {Object} [cbPayload] Payload on cb calling.
  5694. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  5695. */
  5696. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  5697. if (!newImageOrSrc) {
  5698. return image;
  5699. }
  5700. else if (typeof newImageOrSrc === 'string') {
  5701. // Image should not be loaded repeatly.
  5702. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  5703. return image;
  5704. }
  5705. // Only when there is no existent image or existent image src
  5706. // is different, this method is responsible for load.
  5707. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  5708. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  5709. if (cachedImgObj) {
  5710. image = cachedImgObj.image;
  5711. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  5712. }
  5713. else {
  5714. !image && (image = new Image());
  5715. image.onload = imageOnLoad;
  5716. globalImageCache.put(
  5717. newImageOrSrc,
  5718. image.__cachedImgObj = {
  5719. image: image,
  5720. pending: [pendingWrap]
  5721. }
  5722. );
  5723. image.src = image.__zrImageSrc = newImageOrSrc;
  5724. }
  5725. return image;
  5726. }
  5727. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  5728. else {
  5729. return newImageOrSrc;
  5730. }
  5731. }
  5732. function imageOnLoad() {
  5733. var cachedImgObj = this.__cachedImgObj;
  5734. this.onload = this.__cachedImgObj = null;
  5735. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  5736. var pendingWrap = cachedImgObj.pending[i];
  5737. var cb = pendingWrap.cb;
  5738. cb && cb(this, pendingWrap.cbPayload);
  5739. pendingWrap.hostEl.dirty();
  5740. }
  5741. cachedImgObj.pending.length = 0;
  5742. }
  5743. function isImageReady(image) {
  5744. return image && image.width && image.height;
  5745. }
  5746. var textWidthCache = {};
  5747. var textWidthCacheCounter = 0;
  5748. var TEXT_CACHE_MAX = 5000;
  5749. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  5750. var DEFAULT_FONT = '12px sans-serif';
  5751. // Avoid assign to an exported variable, for transforming to cjs.
  5752. var methods$1 = {};
  5753. /**
  5754. * @public
  5755. * @param {string} text
  5756. * @param {string} font
  5757. * @return {number} width
  5758. */
  5759. function getWidth(text, font) {
  5760. font = font || DEFAULT_FONT;
  5761. var key = text + ':' + font;
  5762. if (textWidthCache[key]) {
  5763. return textWidthCache[key];
  5764. }
  5765. var textLines = (text + '').split('\n');
  5766. var width = 0;
  5767. for (var i = 0, l = textLines.length; i < l; i++) {
  5768. // textContain.measureText may be overrided in SVG or VML
  5769. width = Math.max(measureText(textLines[i], font).width, width);
  5770. }
  5771. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  5772. textWidthCacheCounter = 0;
  5773. textWidthCache = {};
  5774. }
  5775. textWidthCacheCounter++;
  5776. textWidthCache[key] = width;
  5777. return width;
  5778. }
  5779. /**
  5780. * @public
  5781. * @param {string} text
  5782. * @param {string} font
  5783. * @param {string} [textAlign='left']
  5784. * @param {string} [textVerticalAlign='top']
  5785. * @param {Array.<number>} [textPadding]
  5786. * @param {Object} [rich]
  5787. * @param {Object} [truncate]
  5788. * @return {Object} {x, y, width, height, lineHeight}
  5789. */
  5790. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  5791. return rich
  5792. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  5793. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  5794. }
  5795. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  5796. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  5797. var outerWidth = getWidth(text, font);
  5798. if (textPadding) {
  5799. outerWidth += textPadding[1] + textPadding[3];
  5800. }
  5801. var outerHeight = contentBlock.outerHeight;
  5802. var x = adjustTextX(0, outerWidth, textAlign);
  5803. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  5804. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  5805. rect.lineHeight = contentBlock.lineHeight;
  5806. return rect;
  5807. }
  5808. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  5809. var contentBlock = parseRichText(text, {
  5810. rich: rich,
  5811. truncate: truncate,
  5812. font: font,
  5813. textAlign: textAlign,
  5814. textPadding: textPadding
  5815. });
  5816. var outerWidth = contentBlock.outerWidth;
  5817. var outerHeight = contentBlock.outerHeight;
  5818. var x = adjustTextX(0, outerWidth, textAlign);
  5819. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  5820. return new BoundingRect(x, y, outerWidth, outerHeight);
  5821. }
  5822. /**
  5823. * @public
  5824. * @param {number} x
  5825. * @param {number} width
  5826. * @param {string} [textAlign='left']
  5827. * @return {number} Adjusted x.
  5828. */
  5829. function adjustTextX(x, width, textAlign) {
  5830. // FIXME Right to left language
  5831. if (textAlign === 'right') {
  5832. x -= width;
  5833. }
  5834. else if (textAlign === 'center') {
  5835. x -= width / 2;
  5836. }
  5837. return x;
  5838. }
  5839. /**
  5840. * @public
  5841. * @param {number} y
  5842. * @param {number} height
  5843. * @param {string} [textVerticalAlign='top']
  5844. * @return {number} Adjusted y.
  5845. */
  5846. function adjustTextY(y, height, textVerticalAlign) {
  5847. if (textVerticalAlign === 'middle') {
  5848. y -= height / 2;
  5849. }
  5850. else if (textVerticalAlign === 'bottom') {
  5851. y -= height;
  5852. }
  5853. return y;
  5854. }
  5855. /**
  5856. * @public
  5857. * @param {stirng} textPosition
  5858. * @param {Object} rect {x, y, width, height}
  5859. * @param {number} distance
  5860. * @return {Object} {x, y, textAlign, textVerticalAlign}
  5861. */
  5862. function adjustTextPositionOnRect(textPosition, rect, distance) {
  5863. var x = rect.x;
  5864. var y = rect.y;
  5865. var height = rect.height;
  5866. var width = rect.width;
  5867. var halfHeight = height / 2;
  5868. var textAlign = 'left';
  5869. var textVerticalAlign = 'top';
  5870. switch (textPosition) {
  5871. case 'left':
  5872. x -= distance;
  5873. y += halfHeight;
  5874. textAlign = 'right';
  5875. textVerticalAlign = 'middle';
  5876. break;
  5877. case 'right':
  5878. x += distance + width;
  5879. y += halfHeight;
  5880. textVerticalAlign = 'middle';
  5881. break;
  5882. case 'top':
  5883. x += width / 2;
  5884. y -= distance;
  5885. textAlign = 'center';
  5886. textVerticalAlign = 'bottom';
  5887. break;
  5888. case 'bottom':
  5889. x += width / 2;
  5890. y += height + distance;
  5891. textAlign = 'center';
  5892. break;
  5893. case 'inside':
  5894. x += width / 2;
  5895. y += halfHeight;
  5896. textAlign = 'center';
  5897. textVerticalAlign = 'middle';
  5898. break;
  5899. case 'insideLeft':
  5900. x += distance;
  5901. y += halfHeight;
  5902. textVerticalAlign = 'middle';
  5903. break;
  5904. case 'insideRight':
  5905. x += width - distance;
  5906. y += halfHeight;
  5907. textAlign = 'right';
  5908. textVerticalAlign = 'middle';
  5909. break;
  5910. case 'insideTop':
  5911. x += width / 2;
  5912. y += distance;
  5913. textAlign = 'center';
  5914. break;
  5915. case 'insideBottom':
  5916. x += width / 2;
  5917. y += height - distance;
  5918. textAlign = 'center';
  5919. textVerticalAlign = 'bottom';
  5920. break;
  5921. case 'insideTopLeft':
  5922. x += distance;
  5923. y += distance;
  5924. break;
  5925. case 'insideTopRight':
  5926. x += width - distance;
  5927. y += distance;
  5928. textAlign = 'right';
  5929. break;
  5930. case 'insideBottomLeft':
  5931. x += distance;
  5932. y += height - distance;
  5933. textVerticalAlign = 'bottom';
  5934. break;
  5935. case 'insideBottomRight':
  5936. x += width - distance;
  5937. y += height - distance;
  5938. textAlign = 'right';
  5939. textVerticalAlign = 'bottom';
  5940. break;
  5941. }
  5942. return {
  5943. x: x,
  5944. y: y,
  5945. textAlign: textAlign,
  5946. textVerticalAlign: textVerticalAlign
  5947. };
  5948. }
  5949. /**
  5950. * Show ellipsis if overflow.
  5951. *
  5952. * @public
  5953. * @param {string} text
  5954. * @param {string} containerWidth
  5955. * @param {string} font
  5956. * @param {number} [ellipsis='...']
  5957. * @param {Object} [options]
  5958. * @param {number} [options.maxIterations=3]
  5959. * @param {number} [options.minChar=0] If truncate result are less
  5960. * then minChar, ellipsis will not show, which is
  5961. * better for user hint in some cases.
  5962. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  5963. * @return {string}
  5964. */
  5965. function truncateText(text, containerWidth, font, ellipsis, options) {
  5966. if (!containerWidth) {
  5967. return '';
  5968. }
  5969. var textLines = (text + '').split('\n');
  5970. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  5971. // FIXME
  5972. // It is not appropriate that every line has '...' when truncate multiple lines.
  5973. for (var i = 0, len = textLines.length; i < len; i++) {
  5974. textLines[i] = truncateSingleLine(textLines[i], options);
  5975. }
  5976. return textLines.join('\n');
  5977. }
  5978. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  5979. options = extend({}, options);
  5980. options.font = font;
  5981. var ellipsis = retrieve2(ellipsis, '...');
  5982. options.maxIterations = retrieve2(options.maxIterations, 2);
  5983. var minChar = options.minChar = retrieve2(options.minChar, 0);
  5984. // FIXME
  5985. // Other languages?
  5986. options.cnCharWidth = getWidth('国', font);
  5987. // FIXME
  5988. // Consider proportional font?
  5989. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  5990. options.placeholder = retrieve2(options.placeholder, '');
  5991. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  5992. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  5993. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  5994. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  5995. contentWidth -= ascCharWidth;
  5996. }
  5997. var ellipsisWidth = getWidth(ellipsis);
  5998. if (ellipsisWidth > contentWidth) {
  5999. ellipsis = '';
  6000. ellipsisWidth = 0;
  6001. }
  6002. contentWidth = containerWidth - ellipsisWidth;
  6003. options.ellipsis = ellipsis;
  6004. options.ellipsisWidth = ellipsisWidth;
  6005. options.contentWidth = contentWidth;
  6006. options.containerWidth = containerWidth;
  6007. return options;
  6008. }
  6009. function truncateSingleLine(textLine, options) {
  6010. var containerWidth = options.containerWidth;
  6011. var font = options.font;
  6012. var contentWidth = options.contentWidth;
  6013. if (!containerWidth) {
  6014. return '';
  6015. }
  6016. var lineWidth = getWidth(textLine, font);
  6017. if (lineWidth <= containerWidth) {
  6018. return textLine;
  6019. }
  6020. for (var j = 0;; j++) {
  6021. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6022. textLine += options.ellipsis;
  6023. break;
  6024. }
  6025. var subLength = j === 0
  6026. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6027. : lineWidth > 0
  6028. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6029. : 0;
  6030. textLine = textLine.substr(0, subLength);
  6031. lineWidth = getWidth(textLine, font);
  6032. }
  6033. if (textLine === '') {
  6034. textLine = options.placeholder;
  6035. }
  6036. return textLine;
  6037. }
  6038. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6039. var width = 0;
  6040. var i = 0;
  6041. for (var len = text.length; i < len && width < contentWidth; i++) {
  6042. var charCode = text.charCodeAt(i);
  6043. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6044. }
  6045. return i;
  6046. }
  6047. /**
  6048. * @public
  6049. * @param {string} font
  6050. * @return {number} line height
  6051. */
  6052. function getLineHeight(font) {
  6053. // FIXME A rough approach.
  6054. return getWidth('国', font);
  6055. }
  6056. /**
  6057. * @public
  6058. * @param {string} text
  6059. * @param {string} font
  6060. * @return {Object} width
  6061. */
  6062. function measureText(text, font) {
  6063. return methods$1.measureText(text, font);
  6064. }
  6065. // Avoid assign to an exported variable, for transforming to cjs.
  6066. methods$1.measureText = function (text, font) {
  6067. var ctx = getContext();
  6068. ctx.font = font || DEFAULT_FONT;
  6069. return ctx.measureText(text);
  6070. };
  6071. /**
  6072. * @public
  6073. * @param {string} text
  6074. * @param {string} font
  6075. * @param {Object} [truncate]
  6076. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6077. * Notice: for performance, do not calculate outerWidth util needed.
  6078. */
  6079. function parsePlainText(text, font, padding, truncate) {
  6080. text != null && (text += '');
  6081. var lineHeight = getLineHeight(font);
  6082. var lines = text ? text.split('\n') : [];
  6083. var height = lines.length * lineHeight;
  6084. var outerHeight = height;
  6085. if (padding) {
  6086. outerHeight += padding[0] + padding[2];
  6087. }
  6088. if (text && truncate) {
  6089. var truncOuterHeight = truncate.outerHeight;
  6090. var truncOuterWidth = truncate.outerWidth;
  6091. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6092. text = '';
  6093. lines = [];
  6094. }
  6095. else if (truncOuterWidth != null) {
  6096. var options = prepareTruncateOptions(
  6097. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6098. font,
  6099. truncate.ellipsis,
  6100. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6101. );
  6102. // FIXME
  6103. // It is not appropriate that every line has '...' when truncate multiple lines.
  6104. for (var i = 0, len = lines.length; i < len; i++) {
  6105. lines[i] = truncateSingleLine(lines[i], options);
  6106. }
  6107. }
  6108. }
  6109. return {
  6110. lines: lines,
  6111. height: height,
  6112. outerHeight: outerHeight,
  6113. lineHeight: lineHeight
  6114. };
  6115. }
  6116. /**
  6117. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6118. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6119. *
  6120. * @public
  6121. * @param {string} text
  6122. * @param {Object} style
  6123. * @return {Object} block
  6124. * {
  6125. * width,
  6126. * height,
  6127. * lines: [{
  6128. * lineHeight,
  6129. * width,
  6130. * tokens: [[{
  6131. * styleName,
  6132. * text,
  6133. * width, // include textPadding
  6134. * height, // include textPadding
  6135. * textWidth, // pure text width
  6136. * textHeight, // pure text height
  6137. * lineHeihgt,
  6138. * font,
  6139. * textAlign,
  6140. * textVerticalAlign
  6141. * }], [...], ...]
  6142. * }, ...]
  6143. * }
  6144. * If styleName is undefined, it is plain text.
  6145. */
  6146. function parseRichText(text, style) {
  6147. var contentBlock = {lines: [], width: 0, height: 0};
  6148. text != null && (text += '');
  6149. if (!text) {
  6150. return contentBlock;
  6151. }
  6152. var lastIndex = STYLE_REG.lastIndex = 0;
  6153. var result;
  6154. while ((result = STYLE_REG.exec(text)) != null) {
  6155. var matchedIndex = result.index;
  6156. if (matchedIndex > lastIndex) {
  6157. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6158. }
  6159. pushTokens(contentBlock, result[2], result[1]);
  6160. lastIndex = STYLE_REG.lastIndex;
  6161. }
  6162. if (lastIndex < text.length) {
  6163. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6164. }
  6165. var lines = contentBlock.lines;
  6166. var contentHeight = 0;
  6167. var contentWidth = 0;
  6168. // For `textWidth: 100%`
  6169. var pendingList = [];
  6170. var stlPadding = style.textPadding;
  6171. var truncate = style.truncate;
  6172. var truncateWidth = truncate && truncate.outerWidth;
  6173. var truncateHeight = truncate && truncate.outerHeight;
  6174. if (stlPadding) {
  6175. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6176. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6177. }
  6178. // Calculate layout info of tokens.
  6179. for (var i = 0; i < lines.length; i++) {
  6180. var line = lines[i];
  6181. var lineHeight = 0;
  6182. var lineWidth = 0;
  6183. for (var j = 0; j < line.tokens.length; j++) {
  6184. var token = line.tokens[j];
  6185. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6186. // textPadding should not inherit from style.
  6187. var textPadding = token.textPadding = tokenStyle.textPadding;
  6188. // textFont has been asigned to font by `normalizeStyle`.
  6189. var font = token.font = tokenStyle.font || style.font;
  6190. // textHeight can be used when textVerticalAlign is specified in token.
  6191. var tokenHeight = token.textHeight = retrieve2(
  6192. // textHeight should not be inherited, consider it can be specified
  6193. // as box height of the block.
  6194. tokenStyle.textHeight, getLineHeight(font)
  6195. );
  6196. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6197. token.height = tokenHeight;
  6198. token.lineHeight = retrieve3(
  6199. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6200. );
  6201. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6202. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6203. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6204. return {lines: [], width: 0, height: 0};
  6205. }
  6206. token.textWidth = getWidth(token.text, font);
  6207. var tokenWidth = tokenStyle.textWidth;
  6208. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6209. // Percent width, can be `100%`, can be used in drawing separate
  6210. // line when box width is needed to be auto.
  6211. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6212. token.percentWidth = tokenWidth;
  6213. pendingList.push(token);
  6214. tokenWidth = 0;
  6215. // Do not truncate in this case, because there is no user case
  6216. // and it is too complicated.
  6217. }
  6218. else {
  6219. if (tokenWidthNotSpecified) {
  6220. tokenWidth = token.textWidth;
  6221. // FIXME: If image is not loaded and textWidth is not specified, calling
  6222. // `getBoundingRect()` will not get correct result.
  6223. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6224. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6225. // Use cases:
  6226. // (1) If image is not loaded, it will be loaded at render phase and call
  6227. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6228. // image, and then the right size will be calculated here at the next tick.
  6229. // See `graphic/helper/text.js`.
  6230. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6231. // use `imageHelper.findExistImage` to find cached image.
  6232. // `imageHelper.findExistImage` will always be called here before
  6233. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6234. // which ensures that image will not be rendered before correct size calcualted.
  6235. if (bgImg) {
  6236. bgImg = findExistImage(bgImg);
  6237. if (isImageReady(bgImg)) {
  6238. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6239. }
  6240. }
  6241. }
  6242. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6243. tokenWidth += paddingW;
  6244. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6245. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6246. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6247. token.text = '';
  6248. token.textWidth = tokenWidth = 0;
  6249. }
  6250. else {
  6251. token.text = truncateText(
  6252. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6253. {minChar: truncate.minChar}
  6254. );
  6255. token.textWidth = getWidth(token.text, font);
  6256. tokenWidth = token.textWidth + paddingW;
  6257. }
  6258. }
  6259. }
  6260. lineWidth += (token.width = tokenWidth);
  6261. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6262. }
  6263. line.width = lineWidth;
  6264. line.lineHeight = lineHeight;
  6265. contentHeight += lineHeight;
  6266. contentWidth = Math.max(contentWidth, lineWidth);
  6267. }
  6268. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6269. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6270. if (stlPadding) {
  6271. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6272. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6273. }
  6274. for (var i = 0; i < pendingList.length; i++) {
  6275. var token = pendingList[i];
  6276. var percentWidth = token.percentWidth;
  6277. // Should not base on outerWidth, because token can not be placed out of padding.
  6278. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6279. }
  6280. return contentBlock;
  6281. }
  6282. function pushTokens(block, str, styleName) {
  6283. var isEmptyStr = str === '';
  6284. var strs = str.split('\n');
  6285. var lines = block.lines;
  6286. for (var i = 0; i < strs.length; i++) {
  6287. var text = strs[i];
  6288. var token = {
  6289. styleName: styleName,
  6290. text: text,
  6291. isLineHolder: !text && !isEmptyStr
  6292. };
  6293. // The first token should be appended to the last line.
  6294. if (!i) {
  6295. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6296. // Consider cases:
  6297. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6298. // (which is a placeholder) should be replaced by new token.
  6299. // (2) A image backage, where token likes {a|}.
  6300. // (3) A redundant '' will affect textAlign in line.
  6301. // (4) tokens with the same tplName should not be merged, because
  6302. // they should be displayed in different box (with border and padding).
  6303. var tokensLen = tokens.length;
  6304. (tokensLen === 1 && tokens[0].isLineHolder)
  6305. ? (tokens[0] = token)
  6306. // Consider text is '', only insert when it is the "lineHolder" or
  6307. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6308. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6309. }
  6310. // Other tokens always start a new line.
  6311. else {
  6312. // If there is '', insert it as a placeholder.
  6313. lines.push({tokens: [token]});
  6314. }
  6315. }
  6316. }
  6317. function makeFont(style) {
  6318. // FIXME in node-canvas fontWeight is before fontStyle
  6319. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6320. var font = (style.fontSize || style.fontFamily) && [
  6321. style.fontStyle,
  6322. style.fontWeight,
  6323. (style.fontSize || 12) + 'px',
  6324. // If font properties are defined, `fontFamily` should not be ignored.
  6325. style.fontFamily || 'sans-serif'
  6326. ].join(' ');
  6327. return font && trim(font) || style.textFont || style.font;
  6328. }
  6329. function buildPath(ctx, shape) {
  6330. var x = shape.x;
  6331. var y = shape.y;
  6332. var width = shape.width;
  6333. var height = shape.height;
  6334. var r = shape.r;
  6335. var r1;
  6336. var r2;
  6337. var r3;
  6338. var r4;
  6339. // Convert width and height to positive for better borderRadius
  6340. if (width < 0) {
  6341. x = x + width;
  6342. width = -width;
  6343. }
  6344. if (height < 0) {
  6345. y = y + height;
  6346. height = -height;
  6347. }
  6348. if (typeof r === 'number') {
  6349. r1 = r2 = r3 = r4 = r;
  6350. }
  6351. else if (r instanceof Array) {
  6352. if (r.length === 1) {
  6353. r1 = r2 = r3 = r4 = r[0];
  6354. }
  6355. else if (r.length === 2) {
  6356. r1 = r3 = r[0];
  6357. r2 = r4 = r[1];
  6358. }
  6359. else if (r.length === 3) {
  6360. r1 = r[0];
  6361. r2 = r4 = r[1];
  6362. r3 = r[2];
  6363. }
  6364. else {
  6365. r1 = r[0];
  6366. r2 = r[1];
  6367. r3 = r[2];
  6368. r4 = r[3];
  6369. }
  6370. }
  6371. else {
  6372. r1 = r2 = r3 = r4 = 0;
  6373. }
  6374. var total;
  6375. if (r1 + r2 > width) {
  6376. total = r1 + r2;
  6377. r1 *= width / total;
  6378. r2 *= width / total;
  6379. }
  6380. if (r3 + r4 > width) {
  6381. total = r3 + r4;
  6382. r3 *= width / total;
  6383. r4 *= width / total;
  6384. }
  6385. if (r2 + r3 > height) {
  6386. total = r2 + r3;
  6387. r2 *= height / total;
  6388. r3 *= height / total;
  6389. }
  6390. if (r1 + r4 > height) {
  6391. total = r1 + r4;
  6392. r1 *= height / total;
  6393. r4 *= height / total;
  6394. }
  6395. ctx.moveTo(x + r1, y);
  6396. ctx.lineTo(x + width - r2, y);
  6397. r2 !== 0 && ctx.quadraticCurveTo(
  6398. x + width, y, x + width, y + r2
  6399. );
  6400. ctx.lineTo(x + width, y + height - r3);
  6401. r3 !== 0 && ctx.quadraticCurveTo(
  6402. x + width, y + height, x + width - r3, y + height
  6403. );
  6404. ctx.lineTo(x + r4, y + height);
  6405. r4 !== 0 && ctx.quadraticCurveTo(
  6406. x, y + height, x, y + height - r4
  6407. );
  6408. ctx.lineTo(x, y + r1);
  6409. r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y);
  6410. }
  6411. // TODO: Have not support 'start', 'end' yet.
  6412. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6413. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6414. /**
  6415. * @param {module:zrender/graphic/Style} style
  6416. * @return {module:zrender/graphic/Style} The input style.
  6417. */
  6418. function normalizeTextStyle(style) {
  6419. normalizeStyle(style);
  6420. each$1(style.rich, normalizeStyle);
  6421. return style;
  6422. }
  6423. function normalizeStyle(style) {
  6424. if (style) {
  6425. style.font = makeFont(style);
  6426. var textAlign = style.textAlign;
  6427. textAlign === 'middle' && (textAlign = 'center');
  6428. style.textAlign = (
  6429. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6430. ) ? textAlign : 'left';
  6431. // Compatible with textBaseline.
  6432. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6433. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6434. style.textVerticalAlign = (
  6435. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6436. ) ? textVerticalAlign : 'top';
  6437. var textPadding = style.textPadding;
  6438. if (textPadding) {
  6439. style.textPadding = normalizeCssArray(style.textPadding);
  6440. }
  6441. }
  6442. }
  6443. /**
  6444. * @param {CanvasRenderingContext2D} ctx
  6445. * @param {string} text
  6446. * @param {module:zrender/graphic/Style} style
  6447. * @param {Object|boolean} [rect] {x, y, width, height}
  6448. * If set false, rect text is not used.
  6449. */
  6450. function renderText(hostEl, ctx, text, style, rect) {
  6451. style.rich
  6452. ? renderRichText(hostEl, ctx, text, style, rect)
  6453. : renderPlainText(hostEl, ctx, text, style, rect);
  6454. }
  6455. function renderPlainText(hostEl, ctx, text, style, rect) {
  6456. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6457. var textPadding = style.textPadding;
  6458. var contentBlock = hostEl.__textCotentBlock;
  6459. if (!contentBlock || hostEl.__dirty) {
  6460. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6461. text, font, textPadding, style.truncate
  6462. );
  6463. }
  6464. var outerHeight = contentBlock.outerHeight;
  6465. var textLines = contentBlock.lines;
  6466. var lineHeight = contentBlock.lineHeight;
  6467. var boxPos = getBoxPosition(outerHeight, style, rect);
  6468. var baseX = boxPos.baseX;
  6469. var baseY = boxPos.baseY;
  6470. var textAlign = boxPos.textAlign;
  6471. var textVerticalAlign = boxPos.textVerticalAlign;
  6472. // Origin of textRotation should be the base point of text drawing.
  6473. applyTextRotation(ctx, style, rect, baseX, baseY);
  6474. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6475. var textX = baseX;
  6476. var textY = boxY;
  6477. var needDrawBg = needDrawBackground(style);
  6478. if (needDrawBg || textPadding) {
  6479. // Consider performance, do not call getTextWidth util necessary.
  6480. var textWidth = getWidth(text, font);
  6481. var outerWidth = textWidth;
  6482. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6483. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6484. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6485. if (textPadding) {
  6486. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6487. textY += textPadding[0];
  6488. }
  6489. }
  6490. setCtx(ctx, 'textAlign', textAlign || 'left');
  6491. // Force baseline to be "middle". Otherwise, if using "top", the
  6492. // text will offset downward a little bit in font "Microsoft YaHei".
  6493. setCtx(ctx, 'textBaseline', 'middle');
  6494. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6495. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6496. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6497. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6498. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6499. // `textBaseline` is set as 'middle'.
  6500. textY += lineHeight / 2;
  6501. var textStrokeWidth = style.textStrokeWidth;
  6502. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6503. var textFill = getFill(style.textFill);
  6504. if (textStroke) {
  6505. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6506. setCtx(ctx, 'strokeStyle', textStroke);
  6507. }
  6508. if (textFill) {
  6509. setCtx(ctx, 'fillStyle', textFill);
  6510. }
  6511. for (var i = 0; i < textLines.length; i++) {
  6512. // Fill after stroke so the outline will not cover the main part.
  6513. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6514. textFill && ctx.fillText(textLines[i], textX, textY);
  6515. textY += lineHeight;
  6516. }
  6517. }
  6518. function renderRichText(hostEl, ctx, text, style, rect) {
  6519. var contentBlock = hostEl.__textCotentBlock;
  6520. if (!contentBlock || hostEl.__dirty) {
  6521. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6522. }
  6523. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6524. }
  6525. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6526. var contentWidth = contentBlock.width;
  6527. var outerWidth = contentBlock.outerWidth;
  6528. var outerHeight = contentBlock.outerHeight;
  6529. var textPadding = style.textPadding;
  6530. var boxPos = getBoxPosition(outerHeight, style, rect);
  6531. var baseX = boxPos.baseX;
  6532. var baseY = boxPos.baseY;
  6533. var textAlign = boxPos.textAlign;
  6534. var textVerticalAlign = boxPos.textVerticalAlign;
  6535. // Origin of textRotation should be the base point of text drawing.
  6536. applyTextRotation(ctx, style, rect, baseX, baseY);
  6537. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6538. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6539. var xLeft = boxX;
  6540. var lineTop = boxY;
  6541. if (textPadding) {
  6542. xLeft += textPadding[3];
  6543. lineTop += textPadding[0];
  6544. }
  6545. var xRight = xLeft + contentWidth;
  6546. needDrawBackground(style) && drawBackground(
  6547. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6548. );
  6549. for (var i = 0; i < contentBlock.lines.length; i++) {
  6550. var line = contentBlock.lines[i];
  6551. var tokens = line.tokens;
  6552. var tokenCount = tokens.length;
  6553. var lineHeight = line.lineHeight;
  6554. var usedWidth = line.width;
  6555. var leftIndex = 0;
  6556. var lineXLeft = xLeft;
  6557. var lineXRight = xRight;
  6558. var rightIndex = tokenCount - 1;
  6559. var token;
  6560. while (
  6561. leftIndex < tokenCount
  6562. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6563. ) {
  6564. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6565. usedWidth -= token.width;
  6566. lineXLeft += token.width;
  6567. leftIndex++;
  6568. }
  6569. while (
  6570. rightIndex >= 0
  6571. && (token = tokens[rightIndex], token.textAlign === 'right')
  6572. ) {
  6573. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6574. usedWidth -= token.width;
  6575. lineXRight -= token.width;
  6576. rightIndex--;
  6577. }
  6578. // The other tokens are placed as textAlign 'center' if there is enough space.
  6579. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6580. while (leftIndex <= rightIndex) {
  6581. token = tokens[leftIndex];
  6582. // Consider width specified by user, use 'center' rather than 'left'.
  6583. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6584. lineXLeft += token.width;
  6585. leftIndex++;
  6586. }
  6587. lineTop += lineHeight;
  6588. }
  6589. }
  6590. function applyTextRotation(ctx, style, rect, x, y) {
  6591. // textRotation only apply in RectText.
  6592. if (rect && style.textRotation) {
  6593. var origin = style.textOrigin;
  6594. if (origin === 'center') {
  6595. x = rect.width / 2 + rect.x;
  6596. y = rect.height / 2 + rect.y;
  6597. }
  6598. else if (origin) {
  6599. x = origin[0] + rect.x;
  6600. y = origin[1] + rect.y;
  6601. }
  6602. ctx.translate(x, y);
  6603. // Positive: anticlockwise
  6604. ctx.rotate(-style.textRotation);
  6605. ctx.translate(-x, -y);
  6606. }
  6607. }
  6608. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6609. var tokenStyle = style.rich[token.styleName] || {};
  6610. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6611. // the bias of "Microsoft YaHei".
  6612. var textVerticalAlign = token.textVerticalAlign;
  6613. var y = lineTop + lineHeight / 2;
  6614. if (textVerticalAlign === 'top') {
  6615. y = lineTop + token.height / 2;
  6616. }
  6617. else if (textVerticalAlign === 'bottom') {
  6618. y = lineTop + lineHeight - token.height / 2;
  6619. }
  6620. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6621. hostEl,
  6622. ctx,
  6623. tokenStyle,
  6624. textAlign === 'right'
  6625. ? x - token.width
  6626. : textAlign === 'center'
  6627. ? x - token.width / 2
  6628. : x,
  6629. y - token.height / 2,
  6630. token.width,
  6631. token.height
  6632. );
  6633. var textPadding = token.textPadding;
  6634. if (textPadding) {
  6635. x = getTextXForPadding(x, textAlign, textPadding);
  6636. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6637. }
  6638. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6639. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6640. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6641. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6642. setCtx(ctx, 'textAlign', textAlign);
  6643. // Force baseline to be "middle". Otherwise, if using "top", the
  6644. // text will offset downward a little bit in font "Microsoft YaHei".
  6645. setCtx(ctx, 'textBaseline', 'middle');
  6646. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6647. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6648. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6649. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6650. // Fill after stroke so the outline will not cover the main part.
  6651. if (textStroke) {
  6652. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6653. setCtx(ctx, 'strokeStyle', textStroke);
  6654. ctx.strokeText(token.text, x, y);
  6655. }
  6656. if (textFill) {
  6657. setCtx(ctx, 'fillStyle', textFill);
  6658. ctx.fillText(token.text, x, y);
  6659. }
  6660. }
  6661. function needDrawBackground(style) {
  6662. return style.textBackgroundColor
  6663. || (style.textBorderWidth && style.textBorderColor);
  6664. }
  6665. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6666. // shape: {x, y, width, height}
  6667. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6668. var textBackgroundColor = style.textBackgroundColor;
  6669. var textBorderWidth = style.textBorderWidth;
  6670. var textBorderColor = style.textBorderColor;
  6671. var isPlainBg = isString(textBackgroundColor);
  6672. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  6673. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  6674. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  6675. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  6676. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  6677. ctx.beginPath();
  6678. var textBorderRadius = style.textBorderRadius;
  6679. if (!textBorderRadius) {
  6680. ctx.rect(x, y, width, height);
  6681. }
  6682. else {
  6683. buildPath(ctx, {
  6684. x: x, y: y, width: width, height: height, r: textBorderRadius
  6685. });
  6686. }
  6687. ctx.closePath();
  6688. }
  6689. if (isPlainBg) {
  6690. setCtx(ctx, 'fillStyle', textBackgroundColor);
  6691. ctx.fill();
  6692. }
  6693. else if (isObject$1(textBackgroundColor)) {
  6694. var image = textBackgroundColor.image;
  6695. image = createOrUpdateImage(
  6696. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  6697. );
  6698. if (image && isImageReady(image)) {
  6699. ctx.drawImage(image, x, y, width, height);
  6700. }
  6701. }
  6702. if (textBorderWidth && textBorderColor) {
  6703. setCtx(ctx, 'lineWidth', textBorderWidth);
  6704. setCtx(ctx, 'strokeStyle', textBorderColor);
  6705. ctx.stroke();
  6706. }
  6707. }
  6708. function onBgImageLoaded(image, textBackgroundColor) {
  6709. // Replace image, so that `contain/text.js#parseRichText`
  6710. // will get correct result in next tick.
  6711. textBackgroundColor.image = image;
  6712. }
  6713. function getBoxPosition(blockHeiht, style, rect) {
  6714. var baseX = style.x || 0;
  6715. var baseY = style.y || 0;
  6716. var textAlign = style.textAlign;
  6717. var textVerticalAlign = style.textVerticalAlign;
  6718. // Text position represented by coord
  6719. if (rect) {
  6720. var textPosition = style.textPosition;
  6721. if (textPosition instanceof Array) {
  6722. // Percent
  6723. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  6724. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  6725. }
  6726. else {
  6727. var res = adjustTextPositionOnRect(
  6728. textPosition, rect, style.textDistance
  6729. );
  6730. baseX = res.x;
  6731. baseY = res.y;
  6732. // Default align and baseline when has textPosition
  6733. textAlign = textAlign || res.textAlign;
  6734. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  6735. }
  6736. // textOffset is only support in RectText, otherwise
  6737. // we have to adjust boundingRect for textOffset.
  6738. var textOffset = style.textOffset;
  6739. if (textOffset) {
  6740. baseX += textOffset[0];
  6741. baseY += textOffset[1];
  6742. }
  6743. }
  6744. return {
  6745. baseX: baseX,
  6746. baseY: baseY,
  6747. textAlign: textAlign,
  6748. textVerticalAlign: textVerticalAlign
  6749. };
  6750. }
  6751. function setCtx(ctx, prop, value) {
  6752. ctx[prop] = fixShadow(ctx, prop, value);
  6753. return ctx[prop];
  6754. }
  6755. /**
  6756. * @param {string} [stroke] If specified, do not check style.textStroke.
  6757. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  6758. * @param {number} style
  6759. */
  6760. function getStroke(stroke, lineWidth) {
  6761. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  6762. ? null
  6763. // TODO pattern and gradient?
  6764. : (stroke.image || stroke.colorStops)
  6765. ? '#000'
  6766. : stroke;
  6767. }
  6768. function getFill(fill) {
  6769. return (fill == null || fill === 'none')
  6770. ? null
  6771. // TODO pattern and gradient?
  6772. : (fill.image || fill.colorStops)
  6773. ? '#000'
  6774. : fill;
  6775. }
  6776. function parsePercent(value, maxValue) {
  6777. if (typeof value === 'string') {
  6778. if (value.lastIndexOf('%') >= 0) {
  6779. return parseFloat(value) / 100 * maxValue;
  6780. }
  6781. return parseFloat(value);
  6782. }
  6783. return value;
  6784. }
  6785. function getTextXForPadding(x, textAlign, textPadding) {
  6786. return textAlign === 'right'
  6787. ? (x - textPadding[1])
  6788. : textAlign === 'center'
  6789. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  6790. : (x + textPadding[3]);
  6791. }
  6792. /**
  6793. * @param {string} text
  6794. * @param {module:zrender/Style} style
  6795. * @return {boolean}
  6796. */
  6797. function needDrawText(text, style) {
  6798. return text != null
  6799. && (text
  6800. || style.textBackgroundColor
  6801. || (style.textBorderWidth && style.textBorderColor)
  6802. || style.textPadding
  6803. );
  6804. }
  6805. /**
  6806. * Mixin for drawing text in a element bounding rect
  6807. * @module zrender/mixin/RectText
  6808. */
  6809. var tmpRect$1 = new BoundingRect();
  6810. var RectText = function () {};
  6811. RectText.prototype = {
  6812. constructor: RectText,
  6813. /**
  6814. * Draw text in a rect with specified position.
  6815. * @param {CanvasRenderingContext2D} ctx
  6816. * @param {Object} rect Displayable rect
  6817. */
  6818. drawRectText: function (ctx, rect) {
  6819. var style = this.style;
  6820. rect = style.textRect || rect;
  6821. // Optimize, avoid normalize every time.
  6822. this.__dirty && normalizeTextStyle(style, true);
  6823. var text = style.text;
  6824. // Convert to string
  6825. text != null && (text += '');
  6826. if (!needDrawText(text, style)) {
  6827. return;
  6828. }
  6829. // FIXME
  6830. ctx.save();
  6831. // Transform rect to view space
  6832. var transform = this.transform;
  6833. if (!style.transformText) {
  6834. if (transform) {
  6835. tmpRect$1.copy(rect);
  6836. tmpRect$1.applyTransform(transform);
  6837. rect = tmpRect$1;
  6838. }
  6839. }
  6840. else {
  6841. this.setTransform(ctx);
  6842. }
  6843. // transformText and textRotation can not be used at the same time.
  6844. renderText(this, ctx, text, style, rect);
  6845. ctx.restore();
  6846. }
  6847. };
  6848. /**
  6849. * 可绘制的图形基类
  6850. * Base class of all displayable graphic objects
  6851. * @module zrender/graphic/Displayable
  6852. */
  6853. /**
  6854. * @alias module:zrender/graphic/Displayable
  6855. * @extends module:zrender/Element
  6856. * @extends module:zrender/graphic/mixin/RectText
  6857. */
  6858. function Displayable(opts) {
  6859. opts = opts || {};
  6860. Element.call(this, opts);
  6861. // Extend properties
  6862. for (var name in opts) {
  6863. if (
  6864. opts.hasOwnProperty(name) &&
  6865. name !== 'style'
  6866. ) {
  6867. this[name] = opts[name];
  6868. }
  6869. }
  6870. /**
  6871. * @type {module:zrender/graphic/Style}
  6872. */
  6873. this.style = new Style(opts.style, this);
  6874. this._rect = null;
  6875. // Shapes for cascade clipping.
  6876. this.__clipPaths = [];
  6877. // FIXME Stateful must be mixined after style is setted
  6878. // Stateful.call(this, opts);
  6879. }
  6880. Displayable.prototype = {
  6881. constructor: Displayable,
  6882. type: 'displayable',
  6883. /**
  6884. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  6885. * Dirty flag. From which painter will determine if this displayable object needs brush
  6886. * @name module:zrender/graphic/Displayable#__dirty
  6887. * @type {boolean}
  6888. */
  6889. __dirty: true,
  6890. /**
  6891. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  6892. * If ignore drawing of the displayable object. Mouse event will still be triggered
  6893. * @name module:/zrender/graphic/Displayable#invisible
  6894. * @type {boolean}
  6895. * @default false
  6896. */
  6897. invisible: false,
  6898. /**
  6899. * @name module:/zrender/graphic/Displayable#z
  6900. * @type {number}
  6901. * @default 0
  6902. */
  6903. z: 0,
  6904. /**
  6905. * @name module:/zrender/graphic/Displayable#z
  6906. * @type {number}
  6907. * @default 0
  6908. */
  6909. z2: 0,
  6910. /**
  6911. * z层level,决定绘画在哪层canvas中
  6912. * @name module:/zrender/graphic/Displayable#zlevel
  6913. * @type {number}
  6914. * @default 0
  6915. */
  6916. zlevel: 0,
  6917. /**
  6918. * 是否可拖拽
  6919. * @name module:/zrender/graphic/Displayable#draggable
  6920. * @type {boolean}
  6921. * @default false
  6922. */
  6923. draggable: false,
  6924. /**
  6925. * 是否正在拖拽
  6926. * @name module:/zrender/graphic/Displayable#draggable
  6927. * @type {boolean}
  6928. * @default false
  6929. */
  6930. dragging: false,
  6931. /**
  6932. * 是否相应鼠标事件
  6933. * @name module:/zrender/graphic/Displayable#silent
  6934. * @type {boolean}
  6935. * @default false
  6936. */
  6937. silent: false,
  6938. /**
  6939. * If enable culling
  6940. * @type {boolean}
  6941. * @default false
  6942. */
  6943. culling: false,
  6944. /**
  6945. * Mouse cursor when hovered
  6946. * @name module:/zrender/graphic/Displayable#cursor
  6947. * @type {string}
  6948. */
  6949. cursor: 'pointer',
  6950. /**
  6951. * If hover area is bounding rect
  6952. * @name module:/zrender/graphic/Displayable#rectHover
  6953. * @type {string}
  6954. */
  6955. rectHover: false,
  6956. /**
  6957. * Render the element progressively when the value >= 0,
  6958. * usefull for large data.
  6959. * @type {boolean}
  6960. */
  6961. progressive: false,
  6962. /**
  6963. * @type {boolean}
  6964. */
  6965. incremental: false,
  6966. // inplace is used with incremental
  6967. inplace: false,
  6968. beforeBrush: function (ctx) {},
  6969. afterBrush: function (ctx) {},
  6970. /**
  6971. * 图形绘制方法
  6972. * @param {CanvasRenderingContext2D} ctx
  6973. */
  6974. // Interface
  6975. brush: function (ctx, prevEl) {},
  6976. /**
  6977. * 获取最小包围盒
  6978. * @return {module:zrender/core/BoundingRect}
  6979. */
  6980. // Interface
  6981. getBoundingRect: function () {},
  6982. /**
  6983. * 判断坐标 x, y 是否在图形上
  6984. * If displayable element contain coord x, y
  6985. * @param {number} x
  6986. * @param {number} y
  6987. * @return {boolean}
  6988. */
  6989. contain: function (x, y) {
  6990. return this.rectContain(x, y);
  6991. },
  6992. /**
  6993. * @param {Function} cb
  6994. * @param {} context
  6995. */
  6996. traverse: function (cb, context) {
  6997. cb.call(context, this);
  6998. },
  6999. /**
  7000. * 判断坐标 x, y 是否在图形的包围盒上
  7001. * If bounding rect of element contain coord x, y
  7002. * @param {number} x
  7003. * @param {number} y
  7004. * @return {boolean}
  7005. */
  7006. rectContain: function (x, y) {
  7007. var coord = this.transformCoordToLocal(x, y);
  7008. var rect = this.getBoundingRect();
  7009. return rect.contain(coord[0], coord[1]);
  7010. },
  7011. /**
  7012. * 标记图形元素为脏,并且在下一帧重绘
  7013. * Mark displayable element dirty and refresh next frame
  7014. */
  7015. dirty: function () {
  7016. this.__dirty = true;
  7017. this._rect = null;
  7018. this.__zr && this.__zr.refresh();
  7019. },
  7020. /**
  7021. * 图形是否会触发事件
  7022. * If displayable object binded any event
  7023. * @return {boolean}
  7024. */
  7025. // TODO, 通过 bind 绑定的事件
  7026. // isSilent: function () {
  7027. // return !(
  7028. // this.hoverable || this.draggable
  7029. // || this.onmousemove || this.onmouseover || this.onmouseout
  7030. // || this.onmousedown || this.onmouseup || this.onclick
  7031. // || this.ondragenter || this.ondragover || this.ondragleave
  7032. // || this.ondrop
  7033. // );
  7034. // },
  7035. /**
  7036. * Alias for animate('style')
  7037. * @param {boolean} loop
  7038. */
  7039. animateStyle: function (loop) {
  7040. return this.animate('style', loop);
  7041. },
  7042. attrKV: function (key, value) {
  7043. if (key !== 'style') {
  7044. Element.prototype.attrKV.call(this, key, value);
  7045. }
  7046. else {
  7047. this.style.set(value);
  7048. }
  7049. },
  7050. /**
  7051. * @param {Object|string} key
  7052. * @param {*} value
  7053. */
  7054. setStyle: function (key, value) {
  7055. this.style.set(key, value);
  7056. this.dirty(false);
  7057. return this;
  7058. },
  7059. /**
  7060. * Use given style object
  7061. * @param {Object} obj
  7062. */
  7063. useStyle: function (obj) {
  7064. this.style = new Style(obj, this);
  7065. this.dirty(false);
  7066. return this;
  7067. }
  7068. };
  7069. inherits(Displayable, Element);
  7070. mixin(Displayable, RectText);
  7071. /**
  7072. * @alias zrender/graphic/Image
  7073. * @extends module:zrender/graphic/Displayable
  7074. * @constructor
  7075. * @param {Object} opts
  7076. */
  7077. function ZImage(opts) {
  7078. Displayable.call(this, opts);
  7079. }
  7080. ZImage.prototype = {
  7081. constructor: ZImage,
  7082. type: 'image',
  7083. brush: function (ctx, prevEl) {
  7084. var style = this.style;
  7085. var src = style.image;
  7086. // Must bind each time
  7087. style.bind(ctx, this, prevEl);
  7088. var image = this._image = createOrUpdateImage(
  7089. src,
  7090. this._image,
  7091. this,
  7092. this.onload
  7093. );
  7094. if (!image || !isImageReady(image)) {
  7095. return;
  7096. }
  7097. // 图片已经加载完成
  7098. // if (image.nodeName.toUpperCase() == 'IMG') {
  7099. // if (!image.complete) {
  7100. // return;
  7101. // }
  7102. // }
  7103. // Else is canvas
  7104. var x = style.x || 0;
  7105. var y = style.y || 0;
  7106. var width = style.width;
  7107. var height = style.height;
  7108. var aspect = image.width / image.height;
  7109. if (width == null && height != null) {
  7110. // Keep image/height ratio
  7111. width = height * aspect;
  7112. }
  7113. else if (height == null && width != null) {
  7114. height = width / aspect;
  7115. }
  7116. else if (width == null && height == null) {
  7117. width = image.width;
  7118. height = image.height;
  7119. }
  7120. // 设置transform
  7121. this.setTransform(ctx);
  7122. if (style.sWidth && style.sHeight) {
  7123. var sx = style.sx || 0;
  7124. var sy = style.sy || 0;
  7125. ctx.drawImage(
  7126. image,
  7127. sx, sy, style.sWidth, style.sHeight,
  7128. x, y, width, height
  7129. );
  7130. }
  7131. else if (style.sx && style.sy) {
  7132. var sx = style.sx;
  7133. var sy = style.sy;
  7134. var sWidth = width - sx;
  7135. var sHeight = height - sy;
  7136. ctx.drawImage(
  7137. image,
  7138. sx, sy, sWidth, sHeight,
  7139. x, y, width, height
  7140. );
  7141. }
  7142. else {
  7143. ctx.drawImage(image, x, y, width, height);
  7144. }
  7145. // Draw rect text
  7146. if (style.text != null) {
  7147. // Only restore transform when needs draw text.
  7148. this.restoreTransform(ctx);
  7149. this.drawRectText(ctx, this.getBoundingRect());
  7150. }
  7151. },
  7152. getBoundingRect: function () {
  7153. var style = this.style;
  7154. if (! this._rect) {
  7155. this._rect = new BoundingRect(
  7156. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7157. );
  7158. }
  7159. return this._rect;
  7160. }
  7161. };
  7162. inherits(ZImage, Displayable);
  7163. var HOVER_LAYER_ZLEVEL = 1e5;
  7164. var CANVAS_ZLEVEL = 314159;
  7165. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7166. var INCREMENTAL_INC = 0.001;
  7167. function parseInt10(val) {
  7168. return parseInt(val, 10);
  7169. }
  7170. function isLayerValid(layer) {
  7171. if (!layer) {
  7172. return false;
  7173. }
  7174. if (layer.__builtin__) {
  7175. return true;
  7176. }
  7177. if (typeof(layer.resize) !== 'function'
  7178. || typeof(layer.refresh) !== 'function'
  7179. ) {
  7180. return false;
  7181. }
  7182. return true;
  7183. }
  7184. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7185. var viewRect = new BoundingRect(0, 0, 0, 0);
  7186. function isDisplayableCulled(el, width, height) {
  7187. tmpRect.copy(el.getBoundingRect());
  7188. if (el.transform) {
  7189. tmpRect.applyTransform(el.transform);
  7190. }
  7191. viewRect.width = width;
  7192. viewRect.height = height;
  7193. return !tmpRect.intersect(viewRect);
  7194. }
  7195. function isClipPathChanged(clipPaths, prevClipPaths) {
  7196. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7197. return false;
  7198. }
  7199. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7200. return true;
  7201. }
  7202. for (var i = 0; i < clipPaths.length; i++) {
  7203. if (clipPaths[i] !== prevClipPaths[i]) {
  7204. return true;
  7205. }
  7206. }
  7207. }
  7208. function doClip(clipPaths, ctx) {
  7209. for (var i = 0; i < clipPaths.length; i++) {
  7210. var clipPath = clipPaths[i];
  7211. clipPath.setTransform(ctx);
  7212. ctx.beginPath();
  7213. clipPath.buildPath(ctx, clipPath.shape);
  7214. ctx.clip();
  7215. // Transform back
  7216. clipPath.restoreTransform(ctx);
  7217. }
  7218. }
  7219. function createRoot(width, height) {
  7220. var domRoot = document.createElement('div');
  7221. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7222. domRoot.style.cssText = [
  7223. 'position:relative',
  7224. 'overflow:hidden',
  7225. 'width:' + width + 'px',
  7226. 'height:' + height + 'px',
  7227. 'padding:0',
  7228. 'margin:0',
  7229. 'border-width:0'
  7230. ].join(';') + ';';
  7231. return domRoot;
  7232. }
  7233. /**
  7234. * @alias module:zrender/Painter
  7235. * @constructor
  7236. * @param {HTMLElement} root 绘图容器
  7237. * @param {module:zrender/Storage} storage
  7238. * @param {Object} opts
  7239. */
  7240. var Painter = function (root, storage, opts) {
  7241. this.type = 'canvas';
  7242. // In node environment using node-canvas
  7243. var singleCanvas = !root.nodeName // In node ?
  7244. || root.nodeName.toUpperCase() === 'CANVAS';
  7245. this._opts = opts = extend({}, opts || {});
  7246. /**
  7247. * @type {number}
  7248. */
  7249. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7250. /**
  7251. * @type {boolean}
  7252. * @private
  7253. */
  7254. this._singleCanvas = singleCanvas;
  7255. /**
  7256. * 绘图容器
  7257. * @type {HTMLElement}
  7258. */
  7259. this.root = root;
  7260. var rootStyle = root.style;
  7261. if (rootStyle) {
  7262. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7263. rootStyle['-webkit-user-select'] =
  7264. rootStyle['user-select'] =
  7265. rootStyle['-webkit-touch-callout'] = 'none';
  7266. root.innerHTML = '';
  7267. }
  7268. /**
  7269. * @type {module:zrender/Storage}
  7270. */
  7271. this.storage = storage;
  7272. /**
  7273. * @type {Array.<number>}
  7274. * @private
  7275. */
  7276. var zlevelList = this._zlevelList = [];
  7277. /**
  7278. * @type {Object.<string, module:zrender/Layer>}
  7279. * @private
  7280. */
  7281. var layers = this._layers = {};
  7282. /**
  7283. * @type {Object.<string, Object>}
  7284. * @private
  7285. */
  7286. this._layerConfig = {};
  7287. /**
  7288. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7289. */
  7290. this._needsManuallyCompositing = false;
  7291. if (!singleCanvas) {
  7292. this._width = this._getSize(0);
  7293. this._height = this._getSize(1);
  7294. var domRoot = this._domRoot = createRoot(
  7295. this._width, this._height
  7296. );
  7297. root.appendChild(domRoot);
  7298. }
  7299. else {
  7300. if (opts.width != null) {
  7301. root.width = opts.width;
  7302. }
  7303. if (opts.height != null) {
  7304. root.height = opts.height;
  7305. }
  7306. // Use canvas width and height directly
  7307. var width = root.width;
  7308. var height = root.height;
  7309. this._width = width;
  7310. this._height = height;
  7311. // Create layer if only one given canvas
  7312. // Device pixel ratio is fixed to 1 because given canvas has its specified width and height
  7313. var mainLayer = new Layer(root, this, 1);
  7314. mainLayer.__builtin__ = true;
  7315. mainLayer.initContext();
  7316. // FIXME Use canvas width and height
  7317. // mainLayer.resize(width, height);
  7318. layers[CANVAS_ZLEVEL] = mainLayer;
  7319. // Not use common zlevel.
  7320. zlevelList.push(CANVAS_ZLEVEL);
  7321. this._domRoot = root;
  7322. }
  7323. /**
  7324. * @type {module:zrender/Layer}
  7325. * @private
  7326. */
  7327. this._hoverlayer = null;
  7328. this._hoverElements = [];
  7329. };
  7330. Painter.prototype = {
  7331. constructor: Painter,
  7332. getType: function () {
  7333. return 'canvas';
  7334. },
  7335. /**
  7336. * If painter use a single canvas
  7337. * @return {boolean}
  7338. */
  7339. isSingleCanvas: function () {
  7340. return this._singleCanvas;
  7341. },
  7342. /**
  7343. * @return {HTMLDivElement}
  7344. */
  7345. getViewportRoot: function () {
  7346. return this._domRoot;
  7347. },
  7348. getViewportRootOffset: function () {
  7349. var viewportRoot = this.getViewportRoot();
  7350. if (viewportRoot) {
  7351. return {
  7352. offsetLeft: viewportRoot.offsetLeft || 0,
  7353. offsetTop: viewportRoot.offsetTop || 0
  7354. };
  7355. }
  7356. },
  7357. /**
  7358. * 刷新
  7359. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7360. */
  7361. refresh: function (paintAll) {
  7362. var list = this.storage.getDisplayList(true);
  7363. var zlevelList = this._zlevelList;
  7364. this._redrawId = Math.random();
  7365. this._paintList(list, paintAll, this._redrawId);
  7366. // Paint custum layers
  7367. for (var i = 0; i < zlevelList.length; i++) {
  7368. var z = zlevelList[i];
  7369. var layer = this._layers[z];
  7370. if (!layer.__builtin__ && layer.refresh) {
  7371. layer.refresh();
  7372. }
  7373. }
  7374. this.refreshHover();
  7375. return this;
  7376. },
  7377. addHover: function (el, hoverStyle) {
  7378. if (el.__hoverMir) {
  7379. return;
  7380. }
  7381. var elMirror = new el.constructor({
  7382. style: el.style,
  7383. shape: el.shape
  7384. });
  7385. elMirror.__from = el;
  7386. el.__hoverMir = elMirror;
  7387. elMirror.setStyle(hoverStyle);
  7388. this._hoverElements.push(elMirror);
  7389. },
  7390. removeHover: function (el) {
  7391. var elMirror = el.__hoverMir;
  7392. var hoverElements = this._hoverElements;
  7393. var idx = indexOf(hoverElements, elMirror);
  7394. if (idx >= 0) {
  7395. hoverElements.splice(idx, 1);
  7396. }
  7397. el.__hoverMir = null;
  7398. },
  7399. clearHover: function (el) {
  7400. var hoverElements = this._hoverElements;
  7401. for (var i = 0; i < hoverElements.length; i++) {
  7402. var from = hoverElements[i].__from;
  7403. if (from) {
  7404. from.__hoverMir = null;
  7405. }
  7406. }
  7407. hoverElements.length = 0;
  7408. },
  7409. refreshHover: function () {
  7410. var hoverElements = this._hoverElements;
  7411. var len = hoverElements.length;
  7412. var hoverLayer = this._hoverlayer;
  7413. hoverLayer && hoverLayer.clear();
  7414. if (!len) {
  7415. return;
  7416. }
  7417. sort(hoverElements, this.storage.displayableSortFunc);
  7418. // Use a extream large zlevel
  7419. // FIXME?
  7420. if (!hoverLayer) {
  7421. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7422. }
  7423. var scope = {};
  7424. hoverLayer.ctx.save();
  7425. for (var i = 0; i < len;) {
  7426. var el = hoverElements[i];
  7427. var originalEl = el.__from;
  7428. // Original el is removed
  7429. // PENDING
  7430. if (!(originalEl && originalEl.__zr)) {
  7431. hoverElements.splice(i, 1);
  7432. originalEl.__hoverMir = null;
  7433. len--;
  7434. continue;
  7435. }
  7436. i++;
  7437. // Use transform
  7438. // FIXME style and shape ?
  7439. if (!originalEl.invisible) {
  7440. el.transform = originalEl.transform;
  7441. el.invTransform = originalEl.invTransform;
  7442. el.__clipPaths = originalEl.__clipPaths;
  7443. // el.
  7444. this._doPaintEl(el, hoverLayer, true, scope);
  7445. }
  7446. }
  7447. hoverLayer.ctx.restore();
  7448. },
  7449. getHoverLayer: function () {
  7450. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7451. },
  7452. _paintList: function (list, paintAll, redrawId) {
  7453. if (this._redrawId !== redrawId) {
  7454. return;
  7455. }
  7456. paintAll = paintAll || false;
  7457. this._updateLayerStatus(list);
  7458. var finished = this._doPaintList(list, paintAll);
  7459. if (this._needsManuallyCompositing) {
  7460. this._compositeManually();
  7461. }
  7462. if (!finished) {
  7463. var self = this;
  7464. requestAnimationFrame(function () {
  7465. self._paintList(list, paintAll, redrawId);
  7466. });
  7467. }
  7468. },
  7469. _compositeManually: function () {
  7470. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7471. var width = this._domRoot.width;
  7472. var height = this._domRoot.height;
  7473. ctx.clearRect(0, 0, width, height);
  7474. // PENDING, If only builtin layer?
  7475. this.eachBuiltinLayer(function (layer) {
  7476. if (layer.virtual) {
  7477. ctx.drawImage(layer.dom, 0, 0, width, height);
  7478. }
  7479. });
  7480. },
  7481. _doPaintList: function (list, paintAll) {
  7482. var layerList = [];
  7483. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7484. var zlevel = this._zlevelList[zi];
  7485. var layer = this._layers[zlevel];
  7486. if (layer.__builtin__
  7487. && layer !== this._hoverlayer
  7488. && (layer.__dirty || paintAll)
  7489. ) {
  7490. layerList.push(layer);
  7491. }
  7492. }
  7493. var finished = true;
  7494. for (var k = 0; k < layerList.length; k++) {
  7495. var layer = layerList[k];
  7496. var ctx = layer.ctx;
  7497. var scope = {};
  7498. ctx.save();
  7499. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7500. var useTimer = !paintAll && layer.incremental && Date.now;
  7501. var startTime = useTimer && Date.now();
  7502. // All elements in this layer are cleared.
  7503. if (layer.__startIndex === layer.__endIndex) {
  7504. layer.clear();
  7505. }
  7506. else if (start === layer.__startIndex) {
  7507. var firstEl = list[start];
  7508. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7509. layer.clear();
  7510. }
  7511. }
  7512. if (start === -1) {
  7513. console.error('For some unknown reason. drawIndex is -1');
  7514. start = layer.__startIndex;
  7515. }
  7516. for (var i = start; i < layer.__endIndex; i++) {
  7517. var el = list[i];
  7518. this._doPaintEl(el, layer, paintAll, scope);
  7519. el.__dirty = false;
  7520. if (useTimer) {
  7521. // Date.now can be executed in 13,025,305 ops/second.
  7522. var dTime = Date.now() - startTime;
  7523. // Give 15 millisecond to draw.
  7524. // The rest elements will be drawn in the next frame.
  7525. if (dTime > 15) {
  7526. break;
  7527. }
  7528. }
  7529. }
  7530. layer.__drawIndex = i;
  7531. if (layer.__drawIndex < layer.__endIndex) {
  7532. finished = false;
  7533. }
  7534. if (scope.prevElClipPaths) {
  7535. // Needs restore the state. If last drawn element is in the clipping area.
  7536. ctx.restore();
  7537. }
  7538. ctx.restore();
  7539. }
  7540. if (env$1.wxa) {
  7541. // Flush for weixin application
  7542. each$1(this._layers, function (layer) {
  7543. if (layer && layer.ctx && layer.ctx.draw) {
  7544. layer.ctx.draw();
  7545. }
  7546. });
  7547. }
  7548. return finished;
  7549. },
  7550. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7551. var ctx = currentLayer.ctx;
  7552. var m = el.transform;
  7553. if (
  7554. (currentLayer.__dirty || forcePaint)
  7555. // Ignore invisible element
  7556. && !el.invisible
  7557. // Ignore transparent element
  7558. && el.style.opacity !== 0
  7559. // Ignore scale 0 element, in some environment like node-canvas
  7560. // Draw a scale 0 element can cause all following draw wrong
  7561. // And setTransform with scale 0 will cause set back transform failed.
  7562. && !(m && !m[0] && !m[3])
  7563. // Ignore culled element
  7564. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7565. ) {
  7566. var clipPaths = el.__clipPaths;
  7567. // Optimize when clipping on group with several elements
  7568. if (!scope.prevElClipPaths
  7569. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7570. ) {
  7571. // If has previous clipping state, restore from it
  7572. if (scope.prevElClipPaths) {
  7573. currentLayer.ctx.restore();
  7574. scope.prevElClipPaths = null;
  7575. // Reset prevEl since context has been restored
  7576. scope.prevEl = null;
  7577. }
  7578. // New clipping state
  7579. if (clipPaths) {
  7580. ctx.save();
  7581. doClip(clipPaths, ctx);
  7582. scope.prevElClipPaths = clipPaths;
  7583. }
  7584. }
  7585. el.beforeBrush && el.beforeBrush(ctx);
  7586. el.brush(ctx, scope.prevEl || null);
  7587. scope.prevEl = el;
  7588. el.afterBrush && el.afterBrush(ctx);
  7589. }
  7590. },
  7591. /**
  7592. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7593. * @param {number} zlevel
  7594. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7595. * @return {module:zrender/Layer}
  7596. */
  7597. getLayer: function (zlevel, virtual) {
  7598. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7599. zlevel = CANVAS_ZLEVEL;
  7600. }
  7601. var layer = this._layers[zlevel];
  7602. if (!layer) {
  7603. // Create a new layer
  7604. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7605. layer.zlevel = zlevel;
  7606. layer.__builtin__ = true;
  7607. if (this._layerConfig[zlevel]) {
  7608. merge(layer, this._layerConfig[zlevel], true);
  7609. }
  7610. if (virtual) {
  7611. layer.virtual = virtual;
  7612. }
  7613. this.insertLayer(zlevel, layer);
  7614. // Context is created after dom inserted to document
  7615. // Or excanvas will get 0px clientWidth and clientHeight
  7616. layer.initContext();
  7617. }
  7618. return layer;
  7619. },
  7620. insertLayer: function (zlevel, layer) {
  7621. var layersMap = this._layers;
  7622. var zlevelList = this._zlevelList;
  7623. var len = zlevelList.length;
  7624. var prevLayer = null;
  7625. var i = -1;
  7626. var domRoot = this._domRoot;
  7627. if (layersMap[zlevel]) {
  7628. log$1('ZLevel ' + zlevel + ' has been used already');
  7629. return;
  7630. }
  7631. // Check if is a valid layer
  7632. if (!isLayerValid(layer)) {
  7633. log$1('Layer of zlevel ' + zlevel + ' is not valid');
  7634. return;
  7635. }
  7636. if (len > 0 && zlevel > zlevelList[0]) {
  7637. for (i = 0; i < len - 1; i++) {
  7638. if (
  7639. zlevelList[i] < zlevel
  7640. && zlevelList[i + 1] > zlevel
  7641. ) {
  7642. break;
  7643. }
  7644. }
  7645. prevLayer = layersMap[zlevelList[i]];
  7646. }
  7647. zlevelList.splice(i + 1, 0, zlevel);
  7648. layersMap[zlevel] = layer;
  7649. // Vitual layer will not directly show on the screen.
  7650. // (It can be a WebGL layer and assigned to a ZImage element)
  7651. // But it still under management of zrender.
  7652. if (!layer.virtual) {
  7653. if (prevLayer) {
  7654. var prevDom = prevLayer.dom;
  7655. if (prevDom.nextSibling) {
  7656. domRoot.insertBefore(
  7657. layer.dom,
  7658. prevDom.nextSibling
  7659. );
  7660. }
  7661. else {
  7662. domRoot.appendChild(layer.dom);
  7663. }
  7664. }
  7665. else {
  7666. if (domRoot.firstChild) {
  7667. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  7668. }
  7669. else {
  7670. domRoot.appendChild(layer.dom);
  7671. }
  7672. }
  7673. }
  7674. },
  7675. // Iterate each layer
  7676. eachLayer: function (cb, context) {
  7677. var zlevelList = this._zlevelList;
  7678. var z;
  7679. var i;
  7680. for (i = 0; i < zlevelList.length; i++) {
  7681. z = zlevelList[i];
  7682. cb.call(context, this._layers[z], z);
  7683. }
  7684. },
  7685. // Iterate each buildin layer
  7686. eachBuiltinLayer: function (cb, context) {
  7687. var zlevelList = this._zlevelList;
  7688. var layer;
  7689. var z;
  7690. var i;
  7691. for (i = 0; i < zlevelList.length; i++) {
  7692. z = zlevelList[i];
  7693. layer = this._layers[z];
  7694. if (layer.__builtin__) {
  7695. cb.call(context, layer, z);
  7696. }
  7697. }
  7698. },
  7699. // Iterate each other layer except buildin layer
  7700. eachOtherLayer: function (cb, context) {
  7701. var zlevelList = this._zlevelList;
  7702. var layer;
  7703. var z;
  7704. var i;
  7705. for (i = 0; i < zlevelList.length; i++) {
  7706. z = zlevelList[i];
  7707. layer = this._layers[z];
  7708. if (!layer.__builtin__) {
  7709. cb.call(context, layer, z);
  7710. }
  7711. }
  7712. },
  7713. /**
  7714. * 获取所有已创建的层
  7715. * @param {Array.<module:zrender/Layer>} [prevLayer]
  7716. */
  7717. getLayers: function () {
  7718. return this._layers;
  7719. },
  7720. _updateLayerStatus: function (list) {
  7721. this.eachBuiltinLayer(function (layer, z) {
  7722. layer.__dirty = layer.__used = false;
  7723. });
  7724. function updatePrevLayer(idx) {
  7725. if (prevLayer) {
  7726. if (prevLayer.__endIndex !== idx) {
  7727. prevLayer.__dirty = true;
  7728. }
  7729. prevLayer.__endIndex = idx;
  7730. }
  7731. }
  7732. if (this._singleCanvas) {
  7733. for (var i = 1; i < list.length; i++) {
  7734. var el = list[i];
  7735. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  7736. this._needsManuallyCompositing = true;
  7737. break;
  7738. }
  7739. }
  7740. }
  7741. var prevLayer = null;
  7742. var incrementalLayerCount = 0;
  7743. for (var i = 0; i < list.length; i++) {
  7744. var el = list[i];
  7745. var zlevel = el.zlevel;
  7746. var layer;
  7747. // PENDING If change one incremental element style ?
  7748. // TODO Where there are non-incremental elements between incremental elements.
  7749. if (el.incremental) {
  7750. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  7751. layer.incremental = true;
  7752. incrementalLayerCount = 1;
  7753. }
  7754. else {
  7755. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  7756. }
  7757. if (!layer.__builtin__) {
  7758. log$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  7759. }
  7760. if (layer !== prevLayer) {
  7761. layer.__used = true;
  7762. if (layer.__startIndex !== i) {
  7763. layer.__dirty = true;
  7764. }
  7765. layer.__startIndex = i;
  7766. if (!layer.incremental) {
  7767. layer.__drawIndex = i;
  7768. }
  7769. else {
  7770. // Mark layer draw index needs to update.
  7771. layer.__drawIndex = -1;
  7772. }
  7773. updatePrevLayer(i);
  7774. prevLayer = layer;
  7775. }
  7776. if (el.__dirty) {
  7777. layer.__dirty = true;
  7778. if (layer.incremental && layer.__drawIndex < 0) {
  7779. // Start draw from the first dirty element.
  7780. layer.__drawIndex = i;
  7781. }
  7782. }
  7783. }
  7784. updatePrevLayer(i);
  7785. this.eachBuiltinLayer(function (layer, z) {
  7786. // Used in last frame but not in this frame. Needs clear
  7787. if (!layer.__used && layer.getElementCount() > 0) {
  7788. layer.__dirty = true;
  7789. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  7790. }
  7791. // For incremental layer. In case start index changed and no elements are dirty.
  7792. if (layer.__dirty && layer.__drawIndex < 0) {
  7793. layer.__drawIndex = layer.__startIndex;
  7794. }
  7795. });
  7796. },
  7797. /**
  7798. * 清除hover层外所有内容
  7799. */
  7800. clear: function () {
  7801. this.eachBuiltinLayer(this._clearLayer);
  7802. return this;
  7803. },
  7804. _clearLayer: function (layer) {
  7805. layer.clear();
  7806. },
  7807. /**
  7808. * 修改指定zlevel的绘制参数
  7809. *
  7810. * @param {string} zlevel
  7811. * @param {Object} config 配置对象
  7812. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  7813. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  7814. * @param {number} [config.lastFrameAlpha=0.7]
  7815. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  7816. */
  7817. configLayer: function (zlevel, config) {
  7818. if (config) {
  7819. var layerConfig = this._layerConfig;
  7820. if (!layerConfig[zlevel]) {
  7821. layerConfig[zlevel] = config;
  7822. }
  7823. else {
  7824. merge(layerConfig[zlevel], config, true);
  7825. }
  7826. for (var i = 0; i < this._zlevelList.length; i++) {
  7827. var _zlevel = this._zlevelList[i];
  7828. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  7829. var layer = this._layers[_zlevel];
  7830. merge(layer, layerConfig[zlevel], true);
  7831. }
  7832. }
  7833. }
  7834. },
  7835. /**
  7836. * 删除指定层
  7837. * @param {number} zlevel 层所在的zlevel
  7838. */
  7839. delLayer: function (zlevel) {
  7840. var layers = this._layers;
  7841. var zlevelList = this._zlevelList;
  7842. var layer = layers[zlevel];
  7843. if (!layer) {
  7844. return;
  7845. }
  7846. layer.dom.parentNode.removeChild(layer.dom);
  7847. delete layers[zlevel];
  7848. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  7849. },
  7850. /**
  7851. * 区域大小变化后重绘
  7852. */
  7853. resize: function (width, height) {
  7854. if (!this._domRoot.style) { // Maybe in node or worker
  7855. if (width == null || height == null) {
  7856. return;
  7857. }
  7858. this._width = width;
  7859. this._height = height;
  7860. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  7861. }
  7862. else {
  7863. var domRoot = this._domRoot;
  7864. // FIXME Why ?
  7865. domRoot.style.display = 'none';
  7866. // Save input w/h
  7867. var opts = this._opts;
  7868. width != null && (opts.width = width);
  7869. height != null && (opts.height = height);
  7870. width = this._getSize(0);
  7871. height = this._getSize(1);
  7872. domRoot.style.display = '';
  7873. // 优化没有实际改变的resize
  7874. if (this._width != width || height != this._height) {
  7875. domRoot.style.width = width + 'px';
  7876. domRoot.style.height = height + 'px';
  7877. for (var id in this._layers) {
  7878. if (this._layers.hasOwnProperty(id)) {
  7879. this._layers[id].resize(width, height);
  7880. }
  7881. }
  7882. each$1(this._progressiveLayers, function (layer) {
  7883. layer.resize(width, height);
  7884. });
  7885. this.refresh(true);
  7886. }
  7887. this._width = width;
  7888. this._height = height;
  7889. }
  7890. return this;
  7891. },
  7892. /**
  7893. * 清除单独的一个层
  7894. * @param {number} zlevel
  7895. */
  7896. clearLayer: function (zlevel) {
  7897. var layer = this._layers[zlevel];
  7898. if (layer) {
  7899. layer.clear();
  7900. }
  7901. },
  7902. /**
  7903. * 释放
  7904. */
  7905. dispose: function () {
  7906. this.root.innerHTML = '';
  7907. this.root =
  7908. this.storage =
  7909. this._domRoot =
  7910. this._layers = null;
  7911. },
  7912. /**
  7913. * Get canvas which has all thing rendered
  7914. * @param {Object} opts
  7915. * @param {string} [opts.backgroundColor]
  7916. * @param {number} [opts.pixelRatio]
  7917. */
  7918. getRenderedCanvas: function (opts) {
  7919. opts = opts || {};
  7920. if (this._singleCanvas && !this._compositeManually) {
  7921. return this._layers[CANVAS_ZLEVEL].dom;
  7922. }
  7923. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  7924. imageLayer.initContext();
  7925. imageLayer.clearColor = opts.backgroundColor;
  7926. imageLayer.clear();
  7927. if (opts.pixelRatio <= this.dpr) {
  7928. this.refresh();
  7929. var width = imageLayer.dom.width;
  7930. var height = imageLayer.dom.height;
  7931. var ctx = imageLayer.ctx;
  7932. this.eachLayer(function (layer) {
  7933. if (layer.__builtin__) {
  7934. ctx.drawImage(layer.dom, 0, 0, width, height);
  7935. }
  7936. else if (layer.renderToCanvas) {
  7937. imageLayer.ctx.save();
  7938. layer.renderToCanvas(imageLayer.ctx);
  7939. imageLayer.ctx.restore();
  7940. }
  7941. });
  7942. }
  7943. else {
  7944. // PENDING, echarts-gl and incremental rendering.
  7945. var scope = {};
  7946. var displayList = this.storage.getDisplayList(true);
  7947. for (var i = 0; i < displayList.length; i++) {
  7948. var el = displayList[i];
  7949. this._doPaintEl(el, imageLayer, true, scope);
  7950. }
  7951. }
  7952. return imageLayer.dom;
  7953. },
  7954. /**
  7955. * 获取绘图区域宽度
  7956. */
  7957. getWidth: function () {
  7958. return this._width;
  7959. },
  7960. /**
  7961. * 获取绘图区域高度
  7962. */
  7963. getHeight: function () {
  7964. return this._height;
  7965. },
  7966. _getSize: function (whIdx) {
  7967. var opts = this._opts;
  7968. var wh = ['width', 'height'][whIdx];
  7969. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  7970. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  7971. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  7972. if (opts[wh] != null && opts[wh] !== 'auto') {
  7973. return parseFloat(opts[wh]);
  7974. }
  7975. var root = this.root;
  7976. // IE8 does not support getComputedStyle, but it use VML.
  7977. var stl = document.defaultView.getComputedStyle(root);
  7978. return (
  7979. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  7980. - (parseInt10(stl[plt]) || 0)
  7981. - (parseInt10(stl[prb]) || 0)
  7982. ) | 0;
  7983. },
  7984. pathToImage: function (path, dpr) {
  7985. dpr = dpr || this.dpr;
  7986. var canvas = document.createElement('canvas');
  7987. var ctx = canvas.getContext('2d');
  7988. var rect = path.getBoundingRect();
  7989. var style = path.style;
  7990. var shadowBlurSize = style.shadowBlur * dpr;
  7991. var shadowOffsetX = style.shadowOffsetX * dpr;
  7992. var shadowOffsetY = style.shadowOffsetY * dpr;
  7993. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  7994. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  7995. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  7996. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  7997. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  7998. var width = rect.width + leftMargin + rightMargin;
  7999. var height = rect.height + topMargin + bottomMargin;
  8000. canvas.width = width * dpr;
  8001. canvas.height = height * dpr;
  8002. ctx.scale(dpr, dpr);
  8003. ctx.clearRect(0, 0, width, height);
  8004. ctx.dpr = dpr;
  8005. var pathTransform = {
  8006. position: path.position,
  8007. rotation: path.rotation,
  8008. scale: path.scale
  8009. };
  8010. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8011. path.rotation = 0;
  8012. path.scale = [1, 1];
  8013. path.updateTransform();
  8014. if (path) {
  8015. path.brush(ctx);
  8016. }
  8017. var ImageShape = ZImage;
  8018. var imgShape = new ImageShape({
  8019. style: {
  8020. x: 0,
  8021. y: 0,
  8022. image: canvas
  8023. }
  8024. });
  8025. if (pathTransform.position != null) {
  8026. imgShape.position = path.position = pathTransform.position;
  8027. }
  8028. if (pathTransform.rotation != null) {
  8029. imgShape.rotation = path.rotation = pathTransform.rotation;
  8030. }
  8031. if (pathTransform.scale != null) {
  8032. imgShape.scale = path.scale = pathTransform.scale;
  8033. }
  8034. return imgShape;
  8035. }
  8036. };
  8037. /**
  8038. * 事件辅助类
  8039. * @module zrender/core/event
  8040. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8041. */
  8042. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8043. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8044. function getBoundingClientRect(el) {
  8045. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8046. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8047. }
  8048. // `calculate` is optional, default false
  8049. function clientToLocal(el, e, out, calculate) {
  8050. out = out || {};
  8051. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8052. // to the padding edge of the target element. The only browser using this convention
  8053. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8054. // not support the properties.
  8055. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8056. // In zr painter.dom, padding edge equals to border edge.
  8057. // FIXME
  8058. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8059. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8060. // is too complex. So css-transfrom dont support in this case temporarily.
  8061. if (calculate || !env$1.canvasSupported) {
  8062. defaultGetZrXY(el, e, out);
  8063. }
  8064. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8065. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8066. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8067. // zoom-factor, overflow / opacity layers, transforms ...)
  8068. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8069. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8070. // BTW3, In ff, offsetX/offsetY is always 0.
  8071. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8072. out.zrX = e.layerX;
  8073. out.zrY = e.layerY;
  8074. }
  8075. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8076. else if (e.offsetX != null) {
  8077. out.zrX = e.offsetX;
  8078. out.zrY = e.offsetY;
  8079. }
  8080. // For some other device, e.g., IOS safari.
  8081. else {
  8082. defaultGetZrXY(el, e, out);
  8083. }
  8084. return out;
  8085. }
  8086. function defaultGetZrXY(el, e, out) {
  8087. // This well-known method below does not support css transform.
  8088. var box = getBoundingClientRect(el);
  8089. out.zrX = e.clientX - box.left;
  8090. out.zrY = e.clientY - box.top;
  8091. }
  8092. /**
  8093. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8094. * `calculate` is optional, default false.
  8095. */
  8096. function normalizeEvent(el, e, calculate) {
  8097. e = e || window.event;
  8098. if (e.zrX != null) {
  8099. return e;
  8100. }
  8101. var eventType = e.type;
  8102. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8103. if (!isTouch) {
  8104. clientToLocal(el, e, e, calculate);
  8105. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8106. }
  8107. else {
  8108. var touch = eventType != 'touchend'
  8109. ? e.targetTouches[0]
  8110. : e.changedTouches[0];
  8111. touch && clientToLocal(el, touch, e, calculate);
  8112. }
  8113. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8114. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8115. // If e.which has been defined, if may be readonly,
  8116. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8117. var button = e.button;
  8118. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8119. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8120. }
  8121. return e;
  8122. }
  8123. function addEventListener(el, name, handler) {
  8124. if (isDomLevel2) {
  8125. el.addEventListener(name, handler);
  8126. }
  8127. else {
  8128. el.attachEvent('on' + name, handler);
  8129. }
  8130. }
  8131. function removeEventListener(el, name, handler) {
  8132. if (isDomLevel2) {
  8133. el.removeEventListener(name, handler);
  8134. }
  8135. else {
  8136. el.detachEvent('on' + name, handler);
  8137. }
  8138. }
  8139. /**
  8140. * preventDefault and stopPropagation.
  8141. * Notice: do not do that in zrender. Upper application
  8142. * do that if necessary.
  8143. *
  8144. * @memberOf module:zrender/core/event
  8145. * @method
  8146. * @param {Event} e : event对象
  8147. */
  8148. /**
  8149. * 动画主类, 调度和管理所有动画控制器
  8150. *
  8151. * @module zrender/animation/Animation
  8152. * @author pissang(https://github.com/pissang)
  8153. */
  8154. // TODO Additive animation
  8155. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8156. // https://developer.apple.com/videos/wwdc2014/#236
  8157. /**
  8158. * @typedef {Object} IZRenderStage
  8159. * @property {Function} update
  8160. */
  8161. /**
  8162. * @alias module:zrender/animation/Animation
  8163. * @constructor
  8164. * @param {Object} [options]
  8165. * @param {Function} [options.onframe]
  8166. * @param {IZRenderStage} [options.stage]
  8167. * @example
  8168. * var animation = new Animation();
  8169. * var obj = {
  8170. * x: 100,
  8171. * y: 100
  8172. * };
  8173. * animation.animate(node.position)
  8174. * .when(1000, {
  8175. * x: 500,
  8176. * y: 500
  8177. * })
  8178. * .when(2000, {
  8179. * x: 100,
  8180. * y: 100
  8181. * })
  8182. * .start('spline');
  8183. */
  8184. var Animation = function (options) {
  8185. options = options || {};
  8186. this.stage = options.stage || {};
  8187. this.onframe = options.onframe || function() {};
  8188. // private properties
  8189. this._clips = [];
  8190. this._running = false;
  8191. this._time;
  8192. this._pausedTime;
  8193. this._pauseStart;
  8194. this._paused = false;
  8195. Eventful.call(this);
  8196. };
  8197. Animation.prototype = {
  8198. constructor: Animation,
  8199. /**
  8200. * 添加 clip
  8201. * @param {module:zrender/animation/Clip} clip
  8202. */
  8203. addClip: function (clip) {
  8204. this._clips.push(clip);
  8205. },
  8206. /**
  8207. * 添加 animator
  8208. * @param {module:zrender/animation/Animator} animator
  8209. */
  8210. addAnimator: function (animator) {
  8211. animator.animation = this;
  8212. var clips = animator.getClips();
  8213. for (var i = 0; i < clips.length; i++) {
  8214. this.addClip(clips[i]);
  8215. }
  8216. },
  8217. /**
  8218. * 删除动画片段
  8219. * @param {module:zrender/animation/Clip} clip
  8220. */
  8221. removeClip: function(clip) {
  8222. var idx = indexOf(this._clips, clip);
  8223. if (idx >= 0) {
  8224. this._clips.splice(idx, 1);
  8225. }
  8226. },
  8227. /**
  8228. * 删除动画片段
  8229. * @param {module:zrender/animation/Animator} animator
  8230. */
  8231. removeAnimator: function (animator) {
  8232. var clips = animator.getClips();
  8233. for (var i = 0; i < clips.length; i++) {
  8234. this.removeClip(clips[i]);
  8235. }
  8236. animator.animation = null;
  8237. },
  8238. _update: function() {
  8239. var time = new Date().getTime() - this._pausedTime;
  8240. var delta = time - this._time;
  8241. var clips = this._clips;
  8242. var len = clips.length;
  8243. var deferredEvents = [];
  8244. var deferredClips = [];
  8245. for (var i = 0; i < len; i++) {
  8246. var clip = clips[i];
  8247. var e = clip.step(time, delta);
  8248. // Throw out the events need to be called after
  8249. // stage.update, like destroy
  8250. if (e) {
  8251. deferredEvents.push(e);
  8252. deferredClips.push(clip);
  8253. }
  8254. }
  8255. // Remove the finished clip
  8256. for (var i = 0; i < len;) {
  8257. if (clips[i]._needsRemove) {
  8258. clips[i] = clips[len - 1];
  8259. clips.pop();
  8260. len--;
  8261. }
  8262. else {
  8263. i++;
  8264. }
  8265. }
  8266. len = deferredEvents.length;
  8267. for (var i = 0; i < len; i++) {
  8268. deferredClips[i].fire(deferredEvents[i]);
  8269. }
  8270. this._time = time;
  8271. this.onframe(delta);
  8272. // Frame should before stage update. Upper application
  8273. // depends on the sequence (e.g., echarts-stream)
  8274. this.trigger('frame', delta);
  8275. if (this.stage.update) {
  8276. this.stage.update();
  8277. }
  8278. },
  8279. _startLoop: function () {
  8280. var self = this;
  8281. this._running = true;
  8282. function step() {
  8283. if (self._running) {
  8284. requestAnimationFrame(step);
  8285. !self._paused && self._update();
  8286. }
  8287. }
  8288. requestAnimationFrame(step);
  8289. },
  8290. /**
  8291. * 开始运行动画
  8292. */
  8293. start: function () {
  8294. this._time = new Date().getTime();
  8295. this._pausedTime = 0;
  8296. this._startLoop();
  8297. },
  8298. /**
  8299. * 停止运行动画
  8300. */
  8301. stop: function () {
  8302. this._running = false;
  8303. },
  8304. /**
  8305. * Pause
  8306. */
  8307. pause: function () {
  8308. if (!this._paused) {
  8309. this._pauseStart = new Date().getTime();
  8310. this._paused = true;
  8311. }
  8312. },
  8313. /**
  8314. * Resume
  8315. */
  8316. resume: function () {
  8317. if (this._paused) {
  8318. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8319. this._paused = false;
  8320. }
  8321. },
  8322. /**
  8323. * 清除所有动画片段
  8324. */
  8325. clear: function () {
  8326. this._clips = [];
  8327. },
  8328. /**
  8329. * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画
  8330. * @param {Object} target
  8331. * @param {Object} options
  8332. * @param {boolean} [options.loop=false] 是否循环播放动画
  8333. * @param {Function} [options.getter=null]
  8334. * 如果指定getter函数,会通过getter函数取属性值
  8335. * @param {Function} [options.setter=null]
  8336. * 如果指定setter函数,会通过setter函数设置属性值
  8337. * @return {module:zrender/animation/Animation~Animator}
  8338. */
  8339. // TODO Gap
  8340. animate: function (target, options) {
  8341. options = options || {};
  8342. var animator = new Animator(
  8343. target,
  8344. options.loop,
  8345. options.getter,
  8346. options.setter
  8347. );
  8348. this.addAnimator(animator);
  8349. return animator;
  8350. }
  8351. };
  8352. mixin(Animation, Eventful);
  8353. /**
  8354. * Only implements needed gestures for mobile.
  8355. */
  8356. var GestureMgr = function () {
  8357. /**
  8358. * @private
  8359. * @type {Array.<Object>}
  8360. */
  8361. this._track = [];
  8362. };
  8363. GestureMgr.prototype = {
  8364. constructor: GestureMgr,
  8365. recognize: function (event, target, root) {
  8366. this._doTrack(event, target, root);
  8367. return this._recognize(event);
  8368. },
  8369. clear: function () {
  8370. this._track.length = 0;
  8371. return this;
  8372. },
  8373. _doTrack: function (event, target, root) {
  8374. var touches = event.touches;
  8375. if (!touches) {
  8376. return;
  8377. }
  8378. var trackItem = {
  8379. points: [],
  8380. touches: [],
  8381. target: target,
  8382. event: event
  8383. };
  8384. for (var i = 0, len = touches.length; i < len; i++) {
  8385. var touch = touches[i];
  8386. var pos = clientToLocal(root, touch, {});
  8387. trackItem.points.push([pos.zrX, pos.zrY]);
  8388. trackItem.touches.push(touch);
  8389. }
  8390. this._track.push(trackItem);
  8391. },
  8392. _recognize: function (event) {
  8393. for (var eventName in recognizers) {
  8394. if (recognizers.hasOwnProperty(eventName)) {
  8395. var gestureInfo = recognizers[eventName](this._track, event);
  8396. if (gestureInfo) {
  8397. return gestureInfo;
  8398. }
  8399. }
  8400. }
  8401. }
  8402. };
  8403. function dist$1(pointPair) {
  8404. var dx = pointPair[1][0] - pointPair[0][0];
  8405. var dy = pointPair[1][1] - pointPair[0][1];
  8406. return Math.sqrt(dx * dx + dy * dy);
  8407. }
  8408. function center(pointPair) {
  8409. return [
  8410. (pointPair[0][0] + pointPair[1][0]) / 2,
  8411. (pointPair[0][1] + pointPair[1][1]) / 2
  8412. ];
  8413. }
  8414. var recognizers = {
  8415. pinch: function (track, event) {
  8416. var trackLen = track.length;
  8417. if (!trackLen) {
  8418. return;
  8419. }
  8420. var pinchEnd = (track[trackLen - 1] || {}).points;
  8421. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8422. if (pinchPre
  8423. && pinchPre.length > 1
  8424. && pinchEnd
  8425. && pinchEnd.length > 1
  8426. ) {
  8427. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8428. !isFinite(pinchScale) && (pinchScale = 1);
  8429. event.pinchScale = pinchScale;
  8430. var pinchCenter = center(pinchEnd);
  8431. event.pinchX = pinchCenter[0];
  8432. event.pinchY = pinchCenter[1];
  8433. return {
  8434. type: 'pinch',
  8435. target: track[0].target,
  8436. event: event
  8437. };
  8438. }
  8439. }
  8440. // Only pinch currently.
  8441. };
  8442. var TOUCH_CLICK_DELAY = 300;
  8443. var mouseHandlerNames = [
  8444. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8445. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8446. ];
  8447. var touchHandlerNames = [
  8448. 'touchstart', 'touchend', 'touchmove'
  8449. ];
  8450. var pointerEventNames = {
  8451. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8452. };
  8453. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8454. var nm = name.replace('mouse', 'pointer');
  8455. return pointerEventNames[nm] ? nm : name;
  8456. });
  8457. function eventNameFix(name) {
  8458. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8459. }
  8460. function processGesture(proxy, event, stage) {
  8461. var gestureMgr = proxy._gestureMgr;
  8462. stage === 'start' && gestureMgr.clear();
  8463. var gestureInfo = gestureMgr.recognize(
  8464. event,
  8465. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8466. proxy.dom
  8467. );
  8468. stage === 'end' && gestureMgr.clear();
  8469. // Do not do any preventDefault here. Upper application do that if necessary.
  8470. if (gestureInfo) {
  8471. var type = gestureInfo.type;
  8472. event.gestureEvent = type;
  8473. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8474. }
  8475. }
  8476. // function onMSGestureChange(proxy, event) {
  8477. // if (event.translationX || event.translationY) {
  8478. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8479. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8480. // }
  8481. // if (event.scale !== 1) {
  8482. // event.pinchX = event.offsetX;
  8483. // event.pinchY = event.offsetY;
  8484. // event.pinchScale = event.scale;
  8485. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8486. // }
  8487. // }
  8488. /**
  8489. * Prevent mouse event from being dispatched after Touch Events action
  8490. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8491. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8492. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8493. * Result: Blocking Mouse Events for 700ms.
  8494. */
  8495. function setTouchTimer(instance) {
  8496. instance._touching = true;
  8497. clearTimeout(instance._touchTimer);
  8498. instance._touchTimer = setTimeout(function () {
  8499. instance._touching = false;
  8500. }, 700);
  8501. }
  8502. var domHandlers = {
  8503. /**
  8504. * Mouse move handler
  8505. * @inner
  8506. * @param {Event} event
  8507. */
  8508. mousemove: function (event) {
  8509. event = normalizeEvent(this.dom, event);
  8510. this.trigger('mousemove', event);
  8511. },
  8512. /**
  8513. * Mouse out handler
  8514. * @inner
  8515. * @param {Event} event
  8516. */
  8517. mouseout: function (event) {
  8518. event = normalizeEvent(this.dom, event);
  8519. var element = event.toElement || event.relatedTarget;
  8520. if (element != this.dom) {
  8521. while (element && element.nodeType != 9) {
  8522. // 忽略包含在root中的dom引起的mouseOut
  8523. if (element === this.dom) {
  8524. return;
  8525. }
  8526. element = element.parentNode;
  8527. }
  8528. }
  8529. this.trigger('mouseout', event);
  8530. },
  8531. /**
  8532. * Touch开始响应函数
  8533. * @inner
  8534. * @param {Event} event
  8535. */
  8536. touchstart: function (event) {
  8537. // Default mouse behaviour should not be disabled here.
  8538. // For example, page may needs to be slided.
  8539. event = normalizeEvent(this.dom, event);
  8540. // Mark touch, which is useful in distinguish touch and
  8541. // mouse event in upper applicatoin.
  8542. event.zrByTouch = true;
  8543. this._lastTouchMoment = new Date();
  8544. processGesture(this, event, 'start');
  8545. // In touch device, trigger `mousemove`(`mouseover`) should
  8546. // be triggered, and must before `mousedown` triggered.
  8547. domHandlers.mousemove.call(this, event);
  8548. domHandlers.mousedown.call(this, event);
  8549. setTouchTimer(this);
  8550. },
  8551. /**
  8552. * Touch移动响应函数
  8553. * @inner
  8554. * @param {Event} event
  8555. */
  8556. touchmove: function (event) {
  8557. event = normalizeEvent(this.dom, event);
  8558. // Mark touch, which is useful in distinguish touch and
  8559. // mouse event in upper applicatoin.
  8560. event.zrByTouch = true;
  8561. processGesture(this, event, 'change');
  8562. // Mouse move should always be triggered no matter whether
  8563. // there is gestrue event, because mouse move and pinch may
  8564. // be used at the same time.
  8565. domHandlers.mousemove.call(this, event);
  8566. setTouchTimer(this);
  8567. },
  8568. /**
  8569. * Touch结束响应函数
  8570. * @inner
  8571. * @param {Event} event
  8572. */
  8573. touchend: function (event) {
  8574. event = normalizeEvent(this.dom, event);
  8575. // Mark touch, which is useful in distinguish touch and
  8576. // mouse event in upper applicatoin.
  8577. event.zrByTouch = true;
  8578. processGesture(this, event, 'end');
  8579. domHandlers.mouseup.call(this, event);
  8580. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8581. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8582. // we can conveniently implement "hover style" in both PC and touch device just
  8583. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8584. // to remove "hover style" on an element, without any additional code for
  8585. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8586. // style" will remain for user view)
  8587. // click event should always be triggered no matter whether
  8588. // there is gestrue event. System click can not be prevented.
  8589. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8590. domHandlers.click.call(this, event);
  8591. }
  8592. setTouchTimer(this);
  8593. },
  8594. pointerdown: function (event) {
  8595. domHandlers.mousedown.call(this, event);
  8596. // if (useMSGuesture(this, event)) {
  8597. // this._msGesture.addPointer(event.pointerId);
  8598. // }
  8599. },
  8600. pointermove: function (event) {
  8601. // FIXME
  8602. // pointermove is so sensitive that it always triggered when
  8603. // tap(click) on touch screen, which affect some judgement in
  8604. // upper application. So, we dont support mousemove on MS touch
  8605. // device yet.
  8606. if (!isPointerFromTouch(event)) {
  8607. domHandlers.mousemove.call(this, event);
  8608. }
  8609. },
  8610. pointerup: function (event) {
  8611. domHandlers.mouseup.call(this, event);
  8612. },
  8613. pointerout: function (event) {
  8614. // pointerout will be triggered when tap on touch screen
  8615. // (IE11+/Edge on MS Surface) after click event triggered,
  8616. // which is inconsistent with the mousout behavior we defined
  8617. // in touchend. So we unify them.
  8618. // (check domHandlers.touchend for detailed explanation)
  8619. if (!isPointerFromTouch(event)) {
  8620. domHandlers.mouseout.call(this, event);
  8621. }
  8622. }
  8623. };
  8624. function isPointerFromTouch(event) {
  8625. var pointerType = event.pointerType;
  8626. return pointerType === 'pen' || pointerType === 'touch';
  8627. }
  8628. // function useMSGuesture(handlerProxy, event) {
  8629. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  8630. // }
  8631. // Common handlers
  8632. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  8633. domHandlers[name] = function (event) {
  8634. event = normalizeEvent(this.dom, event);
  8635. this.trigger(name, event);
  8636. };
  8637. });
  8638. /**
  8639. * 为控制类实例初始化dom 事件处理函数
  8640. *
  8641. * @inner
  8642. * @param {module:zrender/Handler} instance 控制类实例
  8643. */
  8644. function initDomHandler(instance) {
  8645. each$1(touchHandlerNames, function (name) {
  8646. instance._handlers[name] = bind(domHandlers[name], instance);
  8647. });
  8648. each$1(pointerHandlerNames, function (name) {
  8649. instance._handlers[name] = bind(domHandlers[name], instance);
  8650. });
  8651. each$1(mouseHandlerNames, function (name) {
  8652. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  8653. });
  8654. function makeMouseHandler(fn, instance) {
  8655. return function () {
  8656. if (instance._touching) {
  8657. return;
  8658. }
  8659. return fn.apply(instance, arguments);
  8660. };
  8661. }
  8662. }
  8663. function HandlerDomProxy(dom) {
  8664. Eventful.call(this);
  8665. this.dom = dom;
  8666. /**
  8667. * @private
  8668. * @type {boolean}
  8669. */
  8670. this._touching = false;
  8671. /**
  8672. * @private
  8673. * @type {number}
  8674. */
  8675. this._touchTimer;
  8676. /**
  8677. * @private
  8678. * @type {module:zrender/core/GestureMgr}
  8679. */
  8680. this._gestureMgr = new GestureMgr();
  8681. this._handlers = {};
  8682. initDomHandler(this);
  8683. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  8684. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  8685. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  8686. // at the same time.
  8687. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  8688. // screen, which do not occurs in pointer event.
  8689. // So we use pointer event to both detect touch gesture and mouse behavior.
  8690. mountHandlers(pointerHandlerNames, this);
  8691. // FIXME
  8692. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  8693. // which does not prevent defuault behavior occasionally (which may cause view port
  8694. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  8695. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  8696. // touch screen. And we only support click behavior on MS touch screen now.
  8697. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  8698. // We dont support touch on IE on win7.
  8699. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  8700. // if (typeof MSGesture === 'function') {
  8701. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  8702. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  8703. // }
  8704. }
  8705. else {
  8706. if (env$1.touchEventsSupported) {
  8707. mountHandlers(touchHandlerNames, this);
  8708. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  8709. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  8710. }
  8711. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  8712. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  8713. // mouse event can not be handle in those devices.
  8714. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  8715. // mouseevent after touch event triggered, see `setTouchTimer`.
  8716. mountHandlers(mouseHandlerNames, this);
  8717. }
  8718. function mountHandlers(handlerNames, instance) {
  8719. each$1(handlerNames, function (name) {
  8720. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  8721. }, instance);
  8722. }
  8723. }
  8724. var handlerDomProxyProto = HandlerDomProxy.prototype;
  8725. handlerDomProxyProto.dispose = function () {
  8726. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  8727. for (var i = 0; i < handlerNames.length; i++) {
  8728. var name = handlerNames[i];
  8729. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  8730. }
  8731. };
  8732. handlerDomProxyProto.setCursor = function (cursorStyle) {
  8733. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  8734. };
  8735. mixin(HandlerDomProxy, Eventful);
  8736. /*!
  8737. * ZRender, a high performance 2d drawing library.
  8738. *
  8739. * Copyright (c) 2013, Baidu Inc.
  8740. * All rights reserved.
  8741. *
  8742. * LICENSE
  8743. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  8744. */
  8745. var useVML = !env$1.canvasSupported;
  8746. var painterCtors = {
  8747. canvas: Painter
  8748. };
  8749. /**
  8750. * @type {string}
  8751. */
  8752. var version$1 = '4.0.1';
  8753. /**
  8754. * Initializing a zrender instance
  8755. * @param {HTMLElement} dom
  8756. * @param {Object} opts
  8757. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  8758. * @param {number} [opts.devicePixelRatio]
  8759. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  8760. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  8761. * @return {module:zrender/ZRender}
  8762. */
  8763. function init$1(dom, opts) {
  8764. var zr = new ZRender(guid(), dom, opts);
  8765. return zr;
  8766. }
  8767. /**
  8768. * Dispose zrender instance
  8769. * @param {module:zrender/ZRender} zr
  8770. */
  8771. /**
  8772. * Get zrender instance by id
  8773. * @param {string} id zrender instance id
  8774. * @return {module:zrender/ZRender}
  8775. */
  8776. /**
  8777. * @module zrender/ZRender
  8778. */
  8779. /**
  8780. * @constructor
  8781. * @alias module:zrender/ZRender
  8782. * @param {string} id
  8783. * @param {HTMLElement} dom
  8784. * @param {Object} opts
  8785. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  8786. * @param {number} [opts.devicePixelRatio]
  8787. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  8788. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  8789. */
  8790. var ZRender = function (id, dom, opts) {
  8791. opts = opts || {};
  8792. /**
  8793. * @type {HTMLDomElement}
  8794. */
  8795. this.dom = dom;
  8796. /**
  8797. * @type {string}
  8798. */
  8799. this.id = id;
  8800. var self = this;
  8801. var storage = new Storage();
  8802. var rendererType = opts.renderer;
  8803. // TODO WebGL
  8804. if (useVML) {
  8805. if (!painterCtors.vml) {
  8806. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  8807. }
  8808. rendererType = 'vml';
  8809. }
  8810. else if (!rendererType || !painterCtors[rendererType]) {
  8811. rendererType = 'canvas';
  8812. }
  8813. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  8814. this.storage = storage;
  8815. this.painter = painter;
  8816. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  8817. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  8818. /**
  8819. * @type {module:zrender/animation/Animation}
  8820. */
  8821. this.animation = new Animation({
  8822. stage: {
  8823. update: bind(this.flush, this)
  8824. }
  8825. });
  8826. this.animation.start();
  8827. /**
  8828. * @type {boolean}
  8829. * @private
  8830. */
  8831. this._needsRefresh;
  8832. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  8833. // FIXME 有点ugly
  8834. var oldDelFromStorage = storage.delFromStorage;
  8835. var oldAddToStorage = storage.addToStorage;
  8836. storage.delFromStorage = function (el) {
  8837. oldDelFromStorage.call(storage, el);
  8838. el && el.removeSelfFromZr(self);
  8839. };
  8840. storage.addToStorage = function (el) {
  8841. oldAddToStorage.call(storage, el);
  8842. el.addSelfToZr(self);
  8843. };
  8844. };
  8845. ZRender.prototype = {
  8846. constructor: ZRender,
  8847. /**
  8848. * 获取实例唯一标识
  8849. * @return {string}
  8850. */
  8851. getId: function () {
  8852. return this.id;
  8853. },
  8854. /**
  8855. * 添加元素
  8856. * @param {module:zrender/Element} el
  8857. */
  8858. add: function (el) {
  8859. this.storage.addRoot(el);
  8860. this._needsRefresh = true;
  8861. },
  8862. /**
  8863. * 删除元素
  8864. * @param {module:zrender/Element} el
  8865. */
  8866. remove: function (el) {
  8867. this.storage.delRoot(el);
  8868. this._needsRefresh = true;
  8869. },
  8870. /**
  8871. * Change configuration of layer
  8872. * @param {string} zLevel
  8873. * @param {Object} config
  8874. * @param {string} [config.clearColor=0] Clear color
  8875. * @param {string} [config.motionBlur=false] If enable motion blur
  8876. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  8877. */
  8878. configLayer: function (zLevel, config) {
  8879. this.painter.configLayer(zLevel, config);
  8880. this._needsRefresh = true;
  8881. },
  8882. /**
  8883. * Repaint the canvas immediately
  8884. */
  8885. refreshImmediately: function () {
  8886. // var start = new Date();
  8887. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  8888. // Or it will cause zrender refreshes again and again.
  8889. this._needsRefresh = false;
  8890. this.painter.refresh();
  8891. /**
  8892. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  8893. */
  8894. this._needsRefresh = false;
  8895. // var end = new Date();
  8896. // var log = document.getElementById('log');
  8897. // if (log) {
  8898. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  8899. // }
  8900. },
  8901. /**
  8902. * Mark and repaint the canvas in the next frame of browser
  8903. */
  8904. refresh: function() {
  8905. this._needsRefresh = true;
  8906. },
  8907. /**
  8908. * Perform all refresh
  8909. */
  8910. flush: function () {
  8911. if (this._needsRefresh) {
  8912. this.refreshImmediately();
  8913. }
  8914. if (this._needsRefreshHover) {
  8915. this.refreshHoverImmediately();
  8916. }
  8917. },
  8918. /**
  8919. * Add element to hover layer
  8920. * @param {module:zrender/Element} el
  8921. * @param {Object} style
  8922. */
  8923. addHover: function (el, style) {
  8924. if (this.painter.addHover) {
  8925. this.painter.addHover(el, style);
  8926. this.refreshHover();
  8927. }
  8928. },
  8929. /**
  8930. * Add element from hover layer
  8931. * @param {module:zrender/Element} el
  8932. */
  8933. removeHover: function (el) {
  8934. if (this.painter.removeHover) {
  8935. this.painter.removeHover(el);
  8936. this.refreshHover();
  8937. }
  8938. },
  8939. /**
  8940. * Clear all hover elements in hover layer
  8941. * @param {module:zrender/Element} el
  8942. */
  8943. clearHover: function () {
  8944. if (this.painter.clearHover) {
  8945. this.painter.clearHover();
  8946. this.refreshHover();
  8947. }
  8948. },
  8949. /**
  8950. * Refresh hover in next frame
  8951. */
  8952. refreshHover: function () {
  8953. this._needsRefreshHover = true;
  8954. },
  8955. /**
  8956. * Refresh hover immediately
  8957. */
  8958. refreshHoverImmediately: function () {
  8959. this._needsRefreshHover = false;
  8960. this.painter.refreshHover && this.painter.refreshHover();
  8961. },
  8962. /**
  8963. * Resize the canvas.
  8964. * Should be invoked when container size is changed
  8965. * @param {Object} [opts]
  8966. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  8967. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  8968. */
  8969. resize: function(opts) {
  8970. opts = opts || {};
  8971. this.painter.resize(opts.width, opts.height);
  8972. this.handler.resize();
  8973. },
  8974. /**
  8975. * Stop and clear all animation immediately
  8976. */
  8977. clearAnimation: function () {
  8978. this.animation.clear();
  8979. },
  8980. /**
  8981. * Get container width
  8982. */
  8983. getWidth: function() {
  8984. return this.painter.getWidth();
  8985. },
  8986. /**
  8987. * Get container height
  8988. */
  8989. getHeight: function() {
  8990. return this.painter.getHeight();
  8991. },
  8992. /**
  8993. * Export the canvas as Base64 URL
  8994. * @param {string} type
  8995. * @param {string} [backgroundColor='#fff']
  8996. * @return {string} Base64 URL
  8997. */
  8998. // toDataURL: function(type, backgroundColor) {
  8999. // return this.painter.getRenderedCanvas({
  9000. // backgroundColor: backgroundColor
  9001. // }).toDataURL(type);
  9002. // },
  9003. /**
  9004. * Converting a path to image.
  9005. * It has much better performance of drawing image rather than drawing a vector path.
  9006. * @param {module:zrender/graphic/Path} e
  9007. * @param {number} width
  9008. * @param {number} height
  9009. */
  9010. pathToImage: function(e, dpr) {
  9011. return this.painter.pathToImage(e, dpr);
  9012. },
  9013. /**
  9014. * Set default cursor
  9015. * @param {string} [cursorStyle='default'] 例如 crosshair
  9016. */
  9017. setCursorStyle: function (cursorStyle) {
  9018. this.handler.setCursorStyle(cursorStyle);
  9019. },
  9020. /**
  9021. * Find hovered element
  9022. * @param {number} x
  9023. * @param {number} y
  9024. * @return {Object} {target, topTarget}
  9025. */
  9026. findHover: function (x, y) {
  9027. return this.handler.findHover(x, y);
  9028. },
  9029. /**
  9030. * Bind event
  9031. *
  9032. * @param {string} eventName Event name
  9033. * @param {Function} eventHandler Handler function
  9034. * @param {Object} [context] Context object
  9035. */
  9036. on: function(eventName, eventHandler, context) {
  9037. this.handler.on(eventName, eventHandler, context);
  9038. },
  9039. /**
  9040. * Unbind event
  9041. * @param {string} eventName Event name
  9042. * @param {Function} [eventHandler] Handler function
  9043. */
  9044. off: function(eventName, eventHandler) {
  9045. this.handler.off(eventName, eventHandler);
  9046. },
  9047. /**
  9048. * Trigger event manually
  9049. *
  9050. * @param {string} eventName Event name
  9051. * @param {event=} event Event object
  9052. */
  9053. trigger: function (eventName, event) {
  9054. this.handler.trigger(eventName, event);
  9055. },
  9056. /**
  9057. * Clear all objects and the canvas.
  9058. */
  9059. clear: function () {
  9060. this.storage.delRoot();
  9061. this.painter.clear();
  9062. },
  9063. /**
  9064. * Dispose self.
  9065. */
  9066. dispose: function () {
  9067. this.animation.stop();
  9068. this.clear();
  9069. this.storage.dispose();
  9070. this.painter.dispose();
  9071. this.handler.dispose();
  9072. this.animation =
  9073. this.storage =
  9074. this.painter =
  9075. this.handler = null;
  9076. }
  9077. };
  9078. var each$2 = each$1;
  9079. var isObject$2 = isObject$1;
  9080. var isArray$1 = isArray;
  9081. /**
  9082. * name may be displayed on screen, so use '-'.
  9083. * But we should make sure it is not duplicated
  9084. * with user specified name, so use '\0';
  9085. */
  9086. var DEFAULT_COMPONENT_NAME = '\0-';
  9087. /**
  9088. * If value is not array, then translate it to array.
  9089. * @param {*} value
  9090. * @return {Array} [value] or value
  9091. */
  9092. function normalizeToArray(value) {
  9093. return value instanceof Array
  9094. ? value
  9095. : value == null
  9096. ? []
  9097. : [value];
  9098. }
  9099. /**
  9100. * Sync default option between normal and emphasis like `position` and `show`
  9101. * In case some one will write code like
  9102. * label: {
  9103. * show: false,
  9104. * position: 'outside',
  9105. * fontSize: 18
  9106. * },
  9107. * emphasis: {
  9108. * label: { show: true }
  9109. * }
  9110. * @param {Object} opt
  9111. * @param {string} key
  9112. * @param {Array.<string>} subOpts
  9113. */
  9114. function defaultEmphasis(opt, key, subOpts) {
  9115. if (opt) {
  9116. opt[key] = opt[key] || {};
  9117. opt.emphasis = opt.emphasis || {};
  9118. opt.emphasis[key] = opt.emphasis[key] || {};
  9119. // Default emphasis option from normal
  9120. for (var i = 0, len = subOpts.length; i < len; i++) {
  9121. var subOptName = subOpts[i];
  9122. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9123. && opt[key].hasOwnProperty(subOptName)
  9124. ) {
  9125. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9126. }
  9127. }
  9128. }
  9129. }
  9130. var TEXT_STYLE_OPTIONS = [
  9131. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9132. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9133. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9134. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9135. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9136. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9137. ];
  9138. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9139. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9140. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9141. // // FIXME: deprecated, check and remove it.
  9142. // 'textStyle'
  9143. // ]);
  9144. /**
  9145. * The method do not ensure performance.
  9146. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9147. * This helper method retieves value from data.
  9148. * @param {string|number|Date|Array|Object} dataItem
  9149. * @return {number|string|Date|Array.<number|string|Date>}
  9150. */
  9151. function getDataItemValue(dataItem) {
  9152. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9153. ? dataItem.value : dataItem;
  9154. }
  9155. /**
  9156. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9157. * This helper method determine if dataItem has extra option besides value
  9158. * @param {string|number|Date|Array|Object} dataItem
  9159. */
  9160. function isDataItemOption(dataItem) {
  9161. return isObject$2(dataItem)
  9162. && !(dataItem instanceof Array);
  9163. // // markLine data can be array
  9164. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9165. }
  9166. /**
  9167. * Mapping to exists for merge.
  9168. *
  9169. * @public
  9170. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9171. * @param {Object|Array.<Object>} newCptOptions
  9172. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9173. * index of which is the same as exists.
  9174. */
  9175. function mappingToExists(exists, newCptOptions) {
  9176. // Mapping by the order by original option (but not order of
  9177. // new option) in merge mode. Because we should ensure
  9178. // some specified index (like xAxisIndex) is consistent with
  9179. // original option, which is easy to understand, espatially in
  9180. // media query. And in most case, merge option is used to
  9181. // update partial option but not be expected to change order.
  9182. newCptOptions = (newCptOptions || []).slice();
  9183. var result = map(exists || [], function (obj, index) {
  9184. return {exist: obj};
  9185. });
  9186. // Mapping by id or name if specified.
  9187. each$2(newCptOptions, function (cptOption, index) {
  9188. if (!isObject$2(cptOption)) {
  9189. return;
  9190. }
  9191. // id has highest priority.
  9192. for (var i = 0; i < result.length; i++) {
  9193. if (!result[i].option // Consider name: two map to one.
  9194. && cptOption.id != null
  9195. && result[i].exist.id === cptOption.id + ''
  9196. ) {
  9197. result[i].option = cptOption;
  9198. newCptOptions[index] = null;
  9199. return;
  9200. }
  9201. }
  9202. for (var i = 0; i < result.length; i++) {
  9203. var exist = result[i].exist;
  9204. if (!result[i].option // Consider name: two map to one.
  9205. // Can not match when both ids exist but different.
  9206. && (exist.id == null || cptOption.id == null)
  9207. && cptOption.name != null
  9208. && !isIdInner(cptOption)
  9209. && !isIdInner(exist)
  9210. && exist.name === cptOption.name + ''
  9211. ) {
  9212. result[i].option = cptOption;
  9213. newCptOptions[index] = null;
  9214. return;
  9215. }
  9216. }
  9217. });
  9218. // Otherwise mapping by index.
  9219. each$2(newCptOptions, function (cptOption, index) {
  9220. if (!isObject$2(cptOption)) {
  9221. return;
  9222. }
  9223. var i = 0;
  9224. for (; i < result.length; i++) {
  9225. var exist = result[i].exist;
  9226. if (!result[i].option
  9227. // Existing model that already has id should be able to
  9228. // mapped to (because after mapping performed model may
  9229. // be assigned with a id, whish should not affect next
  9230. // mapping), except those has inner id.
  9231. && !isIdInner(exist)
  9232. // Caution:
  9233. // Do not overwrite id. But name can be overwritten,
  9234. // because axis use name as 'show label text'.
  9235. // 'exist' always has id and name and we dont
  9236. // need to check it.
  9237. && cptOption.id == null
  9238. ) {
  9239. result[i].option = cptOption;
  9240. break;
  9241. }
  9242. }
  9243. if (i >= result.length) {
  9244. result.push({option: cptOption});
  9245. }
  9246. });
  9247. return result;
  9248. }
  9249. /**
  9250. * Make id and name for mapping result (result of mappingToExists)
  9251. * into `keyInfo` field.
  9252. *
  9253. * @public
  9254. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9255. * which order is the same as exists.
  9256. * @return {Array.<Object>} The input.
  9257. */
  9258. function makeIdAndName(mapResult) {
  9259. // We use this id to hash component models and view instances
  9260. // in echarts. id can be specified by user, or auto generated.
  9261. // The id generation rule ensures new view instance are able
  9262. // to mapped to old instance when setOption are called in
  9263. // no-merge mode. So we generate model id by name and plus
  9264. // type in view id.
  9265. // name can be duplicated among components, which is convenient
  9266. // to specify multi components (like series) by one name.
  9267. // Ensure that each id is distinct.
  9268. var idMap = createHashMap();
  9269. each$2(mapResult, function (item, index) {
  9270. var existCpt = item.exist;
  9271. existCpt && idMap.set(existCpt.id, item);
  9272. });
  9273. each$2(mapResult, function (item, index) {
  9274. var opt = item.option;
  9275. assert$1(
  9276. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9277. 'id duplicates: ' + (opt && opt.id)
  9278. );
  9279. opt && opt.id != null && idMap.set(opt.id, item);
  9280. !item.keyInfo && (item.keyInfo = {});
  9281. });
  9282. // Make name and id.
  9283. each$2(mapResult, function (item, index) {
  9284. var existCpt = item.exist;
  9285. var opt = item.option;
  9286. var keyInfo = item.keyInfo;
  9287. if (!isObject$2(opt)) {
  9288. return;
  9289. }
  9290. // name can be overwitten. Consider case: axis.name = '20km'.
  9291. // But id generated by name will not be changed, which affect
  9292. // only in that case: setOption with 'not merge mode' and view
  9293. // instance will be recreated, which can be accepted.
  9294. keyInfo.name = opt.name != null
  9295. ? opt.name + ''
  9296. : existCpt
  9297. ? existCpt.name
  9298. : DEFAULT_COMPONENT_NAME;
  9299. if (existCpt) {
  9300. keyInfo.id = existCpt.id;
  9301. }
  9302. else if (opt.id != null) {
  9303. keyInfo.id = opt.id + '';
  9304. }
  9305. else {
  9306. // Consider this situatoin:
  9307. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9308. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9309. // Series with the same name between optionA and optionB
  9310. // should be mapped.
  9311. var idNum = 0;
  9312. do {
  9313. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9314. }
  9315. while (idMap.get(keyInfo.id));
  9316. }
  9317. idMap.set(keyInfo.id, item);
  9318. });
  9319. }
  9320. /**
  9321. * @public
  9322. * @param {Object} cptOption
  9323. * @return {boolean}
  9324. */
  9325. function isIdInner(cptOption) {
  9326. return isObject$2(cptOption)
  9327. && cptOption.id
  9328. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9329. }
  9330. /**
  9331. * A helper for removing duplicate items between batchA and batchB,
  9332. * and in themselves, and categorize by series.
  9333. *
  9334. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9335. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9336. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9337. */
  9338. /**
  9339. * @param {module:echarts/data/List} data
  9340. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9341. * each of which can be Array or primary type.
  9342. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9343. */
  9344. function queryDataIndex(data, payload) {
  9345. if (payload.dataIndexInside != null) {
  9346. return payload.dataIndexInside;
  9347. }
  9348. else if (payload.dataIndex != null) {
  9349. return isArray(payload.dataIndex)
  9350. ? map(payload.dataIndex, function (value) {
  9351. return data.indexOfRawIndex(value);
  9352. })
  9353. : data.indexOfRawIndex(payload.dataIndex);
  9354. }
  9355. else if (payload.name != null) {
  9356. return isArray(payload.name)
  9357. ? map(payload.name, function (value) {
  9358. return data.indexOfName(value);
  9359. })
  9360. : data.indexOfName(payload.name);
  9361. }
  9362. }
  9363. /**
  9364. * Enable property storage to any host object.
  9365. * Notice: Serialization is not supported.
  9366. *
  9367. * For example:
  9368. * var inner = zrUitl.makeInner();
  9369. *
  9370. * function some1(hostObj) {
  9371. * inner(hostObj).someProperty = 1212;
  9372. * ...
  9373. * }
  9374. * function some2() {
  9375. * var fields = inner(this);
  9376. * fields.someProperty1 = 1212;
  9377. * fields.someProperty2 = 'xx';
  9378. * ...
  9379. * }
  9380. *
  9381. * @return {Function}
  9382. */
  9383. function makeInner() {
  9384. // Consider different scope by es module import.
  9385. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9386. return function (hostObj) {
  9387. return hostObj[key] || (hostObj[key] = {});
  9388. };
  9389. }
  9390. var innerUniqueIndex = 0;
  9391. /**
  9392. * @param {module:echarts/model/Global} ecModel
  9393. * @param {string|Object} finder
  9394. * If string, e.g., 'geo', means {geoIndex: 0}.
  9395. * If Object, could contain some of these properties below:
  9396. * {
  9397. * seriesIndex, seriesId, seriesName,
  9398. * geoIndex, geoId, geoName,
  9399. * bmapIndex, bmapId, bmapName,
  9400. * xAxisIndex, xAxisId, xAxisName,
  9401. * yAxisIndex, yAxisId, yAxisName,
  9402. * gridIndex, gridId, gridName,
  9403. * ... (can be extended)
  9404. * }
  9405. * Each properties can be number|string|Array.<number>|Array.<string>
  9406. * For example, a finder could be
  9407. * {
  9408. * seriesIndex: 3,
  9409. * geoId: ['aa', 'cc'],
  9410. * gridName: ['xx', 'rr']
  9411. * }
  9412. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9413. * If nothing or null/undefined specified, return nothing.
  9414. * @param {Object} [opt]
  9415. * @param {string} [opt.defaultMainType]
  9416. * @param {Array.<string>} [opt.includeMainTypes]
  9417. * @return {Object} result like:
  9418. * {
  9419. * seriesModels: [seriesModel1, seriesModel2],
  9420. * seriesModel: seriesModel1, // The first model
  9421. * geoModels: [geoModel1, geoModel2],
  9422. * geoModel: geoModel1, // The first model
  9423. * ...
  9424. * }
  9425. */
  9426. function parseFinder(ecModel, finder, opt) {
  9427. if (isString(finder)) {
  9428. var obj = {};
  9429. obj[finder + 'Index'] = 0;
  9430. finder = obj;
  9431. }
  9432. var defaultMainType = opt && opt.defaultMainType;
  9433. if (defaultMainType
  9434. && !has(finder, defaultMainType + 'Index')
  9435. && !has(finder, defaultMainType + 'Id')
  9436. && !has(finder, defaultMainType + 'Name')
  9437. ) {
  9438. finder[defaultMainType + 'Index'] = 0;
  9439. }
  9440. var result = {};
  9441. each$2(finder, function (value, key) {
  9442. var value = finder[key];
  9443. // Exclude 'dataIndex' and other illgal keys.
  9444. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9445. result[key] = value;
  9446. return;
  9447. }
  9448. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9449. var mainType = parsedKey[1];
  9450. var queryType = (parsedKey[2] || '').toLowerCase();
  9451. if (!mainType
  9452. || !queryType
  9453. || value == null
  9454. || (queryType === 'index' && value === 'none')
  9455. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9456. ) {
  9457. return;
  9458. }
  9459. var queryParam = {mainType: mainType};
  9460. if (queryType !== 'index' || value !== 'all') {
  9461. queryParam[queryType] = value;
  9462. }
  9463. var models = ecModel.queryComponents(queryParam);
  9464. result[mainType + 'Models'] = models;
  9465. result[mainType + 'Model'] = models[0];
  9466. });
  9467. return result;
  9468. }
  9469. function has(obj, prop) {
  9470. return obj && obj.hasOwnProperty(prop);
  9471. }
  9472. function setAttribute(dom, key, value) {
  9473. dom.setAttribute
  9474. ? dom.setAttribute(key, value)
  9475. : (dom[key] = value);
  9476. }
  9477. function getAttribute(dom, key) {
  9478. return dom.getAttribute
  9479. ? dom.getAttribute(key)
  9480. : dom[key];
  9481. }
  9482. var TYPE_DELIMITER = '.';
  9483. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9484. /**
  9485. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9486. * @public
  9487. */
  9488. function parseClassType$1(componentType) {
  9489. var ret = {main: '', sub: ''};
  9490. if (componentType) {
  9491. componentType = componentType.split(TYPE_DELIMITER);
  9492. ret.main = componentType[0] || '';
  9493. ret.sub = componentType[1] || '';
  9494. }
  9495. return ret;
  9496. }
  9497. /**
  9498. * @public
  9499. */
  9500. function checkClassType(componentType) {
  9501. assert$1(
  9502. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9503. 'componentType "' + componentType + '" illegal'
  9504. );
  9505. }
  9506. /**
  9507. * @public
  9508. */
  9509. function enableClassExtend(RootClass, mandatoryMethods) {
  9510. RootClass.$constructor = RootClass;
  9511. RootClass.extend = function (proto) {
  9512. if (__DEV__) {
  9513. each$1(mandatoryMethods, function (method) {
  9514. if (!proto[method]) {
  9515. console.warn(
  9516. 'Method `' + method + '` should be implemented'
  9517. + (proto.type ? ' in ' + proto.type : '') + '.'
  9518. );
  9519. }
  9520. });
  9521. }
  9522. var superClass = this;
  9523. var ExtendedClass = function () {
  9524. if (!proto.$constructor) {
  9525. superClass.apply(this, arguments);
  9526. }
  9527. else {
  9528. proto.$constructor.apply(this, arguments);
  9529. }
  9530. };
  9531. extend(ExtendedClass.prototype, proto);
  9532. ExtendedClass.extend = this.extend;
  9533. ExtendedClass.superCall = superCall;
  9534. ExtendedClass.superApply = superApply;
  9535. inherits(ExtendedClass, this);
  9536. ExtendedClass.superClass = superClass;
  9537. return ExtendedClass;
  9538. };
  9539. }
  9540. var classBase = 0;
  9541. /**
  9542. * Can not use instanceof, consider different scope by
  9543. * cross domain or es module import in ec extensions.
  9544. * Mount a method "isInstance()" to Clz.
  9545. */
  9546. function enableClassCheck(Clz) {
  9547. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  9548. Clz.prototype[classAttr] = true;
  9549. if (__DEV__) {
  9550. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  9551. }
  9552. Clz.isInstance = function (obj) {
  9553. return !!(obj && obj[classAttr]);
  9554. };
  9555. }
  9556. // superCall should have class info, which can not be fetch from 'this'.
  9557. // Consider this case:
  9558. // class A has method f,
  9559. // class B inherits class A, overrides method f, f call superApply('f'),
  9560. // class C inherits class B, do not overrides method f,
  9561. // then when method of class C is called, dead loop occured.
  9562. function superCall(context, methodName) {
  9563. var args = slice(arguments, 2);
  9564. return this.superClass.prototype[methodName].apply(context, args);
  9565. }
  9566. function superApply(context, methodName, args) {
  9567. return this.superClass.prototype[methodName].apply(context, args);
  9568. }
  9569. /**
  9570. * @param {Object} entity
  9571. * @param {Object} options
  9572. * @param {boolean} [options.registerWhenExtend]
  9573. * @public
  9574. */
  9575. function enableClassManagement(entity, options) {
  9576. options = options || {};
  9577. /**
  9578. * Component model classes
  9579. * key: componentType,
  9580. * value:
  9581. * componentClass, when componentType is 'xxx'
  9582. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  9583. * @type {Object}
  9584. */
  9585. var storage = {};
  9586. entity.registerClass = function (Clazz, componentType) {
  9587. if (componentType) {
  9588. checkClassType(componentType);
  9589. componentType = parseClassType$1(componentType);
  9590. if (!componentType.sub) {
  9591. if (__DEV__) {
  9592. if (storage[componentType.main]) {
  9593. console.warn(componentType.main + ' exists.');
  9594. }
  9595. }
  9596. storage[componentType.main] = Clazz;
  9597. }
  9598. else if (componentType.sub !== IS_CONTAINER) {
  9599. var container = makeContainer(componentType);
  9600. container[componentType.sub] = Clazz;
  9601. }
  9602. }
  9603. return Clazz;
  9604. };
  9605. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  9606. var Clazz = storage[componentMainType];
  9607. if (Clazz && Clazz[IS_CONTAINER]) {
  9608. Clazz = subType ? Clazz[subType] : null;
  9609. }
  9610. if (throwWhenNotFound && !Clazz) {
  9611. throw new Error(
  9612. !subType
  9613. ? componentMainType + '.' + 'type should be specified.'
  9614. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  9615. );
  9616. }
  9617. return Clazz;
  9618. };
  9619. entity.getClassesByMainType = function (componentType) {
  9620. componentType = parseClassType$1(componentType);
  9621. var result = [];
  9622. var obj = storage[componentType.main];
  9623. if (obj && obj[IS_CONTAINER]) {
  9624. each$1(obj, function (o, type) {
  9625. type !== IS_CONTAINER && result.push(o);
  9626. });
  9627. }
  9628. else {
  9629. result.push(obj);
  9630. }
  9631. return result;
  9632. };
  9633. entity.hasClass = function (componentType) {
  9634. // Just consider componentType.main.
  9635. componentType = parseClassType$1(componentType);
  9636. return !!storage[componentType.main];
  9637. };
  9638. /**
  9639. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  9640. */
  9641. entity.getAllClassMainTypes = function () {
  9642. var types = [];
  9643. each$1(storage, function (obj, type) {
  9644. types.push(type);
  9645. });
  9646. return types;
  9647. };
  9648. /**
  9649. * If a main type is container and has sub types
  9650. * @param {string} mainType
  9651. * @return {boolean}
  9652. */
  9653. entity.hasSubTypes = function (componentType) {
  9654. componentType = parseClassType$1(componentType);
  9655. var obj = storage[componentType.main];
  9656. return obj && obj[IS_CONTAINER];
  9657. };
  9658. entity.parseClassType = parseClassType$1;
  9659. function makeContainer(componentType) {
  9660. var container = storage[componentType.main];
  9661. if (!container || !container[IS_CONTAINER]) {
  9662. container = storage[componentType.main] = {};
  9663. container[IS_CONTAINER] = true;
  9664. }
  9665. return container;
  9666. }
  9667. if (options.registerWhenExtend) {
  9668. var originalExtend = entity.extend;
  9669. if (originalExtend) {
  9670. entity.extend = function (proto) {
  9671. var ExtendedClass = originalExtend.call(this, proto);
  9672. return entity.registerClass(ExtendedClass, proto.type);
  9673. };
  9674. }
  9675. }
  9676. return entity;
  9677. }
  9678. /**
  9679. * @param {string|Array.<string>} properties
  9680. */
  9681. // TODO Parse shadow style
  9682. // TODO Only shallow path support
  9683. var makeStyleMapper = function (properties) {
  9684. // Normalize
  9685. for (var i = 0; i < properties.length; i++) {
  9686. if (!properties[i][1]) {
  9687. properties[i][1] = properties[i][0];
  9688. }
  9689. }
  9690. return function (model, excludes, includes) {
  9691. var style = {};
  9692. for (var i = 0; i < properties.length; i++) {
  9693. var propName = properties[i][1];
  9694. if ((excludes && indexOf(excludes, propName) >= 0)
  9695. || (includes && indexOf(includes, propName) < 0)
  9696. ) {
  9697. continue;
  9698. }
  9699. var val = model.getShallow(propName);
  9700. if (val != null) {
  9701. style[properties[i][0]] = val;
  9702. }
  9703. }
  9704. return style;
  9705. };
  9706. };
  9707. var getLineStyle = makeStyleMapper(
  9708. [
  9709. ['lineWidth', 'width'],
  9710. ['stroke', 'color'],
  9711. ['opacity'],
  9712. ['shadowBlur'],
  9713. ['shadowOffsetX'],
  9714. ['shadowOffsetY'],
  9715. ['shadowColor']
  9716. ]
  9717. );
  9718. var lineStyleMixin = {
  9719. getLineStyle: function (excludes) {
  9720. var style = getLineStyle(this, excludes);
  9721. var lineDash = this.getLineDash(style.lineWidth);
  9722. lineDash && (style.lineDash = lineDash);
  9723. return style;
  9724. },
  9725. getLineDash: function (lineWidth) {
  9726. if (lineWidth == null) {
  9727. lineWidth = 1;
  9728. }
  9729. var lineType = this.get('type');
  9730. var dotSize = Math.max(lineWidth, 2);
  9731. var dashSize = lineWidth * 4;
  9732. return (lineType === 'solid' || lineType == null) ? null
  9733. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  9734. }
  9735. };
  9736. var getAreaStyle = makeStyleMapper(
  9737. [
  9738. ['fill', 'color'],
  9739. ['shadowBlur'],
  9740. ['shadowOffsetX'],
  9741. ['shadowOffsetY'],
  9742. ['opacity'],
  9743. ['shadowColor']
  9744. ]
  9745. );
  9746. var areaStyleMixin = {
  9747. getAreaStyle: function (excludes, includes) {
  9748. return getAreaStyle(this, excludes, includes);
  9749. }
  9750. };
  9751. /**
  9752. * 曲线辅助模块
  9753. * @module zrender/core/curve
  9754. * @author pissang(https://www.github.com/pissang)
  9755. */
  9756. var mathPow = Math.pow;
  9757. var mathSqrt$2 = Math.sqrt;
  9758. var EPSILON$1 = 1e-8;
  9759. var EPSILON_NUMERIC = 1e-4;
  9760. var THREE_SQRT = mathSqrt$2(3);
  9761. var ONE_THIRD = 1 / 3;
  9762. // 临时变量
  9763. var _v0 = create();
  9764. var _v1 = create();
  9765. var _v2 = create();
  9766. function isAroundZero(val) {
  9767. return val > -EPSILON$1 && val < EPSILON$1;
  9768. }
  9769. function isNotAroundZero$1(val) {
  9770. return val > EPSILON$1 || val < -EPSILON$1;
  9771. }
  9772. /**
  9773. * 计算三次贝塞尔值
  9774. * @memberOf module:zrender/core/curve
  9775. * @param {number} p0
  9776. * @param {number} p1
  9777. * @param {number} p2
  9778. * @param {number} p3
  9779. * @param {number} t
  9780. * @return {number}
  9781. */
  9782. function cubicAt(p0, p1, p2, p3, t) {
  9783. var onet = 1 - t;
  9784. return onet * onet * (onet * p0 + 3 * t * p1)
  9785. + t * t * (t * p3 + 3 * onet * p2);
  9786. }
  9787. /**
  9788. * 计算三次贝塞尔导数值
  9789. * @memberOf module:zrender/core/curve
  9790. * @param {number} p0
  9791. * @param {number} p1
  9792. * @param {number} p2
  9793. * @param {number} p3
  9794. * @param {number} t
  9795. * @return {number}
  9796. */
  9797. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  9798. var onet = 1 - t;
  9799. return 3 * (
  9800. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  9801. + (p3 - p2) * t * t
  9802. );
  9803. }
  9804. /**
  9805. * 计算三次贝塞尔方程根,使用盛金公式
  9806. * @memberOf module:zrender/core/curve
  9807. * @param {number} p0
  9808. * @param {number} p1
  9809. * @param {number} p2
  9810. * @param {number} p3
  9811. * @param {number} val
  9812. * @param {Array.<number>} roots
  9813. * @return {number} 有效根数目
  9814. */
  9815. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  9816. // Evaluate roots of cubic functions
  9817. var a = p3 + 3 * (p1 - p2) - p0;
  9818. var b = 3 * (p2 - p1 * 2 + p0);
  9819. var c = 3 * (p1 - p0);
  9820. var d = p0 - val;
  9821. var A = b * b - 3 * a * c;
  9822. var B = b * c - 9 * a * d;
  9823. var C = c * c - 3 * b * d;
  9824. var n = 0;
  9825. if (isAroundZero(A) && isAroundZero(B)) {
  9826. if (isAroundZero(b)) {
  9827. roots[0] = 0;
  9828. }
  9829. else {
  9830. var t1 = -c / b; //t1, t2, t3, b is not zero
  9831. if (t1 >= 0 && t1 <= 1) {
  9832. roots[n++] = t1;
  9833. }
  9834. }
  9835. }
  9836. else {
  9837. var disc = B * B - 4 * A * C;
  9838. if (isAroundZero(disc)) {
  9839. var K = B / A;
  9840. var t1 = -b / a + K; // t1, a is not zero
  9841. var t2 = -K / 2; // t2, t3
  9842. if (t1 >= 0 && t1 <= 1) {
  9843. roots[n++] = t1;
  9844. }
  9845. if (t2 >= 0 && t2 <= 1) {
  9846. roots[n++] = t2;
  9847. }
  9848. }
  9849. else if (disc > 0) {
  9850. var discSqrt = mathSqrt$2(disc);
  9851. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  9852. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  9853. if (Y1 < 0) {
  9854. Y1 = -mathPow(-Y1, ONE_THIRD);
  9855. }
  9856. else {
  9857. Y1 = mathPow(Y1, ONE_THIRD);
  9858. }
  9859. if (Y2 < 0) {
  9860. Y2 = -mathPow(-Y2, ONE_THIRD);
  9861. }
  9862. else {
  9863. Y2 = mathPow(Y2, ONE_THIRD);
  9864. }
  9865. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  9866. if (t1 >= 0 && t1 <= 1) {
  9867. roots[n++] = t1;
  9868. }
  9869. }
  9870. else {
  9871. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  9872. var theta = Math.acos(T) / 3;
  9873. var ASqrt = mathSqrt$2(A);
  9874. var tmp = Math.cos(theta);
  9875. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  9876. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  9877. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  9878. if (t1 >= 0 && t1 <= 1) {
  9879. roots[n++] = t1;
  9880. }
  9881. if (t2 >= 0 && t2 <= 1) {
  9882. roots[n++] = t2;
  9883. }
  9884. if (t3 >= 0 && t3 <= 1) {
  9885. roots[n++] = t3;
  9886. }
  9887. }
  9888. }
  9889. return n;
  9890. }
  9891. /**
  9892. * 计算三次贝塞尔方程极限值的位置
  9893. * @memberOf module:zrender/core/curve
  9894. * @param {number} p0
  9895. * @param {number} p1
  9896. * @param {number} p2
  9897. * @param {number} p3
  9898. * @param {Array.<number>} extrema
  9899. * @return {number} 有效数目
  9900. */
  9901. function cubicExtrema(p0, p1, p2, p3, extrema) {
  9902. var b = 6 * p2 - 12 * p1 + 6 * p0;
  9903. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  9904. var c = 3 * p1 - 3 * p0;
  9905. var n = 0;
  9906. if (isAroundZero(a)) {
  9907. if (isNotAroundZero$1(b)) {
  9908. var t1 = -c / b;
  9909. if (t1 >= 0 && t1 <=1) {
  9910. extrema[n++] = t1;
  9911. }
  9912. }
  9913. }
  9914. else {
  9915. var disc = b * b - 4 * a * c;
  9916. if (isAroundZero(disc)) {
  9917. extrema[0] = -b / (2 * a);
  9918. }
  9919. else if (disc > 0) {
  9920. var discSqrt = mathSqrt$2(disc);
  9921. var t1 = (-b + discSqrt) / (2 * a);
  9922. var t2 = (-b - discSqrt) / (2 * a);
  9923. if (t1 >= 0 && t1 <= 1) {
  9924. extrema[n++] = t1;
  9925. }
  9926. if (t2 >= 0 && t2 <= 1) {
  9927. extrema[n++] = t2;
  9928. }
  9929. }
  9930. }
  9931. return n;
  9932. }
  9933. /**
  9934. * 细分三次贝塞尔曲线
  9935. * @memberOf module:zrender/core/curve
  9936. * @param {number} p0
  9937. * @param {number} p1
  9938. * @param {number} p2
  9939. * @param {number} p3
  9940. * @param {number} t
  9941. * @param {Array.<number>} out
  9942. */
  9943. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  9944. var p01 = (p1 - p0) * t + p0;
  9945. var p12 = (p2 - p1) * t + p1;
  9946. var p23 = (p3 - p2) * t + p2;
  9947. var p012 = (p12 - p01) * t + p01;
  9948. var p123 = (p23 - p12) * t + p12;
  9949. var p0123 = (p123 - p012) * t + p012;
  9950. // Seg0
  9951. out[0] = p0;
  9952. out[1] = p01;
  9953. out[2] = p012;
  9954. out[3] = p0123;
  9955. // Seg1
  9956. out[4] = p0123;
  9957. out[5] = p123;
  9958. out[6] = p23;
  9959. out[7] = p3;
  9960. }
  9961. /**
  9962. * 投射点到三次贝塞尔曲线上,返回投射距离。
  9963. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  9964. * @param {number} x0
  9965. * @param {number} y0
  9966. * @param {number} x1
  9967. * @param {number} y1
  9968. * @param {number} x2
  9969. * @param {number} y2
  9970. * @param {number} x3
  9971. * @param {number} y3
  9972. * @param {number} x
  9973. * @param {number} y
  9974. * @param {Array.<number>} [out] 投射点
  9975. * @return {number}
  9976. */
  9977. function cubicProjectPoint(
  9978. x0, y0, x1, y1, x2, y2, x3, y3,
  9979. x, y, out
  9980. ) {
  9981. // http://pomax.github.io/bezierinfo/#projections
  9982. var t;
  9983. var interval = 0.005;
  9984. var d = Infinity;
  9985. var prev;
  9986. var next;
  9987. var d1;
  9988. var d2;
  9989. _v0[0] = x;
  9990. _v0[1] = y;
  9991. // 先粗略估计一下可能的最小距离的 t 值
  9992. // PENDING
  9993. for (var _t = 0; _t < 1; _t += 0.05) {
  9994. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  9995. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  9996. d1 = distSquare(_v0, _v1);
  9997. if (d1 < d) {
  9998. t = _t;
  9999. d = d1;
  10000. }
  10001. }
  10002. d = Infinity;
  10003. // At most 32 iteration
  10004. for (var i = 0; i < 32; i++) {
  10005. if (interval < EPSILON_NUMERIC) {
  10006. break;
  10007. }
  10008. prev = t - interval;
  10009. next = t + interval;
  10010. // t - interval
  10011. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10012. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10013. d1 = distSquare(_v1, _v0);
  10014. if (prev >= 0 && d1 < d) {
  10015. t = prev;
  10016. d = d1;
  10017. }
  10018. else {
  10019. // t + interval
  10020. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10021. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10022. d2 = distSquare(_v2, _v0);
  10023. if (next <= 1 && d2 < d) {
  10024. t = next;
  10025. d = d2;
  10026. }
  10027. else {
  10028. interval *= 0.5;
  10029. }
  10030. }
  10031. }
  10032. // t
  10033. if (out) {
  10034. out[0] = cubicAt(x0, x1, x2, x3, t);
  10035. out[1] = cubicAt(y0, y1, y2, y3, t);
  10036. }
  10037. // console.log(interval, i);
  10038. return mathSqrt$2(d);
  10039. }
  10040. /**
  10041. * 计算二次方贝塞尔值
  10042. * @param {number} p0
  10043. * @param {number} p1
  10044. * @param {number} p2
  10045. * @param {number} t
  10046. * @return {number}
  10047. */
  10048. function quadraticAt(p0, p1, p2, t) {
  10049. var onet = 1 - t;
  10050. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10051. }
  10052. /**
  10053. * 计算二次方贝塞尔导数值
  10054. * @param {number} p0
  10055. * @param {number} p1
  10056. * @param {number} p2
  10057. * @param {number} t
  10058. * @return {number}
  10059. */
  10060. function quadraticDerivativeAt(p0, p1, p2, t) {
  10061. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10062. }
  10063. /**
  10064. * 计算二次方贝塞尔方程根
  10065. * @param {number} p0
  10066. * @param {number} p1
  10067. * @param {number} p2
  10068. * @param {number} t
  10069. * @param {Array.<number>} roots
  10070. * @return {number} 有效根数目
  10071. */
  10072. function quadraticRootAt(p0, p1, p2, val, roots) {
  10073. var a = p0 - 2 * p1 + p2;
  10074. var b = 2 * (p1 - p0);
  10075. var c = p0 - val;
  10076. var n = 0;
  10077. if (isAroundZero(a)) {
  10078. if (isNotAroundZero$1(b)) {
  10079. var t1 = -c / b;
  10080. if (t1 >= 0 && t1 <= 1) {
  10081. roots[n++] = t1;
  10082. }
  10083. }
  10084. }
  10085. else {
  10086. var disc = b * b - 4 * a * c;
  10087. if (isAroundZero(disc)) {
  10088. var t1 = -b / (2 * a);
  10089. if (t1 >= 0 && t1 <= 1) {
  10090. roots[n++] = t1;
  10091. }
  10092. }
  10093. else if (disc > 0) {
  10094. var discSqrt = mathSqrt$2(disc);
  10095. var t1 = (-b + discSqrt) / (2 * a);
  10096. var t2 = (-b - discSqrt) / (2 * a);
  10097. if (t1 >= 0 && t1 <= 1) {
  10098. roots[n++] = t1;
  10099. }
  10100. if (t2 >= 0 && t2 <= 1) {
  10101. roots[n++] = t2;
  10102. }
  10103. }
  10104. }
  10105. return n;
  10106. }
  10107. /**
  10108. * 计算二次贝塞尔方程极限值
  10109. * @memberOf module:zrender/core/curve
  10110. * @param {number} p0
  10111. * @param {number} p1
  10112. * @param {number} p2
  10113. * @return {number}
  10114. */
  10115. function quadraticExtremum(p0, p1, p2) {
  10116. var divider = p0 + p2 - 2 * p1;
  10117. if (divider === 0) {
  10118. // p1 is center of p0 and p2
  10119. return 0.5;
  10120. }
  10121. else {
  10122. return (p0 - p1) / divider;
  10123. }
  10124. }
  10125. /**
  10126. * 细分二次贝塞尔曲线
  10127. * @memberOf module:zrender/core/curve
  10128. * @param {number} p0
  10129. * @param {number} p1
  10130. * @param {number} p2
  10131. * @param {number} t
  10132. * @param {Array.<number>} out
  10133. */
  10134. function quadraticSubdivide(p0, p1, p2, t, out) {
  10135. var p01 = (p1 - p0) * t + p0;
  10136. var p12 = (p2 - p1) * t + p1;
  10137. var p012 = (p12 - p01) * t + p01;
  10138. // Seg0
  10139. out[0] = p0;
  10140. out[1] = p01;
  10141. out[2] = p012;
  10142. // Seg1
  10143. out[3] = p012;
  10144. out[4] = p12;
  10145. out[5] = p2;
  10146. }
  10147. /**
  10148. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10149. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10150. * @param {number} x0
  10151. * @param {number} y0
  10152. * @param {number} x1
  10153. * @param {number} y1
  10154. * @param {number} x2
  10155. * @param {number} y2
  10156. * @param {number} x
  10157. * @param {number} y
  10158. * @param {Array.<number>} out 投射点
  10159. * @return {number}
  10160. */
  10161. function quadraticProjectPoint(
  10162. x0, y0, x1, y1, x2, y2,
  10163. x, y, out
  10164. ) {
  10165. // http://pomax.github.io/bezierinfo/#projections
  10166. var t;
  10167. var interval = 0.005;
  10168. var d = Infinity;
  10169. _v0[0] = x;
  10170. _v0[1] = y;
  10171. // 先粗略估计一下可能的最小距离的 t 值
  10172. // PENDING
  10173. for (var _t = 0; _t < 1; _t += 0.05) {
  10174. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10175. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10176. var d1 = distSquare(_v0, _v1);
  10177. if (d1 < d) {
  10178. t = _t;
  10179. d = d1;
  10180. }
  10181. }
  10182. d = Infinity;
  10183. // At most 32 iteration
  10184. for (var i = 0; i < 32; i++) {
  10185. if (interval < EPSILON_NUMERIC) {
  10186. break;
  10187. }
  10188. var prev = t - interval;
  10189. var next = t + interval;
  10190. // t - interval
  10191. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10192. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10193. var d1 = distSquare(_v1, _v0);
  10194. if (prev >= 0 && d1 < d) {
  10195. t = prev;
  10196. d = d1;
  10197. }
  10198. else {
  10199. // t + interval
  10200. _v2[0] = quadraticAt(x0, x1, x2, next);
  10201. _v2[1] = quadraticAt(y0, y1, y2, next);
  10202. var d2 = distSquare(_v2, _v0);
  10203. if (next <= 1 && d2 < d) {
  10204. t = next;
  10205. d = d2;
  10206. }
  10207. else {
  10208. interval *= 0.5;
  10209. }
  10210. }
  10211. }
  10212. // t
  10213. if (out) {
  10214. out[0] = quadraticAt(x0, x1, x2, t);
  10215. out[1] = quadraticAt(y0, y1, y2, t);
  10216. }
  10217. // console.log(interval, i);
  10218. return mathSqrt$2(d);
  10219. }
  10220. /**
  10221. * @author Yi Shen(https://github.com/pissang)
  10222. */
  10223. var mathMin$3 = Math.min;
  10224. var mathMax$3 = Math.max;
  10225. var mathSin$2 = Math.sin;
  10226. var mathCos$2 = Math.cos;
  10227. var PI2 = Math.PI * 2;
  10228. var start = create();
  10229. var end = create();
  10230. var extremity = create();
  10231. /**
  10232. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10233. * @module zrender/core/bbox
  10234. * @param {Array<Object>} points 顶点数组
  10235. * @param {number} min
  10236. * @param {number} max
  10237. */
  10238. /**
  10239. * @memberOf module:zrender/core/bbox
  10240. * @param {number} x0
  10241. * @param {number} y0
  10242. * @param {number} x1
  10243. * @param {number} y1
  10244. * @param {Array.<number>} min
  10245. * @param {Array.<number>} max
  10246. */
  10247. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10248. min$$1[0] = mathMin$3(x0, x1);
  10249. min$$1[1] = mathMin$3(y0, y1);
  10250. max$$1[0] = mathMax$3(x0, x1);
  10251. max$$1[1] = mathMax$3(y0, y1);
  10252. }
  10253. var xDim = [];
  10254. var yDim = [];
  10255. /**
  10256. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10257. * @memberOf module:zrender/core/bbox
  10258. * @param {number} x0
  10259. * @param {number} y0
  10260. * @param {number} x1
  10261. * @param {number} y1
  10262. * @param {number} x2
  10263. * @param {number} y2
  10264. * @param {number} x3
  10265. * @param {number} y3
  10266. * @param {Array.<number>} min
  10267. * @param {Array.<number>} max
  10268. */
  10269. function fromCubic(
  10270. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10271. ) {
  10272. var cubicExtrema$$1 = cubicExtrema;
  10273. var cubicAt$$1 = cubicAt;
  10274. var i;
  10275. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10276. min$$1[0] = Infinity;
  10277. min$$1[1] = Infinity;
  10278. max$$1[0] = -Infinity;
  10279. max$$1[1] = -Infinity;
  10280. for (i = 0; i < n; i++) {
  10281. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10282. min$$1[0] = mathMin$3(x, min$$1[0]);
  10283. max$$1[0] = mathMax$3(x, max$$1[0]);
  10284. }
  10285. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10286. for (i = 0; i < n; i++) {
  10287. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10288. min$$1[1] = mathMin$3(y, min$$1[1]);
  10289. max$$1[1] = mathMax$3(y, max$$1[1]);
  10290. }
  10291. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10292. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10293. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10294. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10295. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10296. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10297. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10298. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10299. }
  10300. /**
  10301. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10302. * @memberOf module:zrender/core/bbox
  10303. * @param {number} x0
  10304. * @param {number} y0
  10305. * @param {number} x1
  10306. * @param {number} y1
  10307. * @param {number} x2
  10308. * @param {number} y2
  10309. * @param {Array.<number>} min
  10310. * @param {Array.<number>} max
  10311. */
  10312. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10313. var quadraticExtremum$$1 = quadraticExtremum;
  10314. var quadraticAt$$1 = quadraticAt;
  10315. // Find extremities, where derivative in x dim or y dim is zero
  10316. var tx =
  10317. mathMax$3(
  10318. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10319. );
  10320. var ty =
  10321. mathMax$3(
  10322. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10323. );
  10324. var x = quadraticAt$$1(x0, x1, x2, tx);
  10325. var y = quadraticAt$$1(y0, y1, y2, ty);
  10326. min$$1[0] = mathMin$3(x0, x2, x);
  10327. min$$1[1] = mathMin$3(y0, y2, y);
  10328. max$$1[0] = mathMax$3(x0, x2, x);
  10329. max$$1[1] = mathMax$3(y0, y2, y);
  10330. }
  10331. /**
  10332. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10333. * @method
  10334. * @memberOf module:zrender/core/bbox
  10335. * @param {number} x
  10336. * @param {number} y
  10337. * @param {number} rx
  10338. * @param {number} ry
  10339. * @param {number} startAngle
  10340. * @param {number} endAngle
  10341. * @param {number} anticlockwise
  10342. * @param {Array.<number>} min
  10343. * @param {Array.<number>} max
  10344. */
  10345. function fromArc(
  10346. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10347. ) {
  10348. var vec2Min = min;
  10349. var vec2Max = max;
  10350. var diff = Math.abs(startAngle - endAngle);
  10351. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10352. // Is a circle
  10353. min$$1[0] = x - rx;
  10354. min$$1[1] = y - ry;
  10355. max$$1[0] = x + rx;
  10356. max$$1[1] = y + ry;
  10357. return;
  10358. }
  10359. start[0] = mathCos$2(startAngle) * rx + x;
  10360. start[1] = mathSin$2(startAngle) * ry + y;
  10361. end[0] = mathCos$2(endAngle) * rx + x;
  10362. end[1] = mathSin$2(endAngle) * ry + y;
  10363. vec2Min(min$$1, start, end);
  10364. vec2Max(max$$1, start, end);
  10365. // Thresh to [0, Math.PI * 2]
  10366. startAngle = startAngle % (PI2);
  10367. if (startAngle < 0) {
  10368. startAngle = startAngle + PI2;
  10369. }
  10370. endAngle = endAngle % (PI2);
  10371. if (endAngle < 0) {
  10372. endAngle = endAngle + PI2;
  10373. }
  10374. if (startAngle > endAngle && !anticlockwise) {
  10375. endAngle += PI2;
  10376. }
  10377. else if (startAngle < endAngle && anticlockwise) {
  10378. startAngle += PI2;
  10379. }
  10380. if (anticlockwise) {
  10381. var tmp = endAngle;
  10382. endAngle = startAngle;
  10383. startAngle = tmp;
  10384. }
  10385. // var number = 0;
  10386. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10387. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10388. if (angle > startAngle) {
  10389. extremity[0] = mathCos$2(angle) * rx + x;
  10390. extremity[1] = mathSin$2(angle) * ry + y;
  10391. vec2Min(min$$1, extremity, min$$1);
  10392. vec2Max(max$$1, extremity, max$$1);
  10393. }
  10394. }
  10395. }
  10396. /**
  10397. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10398. * 可以用于 isInsidePath 判断以及获取boundingRect
  10399. *
  10400. * @module zrender/core/PathProxy
  10401. * @author Yi Shen (http://www.github.com/pissang)
  10402. */
  10403. // TODO getTotalLength, getPointAtLength
  10404. var CMD = {
  10405. M: 1,
  10406. L: 2,
  10407. C: 3,
  10408. Q: 4,
  10409. A: 5,
  10410. Z: 6,
  10411. // Rect
  10412. R: 7
  10413. };
  10414. // var CMD_MEM_SIZE = {
  10415. // M: 3,
  10416. // L: 3,
  10417. // C: 7,
  10418. // Q: 5,
  10419. // A: 9,
  10420. // R: 5,
  10421. // Z: 1
  10422. // };
  10423. var min$1 = [];
  10424. var max$1 = [];
  10425. var min2 = [];
  10426. var max2 = [];
  10427. var mathMin$2 = Math.min;
  10428. var mathMax$2 = Math.max;
  10429. var mathCos$1 = Math.cos;
  10430. var mathSin$1 = Math.sin;
  10431. var mathSqrt$1 = Math.sqrt;
  10432. var mathAbs = Math.abs;
  10433. var hasTypedArray = typeof Float32Array != 'undefined';
  10434. /**
  10435. * @alias module:zrender/core/PathProxy
  10436. * @constructor
  10437. */
  10438. var PathProxy = function (notSaveData) {
  10439. this._saveData = !(notSaveData || false);
  10440. if (this._saveData) {
  10441. /**
  10442. * Path data. Stored as flat array
  10443. * @type {Array.<Object>}
  10444. */
  10445. this.data = [];
  10446. }
  10447. this._ctx = null;
  10448. };
  10449. /**
  10450. * 快速计算Path包围盒(并不是最小包围盒)
  10451. * @return {Object}
  10452. */
  10453. PathProxy.prototype = {
  10454. constructor: PathProxy,
  10455. _xi: 0,
  10456. _yi: 0,
  10457. _x0: 0,
  10458. _y0: 0,
  10459. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10460. _ux: 0,
  10461. _uy: 0,
  10462. _len: 0,
  10463. _lineDash: null,
  10464. _dashOffset: 0,
  10465. _dashIdx: 0,
  10466. _dashSum: 0,
  10467. /**
  10468. * @readOnly
  10469. */
  10470. setScale: function (sx, sy) {
  10471. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10472. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10473. },
  10474. getContext: function () {
  10475. return this._ctx;
  10476. },
  10477. /**
  10478. * @param {CanvasRenderingContext2D} ctx
  10479. * @return {module:zrender/core/PathProxy}
  10480. */
  10481. beginPath: function (ctx) {
  10482. this._ctx = ctx;
  10483. ctx && ctx.beginPath();
  10484. ctx && (this.dpr = ctx.dpr);
  10485. // Reset
  10486. if (this._saveData) {
  10487. this._len = 0;
  10488. }
  10489. if (this._lineDash) {
  10490. this._lineDash = null;
  10491. this._dashOffset = 0;
  10492. }
  10493. return this;
  10494. },
  10495. /**
  10496. * @param {number} x
  10497. * @param {number} y
  10498. * @return {module:zrender/core/PathProxy}
  10499. */
  10500. moveTo: function (x, y) {
  10501. this.addData(CMD.M, x, y);
  10502. this._ctx && this._ctx.moveTo(x, y);
  10503. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  10504. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  10505. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  10506. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  10507. this._x0 = x;
  10508. this._y0 = y;
  10509. this._xi = x;
  10510. this._yi = y;
  10511. return this;
  10512. },
  10513. /**
  10514. * @param {number} x
  10515. * @param {number} y
  10516. * @return {module:zrender/core/PathProxy}
  10517. */
  10518. lineTo: function (x, y) {
  10519. var exceedUnit = mathAbs(x - this._xi) > this._ux
  10520. || mathAbs(y - this._yi) > this._uy
  10521. // Force draw the first segment
  10522. || this._len < 5;
  10523. this.addData(CMD.L, x, y);
  10524. if (this._ctx && exceedUnit) {
  10525. this._needsDash() ? this._dashedLineTo(x, y)
  10526. : this._ctx.lineTo(x, y);
  10527. }
  10528. if (exceedUnit) {
  10529. this._xi = x;
  10530. this._yi = y;
  10531. }
  10532. return this;
  10533. },
  10534. /**
  10535. * @param {number} x1
  10536. * @param {number} y1
  10537. * @param {number} x2
  10538. * @param {number} y2
  10539. * @param {number} x3
  10540. * @param {number} y3
  10541. * @return {module:zrender/core/PathProxy}
  10542. */
  10543. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  10544. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  10545. if (this._ctx) {
  10546. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  10547. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10548. }
  10549. this._xi = x3;
  10550. this._yi = y3;
  10551. return this;
  10552. },
  10553. /**
  10554. * @param {number} x1
  10555. * @param {number} y1
  10556. * @param {number} x2
  10557. * @param {number} y2
  10558. * @return {module:zrender/core/PathProxy}
  10559. */
  10560. quadraticCurveTo: function (x1, y1, x2, y2) {
  10561. this.addData(CMD.Q, x1, y1, x2, y2);
  10562. if (this._ctx) {
  10563. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  10564. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  10565. }
  10566. this._xi = x2;
  10567. this._yi = y2;
  10568. return this;
  10569. },
  10570. /**
  10571. * @param {number} cx
  10572. * @param {number} cy
  10573. * @param {number} r
  10574. * @param {number} startAngle
  10575. * @param {number} endAngle
  10576. * @param {boolean} anticlockwise
  10577. * @return {module:zrender/core/PathProxy}
  10578. */
  10579. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  10580. this.addData(
  10581. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  10582. );
  10583. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10584. this._xi = mathCos$1(endAngle) * r + cx;
  10585. this._yi = mathSin$1(endAngle) * r + cx;
  10586. return this;
  10587. },
  10588. // TODO
  10589. arcTo: function (x1, y1, x2, y2, radius) {
  10590. if (this._ctx) {
  10591. this._ctx.arcTo(x1, y1, x2, y2, radius);
  10592. }
  10593. return this;
  10594. },
  10595. // TODO
  10596. rect: function (x, y, w, h) {
  10597. this._ctx && this._ctx.rect(x, y, w, h);
  10598. this.addData(CMD.R, x, y, w, h);
  10599. return this;
  10600. },
  10601. /**
  10602. * @return {module:zrender/core/PathProxy}
  10603. */
  10604. closePath: function () {
  10605. this.addData(CMD.Z);
  10606. var ctx = this._ctx;
  10607. var x0 = this._x0;
  10608. var y0 = this._y0;
  10609. if (ctx) {
  10610. this._needsDash() && this._dashedLineTo(x0, y0);
  10611. ctx.closePath();
  10612. }
  10613. this._xi = x0;
  10614. this._yi = y0;
  10615. return this;
  10616. },
  10617. /**
  10618. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  10619. * stroke 同样
  10620. * @param {CanvasRenderingContext2D} ctx
  10621. * @return {module:zrender/core/PathProxy}
  10622. */
  10623. fill: function (ctx) {
  10624. ctx && ctx.fill();
  10625. this.toStatic();
  10626. },
  10627. /**
  10628. * @param {CanvasRenderingContext2D} ctx
  10629. * @return {module:zrender/core/PathProxy}
  10630. */
  10631. stroke: function (ctx) {
  10632. ctx && ctx.stroke();
  10633. this.toStatic();
  10634. },
  10635. /**
  10636. * 必须在其它绘制命令前调用
  10637. * Must be invoked before all other path drawing methods
  10638. * @return {module:zrender/core/PathProxy}
  10639. */
  10640. setLineDash: function (lineDash) {
  10641. if (lineDash instanceof Array) {
  10642. this._lineDash = lineDash;
  10643. this._dashIdx = 0;
  10644. var lineDashSum = 0;
  10645. for (var i = 0; i < lineDash.length; i++) {
  10646. lineDashSum += lineDash[i];
  10647. }
  10648. this._dashSum = lineDashSum;
  10649. }
  10650. return this;
  10651. },
  10652. /**
  10653. * 必须在其它绘制命令前调用
  10654. * Must be invoked before all other path drawing methods
  10655. * @return {module:zrender/core/PathProxy}
  10656. */
  10657. setLineDashOffset: function (offset) {
  10658. this._dashOffset = offset;
  10659. return this;
  10660. },
  10661. /**
  10662. *
  10663. * @return {boolean}
  10664. */
  10665. len: function () {
  10666. return this._len;
  10667. },
  10668. /**
  10669. * 直接设置 Path 数据
  10670. */
  10671. setData: function (data) {
  10672. var len$$1 = data.length;
  10673. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  10674. this.data = new Float32Array(len$$1);
  10675. }
  10676. for (var i = 0; i < len$$1; i++) {
  10677. this.data[i] = data[i];
  10678. }
  10679. this._len = len$$1;
  10680. },
  10681. /**
  10682. * 添加子路径
  10683. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  10684. */
  10685. appendPath: function (path) {
  10686. if (!(path instanceof Array)) {
  10687. path = [path];
  10688. }
  10689. var len$$1 = path.length;
  10690. var appendSize = 0;
  10691. var offset = this._len;
  10692. for (var i = 0; i < len$$1; i++) {
  10693. appendSize += path[i].len();
  10694. }
  10695. if (hasTypedArray && (this.data instanceof Float32Array)) {
  10696. this.data = new Float32Array(offset + appendSize);
  10697. }
  10698. for (var i = 0; i < len$$1; i++) {
  10699. var appendPathData = path[i].data;
  10700. for (var k = 0; k < appendPathData.length; k++) {
  10701. this.data[offset++] = appendPathData[k];
  10702. }
  10703. }
  10704. this._len = offset;
  10705. },
  10706. /**
  10707. * 填充 Path 数据。
  10708. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  10709. */
  10710. addData: function (cmd) {
  10711. if (!this._saveData) {
  10712. return;
  10713. }
  10714. var data = this.data;
  10715. if (this._len + arguments.length > data.length) {
  10716. // 因为之前的数组已经转换成静态的 Float32Array
  10717. // 所以不够用时需要扩展一个新的动态数组
  10718. this._expandData();
  10719. data = this.data;
  10720. }
  10721. for (var i = 0; i < arguments.length; i++) {
  10722. data[this._len++] = arguments[i];
  10723. }
  10724. this._prevCmd = cmd;
  10725. },
  10726. _expandData: function () {
  10727. // Only if data is Float32Array
  10728. if (!(this.data instanceof Array)) {
  10729. var newData = [];
  10730. for (var i = 0; i < this._len; i++) {
  10731. newData[i] = this.data[i];
  10732. }
  10733. this.data = newData;
  10734. }
  10735. },
  10736. /**
  10737. * If needs js implemented dashed line
  10738. * @return {boolean}
  10739. * @private
  10740. */
  10741. _needsDash: function () {
  10742. return this._lineDash;
  10743. },
  10744. _dashedLineTo: function (x1, y1) {
  10745. var dashSum = this._dashSum;
  10746. var offset = this._dashOffset;
  10747. var lineDash = this._lineDash;
  10748. var ctx = this._ctx;
  10749. var x0 = this._xi;
  10750. var y0 = this._yi;
  10751. var dx = x1 - x0;
  10752. var dy = y1 - y0;
  10753. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  10754. var x = x0;
  10755. var y = y0;
  10756. var dash;
  10757. var nDash = lineDash.length;
  10758. var idx;
  10759. dx /= dist$$1;
  10760. dy /= dist$$1;
  10761. if (offset < 0) {
  10762. // Convert to positive offset
  10763. offset = dashSum + offset;
  10764. }
  10765. offset %= dashSum;
  10766. x -= offset * dx;
  10767. y -= offset * dy;
  10768. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  10769. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  10770. idx = this._dashIdx;
  10771. dash = lineDash[idx];
  10772. x += dx * dash;
  10773. y += dy * dash;
  10774. this._dashIdx = (idx + 1) % nDash;
  10775. // Skip positive offset
  10776. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  10777. continue;
  10778. }
  10779. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  10780. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  10781. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  10782. );
  10783. }
  10784. // Offset for next lineTo
  10785. dx = x - x1;
  10786. dy = y - y1;
  10787. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  10788. },
  10789. // Not accurate dashed line to
  10790. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  10791. var dashSum = this._dashSum;
  10792. var offset = this._dashOffset;
  10793. var lineDash = this._lineDash;
  10794. var ctx = this._ctx;
  10795. var x0 = this._xi;
  10796. var y0 = this._yi;
  10797. var t;
  10798. var dx;
  10799. var dy;
  10800. var cubicAt$$1 = cubicAt;
  10801. var bezierLen = 0;
  10802. var idx = this._dashIdx;
  10803. var nDash = lineDash.length;
  10804. var x;
  10805. var y;
  10806. var tmpLen = 0;
  10807. if (offset < 0) {
  10808. // Convert to positive offset
  10809. offset = dashSum + offset;
  10810. }
  10811. offset %= dashSum;
  10812. // Bezier approx length
  10813. for (t = 0; t < 1; t += 0.1) {
  10814. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  10815. - cubicAt$$1(x0, x1, x2, x3, t);
  10816. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  10817. - cubicAt$$1(y0, y1, y2, y3, t);
  10818. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  10819. }
  10820. // Find idx after add offset
  10821. for (; idx < nDash; idx++) {
  10822. tmpLen += lineDash[idx];
  10823. if (tmpLen > offset) {
  10824. break;
  10825. }
  10826. }
  10827. t = (tmpLen - offset) / bezierLen;
  10828. while (t <= 1) {
  10829. x = cubicAt$$1(x0, x1, x2, x3, t);
  10830. y = cubicAt$$1(y0, y1, y2, y3, t);
  10831. // Use line to approximate dashed bezier
  10832. // Bad result if dash is long
  10833. idx % 2 ? ctx.moveTo(x, y)
  10834. : ctx.lineTo(x, y);
  10835. t += lineDash[idx] / bezierLen;
  10836. idx = (idx + 1) % nDash;
  10837. }
  10838. // Finish the last segment and calculate the new offset
  10839. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  10840. dx = x3 - x;
  10841. dy = y3 - y;
  10842. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  10843. },
  10844. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  10845. // Convert quadratic to cubic using degree elevation
  10846. var x3 = x2;
  10847. var y3 = y2;
  10848. x2 = (x2 + 2 * x1) / 3;
  10849. y2 = (y2 + 2 * y1) / 3;
  10850. x1 = (this._xi + 2 * x1) / 3;
  10851. y1 = (this._yi + 2 * y1) / 3;
  10852. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  10853. },
  10854. /**
  10855. * 转成静态的 Float32Array 减少堆内存占用
  10856. * Convert dynamic array to static Float32Array
  10857. */
  10858. toStatic: function () {
  10859. var data = this.data;
  10860. if (data instanceof Array) {
  10861. data.length = this._len;
  10862. if (hasTypedArray) {
  10863. this.data = new Float32Array(data);
  10864. }
  10865. }
  10866. },
  10867. /**
  10868. * @return {module:zrender/core/BoundingRect}
  10869. */
  10870. getBoundingRect: function () {
  10871. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  10872. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  10873. var data = this.data;
  10874. var xi = 0;
  10875. var yi = 0;
  10876. var x0 = 0;
  10877. var y0 = 0;
  10878. for (var i = 0; i < data.length;) {
  10879. var cmd = data[i++];
  10880. if (i == 1) {
  10881. // 如果第一个命令是 L, C, Q
  10882. // 则 previous point 同绘制命令的第一个 point
  10883. //
  10884. // 第一个命令为 Arc 的情况下会在后面特殊处理
  10885. xi = data[i];
  10886. yi = data[i + 1];
  10887. x0 = xi;
  10888. y0 = yi;
  10889. }
  10890. switch (cmd) {
  10891. case CMD.M:
  10892. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  10893. // 在 closePath 的时候使用
  10894. x0 = data[i++];
  10895. y0 = data[i++];
  10896. xi = x0;
  10897. yi = y0;
  10898. min2[0] = x0;
  10899. min2[1] = y0;
  10900. max2[0] = x0;
  10901. max2[1] = y0;
  10902. break;
  10903. case CMD.L:
  10904. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10905. xi = data[i++];
  10906. yi = data[i++];
  10907. break;
  10908. case CMD.C:
  10909. fromCubic(
  10910. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  10911. min2, max2
  10912. );
  10913. xi = data[i++];
  10914. yi = data[i++];
  10915. break;
  10916. case CMD.Q:
  10917. fromQuadratic(
  10918. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  10919. min2, max2
  10920. );
  10921. xi = data[i++];
  10922. yi = data[i++];
  10923. break;
  10924. case CMD.A:
  10925. // TODO Arc 判断的开销比较大
  10926. var cx = data[i++];
  10927. var cy = data[i++];
  10928. var rx = data[i++];
  10929. var ry = data[i++];
  10930. var startAngle = data[i++];
  10931. var endAngle = data[i++] + startAngle;
  10932. // TODO Arc 旋转
  10933. var psi = data[i++];
  10934. var anticlockwise = 1 - data[i++];
  10935. if (i == 1) {
  10936. // 直接使用 arc 命令
  10937. // 第一个命令起点还未定义
  10938. x0 = mathCos$1(startAngle) * rx + cx;
  10939. y0 = mathSin$1(startAngle) * ry + cy;
  10940. }
  10941. fromArc(
  10942. cx, cy, rx, ry, startAngle, endAngle,
  10943. anticlockwise, min2, max2
  10944. );
  10945. xi = mathCos$1(endAngle) * rx + cx;
  10946. yi = mathSin$1(endAngle) * ry + cy;
  10947. break;
  10948. case CMD.R:
  10949. x0 = xi = data[i++];
  10950. y0 = yi = data[i++];
  10951. var width = data[i++];
  10952. var height = data[i++];
  10953. // Use fromLine
  10954. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10955. break;
  10956. case CMD.Z:
  10957. xi = x0;
  10958. yi = y0;
  10959. break;
  10960. }
  10961. // Union
  10962. min(min$1, min$1, min2);
  10963. max(max$1, max$1, max2);
  10964. }
  10965. // No data
  10966. if (i === 0) {
  10967. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10968. }
  10969. return new BoundingRect(
  10970. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  10971. );
  10972. },
  10973. /**
  10974. * Rebuild path from current data
  10975. * Rebuild path will not consider javascript implemented line dash.
  10976. * @param {CanvasRenderingContext2D} ctx
  10977. */
  10978. rebuildPath: function (ctx) {
  10979. var d = this.data;
  10980. var x0, y0;
  10981. var xi, yi;
  10982. var x, y;
  10983. var ux = this._ux;
  10984. var uy = this._uy;
  10985. var len$$1 = this._len;
  10986. for (var i = 0; i < len$$1;) {
  10987. var cmd = d[i++];
  10988. if (i == 1) {
  10989. // 如果第一个命令是 L, C, Q
  10990. // 则 previous point 同绘制命令的第一个 point
  10991. //
  10992. // 第一个命令为 Arc 的情况下会在后面特殊处理
  10993. xi = d[i];
  10994. yi = d[i + 1];
  10995. x0 = xi;
  10996. y0 = yi;
  10997. }
  10998. switch (cmd) {
  10999. case CMD.M:
  11000. x0 = xi = d[i++];
  11001. y0 = yi = d[i++];
  11002. ctx.moveTo(xi, yi);
  11003. break;
  11004. case CMD.L:
  11005. x = d[i++];
  11006. y = d[i++];
  11007. // Not draw too small seg between
  11008. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11009. ctx.lineTo(x, y);
  11010. xi = x;
  11011. yi = y;
  11012. }
  11013. break;
  11014. case CMD.C:
  11015. ctx.bezierCurveTo(
  11016. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11017. );
  11018. xi = d[i - 2];
  11019. yi = d[i - 1];
  11020. break;
  11021. case CMD.Q:
  11022. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11023. xi = d[i - 2];
  11024. yi = d[i - 1];
  11025. break;
  11026. case CMD.A:
  11027. var cx = d[i++];
  11028. var cy = d[i++];
  11029. var rx = d[i++];
  11030. var ry = d[i++];
  11031. var theta = d[i++];
  11032. var dTheta = d[i++];
  11033. var psi = d[i++];
  11034. var fs = d[i++];
  11035. var r = (rx > ry) ? rx : ry;
  11036. var scaleX = (rx > ry) ? 1 : rx / ry;
  11037. var scaleY = (rx > ry) ? ry / rx : 1;
  11038. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11039. var endAngle = theta + dTheta;
  11040. if (isEllipse) {
  11041. ctx.translate(cx, cy);
  11042. ctx.rotate(psi);
  11043. ctx.scale(scaleX, scaleY);
  11044. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11045. ctx.scale(1 / scaleX, 1 / scaleY);
  11046. ctx.rotate(-psi);
  11047. ctx.translate(-cx, -cy);
  11048. }
  11049. else {
  11050. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11051. }
  11052. if (i == 1) {
  11053. // 直接使用 arc 命令
  11054. // 第一个命令起点还未定义
  11055. x0 = mathCos$1(theta) * rx + cx;
  11056. y0 = mathSin$1(theta) * ry + cy;
  11057. }
  11058. xi = mathCos$1(endAngle) * rx + cx;
  11059. yi = mathSin$1(endAngle) * ry + cy;
  11060. break;
  11061. case CMD.R:
  11062. x0 = xi = d[i];
  11063. y0 = yi = d[i + 1];
  11064. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11065. break;
  11066. case CMD.Z:
  11067. ctx.closePath();
  11068. xi = x0;
  11069. yi = y0;
  11070. }
  11071. }
  11072. }
  11073. };
  11074. PathProxy.CMD = CMD;
  11075. /**
  11076. * 线段包含判断
  11077. * @param {number} x0
  11078. * @param {number} y0
  11079. * @param {number} x1
  11080. * @param {number} y1
  11081. * @param {number} lineWidth
  11082. * @param {number} x
  11083. * @param {number} y
  11084. * @return {boolean}
  11085. */
  11086. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11087. if (lineWidth === 0) {
  11088. return false;
  11089. }
  11090. var _l = lineWidth;
  11091. var _a = 0;
  11092. var _b = x0;
  11093. // Quick reject
  11094. if (
  11095. (y > y0 + _l && y > y1 + _l)
  11096. || (y < y0 - _l && y < y1 - _l)
  11097. || (x > x0 + _l && x > x1 + _l)
  11098. || (x < x0 - _l && x < x1 - _l)
  11099. ) {
  11100. return false;
  11101. }
  11102. if (x0 !== x1) {
  11103. _a = (y0 - y1) / (x0 - x1);
  11104. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11105. }
  11106. else {
  11107. return Math.abs(x - x0) <= _l / 2;
  11108. }
  11109. var tmp = _a * x - y + _b;
  11110. var _s = tmp * tmp / (_a * _a + 1);
  11111. return _s <= _l / 2 * _l / 2;
  11112. }
  11113. /**
  11114. * 三次贝塞尔曲线描边包含判断
  11115. * @param {number} x0
  11116. * @param {number} y0
  11117. * @param {number} x1
  11118. * @param {number} y1
  11119. * @param {number} x2
  11120. * @param {number} y2
  11121. * @param {number} x3
  11122. * @param {number} y3
  11123. * @param {number} lineWidth
  11124. * @param {number} x
  11125. * @param {number} y
  11126. * @return {boolean}
  11127. */
  11128. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11129. if (lineWidth === 0) {
  11130. return false;
  11131. }
  11132. var _l = lineWidth;
  11133. // Quick reject
  11134. if (
  11135. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11136. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11137. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11138. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11139. ) {
  11140. return false;
  11141. }
  11142. var d = cubicProjectPoint(
  11143. x0, y0, x1, y1, x2, y2, x3, y3,
  11144. x, y, null
  11145. );
  11146. return d <= _l / 2;
  11147. }
  11148. /**
  11149. * 二次贝塞尔曲线描边包含判断
  11150. * @param {number} x0
  11151. * @param {number} y0
  11152. * @param {number} x1
  11153. * @param {number} y1
  11154. * @param {number} x2
  11155. * @param {number} y2
  11156. * @param {number} lineWidth
  11157. * @param {number} x
  11158. * @param {number} y
  11159. * @return {boolean}
  11160. */
  11161. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11162. if (lineWidth === 0) {
  11163. return false;
  11164. }
  11165. var _l = lineWidth;
  11166. // Quick reject
  11167. if (
  11168. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11169. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11170. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11171. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11172. ) {
  11173. return false;
  11174. }
  11175. var d = quadraticProjectPoint(
  11176. x0, y0, x1, y1, x2, y2,
  11177. x, y, null
  11178. );
  11179. return d <= _l / 2;
  11180. }
  11181. var PI2$3 = Math.PI * 2;
  11182. function normalizeRadian(angle) {
  11183. angle %= PI2$3;
  11184. if (angle < 0) {
  11185. angle += PI2$3;
  11186. }
  11187. return angle;
  11188. }
  11189. var PI2$2 = Math.PI * 2;
  11190. /**
  11191. * 圆弧描边包含判断
  11192. * @param {number} cx
  11193. * @param {number} cy
  11194. * @param {number} r
  11195. * @param {number} startAngle
  11196. * @param {number} endAngle
  11197. * @param {boolean} anticlockwise
  11198. * @param {number} lineWidth
  11199. * @param {number} x
  11200. * @param {number} y
  11201. * @return {Boolean}
  11202. */
  11203. function containStroke$4(
  11204. cx, cy, r, startAngle, endAngle, anticlockwise,
  11205. lineWidth, x, y
  11206. ) {
  11207. if (lineWidth === 0) {
  11208. return false;
  11209. }
  11210. var _l = lineWidth;
  11211. x -= cx;
  11212. y -= cy;
  11213. var d = Math.sqrt(x * x + y * y);
  11214. if ((d - _l > r) || (d + _l < r)) {
  11215. return false;
  11216. }
  11217. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11218. // Is a circle
  11219. return true;
  11220. }
  11221. if (anticlockwise) {
  11222. var tmp = startAngle;
  11223. startAngle = normalizeRadian(endAngle);
  11224. endAngle = normalizeRadian(tmp);
  11225. } else {
  11226. startAngle = normalizeRadian(startAngle);
  11227. endAngle = normalizeRadian(endAngle);
  11228. }
  11229. if (startAngle > endAngle) {
  11230. endAngle += PI2$2;
  11231. }
  11232. var angle = Math.atan2(y, x);
  11233. if (angle < 0) {
  11234. angle += PI2$2;
  11235. }
  11236. return (angle >= startAngle && angle <= endAngle)
  11237. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11238. }
  11239. function windingLine(x0, y0, x1, y1, x, y) {
  11240. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11241. return 0;
  11242. }
  11243. // Ignore horizontal line
  11244. if (y1 === y0) {
  11245. return 0;
  11246. }
  11247. var dir = y1 < y0 ? 1 : -1;
  11248. var t = (y - y0) / (y1 - y0);
  11249. // Avoid winding error when intersection point is the connect point of two line of polygon
  11250. if (t === 1 || t === 0) {
  11251. dir = y1 < y0 ? 0.5 : -0.5;
  11252. }
  11253. var x_ = t * (x1 - x0) + x0;
  11254. return x_ > x ? dir : 0;
  11255. }
  11256. var CMD$1 = PathProxy.CMD;
  11257. var PI2$1 = Math.PI * 2;
  11258. var EPSILON$2 = 1e-4;
  11259. function isAroundEqual(a, b) {
  11260. return Math.abs(a - b) < EPSILON$2;
  11261. }
  11262. // 临时数组
  11263. var roots = [-1, -1, -1];
  11264. var extrema = [-1, -1];
  11265. function swapExtrema() {
  11266. var tmp = extrema[0];
  11267. extrema[0] = extrema[1];
  11268. extrema[1] = tmp;
  11269. }
  11270. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11271. // Quick reject
  11272. if (
  11273. (y > y0 && y > y1 && y > y2 && y > y3)
  11274. || (y < y0 && y < y1 && y < y2 && y < y3)
  11275. ) {
  11276. return 0;
  11277. }
  11278. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11279. if (nRoots === 0) {
  11280. return 0;
  11281. }
  11282. else {
  11283. var w = 0;
  11284. var nExtrema = -1;
  11285. var y0_, y1_;
  11286. for (var i = 0; i < nRoots; i++) {
  11287. var t = roots[i];
  11288. // Avoid winding error when intersection point is the connect point of two line of polygon
  11289. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11290. var x_ = cubicAt(x0, x1, x2, x3, t);
  11291. if (x_ < x) { // Quick reject
  11292. continue;
  11293. }
  11294. if (nExtrema < 0) {
  11295. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11296. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11297. swapExtrema();
  11298. }
  11299. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11300. if (nExtrema > 1) {
  11301. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11302. }
  11303. }
  11304. if (nExtrema == 2) {
  11305. // 分成三段单调函数
  11306. if (t < extrema[0]) {
  11307. w += y0_ < y0 ? unit : -unit;
  11308. }
  11309. else if (t < extrema[1]) {
  11310. w += y1_ < y0_ ? unit : -unit;
  11311. }
  11312. else {
  11313. w += y3 < y1_ ? unit : -unit;
  11314. }
  11315. }
  11316. else {
  11317. // 分成两段单调函数
  11318. if (t < extrema[0]) {
  11319. w += y0_ < y0 ? unit : -unit;
  11320. }
  11321. else {
  11322. w += y3 < y0_ ? unit : -unit;
  11323. }
  11324. }
  11325. }
  11326. return w;
  11327. }
  11328. }
  11329. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11330. // Quick reject
  11331. if (
  11332. (y > y0 && y > y1 && y > y2)
  11333. || (y < y0 && y < y1 && y < y2)
  11334. ) {
  11335. return 0;
  11336. }
  11337. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11338. if (nRoots === 0) {
  11339. return 0;
  11340. }
  11341. else {
  11342. var t = quadraticExtremum(y0, y1, y2);
  11343. if (t >= 0 && t <= 1) {
  11344. var w = 0;
  11345. var y_ = quadraticAt(y0, y1, y2, t);
  11346. for (var i = 0; i < nRoots; i++) {
  11347. // Remove one endpoint.
  11348. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11349. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11350. if (x_ < x) { // Quick reject
  11351. continue;
  11352. }
  11353. if (roots[i] < t) {
  11354. w += y_ < y0 ? unit : -unit;
  11355. }
  11356. else {
  11357. w += y2 < y_ ? unit : -unit;
  11358. }
  11359. }
  11360. return w;
  11361. }
  11362. else {
  11363. // Remove one endpoint.
  11364. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11365. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11366. if (x_ < x) { // Quick reject
  11367. return 0;
  11368. }
  11369. return y2 < y0 ? unit : -unit;
  11370. }
  11371. }
  11372. }
  11373. // TODO
  11374. // Arc 旋转
  11375. function windingArc(
  11376. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11377. ) {
  11378. y -= cy;
  11379. if (y > r || y < -r) {
  11380. return 0;
  11381. }
  11382. var tmp = Math.sqrt(r * r - y * y);
  11383. roots[0] = -tmp;
  11384. roots[1] = tmp;
  11385. var diff = Math.abs(startAngle - endAngle);
  11386. if (diff < 1e-4) {
  11387. return 0;
  11388. }
  11389. if (diff % PI2$1 < 1e-4) {
  11390. // Is a circle
  11391. startAngle = 0;
  11392. endAngle = PI2$1;
  11393. var dir = anticlockwise ? 1 : -1;
  11394. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11395. return dir;
  11396. } else {
  11397. return 0;
  11398. }
  11399. }
  11400. if (anticlockwise) {
  11401. var tmp = startAngle;
  11402. startAngle = normalizeRadian(endAngle);
  11403. endAngle = normalizeRadian(tmp);
  11404. }
  11405. else {
  11406. startAngle = normalizeRadian(startAngle);
  11407. endAngle = normalizeRadian(endAngle);
  11408. }
  11409. if (startAngle > endAngle) {
  11410. endAngle += PI2$1;
  11411. }
  11412. var w = 0;
  11413. for (var i = 0; i < 2; i++) {
  11414. var x_ = roots[i];
  11415. if (x_ + cx > x) {
  11416. var angle = Math.atan2(y, x_);
  11417. var dir = anticlockwise ? 1 : -1;
  11418. if (angle < 0) {
  11419. angle = PI2$1 + angle;
  11420. }
  11421. if (
  11422. (angle >= startAngle && angle <= endAngle)
  11423. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11424. ) {
  11425. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11426. dir = -dir;
  11427. }
  11428. w += dir;
  11429. }
  11430. }
  11431. }
  11432. return w;
  11433. }
  11434. function containPath(data, lineWidth, isStroke, x, y) {
  11435. var w = 0;
  11436. var xi = 0;
  11437. var yi = 0;
  11438. var x0 = 0;
  11439. var y0 = 0;
  11440. for (var i = 0; i < data.length;) {
  11441. var cmd = data[i++];
  11442. // Begin a new subpath
  11443. if (cmd === CMD$1.M && i > 1) {
  11444. // Close previous subpath
  11445. if (!isStroke) {
  11446. w += windingLine(xi, yi, x0, y0, x, y);
  11447. }
  11448. // 如果被任何一个 subpath 包含
  11449. // if (w !== 0) {
  11450. // return true;
  11451. // }
  11452. }
  11453. if (i == 1) {
  11454. // 如果第一个命令是 L, C, Q
  11455. // 则 previous point 同绘制命令的第一个 point
  11456. //
  11457. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11458. xi = data[i];
  11459. yi = data[i + 1];
  11460. x0 = xi;
  11461. y0 = yi;
  11462. }
  11463. switch (cmd) {
  11464. case CMD$1.M:
  11465. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11466. // 在 closePath 的时候使用
  11467. x0 = data[i++];
  11468. y0 = data[i++];
  11469. xi = x0;
  11470. yi = y0;
  11471. break;
  11472. case CMD$1.L:
  11473. if (isStroke) {
  11474. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11475. return true;
  11476. }
  11477. }
  11478. else {
  11479. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11480. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11481. }
  11482. xi = data[i++];
  11483. yi = data[i++];
  11484. break;
  11485. case CMD$1.C:
  11486. if (isStroke) {
  11487. if (containStroke$2(xi, yi,
  11488. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11489. lineWidth, x, y
  11490. )) {
  11491. return true;
  11492. }
  11493. }
  11494. else {
  11495. w += windingCubic(
  11496. xi, yi,
  11497. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11498. x, y
  11499. ) || 0;
  11500. }
  11501. xi = data[i++];
  11502. yi = data[i++];
  11503. break;
  11504. case CMD$1.Q:
  11505. if (isStroke) {
  11506. if (containStroke$3(xi, yi,
  11507. data[i++], data[i++], data[i], data[i + 1],
  11508. lineWidth, x, y
  11509. )) {
  11510. return true;
  11511. }
  11512. }
  11513. else {
  11514. w += windingQuadratic(
  11515. xi, yi,
  11516. data[i++], data[i++], data[i], data[i + 1],
  11517. x, y
  11518. ) || 0;
  11519. }
  11520. xi = data[i++];
  11521. yi = data[i++];
  11522. break;
  11523. case CMD$1.A:
  11524. // TODO Arc 判断的开销比较大
  11525. var cx = data[i++];
  11526. var cy = data[i++];
  11527. var rx = data[i++];
  11528. var ry = data[i++];
  11529. var theta = data[i++];
  11530. var dTheta = data[i++];
  11531. // TODO Arc 旋转
  11532. var psi = data[i++];
  11533. var anticlockwise = 1 - data[i++];
  11534. var x1 = Math.cos(theta) * rx + cx;
  11535. var y1 = Math.sin(theta) * ry + cy;
  11536. // 不是直接使用 arc 命令
  11537. if (i > 1) {
  11538. w += windingLine(xi, yi, x1, y1, x, y);
  11539. }
  11540. else {
  11541. // 第一个命令起点还未定义
  11542. x0 = x1;
  11543. y0 = y1;
  11544. }
  11545. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  11546. var _x = (x - cx) * ry / rx + cx;
  11547. if (isStroke) {
  11548. if (containStroke$4(
  11549. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11550. lineWidth, _x, y
  11551. )) {
  11552. return true;
  11553. }
  11554. }
  11555. else {
  11556. w += windingArc(
  11557. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  11558. _x, y
  11559. );
  11560. }
  11561. xi = Math.cos(theta + dTheta) * rx + cx;
  11562. yi = Math.sin(theta + dTheta) * ry + cy;
  11563. break;
  11564. case CMD$1.R:
  11565. x0 = xi = data[i++];
  11566. y0 = yi = data[i++];
  11567. var width = data[i++];
  11568. var height = data[i++];
  11569. var x1 = x0 + width;
  11570. var y1 = y0 + height;
  11571. if (isStroke) {
  11572. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  11573. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  11574. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  11575. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  11576. ) {
  11577. return true;
  11578. }
  11579. }
  11580. else {
  11581. // FIXME Clockwise ?
  11582. w += windingLine(x1, y0, x1, y1, x, y);
  11583. w += windingLine(x0, y1, x0, y0, x, y);
  11584. }
  11585. break;
  11586. case CMD$1.Z:
  11587. if (isStroke) {
  11588. if (containStroke$1(
  11589. xi, yi, x0, y0, lineWidth, x, y
  11590. )) {
  11591. return true;
  11592. }
  11593. }
  11594. else {
  11595. // Close a subpath
  11596. w += windingLine(xi, yi, x0, y0, x, y);
  11597. // 如果被任何一个 subpath 包含
  11598. // FIXME subpaths may overlap
  11599. // if (w !== 0) {
  11600. // return true;
  11601. // }
  11602. }
  11603. xi = x0;
  11604. yi = y0;
  11605. break;
  11606. }
  11607. }
  11608. if (!isStroke && !isAroundEqual(yi, y0)) {
  11609. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  11610. }
  11611. return w !== 0;
  11612. }
  11613. function contain(pathData, x, y) {
  11614. return containPath(pathData, 0, false, x, y);
  11615. }
  11616. function containStroke(pathData, lineWidth, x, y) {
  11617. return containPath(pathData, lineWidth, true, x, y);
  11618. }
  11619. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  11620. var abs = Math.abs;
  11621. var pathProxyForDraw = new PathProxy(true);
  11622. /**
  11623. * @alias module:zrender/graphic/Path
  11624. * @extends module:zrender/graphic/Displayable
  11625. * @constructor
  11626. * @param {Object} opts
  11627. */
  11628. function Path(opts) {
  11629. Displayable.call(this, opts);
  11630. /**
  11631. * @type {module:zrender/core/PathProxy}
  11632. * @readOnly
  11633. */
  11634. this.path = null;
  11635. }
  11636. Path.prototype = {
  11637. constructor: Path,
  11638. type: 'path',
  11639. __dirtyPath: true,
  11640. strokeContainThreshold: 5,
  11641. brush: function (ctx, prevEl) {
  11642. var style = this.style;
  11643. var path = this.path || pathProxyForDraw;
  11644. var hasStroke = style.hasStroke();
  11645. var hasFill = style.hasFill();
  11646. var fill = style.fill;
  11647. var stroke = style.stroke;
  11648. var hasFillGradient = hasFill && !!(fill.colorStops);
  11649. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  11650. var hasFillPattern = hasFill && !!(fill.image);
  11651. var hasStrokePattern = hasStroke && !!(stroke.image);
  11652. style.bind(ctx, this, prevEl);
  11653. this.setTransform(ctx);
  11654. if (this.__dirty) {
  11655. var rect;
  11656. // Update gradient because bounding rect may changed
  11657. if (hasFillGradient) {
  11658. rect = rect || this.getBoundingRect();
  11659. this._fillGradient = style.getGradient(ctx, fill, rect);
  11660. }
  11661. if (hasStrokeGradient) {
  11662. rect = rect || this.getBoundingRect();
  11663. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  11664. }
  11665. }
  11666. // Use the gradient or pattern
  11667. if (hasFillGradient) {
  11668. // PENDING If may have affect the state
  11669. ctx.fillStyle = this._fillGradient;
  11670. }
  11671. else if (hasFillPattern) {
  11672. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  11673. }
  11674. if (hasStrokeGradient) {
  11675. ctx.strokeStyle = this._strokeGradient;
  11676. }
  11677. else if (hasStrokePattern) {
  11678. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  11679. }
  11680. var lineDash = style.lineDash;
  11681. var lineDashOffset = style.lineDashOffset;
  11682. var ctxLineDash = !!ctx.setLineDash;
  11683. // Update path sx, sy
  11684. var scale = this.getGlobalScale();
  11685. path.setScale(scale[0], scale[1]);
  11686. // Proxy context
  11687. // Rebuild path in following 2 cases
  11688. // 1. Path is dirty
  11689. // 2. Path needs javascript implemented lineDash stroking.
  11690. // In this case, lineDash information will not be saved in PathProxy
  11691. if (this.__dirtyPath
  11692. || (lineDash && !ctxLineDash && hasStroke)
  11693. ) {
  11694. path.beginPath(ctx);
  11695. // Setting line dash before build path
  11696. if (lineDash && !ctxLineDash) {
  11697. path.setLineDash(lineDash);
  11698. path.setLineDashOffset(lineDashOffset);
  11699. }
  11700. this.buildPath(path, this.shape, false);
  11701. // Clear path dirty flag
  11702. if (this.path) {
  11703. this.__dirtyPath = false;
  11704. }
  11705. }
  11706. else {
  11707. // Replay path building
  11708. ctx.beginPath();
  11709. this.path.rebuildPath(ctx);
  11710. }
  11711. hasFill && path.fill(ctx);
  11712. if (lineDash && ctxLineDash) {
  11713. ctx.setLineDash(lineDash);
  11714. ctx.lineDashOffset = lineDashOffset;
  11715. }
  11716. hasStroke && path.stroke(ctx);
  11717. if (lineDash && ctxLineDash) {
  11718. // PENDING
  11719. // Remove lineDash
  11720. ctx.setLineDash([]);
  11721. }
  11722. // Draw rect text
  11723. if (style.text != null) {
  11724. // Only restore transform when needs draw text.
  11725. this.restoreTransform(ctx);
  11726. this.drawRectText(ctx, this.getBoundingRect());
  11727. }
  11728. },
  11729. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  11730. // Like in circle
  11731. buildPath: function (ctx, shapeCfg, inBundle) {},
  11732. createPathProxy: function () {
  11733. this.path = new PathProxy();
  11734. },
  11735. getBoundingRect: function () {
  11736. var rect = this._rect;
  11737. var style = this.style;
  11738. var needsUpdateRect = !rect;
  11739. if (needsUpdateRect) {
  11740. var path = this.path;
  11741. if (!path) {
  11742. // Create path on demand.
  11743. path = this.path = new PathProxy();
  11744. }
  11745. if (this.__dirtyPath) {
  11746. path.beginPath();
  11747. this.buildPath(path, this.shape, false);
  11748. }
  11749. rect = path.getBoundingRect();
  11750. }
  11751. this._rect = rect;
  11752. if (style.hasStroke()) {
  11753. // Needs update rect with stroke lineWidth when
  11754. // 1. Element changes scale or lineWidth
  11755. // 2. Shape is changed
  11756. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  11757. if (this.__dirty || needsUpdateRect) {
  11758. rectWithStroke.copy(rect);
  11759. // FIXME Must after updateTransform
  11760. var w = style.lineWidth;
  11761. // PENDING, Min line width is needed when line is horizontal or vertical
  11762. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11763. // Only add extra hover lineWidth when there are no fill
  11764. if (!style.hasFill()) {
  11765. w = Math.max(w, this.strokeContainThreshold || 4);
  11766. }
  11767. // Consider line width
  11768. // Line scale can't be 0;
  11769. if (lineScale > 1e-10) {
  11770. rectWithStroke.width += w / lineScale;
  11771. rectWithStroke.height += w / lineScale;
  11772. rectWithStroke.x -= w / lineScale / 2;
  11773. rectWithStroke.y -= w / lineScale / 2;
  11774. }
  11775. }
  11776. // Return rect with stroke
  11777. return rectWithStroke;
  11778. }
  11779. return rect;
  11780. },
  11781. contain: function (x, y) {
  11782. var localPos = this.transformCoordToLocal(x, y);
  11783. var rect = this.getBoundingRect();
  11784. var style = this.style;
  11785. x = localPos[0];
  11786. y = localPos[1];
  11787. if (rect.contain(x, y)) {
  11788. var pathData = this.path.data;
  11789. if (style.hasStroke()) {
  11790. var lineWidth = style.lineWidth;
  11791. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11792. // Line scale can't be 0;
  11793. if (lineScale > 1e-10) {
  11794. // Only add extra hover lineWidth when there are no fill
  11795. if (!style.hasFill()) {
  11796. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11797. }
  11798. if (containStroke(
  11799. pathData, lineWidth / lineScale, x, y
  11800. )) {
  11801. return true;
  11802. }
  11803. }
  11804. }
  11805. if (style.hasFill()) {
  11806. return contain(pathData, x, y);
  11807. }
  11808. }
  11809. return false;
  11810. },
  11811. /**
  11812. * @param {boolean} dirtyPath
  11813. */
  11814. dirty: function (dirtyPath) {
  11815. if (dirtyPath == null) {
  11816. dirtyPath = true;
  11817. }
  11818. // Only mark dirty, not mark clean
  11819. if (dirtyPath) {
  11820. this.__dirtyPath = dirtyPath;
  11821. this._rect = null;
  11822. }
  11823. this.__dirty = true;
  11824. this.__zr && this.__zr.refresh();
  11825. // Used as a clipping path
  11826. if (this.__clipTarget) {
  11827. this.__clipTarget.dirty();
  11828. }
  11829. },
  11830. /**
  11831. * Alias for animate('shape')
  11832. * @param {boolean} loop
  11833. */
  11834. animateShape: function (loop) {
  11835. return this.animate('shape', loop);
  11836. },
  11837. // Overwrite attrKV
  11838. attrKV: function (key, value) {
  11839. // FIXME
  11840. if (key === 'shape') {
  11841. this.setShape(value);
  11842. this.__dirtyPath = true;
  11843. this._rect = null;
  11844. }
  11845. else {
  11846. Displayable.prototype.attrKV.call(this, key, value);
  11847. }
  11848. },
  11849. /**
  11850. * @param {Object|string} key
  11851. * @param {*} value
  11852. */
  11853. setShape: function (key, value) {
  11854. var shape = this.shape;
  11855. // Path from string may not have shape
  11856. if (shape) {
  11857. if (isObject$1(key)) {
  11858. for (var name in key) {
  11859. if (key.hasOwnProperty(name)) {
  11860. shape[name] = key[name];
  11861. }
  11862. }
  11863. }
  11864. else {
  11865. shape[key] = value;
  11866. }
  11867. this.dirty(true);
  11868. }
  11869. return this;
  11870. },
  11871. getLineScale: function () {
  11872. var m = this.transform;
  11873. // Get the line scale.
  11874. // Determinant of `m` means how much the area is enlarged by the
  11875. // transformation. So its square root can be used as a scale factor
  11876. // for width.
  11877. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  11878. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  11879. : 1;
  11880. }
  11881. };
  11882. /**
  11883. * 扩展一个 Path element, 比如星形,圆等。
  11884. * Extend a path element
  11885. * @param {Object} props
  11886. * @param {string} props.type Path type
  11887. * @param {Function} props.init Initialize
  11888. * @param {Function} props.buildPath Overwrite buildPath method
  11889. * @param {Object} [props.style] Extended default style config
  11890. * @param {Object} [props.shape] Extended default shape config
  11891. */
  11892. Path.extend = function (defaults$$1) {
  11893. var Sub = function (opts) {
  11894. Path.call(this, opts);
  11895. if (defaults$$1.style) {
  11896. // Extend default style
  11897. this.style.extendFrom(defaults$$1.style, false);
  11898. }
  11899. // Extend default shape
  11900. var defaultShape = defaults$$1.shape;
  11901. if (defaultShape) {
  11902. this.shape = this.shape || {};
  11903. var thisShape = this.shape;
  11904. for (var name in defaultShape) {
  11905. if (
  11906. ! thisShape.hasOwnProperty(name)
  11907. && defaultShape.hasOwnProperty(name)
  11908. ) {
  11909. thisShape[name] = defaultShape[name];
  11910. }
  11911. }
  11912. }
  11913. defaults$$1.init && defaults$$1.init.call(this, opts);
  11914. };
  11915. inherits(Sub, Path);
  11916. // FIXME 不能 extend position, rotation 等引用对象
  11917. for (var name in defaults$$1) {
  11918. // Extending prototype values and methods
  11919. if (name !== 'style' && name !== 'shape') {
  11920. Sub.prototype[name] = defaults$$1[name];
  11921. }
  11922. }
  11923. return Sub;
  11924. };
  11925. inherits(Path, Displayable);
  11926. var CMD$2 = PathProxy.CMD;
  11927. var points = [[], [], []];
  11928. var mathSqrt$3 = Math.sqrt;
  11929. var mathAtan2 = Math.atan2;
  11930. var transformPath = function (path, m) {
  11931. var data = path.data;
  11932. var cmd;
  11933. var nPoint;
  11934. var i;
  11935. var j;
  11936. var k;
  11937. var p;
  11938. var M = CMD$2.M;
  11939. var C = CMD$2.C;
  11940. var L = CMD$2.L;
  11941. var R = CMD$2.R;
  11942. var A = CMD$2.A;
  11943. var Q = CMD$2.Q;
  11944. for (i = 0, j = 0; i < data.length;) {
  11945. cmd = data[i++];
  11946. j = i;
  11947. nPoint = 0;
  11948. switch (cmd) {
  11949. case M:
  11950. nPoint = 1;
  11951. break;
  11952. case L:
  11953. nPoint = 1;
  11954. break;
  11955. case C:
  11956. nPoint = 3;
  11957. break;
  11958. case Q:
  11959. nPoint = 2;
  11960. break;
  11961. case A:
  11962. var x = m[4];
  11963. var y = m[5];
  11964. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  11965. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  11966. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  11967. // cx
  11968. data[i] *= sx;
  11969. data[i++] += x;
  11970. // cy
  11971. data[i] *= sy;
  11972. data[i++] += y;
  11973. // Scale rx and ry
  11974. // FIXME Assume psi is 0 here
  11975. data[i++] *= sx;
  11976. data[i++] *= sy;
  11977. // Start angle
  11978. data[i++] += angle;
  11979. // end angle
  11980. data[i++] += angle;
  11981. // FIXME psi
  11982. i += 2;
  11983. j = i;
  11984. break;
  11985. case R:
  11986. // x0, y0
  11987. p[0] = data[i++];
  11988. p[1] = data[i++];
  11989. applyTransform(p, p, m);
  11990. data[j++] = p[0];
  11991. data[j++] = p[1];
  11992. // x1, y1
  11993. p[0] += data[i++];
  11994. p[1] += data[i++];
  11995. applyTransform(p, p, m);
  11996. data[j++] = p[0];
  11997. data[j++] = p[1];
  11998. }
  11999. for (k = 0; k < nPoint; k++) {
  12000. var p = points[k];
  12001. p[0] = data[i++];
  12002. p[1] = data[i++];
  12003. applyTransform(p, p, m);
  12004. // Write back
  12005. data[j++] = p[0];
  12006. data[j++] = p[1];
  12007. }
  12008. }
  12009. };
  12010. // command chars
  12011. var cc = [
  12012. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12013. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12014. ];
  12015. var mathSqrt = Math.sqrt;
  12016. var mathSin = Math.sin;
  12017. var mathCos = Math.cos;
  12018. var PI = Math.PI;
  12019. var vMag = function(v) {
  12020. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12021. };
  12022. var vRatio = function(u, v) {
  12023. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12024. };
  12025. var vAngle = function(u, v) {
  12026. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12027. * Math.acos(vRatio(u, v));
  12028. };
  12029. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12030. var psi = psiDeg * (PI / 180.0);
  12031. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12032. + mathSin(psi) * (y1 - y2) / 2.0;
  12033. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12034. + mathCos(psi) * (y1 - y2) / 2.0;
  12035. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12036. if (lambda > 1) {
  12037. rx *= mathSqrt(lambda);
  12038. ry *= mathSqrt(lambda);
  12039. }
  12040. var f = (fa === fs ? -1 : 1)
  12041. * mathSqrt((((rx * rx) * (ry * ry))
  12042. - ((rx * rx) * (yp * yp))
  12043. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12044. + (ry * ry) * (xp * xp))
  12045. ) || 0;
  12046. var cxp = f * rx * yp / ry;
  12047. var cyp = f * -ry * xp / rx;
  12048. var cx = (x1 + x2) / 2.0
  12049. + mathCos(psi) * cxp
  12050. - mathSin(psi) * cyp;
  12051. var cy = (y1 + y2) / 2.0
  12052. + mathSin(psi) * cxp
  12053. + mathCos(psi) * cyp;
  12054. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12055. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12056. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12057. var dTheta = vAngle(u, v);
  12058. if (vRatio(u, v) <= -1) {
  12059. dTheta = PI;
  12060. }
  12061. if (vRatio(u, v) >= 1) {
  12062. dTheta = 0;
  12063. }
  12064. if (fs === 0 && dTheta > 0) {
  12065. dTheta = dTheta - 2 * PI;
  12066. }
  12067. if (fs === 1 && dTheta < 0) {
  12068. dTheta = dTheta + 2 * PI;
  12069. }
  12070. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12071. }
  12072. function createPathProxyFromString(data) {
  12073. if (!data) {
  12074. return [];
  12075. }
  12076. // command string
  12077. var cs = data.replace(/-/g, ' -')
  12078. .replace(/ /g, ' ')
  12079. .replace(/ /g, ',')
  12080. .replace(/,,/g, ',');
  12081. var n;
  12082. // create pipes so that we can split the data
  12083. for (n = 0; n < cc.length; n++) {
  12084. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12085. }
  12086. // create array
  12087. var arr = cs.split('|');
  12088. // init context point
  12089. var cpx = 0;
  12090. var cpy = 0;
  12091. var path = new PathProxy();
  12092. var CMD = PathProxy.CMD;
  12093. var prevCmd;
  12094. for (n = 1; n < arr.length; n++) {
  12095. var str = arr[n];
  12096. var c = str.charAt(0);
  12097. var off = 0;
  12098. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12099. var cmd;
  12100. if (p.length > 0 && p[0] === '') {
  12101. p.shift();
  12102. }
  12103. for (var i = 0; i < p.length; i++) {
  12104. p[i] = parseFloat(p[i]);
  12105. }
  12106. while (off < p.length && !isNaN(p[off])) {
  12107. if (isNaN(p[0])) {
  12108. break;
  12109. }
  12110. var ctlPtx;
  12111. var ctlPty;
  12112. var rx;
  12113. var ry;
  12114. var psi;
  12115. var fa;
  12116. var fs;
  12117. var x1 = cpx;
  12118. var y1 = cpy;
  12119. // convert l, H, h, V, and v to L
  12120. switch (c) {
  12121. case 'l':
  12122. cpx += p[off++];
  12123. cpy += p[off++];
  12124. cmd = CMD.L;
  12125. path.addData(cmd, cpx, cpy);
  12126. break;
  12127. case 'L':
  12128. cpx = p[off++];
  12129. cpy = p[off++];
  12130. cmd = CMD.L;
  12131. path.addData(cmd, cpx, cpy);
  12132. break;
  12133. case 'm':
  12134. cpx += p[off++];
  12135. cpy += p[off++];
  12136. cmd = CMD.M;
  12137. path.addData(cmd, cpx, cpy);
  12138. c = 'l';
  12139. break;
  12140. case 'M':
  12141. cpx = p[off++];
  12142. cpy = p[off++];
  12143. cmd = CMD.M;
  12144. path.addData(cmd, cpx, cpy);
  12145. c = 'L';
  12146. break;
  12147. case 'h':
  12148. cpx += p[off++];
  12149. cmd = CMD.L;
  12150. path.addData(cmd, cpx, cpy);
  12151. break;
  12152. case 'H':
  12153. cpx = p[off++];
  12154. cmd = CMD.L;
  12155. path.addData(cmd, cpx, cpy);
  12156. break;
  12157. case 'v':
  12158. cpy += p[off++];
  12159. cmd = CMD.L;
  12160. path.addData(cmd, cpx, cpy);
  12161. break;
  12162. case 'V':
  12163. cpy = p[off++];
  12164. cmd = CMD.L;
  12165. path.addData(cmd, cpx, cpy);
  12166. break;
  12167. case 'C':
  12168. cmd = CMD.C;
  12169. path.addData(
  12170. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12171. );
  12172. cpx = p[off - 2];
  12173. cpy = p[off - 1];
  12174. break;
  12175. case 'c':
  12176. cmd = CMD.C;
  12177. path.addData(
  12178. cmd,
  12179. p[off++] + cpx, p[off++] + cpy,
  12180. p[off++] + cpx, p[off++] + cpy,
  12181. p[off++] + cpx, p[off++] + cpy
  12182. );
  12183. cpx += p[off - 2];
  12184. cpy += p[off - 1];
  12185. break;
  12186. case 'S':
  12187. ctlPtx = cpx;
  12188. ctlPty = cpy;
  12189. var len = path.len();
  12190. var pathData = path.data;
  12191. if (prevCmd === CMD.C) {
  12192. ctlPtx += cpx - pathData[len - 4];
  12193. ctlPty += cpy - pathData[len - 3];
  12194. }
  12195. cmd = CMD.C;
  12196. x1 = p[off++];
  12197. y1 = p[off++];
  12198. cpx = p[off++];
  12199. cpy = p[off++];
  12200. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12201. break;
  12202. case 's':
  12203. ctlPtx = cpx;
  12204. ctlPty = cpy;
  12205. var len = path.len();
  12206. var pathData = path.data;
  12207. if (prevCmd === CMD.C) {
  12208. ctlPtx += cpx - pathData[len - 4];
  12209. ctlPty += cpy - pathData[len - 3];
  12210. }
  12211. cmd = CMD.C;
  12212. x1 = cpx + p[off++];
  12213. y1 = cpy + p[off++];
  12214. cpx += p[off++];
  12215. cpy += p[off++];
  12216. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12217. break;
  12218. case 'Q':
  12219. x1 = p[off++];
  12220. y1 = p[off++];
  12221. cpx = p[off++];
  12222. cpy = p[off++];
  12223. cmd = CMD.Q;
  12224. path.addData(cmd, x1, y1, cpx, cpy);
  12225. break;
  12226. case 'q':
  12227. x1 = p[off++] + cpx;
  12228. y1 = p[off++] + cpy;
  12229. cpx += p[off++];
  12230. cpy += p[off++];
  12231. cmd = CMD.Q;
  12232. path.addData(cmd, x1, y1, cpx, cpy);
  12233. break;
  12234. case 'T':
  12235. ctlPtx = cpx;
  12236. ctlPty = cpy;
  12237. var len = path.len();
  12238. var pathData = path.data;
  12239. if (prevCmd === CMD.Q) {
  12240. ctlPtx += cpx - pathData[len - 4];
  12241. ctlPty += cpy - pathData[len - 3];
  12242. }
  12243. cpx = p[off++];
  12244. cpy = p[off++];
  12245. cmd = CMD.Q;
  12246. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12247. break;
  12248. case 't':
  12249. ctlPtx = cpx;
  12250. ctlPty = cpy;
  12251. var len = path.len();
  12252. var pathData = path.data;
  12253. if (prevCmd === CMD.Q) {
  12254. ctlPtx += cpx - pathData[len - 4];
  12255. ctlPty += cpy - pathData[len - 3];
  12256. }
  12257. cpx += p[off++];
  12258. cpy += p[off++];
  12259. cmd = CMD.Q;
  12260. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12261. break;
  12262. case 'A':
  12263. rx = p[off++];
  12264. ry = p[off++];
  12265. psi = p[off++];
  12266. fa = p[off++];
  12267. fs = p[off++];
  12268. x1 = cpx, y1 = cpy;
  12269. cpx = p[off++];
  12270. cpy = p[off++];
  12271. cmd = CMD.A;
  12272. processArc(
  12273. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12274. );
  12275. break;
  12276. case 'a':
  12277. rx = p[off++];
  12278. ry = p[off++];
  12279. psi = p[off++];
  12280. fa = p[off++];
  12281. fs = p[off++];
  12282. x1 = cpx, y1 = cpy;
  12283. cpx += p[off++];
  12284. cpy += p[off++];
  12285. cmd = CMD.A;
  12286. processArc(
  12287. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12288. );
  12289. break;
  12290. }
  12291. }
  12292. if (c === 'z' || c === 'Z') {
  12293. cmd = CMD.Z;
  12294. path.addData(cmd);
  12295. }
  12296. prevCmd = cmd;
  12297. }
  12298. path.toStatic();
  12299. return path;
  12300. }
  12301. // TODO Optimize double memory cost problem
  12302. function createPathOptions(str, opts) {
  12303. var pathProxy = createPathProxyFromString(str);
  12304. opts = opts || {};
  12305. opts.buildPath = function (path) {
  12306. if (path.setData) {
  12307. path.setData(pathProxy.data);
  12308. // Svg and vml renderer don't have context
  12309. var ctx = path.getContext();
  12310. if (ctx) {
  12311. path.rebuildPath(ctx);
  12312. }
  12313. }
  12314. else {
  12315. var ctx = path;
  12316. pathProxy.rebuildPath(ctx);
  12317. }
  12318. };
  12319. opts.applyTransform = function (m) {
  12320. transformPath(pathProxy, m);
  12321. this.dirty(true);
  12322. };
  12323. return opts;
  12324. }
  12325. /**
  12326. * Create a Path object from path string data
  12327. * http://www.w3.org/TR/SVG/paths.html#PathData
  12328. * @param {Object} opts Other options
  12329. */
  12330. function createFromString(str, opts) {
  12331. return new Path(createPathOptions(str, opts));
  12332. }
  12333. /**
  12334. * Create a Path class from path string data
  12335. * @param {string} str
  12336. * @param {Object} opts Other options
  12337. */
  12338. function extendFromString(str, opts) {
  12339. return Path.extend(createPathOptions(str, opts));
  12340. }
  12341. /**
  12342. * Merge multiple paths
  12343. */
  12344. // TODO Apply transform
  12345. // TODO stroke dash
  12346. // TODO Optimize double memory cost problem
  12347. function mergePath$1(pathEls, opts) {
  12348. var pathList = [];
  12349. var len = pathEls.length;
  12350. for (var i = 0; i < len; i++) {
  12351. var pathEl = pathEls[i];
  12352. if (!pathEl.path) {
  12353. pathEl.createPathProxy();
  12354. }
  12355. if (pathEl.__dirtyPath) {
  12356. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12357. }
  12358. pathList.push(pathEl.path);
  12359. }
  12360. var pathBundle = new Path(opts);
  12361. // Need path proxy.
  12362. pathBundle.createPathProxy();
  12363. pathBundle.buildPath = function (path) {
  12364. path.appendPath(pathList);
  12365. // Svg and vml renderer don't have context
  12366. var ctx = path.getContext();
  12367. if (ctx) {
  12368. path.rebuildPath(ctx);
  12369. }
  12370. };
  12371. return pathBundle;
  12372. }
  12373. /**
  12374. * @alias zrender/graphic/Text
  12375. * @extends module:zrender/graphic/Displayable
  12376. * @constructor
  12377. * @param {Object} opts
  12378. */
  12379. var Text = function (opts) { // jshint ignore:line
  12380. Displayable.call(this, opts);
  12381. };
  12382. Text.prototype = {
  12383. constructor: Text,
  12384. type: 'text',
  12385. brush: function (ctx, prevEl) {
  12386. var style = this.style;
  12387. // Optimize, avoid normalize every time.
  12388. this.__dirty && normalizeTextStyle(style, true);
  12389. // Use props with prefix 'text'.
  12390. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12391. style.shadowOffsetX = style.shadowOffsetY = null;
  12392. var text = style.text;
  12393. // Convert to string
  12394. text != null && (text += '');
  12395. // Always bind style
  12396. style.bind(ctx, this, prevEl);
  12397. if (!needDrawText(text, style)) {
  12398. return;
  12399. }
  12400. this.setTransform(ctx);
  12401. renderText(this, ctx, text, style);
  12402. this.restoreTransform(ctx);
  12403. },
  12404. getBoundingRect: function () {
  12405. var style = this.style;
  12406. // Optimize, avoid normalize every time.
  12407. this.__dirty && normalizeTextStyle(style, true);
  12408. if (!this._rect) {
  12409. var text = style.text;
  12410. text != null ? (text += '') : (text = '');
  12411. var rect = getBoundingRect(
  12412. style.text + '',
  12413. style.font,
  12414. style.textAlign,
  12415. style.textVerticalAlign,
  12416. style.textPadding,
  12417. style.rich
  12418. );
  12419. rect.x += style.x || 0;
  12420. rect.y += style.y || 0;
  12421. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12422. var w = style.textStrokeWidth;
  12423. rect.x -= w / 2;
  12424. rect.y -= w / 2;
  12425. rect.width += w;
  12426. rect.height += w;
  12427. }
  12428. this._rect = rect;
  12429. }
  12430. return this._rect;
  12431. }
  12432. };
  12433. inherits(Text, Displayable);
  12434. /**
  12435. * 圆形
  12436. * @module zrender/shape/Circle
  12437. */
  12438. var Circle = Path.extend({
  12439. type: 'circle',
  12440. shape: {
  12441. cx: 0,
  12442. cy: 0,
  12443. r: 0
  12444. },
  12445. buildPath : function (ctx, shape, inBundle) {
  12446. // Better stroking in ShapeBundle
  12447. // Always do it may have performence issue ( fill may be 2x more cost)
  12448. if (inBundle) {
  12449. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12450. }
  12451. // else {
  12452. // if (ctx.allocate && !ctx.data.length) {
  12453. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  12454. // }
  12455. // }
  12456. // Better stroking in ShapeBundle
  12457. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  12458. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  12459. }
  12460. });
  12461. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  12462. // where exception "unexpected call to method or property access"
  12463. // might be thrown when calling ctx.fill or ctx.stroke after a path
  12464. // whose area size is zero is drawn and ctx.clip() is called and
  12465. // shadowBlur is set. See #4572, #3112, #5777.
  12466. // (e.g.,
  12467. // ctx.moveTo(10, 10);
  12468. // ctx.lineTo(20, 10);
  12469. // ctx.closePath();
  12470. // ctx.clip();
  12471. // ctx.shadowBlur = 10;
  12472. // ...
  12473. // ctx.fill();
  12474. // )
  12475. var shadowTemp = [
  12476. ['shadowBlur', 0],
  12477. ['shadowColor', '#000'],
  12478. ['shadowOffsetX', 0],
  12479. ['shadowOffsetY', 0]
  12480. ];
  12481. var fixClipWithShadow = function (orignalBrush) {
  12482. // version string can be: '11.0'
  12483. return (env$1.browser.ie && env$1.browser.version >= 11)
  12484. ? function () {
  12485. var clipPaths = this.__clipPaths;
  12486. var style = this.style;
  12487. var modified;
  12488. if (clipPaths) {
  12489. for (var i = 0; i < clipPaths.length; i++) {
  12490. var clipPath = clipPaths[i];
  12491. var shape = clipPath && clipPath.shape;
  12492. var type = clipPath && clipPath.type;
  12493. if (shape && (
  12494. (type === 'sector' && shape.startAngle === shape.endAngle)
  12495. || (type === 'rect' && (!shape.width || !shape.height))
  12496. )) {
  12497. for (var j = 0; j < shadowTemp.length; j++) {
  12498. // It is save to put shadowTemp static, because shadowTemp
  12499. // will be all modified each item brush called.
  12500. shadowTemp[j][2] = style[shadowTemp[j][0]];
  12501. style[shadowTemp[j][0]] = shadowTemp[j][1];
  12502. }
  12503. modified = true;
  12504. break;
  12505. }
  12506. }
  12507. }
  12508. orignalBrush.apply(this, arguments);
  12509. if (modified) {
  12510. for (var j = 0; j < shadowTemp.length; j++) {
  12511. style[shadowTemp[j][0]] = shadowTemp[j][2];
  12512. }
  12513. }
  12514. }
  12515. : orignalBrush;
  12516. };
  12517. /**
  12518. * 扇形
  12519. * @module zrender/graphic/shape/Sector
  12520. */
  12521. var Sector = Path.extend({
  12522. type: 'sector',
  12523. shape: {
  12524. cx: 0,
  12525. cy: 0,
  12526. r0: 0,
  12527. r: 0,
  12528. startAngle: 0,
  12529. endAngle: Math.PI * 2,
  12530. clockwise: true
  12531. },
  12532. brush: fixClipWithShadow(Path.prototype.brush),
  12533. buildPath: function (ctx, shape) {
  12534. var x = shape.cx;
  12535. var y = shape.cy;
  12536. var r0 = Math.max(shape.r0 || 0, 0);
  12537. var r = Math.max(shape.r, 0);
  12538. var startAngle = shape.startAngle;
  12539. var endAngle = shape.endAngle;
  12540. var clockwise = shape.clockwise;
  12541. var unitX = Math.cos(startAngle);
  12542. var unitY = Math.sin(startAngle);
  12543. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  12544. ctx.lineTo(unitX * r + x, unitY * r + y);
  12545. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  12546. ctx.lineTo(
  12547. Math.cos(endAngle) * r0 + x,
  12548. Math.sin(endAngle) * r0 + y
  12549. );
  12550. if (r0 !== 0) {
  12551. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  12552. }
  12553. ctx.closePath();
  12554. }
  12555. });
  12556. /**
  12557. * 圆环
  12558. * @module zrender/graphic/shape/Ring
  12559. */
  12560. var Ring = Path.extend({
  12561. type: 'ring',
  12562. shape: {
  12563. cx: 0,
  12564. cy: 0,
  12565. r: 0,
  12566. r0: 0
  12567. },
  12568. buildPath: function (ctx, shape) {
  12569. var x = shape.cx;
  12570. var y = shape.cy;
  12571. var PI2 = Math.PI * 2;
  12572. ctx.moveTo(x + shape.r, y);
  12573. ctx.arc(x, y, shape.r, 0, PI2, false);
  12574. ctx.moveTo(x + shape.r0, y);
  12575. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12576. }
  12577. });
  12578. /**
  12579. * Catmull-Rom spline 插值折线
  12580. * @module zrender/shape/util/smoothSpline
  12581. * @author pissang (https://www.github.com/pissang)
  12582. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  12583. * errorrik (errorrik@gmail.com)
  12584. */
  12585. /**
  12586. * @inner
  12587. */
  12588. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12589. var v0 = (p2 - p0) * 0.5;
  12590. var v1 = (p3 - p1) * 0.5;
  12591. return (2 * (p1 - p2) + v0 + v1) * t3
  12592. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12593. + v0 * t + p1;
  12594. }
  12595. /**
  12596. * @alias module:zrender/shape/util/smoothSpline
  12597. * @param {Array} points 线段顶点数组
  12598. * @param {boolean} isLoop
  12599. * @return {Array}
  12600. */
  12601. var smoothSpline = function (points, isLoop) {
  12602. var len$$1 = points.length;
  12603. var ret = [];
  12604. var distance$$1 = 0;
  12605. for (var i = 1; i < len$$1; i++) {
  12606. distance$$1 += distance(points[i - 1], points[i]);
  12607. }
  12608. var segs = distance$$1 / 2;
  12609. segs = segs < len$$1 ? len$$1 : segs;
  12610. for (var i = 0; i < segs; i++) {
  12611. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  12612. var idx = Math.floor(pos);
  12613. var w = pos - idx;
  12614. var p0;
  12615. var p1 = points[idx % len$$1];
  12616. var p2;
  12617. var p3;
  12618. if (!isLoop) {
  12619. p0 = points[idx === 0 ? idx : idx - 1];
  12620. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  12621. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  12622. }
  12623. else {
  12624. p0 = points[(idx - 1 + len$$1) % len$$1];
  12625. p2 = points[(idx + 1) % len$$1];
  12626. p3 = points[(idx + 2) % len$$1];
  12627. }
  12628. var w2 = w * w;
  12629. var w3 = w * w2;
  12630. ret.push([
  12631. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  12632. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  12633. ]);
  12634. }
  12635. return ret;
  12636. };
  12637. /**
  12638. * 贝塞尔平滑曲线
  12639. * @module zrender/shape/util/smoothBezier
  12640. * @author pissang (https://www.github.com/pissang)
  12641. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  12642. * errorrik (errorrik@gmail.com)
  12643. */
  12644. /**
  12645. * 贝塞尔平滑曲线
  12646. * @alias module:zrender/shape/util/smoothBezier
  12647. * @param {Array} points 线段顶点数组
  12648. * @param {number} smooth 平滑等级, 0-1
  12649. * @param {boolean} isLoop
  12650. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  12651. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  12652. * 整个折线的包围盒做一个并集用来约束控制点。
  12653. * @param {Array} 计算出来的控制点数组
  12654. */
  12655. var smoothBezier = function (points, smooth, isLoop, constraint) {
  12656. var cps = [];
  12657. var v = [];
  12658. var v1 = [];
  12659. var v2 = [];
  12660. var prevPoint;
  12661. var nextPoint;
  12662. var min$$1, max$$1;
  12663. if (constraint) {
  12664. min$$1 = [Infinity, Infinity];
  12665. max$$1 = [-Infinity, -Infinity];
  12666. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  12667. min(min$$1, min$$1, points[i]);
  12668. max(max$$1, max$$1, points[i]);
  12669. }
  12670. // 与指定的包围盒做并集
  12671. min(min$$1, min$$1, constraint[0]);
  12672. max(max$$1, max$$1, constraint[1]);
  12673. }
  12674. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  12675. var point = points[i];
  12676. if (isLoop) {
  12677. prevPoint = points[i ? i - 1 : len$$1 - 1];
  12678. nextPoint = points[(i + 1) % len$$1];
  12679. }
  12680. else {
  12681. if (i === 0 || i === len$$1 - 1) {
  12682. cps.push(clone$1(points[i]));
  12683. continue;
  12684. }
  12685. else {
  12686. prevPoint = points[i - 1];
  12687. nextPoint = points[i + 1];
  12688. }
  12689. }
  12690. sub(v, nextPoint, prevPoint);
  12691. // use degree to scale the handle length
  12692. scale(v, v, smooth);
  12693. var d0 = distance(point, prevPoint);
  12694. var d1 = distance(point, nextPoint);
  12695. var sum = d0 + d1;
  12696. if (sum !== 0) {
  12697. d0 /= sum;
  12698. d1 /= sum;
  12699. }
  12700. scale(v1, v, -d0);
  12701. scale(v2, v, d1);
  12702. var cp0 = add([], point, v1);
  12703. var cp1 = add([], point, v2);
  12704. if (constraint) {
  12705. max(cp0, cp0, min$$1);
  12706. min(cp0, cp0, max$$1);
  12707. max(cp1, cp1, min$$1);
  12708. min(cp1, cp1, max$$1);
  12709. }
  12710. cps.push(cp0);
  12711. cps.push(cp1);
  12712. }
  12713. if (isLoop) {
  12714. cps.push(cps.shift());
  12715. }
  12716. return cps;
  12717. };
  12718. function buildPath$1(ctx, shape, closePath) {
  12719. var points = shape.points;
  12720. var smooth = shape.smooth;
  12721. if (points && points.length >= 2) {
  12722. if (smooth && smooth !== 'spline') {
  12723. var controlPoints = smoothBezier(
  12724. points, smooth, closePath, shape.smoothConstraint
  12725. );
  12726. ctx.moveTo(points[0][0], points[0][1]);
  12727. var len = points.length;
  12728. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  12729. var cp1 = controlPoints[i * 2];
  12730. var cp2 = controlPoints[i * 2 + 1];
  12731. var p = points[(i + 1) % len];
  12732. ctx.bezierCurveTo(
  12733. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  12734. );
  12735. }
  12736. }
  12737. else {
  12738. if (smooth === 'spline') {
  12739. points = smoothSpline(points, closePath);
  12740. }
  12741. ctx.moveTo(points[0][0], points[0][1]);
  12742. for (var i = 1, l = points.length; i < l; i++) {
  12743. ctx.lineTo(points[i][0], points[i][1]);
  12744. }
  12745. }
  12746. closePath && ctx.closePath();
  12747. }
  12748. }
  12749. /**
  12750. * 多边形
  12751. * @module zrender/shape/Polygon
  12752. */
  12753. var Polygon = Path.extend({
  12754. type: 'polygon',
  12755. shape: {
  12756. points: null,
  12757. smooth: false,
  12758. smoothConstraint: null
  12759. },
  12760. buildPath: function (ctx, shape) {
  12761. buildPath$1(ctx, shape, true);
  12762. }
  12763. });
  12764. /**
  12765. * @module zrender/graphic/shape/Polyline
  12766. */
  12767. var Polyline = Path.extend({
  12768. type: 'polyline',
  12769. shape: {
  12770. points: null,
  12771. smooth: false,
  12772. smoothConstraint: null
  12773. },
  12774. style: {
  12775. stroke: '#000',
  12776. fill: null
  12777. },
  12778. buildPath: function (ctx, shape) {
  12779. buildPath$1(ctx, shape, false);
  12780. }
  12781. });
  12782. /**
  12783. * 矩形
  12784. * @module zrender/graphic/shape/Rect
  12785. */
  12786. var Rect = Path.extend({
  12787. type: 'rect',
  12788. shape: {
  12789. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  12790. // r缩写为1 相当于 [1, 1, 1, 1]
  12791. // r缩写为[1] 相当于 [1, 1, 1, 1]
  12792. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  12793. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  12794. r: 0,
  12795. x: 0,
  12796. y: 0,
  12797. width: 0,
  12798. height: 0
  12799. },
  12800. buildPath: function (ctx, shape) {
  12801. var x = shape.x;
  12802. var y = shape.y;
  12803. var width = shape.width;
  12804. var height = shape.height;
  12805. if (!shape.r) {
  12806. ctx.rect(x, y, width, height);
  12807. }
  12808. else {
  12809. buildPath(ctx, shape);
  12810. }
  12811. ctx.closePath();
  12812. return;
  12813. }
  12814. });
  12815. /**
  12816. * 直线
  12817. * @module zrender/graphic/shape/Line
  12818. */
  12819. var Line = Path.extend({
  12820. type: 'line',
  12821. shape: {
  12822. // Start point
  12823. x1: 0,
  12824. y1: 0,
  12825. // End point
  12826. x2: 0,
  12827. y2: 0,
  12828. percent: 1
  12829. },
  12830. style: {
  12831. stroke: '#000',
  12832. fill: null
  12833. },
  12834. buildPath: function (ctx, shape) {
  12835. var x1 = shape.x1;
  12836. var y1 = shape.y1;
  12837. var x2 = shape.x2;
  12838. var y2 = shape.y2;
  12839. var percent = shape.percent;
  12840. if (percent === 0) {
  12841. return;
  12842. }
  12843. ctx.moveTo(x1, y1);
  12844. if (percent < 1) {
  12845. x2 = x1 * (1 - percent) + x2 * percent;
  12846. y2 = y1 * (1 - percent) + y2 * percent;
  12847. }
  12848. ctx.lineTo(x2, y2);
  12849. },
  12850. /**
  12851. * Get point at percent
  12852. * @param {number} percent
  12853. * @return {Array.<number>}
  12854. */
  12855. pointAt: function (p) {
  12856. var shape = this.shape;
  12857. return [
  12858. shape.x1 * (1 - p) + shape.x2 * p,
  12859. shape.y1 * (1 - p) + shape.y2 * p
  12860. ];
  12861. }
  12862. });
  12863. /**
  12864. * 贝塞尔曲线
  12865. * @module zrender/shape/BezierCurve
  12866. */
  12867. var out = [];
  12868. function someVectorAt(shape, t, isTangent) {
  12869. var cpx2 = shape.cpx2;
  12870. var cpy2 = shape.cpy2;
  12871. if (cpx2 === null || cpy2 === null) {
  12872. return [
  12873. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  12874. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  12875. ];
  12876. }
  12877. else {
  12878. return [
  12879. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  12880. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  12881. ];
  12882. }
  12883. }
  12884. var BezierCurve = Path.extend({
  12885. type: 'bezier-curve',
  12886. shape: {
  12887. x1: 0,
  12888. y1: 0,
  12889. x2: 0,
  12890. y2: 0,
  12891. cpx1: 0,
  12892. cpy1: 0,
  12893. // cpx2: 0,
  12894. // cpy2: 0
  12895. // Curve show percent, for animating
  12896. percent: 1
  12897. },
  12898. style: {
  12899. stroke: '#000',
  12900. fill: null
  12901. },
  12902. buildPath: function (ctx, shape) {
  12903. var x1 = shape.x1;
  12904. var y1 = shape.y1;
  12905. var x2 = shape.x2;
  12906. var y2 = shape.y2;
  12907. var cpx1 = shape.cpx1;
  12908. var cpy1 = shape.cpy1;
  12909. var cpx2 = shape.cpx2;
  12910. var cpy2 = shape.cpy2;
  12911. var percent = shape.percent;
  12912. if (percent === 0) {
  12913. return;
  12914. }
  12915. ctx.moveTo(x1, y1);
  12916. if (cpx2 == null || cpy2 == null) {
  12917. if (percent < 1) {
  12918. quadraticSubdivide(
  12919. x1, cpx1, x2, percent, out
  12920. );
  12921. cpx1 = out[1];
  12922. x2 = out[2];
  12923. quadraticSubdivide(
  12924. y1, cpy1, y2, percent, out
  12925. );
  12926. cpy1 = out[1];
  12927. y2 = out[2];
  12928. }
  12929. ctx.quadraticCurveTo(
  12930. cpx1, cpy1,
  12931. x2, y2
  12932. );
  12933. }
  12934. else {
  12935. if (percent < 1) {
  12936. cubicSubdivide(
  12937. x1, cpx1, cpx2, x2, percent, out
  12938. );
  12939. cpx1 = out[1];
  12940. cpx2 = out[2];
  12941. x2 = out[3];
  12942. cubicSubdivide(
  12943. y1, cpy1, cpy2, y2, percent, out
  12944. );
  12945. cpy1 = out[1];
  12946. cpy2 = out[2];
  12947. y2 = out[3];
  12948. }
  12949. ctx.bezierCurveTo(
  12950. cpx1, cpy1,
  12951. cpx2, cpy2,
  12952. x2, y2
  12953. );
  12954. }
  12955. },
  12956. /**
  12957. * Get point at percent
  12958. * @param {number} t
  12959. * @return {Array.<number>}
  12960. */
  12961. pointAt: function (t) {
  12962. return someVectorAt(this.shape, t, false);
  12963. },
  12964. /**
  12965. * Get tangent at percent
  12966. * @param {number} t
  12967. * @return {Array.<number>}
  12968. */
  12969. tangentAt: function (t) {
  12970. var p = someVectorAt(this.shape, t, true);
  12971. return normalize(p, p);
  12972. }
  12973. });
  12974. /**
  12975. * 圆弧
  12976. * @module zrender/graphic/shape/Arc
  12977. */
  12978. var Arc = Path.extend({
  12979. type: 'arc',
  12980. shape: {
  12981. cx: 0,
  12982. cy: 0,
  12983. r: 0,
  12984. startAngle: 0,
  12985. endAngle: Math.PI * 2,
  12986. clockwise: true
  12987. },
  12988. style: {
  12989. stroke: '#000',
  12990. fill: null
  12991. },
  12992. buildPath: function (ctx, shape) {
  12993. var x = shape.cx;
  12994. var y = shape.cy;
  12995. var r = Math.max(shape.r, 0);
  12996. var startAngle = shape.startAngle;
  12997. var endAngle = shape.endAngle;
  12998. var clockwise = shape.clockwise;
  12999. var unitX = Math.cos(startAngle);
  13000. var unitY = Math.sin(startAngle);
  13001. ctx.moveTo(unitX * r + x, unitY * r + y);
  13002. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13003. }
  13004. });
  13005. // CompoundPath to improve performance
  13006. var CompoundPath = Path.extend({
  13007. type: 'compound',
  13008. shape: {
  13009. paths: null
  13010. },
  13011. _updatePathDirty: function () {
  13012. var dirtyPath = this.__dirtyPath;
  13013. var paths = this.shape.paths;
  13014. for (var i = 0; i < paths.length; i++) {
  13015. // Mark as dirty if any subpath is dirty
  13016. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13017. }
  13018. this.__dirtyPath = dirtyPath;
  13019. this.__dirty = this.__dirty || dirtyPath;
  13020. },
  13021. beforeBrush: function () {
  13022. this._updatePathDirty();
  13023. var paths = this.shape.paths || [];
  13024. var scale = this.getGlobalScale();
  13025. // Update path scale
  13026. for (var i = 0; i < paths.length; i++) {
  13027. if (!paths[i].path) {
  13028. paths[i].createPathProxy();
  13029. }
  13030. paths[i].path.setScale(scale[0], scale[1]);
  13031. }
  13032. },
  13033. buildPath: function (ctx, shape) {
  13034. var paths = shape.paths || [];
  13035. for (var i = 0; i < paths.length; i++) {
  13036. paths[i].buildPath(ctx, paths[i].shape, true);
  13037. }
  13038. },
  13039. afterBrush: function () {
  13040. var paths = this.shape.paths || [];
  13041. for (var i = 0; i < paths.length; i++) {
  13042. paths[i].__dirtyPath = false;
  13043. }
  13044. },
  13045. getBoundingRect: function () {
  13046. this._updatePathDirty();
  13047. return Path.prototype.getBoundingRect.call(this);
  13048. }
  13049. });
  13050. /**
  13051. * @param {Array.<Object>} colorStops
  13052. */
  13053. var Gradient = function (colorStops) {
  13054. this.colorStops = colorStops || [];
  13055. };
  13056. Gradient.prototype = {
  13057. constructor: Gradient,
  13058. addColorStop: function (offset, color) {
  13059. this.colorStops.push({
  13060. offset: offset,
  13061. color: color
  13062. });
  13063. }
  13064. };
  13065. /**
  13066. * x, y, x2, y2 are all percent from 0 to 1
  13067. * @param {number} [x=0]
  13068. * @param {number} [y=0]
  13069. * @param {number} [x2=1]
  13070. * @param {number} [y2=0]
  13071. * @param {Array.<Object>} colorStops
  13072. * @param {boolean} [globalCoord=false]
  13073. */
  13074. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13075. // Should do nothing more in this constructor. Because gradient can be
  13076. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13077. // this constructor will not be called.
  13078. this.x = x == null ? 0 : x;
  13079. this.y = y == null ? 0 : y;
  13080. this.x2 = x2 == null ? 1 : x2;
  13081. this.y2 = y2 == null ? 0 : y2;
  13082. // Can be cloned
  13083. this.type = 'linear';
  13084. // If use global coord
  13085. this.global = globalCoord || false;
  13086. Gradient.call(this, colorStops);
  13087. };
  13088. LinearGradient.prototype = {
  13089. constructor: LinearGradient
  13090. };
  13091. inherits(LinearGradient, Gradient);
  13092. /**
  13093. * x, y, r are all percent from 0 to 1
  13094. * @param {number} [x=0.5]
  13095. * @param {number} [y=0.5]
  13096. * @param {number} [r=0.5]
  13097. * @param {Array.<Object>} [colorStops]
  13098. * @param {boolean} [globalCoord=false]
  13099. */
  13100. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13101. // Should do nothing more in this constructor. Because gradient can be
  13102. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13103. // this constructor will not be called.
  13104. this.x = x == null ? 0.5 : x;
  13105. this.y = y == null ? 0.5 : y;
  13106. this.r = r == null ? 0.5 : r;
  13107. // Can be cloned
  13108. this.type = 'radial';
  13109. // If use global coord
  13110. this.global = globalCoord || false;
  13111. Gradient.call(this, colorStops);
  13112. };
  13113. RadialGradient.prototype = {
  13114. constructor: RadialGradient
  13115. };
  13116. inherits(RadialGradient, Gradient);
  13117. /**
  13118. * Displayable for incremental rendering. It will be rendered in a separate layer
  13119. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13120. * addDisplayables will render the added displayables incremetally.
  13121. *
  13122. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13123. */
  13124. // TODO Style override ?
  13125. function IncrementalDisplayble(opts) {
  13126. Displayable.call(this, opts);
  13127. this._displayables = [];
  13128. this._temporaryDisplayables = [];
  13129. this._cursor = 0;
  13130. this.notClear = true;
  13131. }
  13132. IncrementalDisplayble.prototype.incremental = true;
  13133. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13134. this._displayables = [];
  13135. this._temporaryDisplayables = [];
  13136. this._cursor = 0;
  13137. this.dirty();
  13138. this.notClear = false;
  13139. };
  13140. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13141. if (notPersistent) {
  13142. this._temporaryDisplayables.push(displayable);
  13143. }
  13144. else {
  13145. this._displayables.push(displayable);
  13146. }
  13147. this.dirty();
  13148. };
  13149. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13150. notPersistent = notPersistent || false;
  13151. for (var i = 0; i < displayables.length; i++) {
  13152. this.addDisplayable(displayables[i], notPersistent);
  13153. }
  13154. };
  13155. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13156. for (var i = this._cursor; i < this._displayables.length; i++) {
  13157. cb && cb(this._displayables[i]);
  13158. }
  13159. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13160. cb && cb(this._temporaryDisplayables[i]);
  13161. }
  13162. };
  13163. IncrementalDisplayble.prototype.update = function () {
  13164. this.updateTransform();
  13165. for (var i = this._cursor; i < this._displayables.length; i++) {
  13166. var displayable = this._displayables[i];
  13167. // PENDING
  13168. displayable.parent = this;
  13169. displayable.update();
  13170. displayable.parent = null;
  13171. }
  13172. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13173. var displayable = this._temporaryDisplayables[i];
  13174. // PENDING
  13175. displayable.parent = this;
  13176. displayable.update();
  13177. displayable.parent = null;
  13178. }
  13179. };
  13180. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13181. // Render persistant displayables.
  13182. for (var i = this._cursor; i < this._displayables.length; i++) {
  13183. var displayable = this._temporaryDisplayables[i];
  13184. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13185. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13186. displayable.afterBrush && displayable.afterBrush(ctx);
  13187. }
  13188. this._cursor = i;
  13189. // Render temporary displayables.
  13190. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13191. var displayable = this._temporaryDisplayables[i];
  13192. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13193. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13194. displayable.afterBrush && displayable.afterBrush(ctx);
  13195. }
  13196. this._temporaryDisplayables = [];
  13197. this.notClear = true;
  13198. };
  13199. var m = [];
  13200. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13201. if (!this._rect) {
  13202. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13203. for (var i = 0; i < this._displayables.length; i++) {
  13204. var displayable = this._displayables[i];
  13205. var childRect = displayable.getBoundingRect().clone();
  13206. if (displayable.needLocalTransform()) {
  13207. childRect.applyTransform(displayable.getLocalTransform(m));
  13208. }
  13209. rect.union(childRect);
  13210. }
  13211. this._rect = rect;
  13212. }
  13213. return this._rect;
  13214. };
  13215. IncrementalDisplayble.prototype.contain = function (x, y) {
  13216. var localPos = this.transformCoordToLocal(x, y);
  13217. var rect = this.getBoundingRect();
  13218. if (rect.contain(localPos[0], localPos[1])) {
  13219. for (var i = 0; i < this._displayables.length; i++) {
  13220. var displayable = this._displayables[i];
  13221. if (displayable.contain(x, y)) {
  13222. return true;
  13223. }
  13224. }
  13225. }
  13226. return false;
  13227. };
  13228. inherits(IncrementalDisplayble, Displayable);
  13229. var round = Math.round;
  13230. var mathMax$1 = Math.max;
  13231. var mathMin$1 = Math.min;
  13232. var EMPTY_OBJ = {};
  13233. /**
  13234. * Extend shape with parameters
  13235. */
  13236. function extendShape(opts) {
  13237. return Path.extend(opts);
  13238. }
  13239. /**
  13240. * Extend path
  13241. */
  13242. function extendPath(pathData, opts) {
  13243. return extendFromString(pathData, opts);
  13244. }
  13245. /**
  13246. * Create a path element from path data string
  13247. * @param {string} pathData
  13248. * @param {Object} opts
  13249. * @param {module:zrender/core/BoundingRect} rect
  13250. * @param {string} [layout=cover] 'center' or 'cover'
  13251. */
  13252. function makePath(pathData, opts, rect, layout) {
  13253. var path = createFromString(pathData, opts);
  13254. var boundingRect = path.getBoundingRect();
  13255. if (rect) {
  13256. if (layout === 'center') {
  13257. rect = centerGraphic(rect, boundingRect);
  13258. }
  13259. resizePath(path, rect);
  13260. }
  13261. return path;
  13262. }
  13263. /**
  13264. * Create a image element from image url
  13265. * @param {string} imageUrl image url
  13266. * @param {Object} opts options
  13267. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13268. * @param {string} [layout=cover] 'center' or 'cover'
  13269. */
  13270. function makeImage(imageUrl, rect, layout) {
  13271. var path = new ZImage({
  13272. style: {
  13273. image: imageUrl,
  13274. x: rect.x,
  13275. y: rect.y,
  13276. width: rect.width,
  13277. height: rect.height
  13278. },
  13279. onload: function (img) {
  13280. if (layout === 'center') {
  13281. var boundingRect = {
  13282. width: img.width,
  13283. height: img.height
  13284. };
  13285. path.setStyle(centerGraphic(rect, boundingRect));
  13286. }
  13287. }
  13288. });
  13289. return path;
  13290. }
  13291. /**
  13292. * Get position of centered element in bounding box.
  13293. *
  13294. * @param {Object} rect element local bounding box
  13295. * @param {Object} boundingRect constraint bounding box
  13296. * @return {Object} element position containing x, y, width, and height
  13297. */
  13298. function centerGraphic(rect, boundingRect) {
  13299. // Set rect to center, keep width / height ratio.
  13300. var aspect = boundingRect.width / boundingRect.height;
  13301. var width = rect.height * aspect;
  13302. var height;
  13303. if (width <= rect.width) {
  13304. height = rect.height;
  13305. }
  13306. else {
  13307. width = rect.width;
  13308. height = width / aspect;
  13309. }
  13310. var cx = rect.x + rect.width / 2;
  13311. var cy = rect.y + rect.height / 2;
  13312. return {
  13313. x: cx - width / 2,
  13314. y: cy - height / 2,
  13315. width: width,
  13316. height: height
  13317. };
  13318. }
  13319. var mergePath = mergePath$1;
  13320. /**
  13321. * Resize a path to fit the rect
  13322. * @param {module:zrender/graphic/Path} path
  13323. * @param {Object} rect
  13324. */
  13325. function resizePath(path, rect) {
  13326. if (!path.applyTransform) {
  13327. return;
  13328. }
  13329. var pathRect = path.getBoundingRect();
  13330. var m = pathRect.calculateTransform(rect);
  13331. path.applyTransform(m);
  13332. }
  13333. /**
  13334. * Sub pixel optimize line for canvas
  13335. *
  13336. * @param {Object} param
  13337. * @param {Object} [param.shape]
  13338. * @param {number} [param.shape.x1]
  13339. * @param {number} [param.shape.y1]
  13340. * @param {number} [param.shape.x2]
  13341. * @param {number} [param.shape.y2]
  13342. * @param {Object} [param.style]
  13343. * @param {number} [param.style.lineWidth]
  13344. * @return {Object} Modified param
  13345. */
  13346. function subPixelOptimizeLine(param) {
  13347. var shape = param.shape;
  13348. var lineWidth = param.style.lineWidth;
  13349. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13350. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13351. }
  13352. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13353. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13354. }
  13355. return param;
  13356. }
  13357. /**
  13358. * Sub pixel optimize rect for canvas
  13359. *
  13360. * @param {Object} param
  13361. * @param {Object} [param.shape]
  13362. * @param {number} [param.shape.x]
  13363. * @param {number} [param.shape.y]
  13364. * @param {number} [param.shape.width]
  13365. * @param {number} [param.shape.height]
  13366. * @param {Object} [param.style]
  13367. * @param {number} [param.style.lineWidth]
  13368. * @return {Object} Modified param
  13369. */
  13370. function subPixelOptimizeRect(param) {
  13371. var shape = param.shape;
  13372. var lineWidth = param.style.lineWidth;
  13373. var originX = shape.x;
  13374. var originY = shape.y;
  13375. var originWidth = shape.width;
  13376. var originHeight = shape.height;
  13377. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13378. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13379. shape.width = Math.max(
  13380. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13381. originWidth === 0 ? 0 : 1
  13382. );
  13383. shape.height = Math.max(
  13384. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13385. originHeight === 0 ? 0 : 1
  13386. );
  13387. return param;
  13388. }
  13389. /**
  13390. * Sub pixel optimize for canvas
  13391. *
  13392. * @param {number} position Coordinate, such as x, y
  13393. * @param {number} lineWidth Should be nonnegative integer.
  13394. * @param {boolean=} positiveOrNegative Default false (negative).
  13395. * @return {number} Optimized position.
  13396. */
  13397. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13398. // Assure that (position + lineWidth / 2) is near integer edge,
  13399. // otherwise line will be fuzzy in canvas.
  13400. var doubledPosition = round(position * 2);
  13401. return (doubledPosition + round(lineWidth)) % 2 === 0
  13402. ? doubledPosition / 2
  13403. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13404. }
  13405. function hasFillOrStroke(fillOrStroke) {
  13406. return fillOrStroke != null && fillOrStroke != 'none';
  13407. }
  13408. function liftColor(color) {
  13409. return typeof color === 'string' ? lift(color, -0.1) : color;
  13410. }
  13411. /**
  13412. * @private
  13413. */
  13414. function cacheElementStl(el) {
  13415. if (el.__hoverStlDirty) {
  13416. var stroke = el.style.stroke;
  13417. var fill = el.style.fill;
  13418. // Create hoverStyle on mouseover
  13419. var hoverStyle = el.__hoverStl;
  13420. hoverStyle.fill = hoverStyle.fill
  13421. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  13422. hoverStyle.stroke = hoverStyle.stroke
  13423. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  13424. var normalStyle = {};
  13425. for (var name in hoverStyle) {
  13426. // See comment in `doSingleEnterHover`.
  13427. if (hoverStyle[name] != null) {
  13428. normalStyle[name] = el.style[name];
  13429. }
  13430. }
  13431. el.__normalStl = normalStyle;
  13432. el.__hoverStlDirty = false;
  13433. }
  13434. }
  13435. /**
  13436. * @private
  13437. */
  13438. function doSingleEnterHover(el) {
  13439. if (el.__isHover) {
  13440. return;
  13441. }
  13442. cacheElementStl(el);
  13443. if (el.useHoverLayer) {
  13444. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  13445. }
  13446. else {
  13447. var style = el.style;
  13448. var insideRollbackOpt = style.insideRollbackOpt;
  13449. // Consider case: only `position: 'top'` is set on emphasis, then text
  13450. // color should be returned to `autoColor`, rather than remain '#fff'.
  13451. // So we should rollback then apply again after style merging.
  13452. insideRollbackOpt && rollbackInsideStyle(style);
  13453. // styles can be:
  13454. // {
  13455. // label: {
  13456. // show: false,
  13457. // position: 'outside',
  13458. // fontSize: 18
  13459. // },
  13460. // emphasis: {
  13461. // label: {
  13462. // show: true
  13463. // }
  13464. // }
  13465. // },
  13466. // where properties of `emphasis` may not appear in `normal`. We previously use
  13467. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  13468. // But consider rich text and setOption in merge mode, it is impossible to cover
  13469. // all properties in merge. So we use merge mode when setting style here, where
  13470. // only properties that is not `null/undefined` can be set. The disadventage:
  13471. // null/undefined can not be used to remove style any more in `emphasis`.
  13472. style.extendFrom(el.__hoverStl);
  13473. // Do not save `insideRollback`.
  13474. if (insideRollbackOpt) {
  13475. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  13476. // textFill may be rollbacked to null.
  13477. if (style.textFill == null) {
  13478. style.textFill = insideRollbackOpt.autoColor;
  13479. }
  13480. }
  13481. el.dirty(false);
  13482. el.z2 += 1;
  13483. }
  13484. el.__isHover = true;
  13485. }
  13486. /**
  13487. * @inner
  13488. */
  13489. function doSingleLeaveHover(el) {
  13490. if (!el.__isHover) {
  13491. return;
  13492. }
  13493. var normalStl = el.__normalStl;
  13494. if (el.useHoverLayer) {
  13495. el.__zr && el.__zr.removeHover(el);
  13496. }
  13497. else {
  13498. // Consider null/undefined value, should use
  13499. // `setStyle` but not `extendFrom(stl, true)`.
  13500. normalStl && el.setStyle(normalStl);
  13501. el.z2 -= 1;
  13502. }
  13503. el.__isHover = false;
  13504. }
  13505. /**
  13506. * @inner
  13507. */
  13508. function doEnterHover(el) {
  13509. el.type === 'group'
  13510. ? el.traverse(function (child) {
  13511. if (child.type !== 'group') {
  13512. doSingleEnterHover(child);
  13513. }
  13514. })
  13515. : doSingleEnterHover(el);
  13516. }
  13517. function doLeaveHover(el) {
  13518. el.type === 'group'
  13519. ? el.traverse(function (child) {
  13520. if (child.type !== 'group') {
  13521. doSingleLeaveHover(child);
  13522. }
  13523. })
  13524. : doSingleLeaveHover(el);
  13525. }
  13526. /**
  13527. * @inner
  13528. */
  13529. function setElementHoverStl(el, hoverStl) {
  13530. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  13531. // Often used when item group has a label element and it's hoverStyle is different
  13532. el.__hoverStl = el.hoverStyle || hoverStl || {};
  13533. el.__hoverStlDirty = true;
  13534. if (el.__isHover) {
  13535. cacheElementStl(el);
  13536. }
  13537. }
  13538. /**
  13539. * @inner
  13540. */
  13541. function onElementMouseOver(e) {
  13542. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13543. return;
  13544. }
  13545. // Only if element is not in emphasis status
  13546. !this.__isEmphasis && doEnterHover(this);
  13547. }
  13548. /**
  13549. * @inner
  13550. */
  13551. function onElementMouseOut(e) {
  13552. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  13553. return;
  13554. }
  13555. // Only if element is not in emphasis status
  13556. !this.__isEmphasis && doLeaveHover(this);
  13557. }
  13558. /**
  13559. * @inner
  13560. */
  13561. function enterEmphasis() {
  13562. this.__isEmphasis = true;
  13563. doEnterHover(this);
  13564. }
  13565. /**
  13566. * @inner
  13567. */
  13568. function leaveEmphasis() {
  13569. this.__isEmphasis = false;
  13570. doLeaveHover(this);
  13571. }
  13572. /**
  13573. * Set hover style of element.
  13574. * This method can be called repeatly without side-effects.
  13575. * @param {module:zrender/Element} el
  13576. * @param {Object} [hoverStyle]
  13577. * @param {Object} [opt]
  13578. * @param {boolean} [opt.hoverSilentOnTouch=false]
  13579. * In touch device, mouseover event will be trigger on touchstart event
  13580. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  13581. * conviniently use hoverStyle when tap on touch screen without additional
  13582. * code for compatibility.
  13583. * But if the chart/component has select feature, which usually also use
  13584. * hoverStyle, there might be conflict between 'select-highlight' and
  13585. * 'hover-highlight' especially when roam is enabled (see geo for example).
  13586. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  13587. * on touch device.
  13588. */
  13589. function setHoverStyle(el, hoverStyle, opt) {
  13590. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  13591. el.type === 'group'
  13592. ? el.traverse(function (child) {
  13593. if (child.type !== 'group') {
  13594. setElementHoverStl(child, hoverStyle);
  13595. }
  13596. })
  13597. : setElementHoverStl(el, hoverStyle);
  13598. // Duplicated function will be auto-ignored, see Eventful.js.
  13599. el.on('mouseover', onElementMouseOver)
  13600. .on('mouseout', onElementMouseOut);
  13601. // Emphasis, normal can be triggered manually
  13602. el.on('emphasis', enterEmphasis)
  13603. .on('normal', leaveEmphasis);
  13604. }
  13605. /**
  13606. * @param {Object|module:zrender/graphic/Style} normalStyle
  13607. * @param {Object} emphasisStyle
  13608. * @param {module:echarts/model/Model} normalModel
  13609. * @param {module:echarts/model/Model} emphasisModel
  13610. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  13611. * @param {string|Function} [opt.defaultText]
  13612. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  13613. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13614. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  13615. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13616. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  13617. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  13618. * @param {Object} [normalSpecified]
  13619. * @param {Object} [emphasisSpecified]
  13620. */
  13621. function setLabelStyle(
  13622. normalStyle, emphasisStyle,
  13623. normalModel, emphasisModel,
  13624. opt,
  13625. normalSpecified, emphasisSpecified
  13626. ) {
  13627. opt = opt || EMPTY_OBJ;
  13628. var labelFetcher = opt.labelFetcher;
  13629. var labelDataIndex = opt.labelDataIndex;
  13630. var labelDimIndex = opt.labelDimIndex;
  13631. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  13632. // is not supported util someone requests.
  13633. var showNormal = normalModel.getShallow('show');
  13634. var showEmphasis = emphasisModel.getShallow('show');
  13635. // Consider performance, only fetch label when necessary.
  13636. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  13637. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  13638. var baseText;
  13639. if (showNormal || showEmphasis) {
  13640. if (labelFetcher) {
  13641. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  13642. }
  13643. if (baseText == null) {
  13644. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  13645. }
  13646. }
  13647. var normalStyleText = showNormal ? baseText : null;
  13648. var emphasisStyleText = showEmphasis
  13649. ? retrieve2(
  13650. labelFetcher
  13651. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  13652. : null,
  13653. baseText
  13654. )
  13655. : null;
  13656. // Optimize: If style.text is null, text will not be drawn.
  13657. if (normalStyleText != null || emphasisStyleText != null) {
  13658. // Always set `textStyle` even if `normalStyle.text` is null, because default
  13659. // values have to be set on `normalStyle`.
  13660. // If we set default values on `emphasisStyle`, consider case:
  13661. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  13662. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  13663. // Then the 'red' will not work on emphasis.
  13664. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  13665. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  13666. }
  13667. normalStyle.text = normalStyleText;
  13668. emphasisStyle.text = emphasisStyleText;
  13669. }
  13670. /**
  13671. * Set basic textStyle properties.
  13672. * @param {Object|module:zrender/graphic/Style} textStyle
  13673. * @param {module:echarts/model/Model} model
  13674. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  13675. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  13676. * @param {boolean} [isEmphasis]
  13677. */
  13678. function setTextStyle(
  13679. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  13680. ) {
  13681. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  13682. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  13683. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  13684. return textStyle;
  13685. }
  13686. /**
  13687. * Set text option in the style.
  13688. * @deprecated
  13689. * @param {Object} textStyle
  13690. * @param {module:echarts/model/Model} labelModel
  13691. * @param {string|boolean} defaultColor Default text color.
  13692. * If set as false, it will be processed as a emphasis style.
  13693. */
  13694. function setText(textStyle, labelModel, defaultColor) {
  13695. var opt = {isRectText: true};
  13696. var isEmphasis;
  13697. if (defaultColor === false) {
  13698. isEmphasis = true;
  13699. }
  13700. else {
  13701. // Support setting color as 'auto' to get visual color.
  13702. opt.autoColor = defaultColor;
  13703. }
  13704. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  13705. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  13706. }
  13707. /**
  13708. * {
  13709. * disableBox: boolean, Whether diable drawing box of block (outer most).
  13710. * isRectText: boolean,
  13711. * autoColor: string, specify a color when color is 'auto',
  13712. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  13713. * If autoColor specified, it is used as default textFill.
  13714. * useInsideStyle:
  13715. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  13716. * if `textFill` is not specified.
  13717. * `false`: Do not use inside style.
  13718. * `null/undefined`: use inside style if `isRectText` is true and
  13719. * `textFill` is not specified and textPosition contains `'inside'`.
  13720. * forceRich: boolean
  13721. * }
  13722. */
  13723. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  13724. // Consider there will be abnormal when merge hover style to normal style if given default value.
  13725. opt = opt || EMPTY_OBJ;
  13726. if (opt.isRectText) {
  13727. var textPosition = textStyleModel.getShallow('position')
  13728. || (isEmphasis ? null : 'inside');
  13729. // 'outside' is not a valid zr textPostion value, but used
  13730. // in bar series, and magric type should be considered.
  13731. textPosition === 'outside' && (textPosition = 'top');
  13732. textStyle.textPosition = textPosition;
  13733. textStyle.textOffset = textStyleModel.getShallow('offset');
  13734. var labelRotate = textStyleModel.getShallow('rotate');
  13735. labelRotate != null && (labelRotate *= Math.PI / 180);
  13736. textStyle.textRotation = labelRotate;
  13737. textStyle.textDistance = retrieve2(
  13738. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  13739. );
  13740. }
  13741. var ecModel = textStyleModel.ecModel;
  13742. var globalTextStyle = ecModel && ecModel.option.textStyle;
  13743. // Consider case:
  13744. // {
  13745. // data: [{
  13746. // value: 12,
  13747. // label: {
  13748. // rich: {
  13749. // // no 'a' here but using parent 'a'.
  13750. // }
  13751. // }
  13752. // }],
  13753. // rich: {
  13754. // a: { ... }
  13755. // }
  13756. // }
  13757. var richItemNames = getRichItemNames(textStyleModel);
  13758. var richResult;
  13759. if (richItemNames) {
  13760. richResult = {};
  13761. for (var name in richItemNames) {
  13762. if (richItemNames.hasOwnProperty(name)) {
  13763. // Cascade is supported in rich.
  13764. var richTextStyle = textStyleModel.getModel(['rich', name]);
  13765. // In rich, never `disableBox`.
  13766. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  13767. }
  13768. }
  13769. }
  13770. textStyle.rich = richResult;
  13771. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  13772. if (opt.forceRich && !opt.textStyle) {
  13773. opt.textStyle = {};
  13774. }
  13775. return textStyle;
  13776. }
  13777. // Consider case:
  13778. // {
  13779. // data: [{
  13780. // value: 12,
  13781. // label: {
  13782. // rich: {
  13783. // // no 'a' here but using parent 'a'.
  13784. // }
  13785. // }
  13786. // }],
  13787. // rich: {
  13788. // a: { ... }
  13789. // }
  13790. // }
  13791. function getRichItemNames(textStyleModel) {
  13792. // Use object to remove duplicated names.
  13793. var richItemNameMap;
  13794. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  13795. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  13796. if (rich) {
  13797. richItemNameMap = richItemNameMap || {};
  13798. for (var name in rich) {
  13799. if (rich.hasOwnProperty(name)) {
  13800. richItemNameMap[name] = 1;
  13801. }
  13802. }
  13803. }
  13804. textStyleModel = textStyleModel.parentModel;
  13805. }
  13806. return richItemNameMap;
  13807. }
  13808. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  13809. // In merge mode, default value should not be given.
  13810. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  13811. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  13812. || globalTextStyle.color;
  13813. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  13814. || globalTextStyle.textBorderColor;
  13815. textStyle.textStrokeWidth = retrieve2(
  13816. textStyleModel.getShallow('textBorderWidth'),
  13817. globalTextStyle.textBorderWidth
  13818. );
  13819. if (!isEmphasis) {
  13820. if (isBlock) {
  13821. // Always set `insideRollback`, for clearing previous.
  13822. var originalTextPosition = textStyle.textPosition;
  13823. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  13824. // Save original textPosition, because style.textPosition will be repalced by
  13825. // real location (like [10, 30]) in zrender.
  13826. textStyle.insideOriginalTextPosition = originalTextPosition;
  13827. textStyle.insideRollbackOpt = opt;
  13828. }
  13829. // Set default finally.
  13830. if (textStyle.textFill == null) {
  13831. textStyle.textFill = opt.autoColor;
  13832. }
  13833. }
  13834. // Do not use `getFont` here, because merge should be supported, where
  13835. // part of these properties may be changed in emphasis style, and the
  13836. // others should remain their original value got from normal style.
  13837. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  13838. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  13839. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  13840. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  13841. textStyle.textAlign = textStyleModel.getShallow('align');
  13842. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  13843. || textStyleModel.getShallow('baseline');
  13844. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  13845. textStyle.textWidth = textStyleModel.getShallow('width');
  13846. textStyle.textHeight = textStyleModel.getShallow('height');
  13847. textStyle.textTag = textStyleModel.getShallow('tag');
  13848. if (!isBlock || !opt.disableBox) {
  13849. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  13850. textStyle.textPadding = textStyleModel.getShallow('padding');
  13851. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  13852. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  13853. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  13854. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  13855. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  13856. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  13857. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  13858. }
  13859. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  13860. || globalTextStyle.textShadowColor;
  13861. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  13862. || globalTextStyle.textShadowBlur;
  13863. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  13864. || globalTextStyle.textShadowOffsetX;
  13865. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  13866. || globalTextStyle.textShadowOffsetY;
  13867. }
  13868. function getAutoColor(color, opt) {
  13869. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  13870. }
  13871. function applyInsideStyle(textStyle, textPosition, opt) {
  13872. var useInsideStyle = opt.useInsideStyle;
  13873. var insideRollback;
  13874. if (textStyle.textFill == null
  13875. && useInsideStyle !== false
  13876. && (useInsideStyle === true
  13877. || (opt.isRectText
  13878. && textPosition
  13879. // textPosition can be [10, 30]
  13880. && typeof textPosition === 'string'
  13881. && textPosition.indexOf('inside') >= 0
  13882. )
  13883. )
  13884. ) {
  13885. insideRollback = {
  13886. textFill: null,
  13887. textStroke: textStyle.textStroke,
  13888. textStrokeWidth: textStyle.textStrokeWidth
  13889. };
  13890. textStyle.textFill = '#fff';
  13891. // Consider text with #fff overflow its container.
  13892. if (textStyle.textStroke == null) {
  13893. textStyle.textStroke = opt.autoColor;
  13894. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  13895. }
  13896. }
  13897. return insideRollback;
  13898. }
  13899. function rollbackInsideStyle(style) {
  13900. var insideRollback = style.insideRollback;
  13901. if (insideRollback) {
  13902. style.textFill = insideRollback.textFill;
  13903. style.textStroke = insideRollback.textStroke;
  13904. style.textStrokeWidth = insideRollback.textStrokeWidth;
  13905. }
  13906. }
  13907. function getFont(opt, ecModel) {
  13908. // ecModel or default text style model.
  13909. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  13910. return trim([
  13911. // FIXME in node-canvas fontWeight is before fontStyle
  13912. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  13913. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  13914. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  13915. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  13916. ].join(' '));
  13917. }
  13918. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  13919. if (typeof dataIndex === 'function') {
  13920. cb = dataIndex;
  13921. dataIndex = null;
  13922. }
  13923. // Do not check 'animation' property directly here. Consider this case:
  13924. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  13925. // but its parent model (`seriesModel`) does.
  13926. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13927. if (animationEnabled) {
  13928. var postfix = isUpdate ? 'Update' : '';
  13929. var duration = animatableModel.getShallow('animationDuration' + postfix);
  13930. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  13931. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  13932. if (typeof animationDelay === 'function') {
  13933. animationDelay = animationDelay(
  13934. dataIndex,
  13935. animatableModel.getAnimationDelayParams
  13936. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  13937. : null
  13938. );
  13939. }
  13940. if (typeof duration === 'function') {
  13941. duration = duration(dataIndex);
  13942. }
  13943. duration > 0
  13944. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  13945. : (el.stopAnimation(), el.attr(props), cb && cb());
  13946. }
  13947. else {
  13948. el.stopAnimation();
  13949. el.attr(props);
  13950. cb && cb();
  13951. }
  13952. }
  13953. /**
  13954. * Update graphic element properties with or without animation according to the
  13955. * configuration in series.
  13956. *
  13957. * Caution: this method will stop previous animation.
  13958. * So if do not use this method to one element twice before
  13959. * animation starts, unless you know what you are doing.
  13960. *
  13961. * @param {module:zrender/Element} el
  13962. * @param {Object} props
  13963. * @param {module:echarts/model/Model} [animatableModel]
  13964. * @param {number} [dataIndex]
  13965. * @param {Function} [cb]
  13966. * @example
  13967. * graphic.updateProps(el, {
  13968. * position: [100, 100]
  13969. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13970. * // Or
  13971. * graphic.updateProps(el, {
  13972. * position: [100, 100]
  13973. * }, seriesModel, function () { console.log('Animation done!'); });
  13974. */
  13975. function updateProps(el, props, animatableModel, dataIndex, cb) {
  13976. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  13977. }
  13978. /**
  13979. * Init graphic element properties with or without animation according to the
  13980. * configuration in series.
  13981. *
  13982. * Caution: this method will stop previous animation.
  13983. * So if do not use this method to one element twice before
  13984. * animation starts, unless you know what you are doing.
  13985. *
  13986. * @param {module:zrender/Element} el
  13987. * @param {Object} props
  13988. * @param {module:echarts/model/Model} [animatableModel]
  13989. * @param {number} [dataIndex]
  13990. * @param {Function} cb
  13991. */
  13992. function initProps(el, props, animatableModel, dataIndex, cb) {
  13993. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  13994. }
  13995. /**
  13996. * Get transform matrix of target (param target),
  13997. * in coordinate of its ancestor (param ancestor)
  13998. *
  13999. * @param {module:zrender/mixin/Transformable} target
  14000. * @param {module:zrender/mixin/Transformable} [ancestor]
  14001. */
  14002. function getTransform(target, ancestor) {
  14003. var mat = identity([]);
  14004. while (target && target !== ancestor) {
  14005. mul$1(mat, target.getLocalTransform(), mat);
  14006. target = target.parent;
  14007. }
  14008. return mat;
  14009. }
  14010. /**
  14011. * Apply transform to an vertex.
  14012. * @param {Array.<number>} target [x, y]
  14013. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14014. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14015. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14016. * @param {boolean=} invert Whether use invert matrix.
  14017. * @return {Array.<number>} [x, y]
  14018. */
  14019. function applyTransform$1(target, transform, invert$$1) {
  14020. if (transform && !isArrayLike(transform)) {
  14021. transform = Transformable.getLocalTransform(transform);
  14022. }
  14023. if (invert$$1) {
  14024. transform = invert([], transform);
  14025. }
  14026. return applyTransform([], target, transform);
  14027. }
  14028. /**
  14029. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14030. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14031. * @param {boolean=} invert Whether use invert matrix.
  14032. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14033. */
  14034. function transformDirection(direction, transform, invert$$1) {
  14035. // Pick a base, ensure that transform result will not be (0, 0).
  14036. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14037. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14038. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14039. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14040. var vertex = [
  14041. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14042. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14043. ];
  14044. vertex = applyTransform$1(vertex, transform, invert$$1);
  14045. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14046. ? (vertex[0] > 0 ? 'right' : 'left')
  14047. : (vertex[1] > 0 ? 'bottom' : 'top');
  14048. }
  14049. /**
  14050. * Apply group transition animation from g1 to g2.
  14051. * If no animatableModel, no animation.
  14052. */
  14053. function groupTransition(g1, g2, animatableModel, cb) {
  14054. if (!g1 || !g2) {
  14055. return;
  14056. }
  14057. function getElMap(g) {
  14058. var elMap = {};
  14059. g.traverse(function (el) {
  14060. if (!el.isGroup && el.anid) {
  14061. elMap[el.anid] = el;
  14062. }
  14063. });
  14064. return elMap;
  14065. }
  14066. function getAnimatableProps(el) {
  14067. var obj = {
  14068. position: clone$1(el.position),
  14069. rotation: el.rotation
  14070. };
  14071. if (el.shape) {
  14072. obj.shape = extend({}, el.shape);
  14073. }
  14074. return obj;
  14075. }
  14076. var elMap1 = getElMap(g1);
  14077. g2.traverse(function (el) {
  14078. if (!el.isGroup && el.anid) {
  14079. var oldEl = elMap1[el.anid];
  14080. if (oldEl) {
  14081. var newProp = getAnimatableProps(el);
  14082. el.attr(getAnimatableProps(oldEl));
  14083. updateProps(el, newProp, animatableModel, el.dataIndex);
  14084. }
  14085. // else {
  14086. // if (el.previousProps) {
  14087. // graphic.updateProps
  14088. // }
  14089. // }
  14090. }
  14091. });
  14092. }
  14093. /**
  14094. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14095. * @param {Object} rect {x, y, width, height}
  14096. * @return {Array.<Array.<number>>} A new clipped points.
  14097. */
  14098. function clipPointsByRect(points, rect) {
  14099. return map(points, function (point) {
  14100. var x = point[0];
  14101. x = mathMax$1(x, rect.x);
  14102. x = mathMin$1(x, rect.x + rect.width);
  14103. var y = point[1];
  14104. y = mathMax$1(y, rect.y);
  14105. y = mathMin$1(y, rect.y + rect.height);
  14106. return [x, y];
  14107. });
  14108. }
  14109. /**
  14110. * @param {Object} targetRect {x, y, width, height}
  14111. * @param {Object} rect {x, y, width, height}
  14112. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14113. */
  14114. function clipRectByRect(targetRect, rect) {
  14115. var x = mathMax$1(targetRect.x, rect.x);
  14116. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14117. var y = mathMax$1(targetRect.y, rect.y);
  14118. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14119. if (x2 >= x && y2 >= y) {
  14120. return {
  14121. x: x,
  14122. y: y,
  14123. width: x2 - x,
  14124. height: y2 - y
  14125. };
  14126. }
  14127. }
  14128. /**
  14129. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14130. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14131. * @param {Object} [rect] {x, y, width, height}
  14132. * @return {module:zrender/Element} Icon path or image element.
  14133. */
  14134. function createIcon(iconStr, opt, rect) {
  14135. opt = extend({rectHover: true}, opt);
  14136. var style = opt.style = {strokeNoScale: true};
  14137. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14138. if (iconStr) {
  14139. return iconStr.indexOf('image://') === 0
  14140. ? (
  14141. style.image = iconStr.slice(8),
  14142. defaults(style, rect),
  14143. new ZImage(opt)
  14144. )
  14145. : (
  14146. makePath(
  14147. iconStr.replace('path://', ''),
  14148. opt,
  14149. rect,
  14150. 'center'
  14151. )
  14152. );
  14153. }
  14154. }
  14155. var graphic = (Object.freeze || Object)({
  14156. extendShape: extendShape,
  14157. extendPath: extendPath,
  14158. makePath: makePath,
  14159. makeImage: makeImage,
  14160. mergePath: mergePath,
  14161. resizePath: resizePath,
  14162. subPixelOptimizeLine: subPixelOptimizeLine,
  14163. subPixelOptimizeRect: subPixelOptimizeRect,
  14164. subPixelOptimize: subPixelOptimize,
  14165. setHoverStyle: setHoverStyle,
  14166. setLabelStyle: setLabelStyle,
  14167. setTextStyle: setTextStyle,
  14168. setText: setText,
  14169. getFont: getFont,
  14170. updateProps: updateProps,
  14171. initProps: initProps,
  14172. getTransform: getTransform,
  14173. applyTransform: applyTransform$1,
  14174. transformDirection: transformDirection,
  14175. groupTransition: groupTransition,
  14176. clipPointsByRect: clipPointsByRect,
  14177. clipRectByRect: clipRectByRect,
  14178. createIcon: createIcon,
  14179. Group: Group,
  14180. Image: ZImage,
  14181. Text: Text,
  14182. Circle: Circle,
  14183. Sector: Sector,
  14184. Ring: Ring,
  14185. Polygon: Polygon,
  14186. Polyline: Polyline,
  14187. Rect: Rect,
  14188. Line: Line,
  14189. BezierCurve: BezierCurve,
  14190. Arc: Arc,
  14191. IncrementalDisplayable: IncrementalDisplayble,
  14192. CompoundPath: CompoundPath,
  14193. LinearGradient: LinearGradient,
  14194. RadialGradient: RadialGradient,
  14195. BoundingRect: BoundingRect
  14196. });
  14197. var PATH_COLOR = ['textStyle', 'color'];
  14198. var textStyleMixin = {
  14199. /**
  14200. * Get color property or get color from option.textStyle.color
  14201. * @param {boolean} [isEmphasis]
  14202. * @return {string}
  14203. */
  14204. getTextColor: function (isEmphasis) {
  14205. var ecModel = this.ecModel;
  14206. return this.getShallow('color')
  14207. || (
  14208. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14209. );
  14210. },
  14211. /**
  14212. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14213. * @return {string}
  14214. */
  14215. getFont: function () {
  14216. return getFont({
  14217. fontStyle: this.getShallow('fontStyle'),
  14218. fontWeight: this.getShallow('fontWeight'),
  14219. fontSize: this.getShallow('fontSize'),
  14220. fontFamily: this.getShallow('fontFamily')
  14221. }, this.ecModel);
  14222. },
  14223. getTextRect: function (text) {
  14224. return getBoundingRect(
  14225. text,
  14226. this.getFont(),
  14227. this.getShallow('align'),
  14228. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14229. this.getShallow('padding'),
  14230. this.getShallow('rich'),
  14231. this.getShallow('truncateText')
  14232. );
  14233. }
  14234. };
  14235. var getItemStyle = makeStyleMapper(
  14236. [
  14237. ['fill', 'color'],
  14238. ['stroke', 'borderColor'],
  14239. ['lineWidth', 'borderWidth'],
  14240. ['opacity'],
  14241. ['shadowBlur'],
  14242. ['shadowOffsetX'],
  14243. ['shadowOffsetY'],
  14244. ['shadowColor'],
  14245. ['textPosition'],
  14246. ['textAlign']
  14247. ]
  14248. );
  14249. var itemStyleMixin = {
  14250. getItemStyle: function (excludes, includes) {
  14251. var style = getItemStyle(this, excludes, includes);
  14252. var lineDash = this.getBorderLineDash();
  14253. lineDash && (style.lineDash = lineDash);
  14254. return style;
  14255. },
  14256. getBorderLineDash: function () {
  14257. var lineType = this.get('borderType');
  14258. return (lineType === 'solid' || lineType == null) ? null
  14259. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14260. }
  14261. };
  14262. /**
  14263. * @module echarts/model/Model
  14264. */
  14265. var mixin$1 = mixin;
  14266. var inner = makeInner();
  14267. /**
  14268. * @alias module:echarts/model/Model
  14269. * @constructor
  14270. * @param {Object} option
  14271. * @param {module:echarts/model/Model} [parentModel]
  14272. * @param {module:echarts/model/Global} [ecModel]
  14273. */
  14274. function Model(option, parentModel, ecModel) {
  14275. /**
  14276. * @type {module:echarts/model/Model}
  14277. * @readOnly
  14278. */
  14279. this.parentModel = parentModel;
  14280. /**
  14281. * @type {module:echarts/model/Global}
  14282. * @readOnly
  14283. */
  14284. this.ecModel = ecModel;
  14285. /**
  14286. * @type {Object}
  14287. * @protected
  14288. */
  14289. this.option = option;
  14290. // Simple optimization
  14291. // if (this.init) {
  14292. // if (arguments.length <= 4) {
  14293. // this.init(option, parentModel, ecModel, extraOpt);
  14294. // }
  14295. // else {
  14296. // this.init.apply(this, arguments);
  14297. // }
  14298. // }
  14299. }
  14300. Model.prototype = {
  14301. constructor: Model,
  14302. /**
  14303. * Model 的初始化函数
  14304. * @param {Object} option
  14305. */
  14306. init: null,
  14307. /**
  14308. * 从新的 Option merge
  14309. */
  14310. mergeOption: function (option) {
  14311. merge(this.option, option, true);
  14312. },
  14313. /**
  14314. * @param {string|Array.<string>} path
  14315. * @param {boolean} [ignoreParent=false]
  14316. * @return {*}
  14317. */
  14318. get: function (path, ignoreParent) {
  14319. if (path == null) {
  14320. return this.option;
  14321. }
  14322. return doGet(
  14323. this.option,
  14324. this.parsePath(path),
  14325. !ignoreParent && getParent(this, path)
  14326. );
  14327. },
  14328. /**
  14329. * @param {string} key
  14330. * @param {boolean} [ignoreParent=false]
  14331. * @return {*}
  14332. */
  14333. getShallow: function (key, ignoreParent) {
  14334. var option = this.option;
  14335. var val = option == null ? option : option[key];
  14336. var parentModel = !ignoreParent && getParent(this, key);
  14337. if (val == null && parentModel) {
  14338. val = parentModel.getShallow(key);
  14339. }
  14340. return val;
  14341. },
  14342. /**
  14343. * @param {string|Array.<string>} [path]
  14344. * @param {module:echarts/model/Model} [parentModel]
  14345. * @return {module:echarts/model/Model}
  14346. */
  14347. getModel: function (path, parentModel) {
  14348. var obj = path == null
  14349. ? this.option
  14350. : doGet(this.option, path = this.parsePath(path));
  14351. var thisParentModel;
  14352. parentModel = parentModel || (
  14353. (thisParentModel = getParent(this, path))
  14354. && thisParentModel.getModel(path)
  14355. );
  14356. return new Model(obj, parentModel, this.ecModel);
  14357. },
  14358. /**
  14359. * If model has option
  14360. */
  14361. isEmpty: function () {
  14362. return this.option == null;
  14363. },
  14364. restoreData: function () {},
  14365. // Pending
  14366. clone: function () {
  14367. var Ctor = this.constructor;
  14368. return new Ctor(clone(this.option));
  14369. },
  14370. setReadOnly: function (properties) {
  14371. // clazzUtil.setReadOnly(this, properties);
  14372. },
  14373. // If path is null/undefined, return null/undefined.
  14374. parsePath: function(path) {
  14375. if (typeof path === 'string') {
  14376. path = path.split('.');
  14377. }
  14378. return path;
  14379. },
  14380. /**
  14381. * @param {Function} getParentMethod
  14382. * param {Array.<string>|string} path
  14383. * return {module:echarts/model/Model}
  14384. */
  14385. customizeGetParent: function (getParentMethod) {
  14386. inner(this).getParent = getParentMethod;
  14387. },
  14388. isAnimationEnabled: function () {
  14389. if (!env$1.node) {
  14390. if (this.option.animation != null) {
  14391. return !!this.option.animation;
  14392. }
  14393. else if (this.parentModel) {
  14394. return this.parentModel.isAnimationEnabled();
  14395. }
  14396. }
  14397. }
  14398. };
  14399. function doGet(obj, pathArr, parentModel) {
  14400. for (var i = 0; i < pathArr.length; i++) {
  14401. // Ignore empty
  14402. if (!pathArr[i]) {
  14403. continue;
  14404. }
  14405. // obj could be number/string/... (like 0)
  14406. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  14407. if (obj == null) {
  14408. break;
  14409. }
  14410. }
  14411. if (obj == null && parentModel) {
  14412. obj = parentModel.get(pathArr);
  14413. }
  14414. return obj;
  14415. }
  14416. // `path` can be null/undefined
  14417. function getParent(model, path) {
  14418. var getParentMethod = inner(model).getParent;
  14419. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  14420. }
  14421. // Enable Model.extend.
  14422. enableClassExtend(Model);
  14423. enableClassCheck(Model);
  14424. mixin$1(Model, lineStyleMixin);
  14425. mixin$1(Model, areaStyleMixin);
  14426. mixin$1(Model, textStyleMixin);
  14427. mixin$1(Model, itemStyleMixin);
  14428. var base = 0;
  14429. /**
  14430. * @public
  14431. * @param {string} type
  14432. * @return {string}
  14433. */
  14434. function getUID(type) {
  14435. // Considering the case of crossing js context,
  14436. // use Math.random to make id as unique as possible.
  14437. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  14438. }
  14439. /**
  14440. * @inner
  14441. */
  14442. function enableSubTypeDefaulter(entity) {
  14443. var subTypeDefaulters = {};
  14444. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  14445. componentType = parseClassType$1(componentType);
  14446. subTypeDefaulters[componentType.main] = defaulter;
  14447. };
  14448. entity.determineSubType = function (componentType, option) {
  14449. var type = option.type;
  14450. if (!type) {
  14451. var componentTypeMain = parseClassType$1(componentType).main;
  14452. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14453. type = subTypeDefaulters[componentTypeMain](option);
  14454. }
  14455. }
  14456. return type;
  14457. };
  14458. return entity;
  14459. }
  14460. /**
  14461. * Topological travel on Activity Network (Activity On Vertices).
  14462. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14463. *
  14464. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14465. *
  14466. * If there is circle dependencey, Error will be thrown.
  14467. *
  14468. */
  14469. function enableTopologicalTravel(entity, dependencyGetter) {
  14470. /**
  14471. * @public
  14472. * @param {Array.<string>} targetNameList Target Component type list.
  14473. * Can be ['aa', 'bb', 'aa.xx']
  14474. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  14475. * @param {Function} callback Params: componentType, dependencies.
  14476. * @param {Object} context Scope of callback.
  14477. */
  14478. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14479. if (!targetNameList.length) {
  14480. return;
  14481. }
  14482. var result = makeDepndencyGraph(fullNameList);
  14483. var graph = result.graph;
  14484. var stack = result.noEntryList;
  14485. var targetNameSet = {};
  14486. each$1(targetNameList, function (name) {
  14487. targetNameSet[name] = true;
  14488. });
  14489. while (stack.length) {
  14490. var currComponentType = stack.pop();
  14491. var currVertex = graph[currComponentType];
  14492. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14493. if (isInTargetNameSet) {
  14494. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14495. delete targetNameSet[currComponentType];
  14496. }
  14497. each$1(
  14498. currVertex.successor,
  14499. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  14500. );
  14501. }
  14502. each$1(targetNameSet, function () {
  14503. throw new Error('Circle dependency may exists');
  14504. });
  14505. function removeEdge(succComponentType) {
  14506. graph[succComponentType].entryCount--;
  14507. if (graph[succComponentType].entryCount === 0) {
  14508. stack.push(succComponentType);
  14509. }
  14510. }
  14511. // Consider this case: legend depends on series, and we call
  14512. // chart.setOption({series: [...]}), where only series is in option.
  14513. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14514. // not be called, but only sereis.mergeOption is called. Thus legend
  14515. // have no chance to update its local record about series (like which
  14516. // name of series is available in legend).
  14517. function removeEdgeAndAdd(succComponentType) {
  14518. targetNameSet[succComponentType] = true;
  14519. removeEdge(succComponentType);
  14520. }
  14521. };
  14522. /**
  14523. * DepndencyGraph: {Object}
  14524. * key: conponentType,
  14525. * value: {
  14526. * successor: [conponentTypes...],
  14527. * originalDeps: [conponentTypes...],
  14528. * entryCount: {number}
  14529. * }
  14530. */
  14531. function makeDepndencyGraph(fullNameList) {
  14532. var graph = {};
  14533. var noEntryList = [];
  14534. each$1(fullNameList, function (name) {
  14535. var thisItem = createDependencyGraphItem(graph, name);
  14536. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14537. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14538. thisItem.entryCount = availableDeps.length;
  14539. if (thisItem.entryCount === 0) {
  14540. noEntryList.push(name);
  14541. }
  14542. each$1(availableDeps, function (dependentName) {
  14543. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14544. thisItem.predecessor.push(dependentName);
  14545. }
  14546. var thatItem = createDependencyGraphItem(graph, dependentName);
  14547. if (indexOf(thatItem.successor, dependentName) < 0) {
  14548. thatItem.successor.push(name);
  14549. }
  14550. });
  14551. });
  14552. return {graph: graph, noEntryList: noEntryList};
  14553. }
  14554. function createDependencyGraphItem(graph, name) {
  14555. if (!graph[name]) {
  14556. graph[name] = {predecessor: [], successor: []};
  14557. }
  14558. return graph[name];
  14559. }
  14560. function getAvailableDependencies(originalDeps, fullNameList) {
  14561. var availableDeps = [];
  14562. each$1(originalDeps, function (dep) {
  14563. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14564. });
  14565. return availableDeps;
  14566. }
  14567. }
  14568. var RADIAN_EPSILON = 1e-4;
  14569. function _trim(str) {
  14570. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  14571. }
  14572. /**
  14573. * Linear mapping a value from domain to range
  14574. * @memberOf module:echarts/util/number
  14575. * @param {(number|Array.<number>)} val
  14576. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  14577. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  14578. * @param {boolean} clamp
  14579. * @return {(number|Array.<number>}
  14580. */
  14581. function linearMap(val, domain, range, clamp) {
  14582. var subDomain = domain[1] - domain[0];
  14583. var subRange = range[1] - range[0];
  14584. if (subDomain === 0) {
  14585. return subRange === 0
  14586. ? range[0]
  14587. : (range[0] + range[1]) / 2;
  14588. }
  14589. // Avoid accuracy problem in edge, such as
  14590. // 146.39 - 62.83 === 83.55999999999999.
  14591. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  14592. // It is a little verbose for efficiency considering this method
  14593. // is a hotspot.
  14594. if (clamp) {
  14595. if (subDomain > 0) {
  14596. if (val <= domain[0]) {
  14597. return range[0];
  14598. }
  14599. else if (val >= domain[1]) {
  14600. return range[1];
  14601. }
  14602. }
  14603. else {
  14604. if (val >= domain[0]) {
  14605. return range[0];
  14606. }
  14607. else if (val <= domain[1]) {
  14608. return range[1];
  14609. }
  14610. }
  14611. }
  14612. else {
  14613. if (val === domain[0]) {
  14614. return range[0];
  14615. }
  14616. if (val === domain[1]) {
  14617. return range[1];
  14618. }
  14619. }
  14620. return (val - domain[0]) / subDomain * subRange + range[0];
  14621. }
  14622. /**
  14623. * Convert a percent string to absolute number.
  14624. * Returns NaN if percent is not a valid string or number
  14625. * @memberOf module:echarts/util/number
  14626. * @param {string|number} percent
  14627. * @param {number} all
  14628. * @return {number}
  14629. */
  14630. function parsePercent$1(percent, all) {
  14631. switch (percent) {
  14632. case 'center':
  14633. case 'middle':
  14634. percent = '50%';
  14635. break;
  14636. case 'left':
  14637. case 'top':
  14638. percent = '0%';
  14639. break;
  14640. case 'right':
  14641. case 'bottom':
  14642. percent = '100%';
  14643. break;
  14644. }
  14645. if (typeof percent === 'string') {
  14646. if (_trim(percent).match(/%$/)) {
  14647. return parseFloat(percent) / 100 * all;
  14648. }
  14649. return parseFloat(percent);
  14650. }
  14651. return percent == null ? NaN : +percent;
  14652. }
  14653. /**
  14654. * (1) Fix rounding error of float numbers.
  14655. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  14656. *
  14657. * @param {number} x
  14658. * @param {number} [precision]
  14659. * @param {boolean} [returnStr]
  14660. * @return {number|string}
  14661. */
  14662. function round$1(x, precision, returnStr) {
  14663. if (precision == null) {
  14664. precision = 10;
  14665. }
  14666. // Avoid range error
  14667. precision = Math.min(Math.max(0, precision), 20);
  14668. x = (+x).toFixed(precision);
  14669. return returnStr ? x : +x;
  14670. }
  14671. /**
  14672. * Get precision
  14673. * @param {number} val
  14674. */
  14675. /**
  14676. * @param {string|number} val
  14677. * @return {number}
  14678. */
  14679. function getPrecisionSafe(val) {
  14680. var str = val.toString();
  14681. // Consider scientific notation: '3.4e-12' '3.4e+12'
  14682. var eIndex = str.indexOf('e');
  14683. if (eIndex > 0) {
  14684. var precision = +str.slice(eIndex + 1);
  14685. return precision < 0 ? -precision : 0;
  14686. }
  14687. else {
  14688. var dotIndex = str.indexOf('.');
  14689. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  14690. }
  14691. }
  14692. /**
  14693. * Minimal dicernible data precisioin according to a single pixel.
  14694. *
  14695. * @param {Array.<number>} dataExtent
  14696. * @param {Array.<number>} pixelExtent
  14697. * @return {number} precision
  14698. */
  14699. function getPixelPrecision(dataExtent, pixelExtent) {
  14700. var log = Math.log;
  14701. var LN10 = Math.LN10;
  14702. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  14703. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  14704. // toFixed() digits argument must be between 0 and 20.
  14705. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  14706. return !isFinite(precision) ? 20 : precision;
  14707. }
  14708. /**
  14709. * Get a data of given precision, assuring the sum of percentages
  14710. * in valueList is 1.
  14711. * The largest remainer method is used.
  14712. * https://en.wikipedia.org/wiki/Largest_remainder_method
  14713. *
  14714. * @param {Array.<number>} valueList a list of all data
  14715. * @param {number} idx index of the data to be processed in valueList
  14716. * @param {number} precision integer number showing digits of precision
  14717. * @return {number} percent ranging from 0 to 100
  14718. */
  14719. function getPercentWithPrecision(valueList, idx, precision) {
  14720. if (!valueList[idx]) {
  14721. return 0;
  14722. }
  14723. var sum = reduce(valueList, function (acc, val) {
  14724. return acc + (isNaN(val) ? 0 : val);
  14725. }, 0);
  14726. if (sum === 0) {
  14727. return 0;
  14728. }
  14729. var digits = Math.pow(10, precision);
  14730. var votesPerQuota = map(valueList, function (val) {
  14731. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  14732. });
  14733. var targetSeats = digits * 100;
  14734. var seats = map(votesPerQuota, function (votes) {
  14735. // Assign automatic seats.
  14736. return Math.floor(votes);
  14737. });
  14738. var currentSum = reduce(seats, function (acc, val) {
  14739. return acc + val;
  14740. }, 0);
  14741. var remainder = map(votesPerQuota, function (votes, idx) {
  14742. return votes - seats[idx];
  14743. });
  14744. // Has remainding votes.
  14745. while (currentSum < targetSeats) {
  14746. // Find next largest remainder.
  14747. var max = Number.NEGATIVE_INFINITY;
  14748. var maxId = null;
  14749. for (var i = 0, len = remainder.length; i < len; ++i) {
  14750. if (remainder[i] > max) {
  14751. max = remainder[i];
  14752. maxId = i;
  14753. }
  14754. }
  14755. // Add a vote to max remainder.
  14756. ++seats[maxId];
  14757. remainder[maxId] = 0;
  14758. ++currentSum;
  14759. }
  14760. return seats[idx] / digits;
  14761. }
  14762. // Number.MAX_SAFE_INTEGER, ie do not support.
  14763. /**
  14764. * To 0 - 2 * PI, considering negative radian.
  14765. * @param {number} radian
  14766. * @return {number}
  14767. */
  14768. function remRadian(radian) {
  14769. var pi2 = Math.PI * 2;
  14770. return (radian % pi2 + pi2) % pi2;
  14771. }
  14772. /**
  14773. * @param {type} radian
  14774. * @return {boolean}
  14775. */
  14776. function isRadianAroundZero(val) {
  14777. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  14778. }
  14779. 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
  14780. /**
  14781. * @param {string|Date|number} value These values can be accepted:
  14782. * + An instance of Date, represent a time in its own time zone.
  14783. * + Or string in a subset of ISO 8601, only including:
  14784. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  14785. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  14786. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  14787. * all of which will be treated as local time if time zone is not specified
  14788. * (see <https://momentjs.com/>).
  14789. * + Or other string format, including (all of which will be treated as loacal time):
  14790. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  14791. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  14792. * + a timestamp, which represent a time in UTC.
  14793. * @return {Date} date
  14794. */
  14795. function parseDate(value) {
  14796. if (value instanceof Date) {
  14797. return value;
  14798. }
  14799. else if (typeof value === 'string') {
  14800. // Different browsers parse date in different way, so we parse it manually.
  14801. // Some other issues:
  14802. // new Date('1970-01-01') is UTC,
  14803. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  14804. // See issue #3623
  14805. var match = TIME_REG.exec(value);
  14806. if (!match) {
  14807. // return Invalid Date.
  14808. return new Date(NaN);
  14809. }
  14810. // Use local time when no timezone offset specifed.
  14811. if (!match[8]) {
  14812. // match[n] can only be string or undefined.
  14813. // But take care of '12' + 1 => '121'.
  14814. return new Date(
  14815. +match[1],
  14816. +(match[2] || 1) - 1,
  14817. +match[3] || 1,
  14818. +match[4] || 0,
  14819. +(match[5] || 0),
  14820. +match[6] || 0,
  14821. +match[7] || 0
  14822. );
  14823. }
  14824. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  14825. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  14826. // For example, system timezone is set as "Time Zone: America/Toronto",
  14827. // then these code will get different result:
  14828. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  14829. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  14830. // So we should not use `new Date`, but use `Date.UTC`.
  14831. else {
  14832. var hour = +match[4] || 0;
  14833. if (match[8].toUpperCase() !== 'Z') {
  14834. hour -= match[8].slice(0, 3);
  14835. }
  14836. return new Date(Date.UTC(
  14837. +match[1],
  14838. +(match[2] || 1) - 1,
  14839. +match[3] || 1,
  14840. hour,
  14841. +(match[5] || 0),
  14842. +match[6] || 0,
  14843. +match[7] || 0
  14844. ));
  14845. }
  14846. }
  14847. else if (value == null) {
  14848. return new Date(NaN);
  14849. }
  14850. return new Date(Math.round(value));
  14851. }
  14852. /**
  14853. * Quantity of a number. e.g. 0.1, 1, 10, 100
  14854. *
  14855. * @param {number} val
  14856. * @return {number}
  14857. */
  14858. function quantity(val) {
  14859. return Math.pow(10, quantityExponent(val));
  14860. }
  14861. function quantityExponent(val) {
  14862. return Math.floor(Math.log(val) / Math.LN10);
  14863. }
  14864. /**
  14865. * find a “nice” number approximately equal to x. Round the number if round = true,
  14866. * take ceiling if round = false. The primary observation is that the “nicest”
  14867. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  14868. *
  14869. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  14870. *
  14871. * @param {number} val Non-negative value.
  14872. * @param {boolean} round
  14873. * @return {number}
  14874. */
  14875. function nice(val, round) {
  14876. var exponent = quantityExponent(val);
  14877. var exp10 = Math.pow(10, exponent);
  14878. var f = val / exp10; // 1 <= f < 10
  14879. var nf;
  14880. if (round) {
  14881. if (f < 1.5) { nf = 1; }
  14882. else if (f < 2.5) { nf = 2; }
  14883. else if (f < 4) { nf = 3; }
  14884. else if (f < 7) { nf = 5; }
  14885. else { nf = 10; }
  14886. }
  14887. else {
  14888. if (f < 1) { nf = 1; }
  14889. else if (f < 2) { nf = 2; }
  14890. else if (f < 3) { nf = 3; }
  14891. else if (f < 5) { nf = 5; }
  14892. else { nf = 10; }
  14893. }
  14894. val = nf * exp10;
  14895. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  14896. // 20 is the uppper bound of toFixed.
  14897. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  14898. }
  14899. /**
  14900. * Order intervals asc, and split them when overlap.
  14901. * expect(numberUtil.reformIntervals([
  14902. * {interval: [18, 62], close: [1, 1]},
  14903. * {interval: [-Infinity, -70], close: [0, 0]},
  14904. * {interval: [-70, -26], close: [1, 1]},
  14905. * {interval: [-26, 18], close: [1, 1]},
  14906. * {interval: [62, 150], close: [1, 1]},
  14907. * {interval: [106, 150], close: [1, 1]},
  14908. * {interval: [150, Infinity], close: [0, 0]}
  14909. * ])).toEqual([
  14910. * {interval: [-Infinity, -70], close: [0, 0]},
  14911. * {interval: [-70, -26], close: [1, 1]},
  14912. * {interval: [-26, 18], close: [0, 1]},
  14913. * {interval: [18, 62], close: [0, 1]},
  14914. * {interval: [62, 150], close: [0, 1]},
  14915. * {interval: [150, Infinity], close: [0, 0]}
  14916. * ]);
  14917. * @param {Array.<Object>} list, where `close` mean open or close
  14918. * of the interval, and Infinity can be used.
  14919. * @return {Array.<Object>} The origin list, which has been reformed.
  14920. */
  14921. /**
  14922. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  14923. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  14924. * subtraction forces infinities to NaN
  14925. *
  14926. * @param {*} v
  14927. * @return {boolean}
  14928. */
  14929. /**
  14930. * 每三位默认加,格式化
  14931. * @param {string|number} x
  14932. * @return {string}
  14933. */
  14934. function addCommas(x) {
  14935. if (isNaN(x)) {
  14936. return '-';
  14937. }
  14938. x = (x + '').split('.');
  14939. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  14940. + (x.length > 1 ? ('.' + x[1]) : '');
  14941. }
  14942. /**
  14943. * @param {string} str
  14944. * @param {boolean} [upperCaseFirst=false]
  14945. * @return {string} str
  14946. */
  14947. var normalizeCssArray$1 = normalizeCssArray;
  14948. function encodeHTML(source) {
  14949. return String(source)
  14950. .replace(/&/g, '&amp;')
  14951. .replace(/</g, '&lt;')
  14952. .replace(/>/g, '&gt;')
  14953. .replace(/"/g, '&quot;')
  14954. .replace(/'/g, '&#39;');
  14955. }
  14956. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  14957. var wrapVar = function (varName, seriesIdx) {
  14958. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  14959. };
  14960. /**
  14961. * Template formatter
  14962. * @param {string} tpl
  14963. * @param {Array.<Object>|Object} paramsList
  14964. * @param {boolean} [encode=false]
  14965. * @return {string}
  14966. */
  14967. function formatTpl(tpl, paramsList, encode) {
  14968. if (!isArray(paramsList)) {
  14969. paramsList = [paramsList];
  14970. }
  14971. var seriesLen = paramsList.length;
  14972. if (!seriesLen) {
  14973. return '';
  14974. }
  14975. var $vars = paramsList[0].$vars || [];
  14976. for (var i = 0; i < $vars.length; i++) {
  14977. var alias = TPL_VAR_ALIAS[i];
  14978. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  14979. }
  14980. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  14981. for (var k = 0; k < $vars.length; k++) {
  14982. var val = paramsList[seriesIdx][$vars[k]];
  14983. tpl = tpl.replace(
  14984. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  14985. encode ? encodeHTML(val) : val
  14986. );
  14987. }
  14988. }
  14989. return tpl;
  14990. }
  14991. /**
  14992. * simple Template formatter
  14993. *
  14994. * @param {string} tpl
  14995. * @param {Object} param
  14996. * @param {boolean} [encode=false]
  14997. * @return {string}
  14998. */
  14999. /**
  15000. * @param {Object|string} [opt] If string, means color.
  15001. * @param {string} [opt.color]
  15002. * @param {string} [opt.extraCssText]
  15003. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15004. * @return {string}
  15005. */
  15006. function getTooltipMarker(opt, extraCssText) {
  15007. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15008. var color = opt.color;
  15009. var type = opt.type;
  15010. var extraCssText = opt.extraCssText;
  15011. if (!color) {
  15012. return '';
  15013. }
  15014. return type === 'subItem'
  15015. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15016. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15017. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15018. : '<span style="display:inline-block;margin-right:5px;'
  15019. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15020. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15021. }
  15022. /**
  15023. * @param {string} str
  15024. * @return {string}
  15025. * @inner
  15026. */
  15027. var s2d = function (str) {
  15028. return str < 10 ? ('0' + str) : str;
  15029. };
  15030. /**
  15031. * ISO Date format
  15032. * @param {string} tpl
  15033. * @param {number} value
  15034. * @param {boolean} [isUTC=false] Default in local time.
  15035. * see `module:echarts/scale/Time`
  15036. * and `module:echarts/util/number#parseDate`.
  15037. * @inner
  15038. */
  15039. function formatTime(tpl, value, isUTC) {
  15040. if (tpl === 'week'
  15041. || tpl === 'month'
  15042. || tpl === 'quarter'
  15043. || tpl === 'half-year'
  15044. || tpl === 'year'
  15045. ) {
  15046. tpl = 'MM-dd\nyyyy';
  15047. }
  15048. var date = parseDate(value);
  15049. var utc = isUTC ? 'UTC' : '';
  15050. var y = date['get' + utc + 'FullYear']();
  15051. var M = date['get' + utc + 'Month']() + 1;
  15052. var d = date['get' + utc + 'Date']();
  15053. var h = date['get' + utc + 'Hours']();
  15054. var m = date['get' + utc + 'Minutes']();
  15055. var s = date['get' + utc + 'Seconds']();
  15056. tpl = tpl.replace('MM', s2d(M))
  15057. .replace('M', M)
  15058. .replace('yyyy', y)
  15059. .replace('yy', y % 100)
  15060. .replace('dd', s2d(d))
  15061. .replace('d', d)
  15062. .replace('hh', s2d(h))
  15063. .replace('h', h)
  15064. .replace('mm', s2d(m))
  15065. .replace('m', m)
  15066. .replace('ss', s2d(s))
  15067. .replace('s', s);
  15068. return tpl;
  15069. }
  15070. /**
  15071. * Capital first
  15072. * @param {string} str
  15073. * @return {string}
  15074. */
  15075. var truncateText$1 = truncateText;
  15076. // Layout helpers for each component positioning
  15077. var each$3 = each$1;
  15078. /**
  15079. * @public
  15080. */
  15081. var LOCATION_PARAMS = [
  15082. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15083. ];
  15084. /**
  15085. * @public
  15086. */
  15087. var HV_NAMES = [
  15088. ['width', 'left', 'right'],
  15089. ['height', 'top', 'bottom']
  15090. ];
  15091. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15092. var x = 0;
  15093. var y = 0;
  15094. if (maxWidth == null) {
  15095. maxWidth = Infinity;
  15096. }
  15097. if (maxHeight == null) {
  15098. maxHeight = Infinity;
  15099. }
  15100. var currentLineMaxSize = 0;
  15101. group.eachChild(function (child, idx) {
  15102. var position = child.position;
  15103. var rect = child.getBoundingRect();
  15104. var nextChild = group.childAt(idx + 1);
  15105. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15106. var nextX;
  15107. var nextY;
  15108. if (orient === 'horizontal') {
  15109. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  15110. nextX = x + moveX;
  15111. // Wrap when width exceeds maxWidth or meet a `newline` group
  15112. // FIXME compare before adding gap?
  15113. if (nextX > maxWidth || child.newline) {
  15114. x = 0;
  15115. nextX = moveX;
  15116. y += currentLineMaxSize + gap;
  15117. currentLineMaxSize = rect.height;
  15118. }
  15119. else {
  15120. // FIXME: consider rect.y is not `0`?
  15121. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15122. }
  15123. }
  15124. else {
  15125. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  15126. nextY = y + moveY;
  15127. // Wrap when width exceeds maxHeight or meet a `newline` group
  15128. if (nextY > maxHeight || child.newline) {
  15129. x += currentLineMaxSize + gap;
  15130. y = 0;
  15131. nextY = moveY;
  15132. currentLineMaxSize = rect.width;
  15133. }
  15134. else {
  15135. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15136. }
  15137. }
  15138. if (child.newline) {
  15139. return;
  15140. }
  15141. position[0] = x;
  15142. position[1] = y;
  15143. orient === 'horizontal'
  15144. ? (x = nextX + gap)
  15145. : (y = nextY + gap);
  15146. });
  15147. }
  15148. /**
  15149. * VBox or HBox layouting
  15150. * @param {string} orient
  15151. * @param {module:zrender/container/Group} group
  15152. * @param {number} gap
  15153. * @param {number} [width=Infinity]
  15154. * @param {number} [height=Infinity]
  15155. */
  15156. /**
  15157. * VBox layouting
  15158. * @param {module:zrender/container/Group} group
  15159. * @param {number} gap
  15160. * @param {number} [width=Infinity]
  15161. * @param {number} [height=Infinity]
  15162. */
  15163. var vbox = curry(boxLayout, 'vertical');
  15164. /**
  15165. * HBox layouting
  15166. * @param {module:zrender/container/Group} group
  15167. * @param {number} gap
  15168. * @param {number} [width=Infinity]
  15169. * @param {number} [height=Infinity]
  15170. */
  15171. var hbox = curry(boxLayout, 'horizontal');
  15172. /**
  15173. * If x or x2 is not specified or 'center' 'left' 'right',
  15174. * the width would be as long as possible.
  15175. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15176. * the height would be as long as possible.
  15177. *
  15178. * @param {Object} positionInfo
  15179. * @param {number|string} [positionInfo.x]
  15180. * @param {number|string} [positionInfo.y]
  15181. * @param {number|string} [positionInfo.x2]
  15182. * @param {number|string} [positionInfo.y2]
  15183. * @param {Object} containerRect {width, height}
  15184. * @param {string|number} margin
  15185. * @return {Object} {width, height}
  15186. */
  15187. /**
  15188. * Parse position info.
  15189. *
  15190. * @param {Object} positionInfo
  15191. * @param {number|string} [positionInfo.left]
  15192. * @param {number|string} [positionInfo.top]
  15193. * @param {number|string} [positionInfo.right]
  15194. * @param {number|string} [positionInfo.bottom]
  15195. * @param {number|string} [positionInfo.width]
  15196. * @param {number|string} [positionInfo.height]
  15197. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  15198. * @param {Object} containerRect
  15199. * @param {string|number} [margin]
  15200. *
  15201. * @return {module:zrender/core/BoundingRect}
  15202. */
  15203. function getLayoutRect(
  15204. positionInfo, containerRect, margin
  15205. ) {
  15206. margin = normalizeCssArray$1(margin || 0);
  15207. var containerWidth = containerRect.width;
  15208. var containerHeight = containerRect.height;
  15209. var left = parsePercent$1(positionInfo.left, containerWidth);
  15210. var top = parsePercent$1(positionInfo.top, containerHeight);
  15211. var right = parsePercent$1(positionInfo.right, containerWidth);
  15212. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15213. var width = parsePercent$1(positionInfo.width, containerWidth);
  15214. var height = parsePercent$1(positionInfo.height, containerHeight);
  15215. var verticalMargin = margin[2] + margin[0];
  15216. var horizontalMargin = margin[1] + margin[3];
  15217. var aspect = positionInfo.aspect;
  15218. // If width is not specified, calculate width from left and right
  15219. if (isNaN(width)) {
  15220. width = containerWidth - right - horizontalMargin - left;
  15221. }
  15222. if (isNaN(height)) {
  15223. height = containerHeight - bottom - verticalMargin - top;
  15224. }
  15225. if (aspect != null) {
  15226. // If width and height are not given
  15227. // 1. Graph should not exceeds the container
  15228. // 2. Aspect must be keeped
  15229. // 3. Graph should take the space as more as possible
  15230. // FIXME
  15231. // Margin is not considered, because there is no case that both
  15232. // using margin and aspect so far.
  15233. if (isNaN(width) && isNaN(height)) {
  15234. if (aspect > containerWidth / containerHeight) {
  15235. width = containerWidth * 0.8;
  15236. }
  15237. else {
  15238. height = containerHeight * 0.8;
  15239. }
  15240. }
  15241. // Calculate width or height with given aspect
  15242. if (isNaN(width)) {
  15243. width = aspect * height;
  15244. }
  15245. if (isNaN(height)) {
  15246. height = width / aspect;
  15247. }
  15248. }
  15249. // If left is not specified, calculate left from right and width
  15250. if (isNaN(left)) {
  15251. left = containerWidth - right - width - horizontalMargin;
  15252. }
  15253. if (isNaN(top)) {
  15254. top = containerHeight - bottom - height - verticalMargin;
  15255. }
  15256. // Align left and top
  15257. switch (positionInfo.left || positionInfo.right) {
  15258. case 'center':
  15259. left = containerWidth / 2 - width / 2 - margin[3];
  15260. break;
  15261. case 'right':
  15262. left = containerWidth - width - horizontalMargin;
  15263. break;
  15264. }
  15265. switch (positionInfo.top || positionInfo.bottom) {
  15266. case 'middle':
  15267. case 'center':
  15268. top = containerHeight / 2 - height / 2 - margin[0];
  15269. break;
  15270. case 'bottom':
  15271. top = containerHeight - height - verticalMargin;
  15272. break;
  15273. }
  15274. // If something is wrong and left, top, width, height are calculated as NaN
  15275. left = left || 0;
  15276. top = top || 0;
  15277. if (isNaN(width)) {
  15278. // Width may be NaN if only one value is given except width
  15279. width = containerWidth - horizontalMargin - left - (right || 0);
  15280. }
  15281. if (isNaN(height)) {
  15282. // Height may be NaN if only one value is given except height
  15283. height = containerHeight - verticalMargin - top - (bottom || 0);
  15284. }
  15285. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15286. rect.margin = margin;
  15287. return rect;
  15288. }
  15289. /**
  15290. * Position a zr element in viewport
  15291. * Group position is specified by either
  15292. * {left, top}, {right, bottom}
  15293. * If all properties exists, right and bottom will be igonred.
  15294. *
  15295. * Logic:
  15296. * 1. Scale (against origin point in parent coord)
  15297. * 2. Rotate (against origin point in parent coord)
  15298. * 3. Traslate (with el.position by this method)
  15299. * So this method only fixes the last step 'Traslate', which does not affect
  15300. * scaling and rotating.
  15301. *
  15302. * If be called repeatly with the same input el, the same result will be gotten.
  15303. *
  15304. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  15305. * @param {Object} positionInfo
  15306. * @param {number|string} [positionInfo.left]
  15307. * @param {number|string} [positionInfo.top]
  15308. * @param {number|string} [positionInfo.right]
  15309. * @param {number|string} [positionInfo.bottom]
  15310. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  15311. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  15312. * @param {Object} containerRect
  15313. * @param {string|number} margin
  15314. * @param {Object} [opt]
  15315. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  15316. * @param {Array.<number>} [opt.boundingMode='all']
  15317. * Specify how to calculate boundingRect when locating.
  15318. * 'all': Position the boundingRect that is transformed and uioned
  15319. * both itself and its descendants.
  15320. * This mode simplies confine the elements in the bounding
  15321. * of their container (e.g., using 'right: 0').
  15322. * 'raw': Position the boundingRect that is not transformed and only itself.
  15323. * This mode is useful when you want a element can overflow its
  15324. * container. (Consider a rotated circle needs to be located in a corner.)
  15325. * In this mode positionInfo.width/height can only be number.
  15326. */
  15327. /**
  15328. * @param {Object} option Contains some of the properties in HV_NAMES.
  15329. * @param {number} hvIdx 0: horizontal; 1: vertical.
  15330. */
  15331. /**
  15332. * Consider Case:
  15333. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  15334. * through setOption or media query, using normal zrUtil.merge will cause
  15335. * {right: 0} does not take effect.
  15336. *
  15337. * @example
  15338. * ComponentModel.extend({
  15339. * init: function () {
  15340. * ...
  15341. * var inputPositionParams = layout.getLayoutParams(option);
  15342. * this.mergeOption(inputPositionParams);
  15343. * },
  15344. * mergeOption: function (newOption) {
  15345. * newOption && zrUtil.merge(thisOption, newOption, true);
  15346. * layout.mergeLayoutParam(thisOption, newOption);
  15347. * }
  15348. * });
  15349. *
  15350. * @param {Object} targetOption
  15351. * @param {Object} newOption
  15352. * @param {Object|string} [opt]
  15353. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  15354. * that width (or height) should not be calculated by left and right (or top and bottom).
  15355. */
  15356. function mergeLayoutParam(targetOption, newOption, opt) {
  15357. !isObject$1(opt) && (opt = {});
  15358. var ignoreSize = opt.ignoreSize;
  15359. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  15360. var hResult = merge$$1(HV_NAMES[0], 0);
  15361. var vResult = merge$$1(HV_NAMES[1], 1);
  15362. copy(HV_NAMES[0], targetOption, hResult);
  15363. copy(HV_NAMES[1], targetOption, vResult);
  15364. function merge$$1(names, hvIdx) {
  15365. var newParams = {};
  15366. var newValueCount = 0;
  15367. var merged = {};
  15368. var mergedValueCount = 0;
  15369. var enoughParamNumber = 2;
  15370. each$3(names, function (name) {
  15371. merged[name] = targetOption[name];
  15372. });
  15373. each$3(names, function (name) {
  15374. // Consider case: newOption.width is null, which is
  15375. // set by user for removing width setting.
  15376. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  15377. hasValue(newParams, name) && newValueCount++;
  15378. hasValue(merged, name) && mergedValueCount++;
  15379. });
  15380. if (ignoreSize[hvIdx]) {
  15381. // Only one of left/right is premitted to exist.
  15382. if (hasValue(newOption, names[1])) {
  15383. merged[names[2]] = null;
  15384. }
  15385. else if (hasValue(newOption, names[2])) {
  15386. merged[names[1]] = null;
  15387. }
  15388. return merged;
  15389. }
  15390. // Case: newOption: {width: ..., right: ...},
  15391. // or targetOption: {right: ...} and newOption: {width: ...},
  15392. // There is no conflict when merged only has params count
  15393. // little than enoughParamNumber.
  15394. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  15395. return merged;
  15396. }
  15397. // Case: newOption: {width: ..., right: ...},
  15398. // Than we can make sure user only want those two, and ignore
  15399. // all origin params in targetOption.
  15400. else if (newValueCount >= enoughParamNumber) {
  15401. return newParams;
  15402. }
  15403. else {
  15404. // Chose another param from targetOption by priority.
  15405. for (var i = 0; i < names.length; i++) {
  15406. var name = names[i];
  15407. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  15408. newParams[name] = targetOption[name];
  15409. break;
  15410. }
  15411. }
  15412. return newParams;
  15413. }
  15414. }
  15415. function hasProp(obj, name) {
  15416. return obj.hasOwnProperty(name);
  15417. }
  15418. function hasValue(obj, name) {
  15419. return obj[name] != null && obj[name] !== 'auto';
  15420. }
  15421. function copy(names, target, source) {
  15422. each$3(names, function (name) {
  15423. target[name] = source[name];
  15424. });
  15425. }
  15426. }
  15427. /**
  15428. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15429. * @param {Object} source
  15430. * @return {Object} Result contains those props.
  15431. */
  15432. function getLayoutParams(source) {
  15433. return copyLayoutParams({}, source);
  15434. }
  15435. /**
  15436. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  15437. * @param {Object} source
  15438. * @return {Object} Result contains those props.
  15439. */
  15440. function copyLayoutParams(target, source) {
  15441. source && target && each$3(LOCATION_PARAMS, function (name) {
  15442. source.hasOwnProperty(name) && (target[name] = source[name]);
  15443. });
  15444. return target;
  15445. }
  15446. var boxLayoutMixin = {
  15447. getBoxLayoutParams: function () {
  15448. return {
  15449. left: this.get('left'),
  15450. top: this.get('top'),
  15451. right: this.get('right'),
  15452. bottom: this.get('bottom'),
  15453. width: this.get('width'),
  15454. height: this.get('height')
  15455. };
  15456. }
  15457. };
  15458. /**
  15459. * Component model
  15460. *
  15461. * @module echarts/model/Component
  15462. */
  15463. var inner$1 = makeInner();
  15464. /**
  15465. * @alias module:echarts/model/Component
  15466. * @constructor
  15467. * @param {Object} option
  15468. * @param {module:echarts/model/Model} parentModel
  15469. * @param {module:echarts/model/Model} ecModel
  15470. */
  15471. var ComponentModel = Model.extend({
  15472. type: 'component',
  15473. /**
  15474. * @readOnly
  15475. * @type {string}
  15476. */
  15477. id: '',
  15478. /**
  15479. * Because simplified concept is probably better, series.name (or component.name)
  15480. * has been having too many resposibilities:
  15481. * (1) Generating id (which requires name in option should not be modified).
  15482. * (2) As an index to mapping series when merging option or calling API (a name
  15483. * can refer to more then one components, which is convinient is some case).
  15484. * (3) Display.
  15485. * @readOnly
  15486. */
  15487. name: '',
  15488. /**
  15489. * @readOnly
  15490. * @type {string}
  15491. */
  15492. mainType: '',
  15493. /**
  15494. * @readOnly
  15495. * @type {string}
  15496. */
  15497. subType: '',
  15498. /**
  15499. * @readOnly
  15500. * @type {number}
  15501. */
  15502. componentIndex: 0,
  15503. /**
  15504. * @type {Object}
  15505. * @protected
  15506. */
  15507. defaultOption: null,
  15508. /**
  15509. * @type {module:echarts/model/Global}
  15510. * @readOnly
  15511. */
  15512. ecModel: null,
  15513. /**
  15514. * key: componentType
  15515. * value: Component model list, can not be null.
  15516. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  15517. * @readOnly
  15518. */
  15519. dependentModels: [],
  15520. /**
  15521. * @type {string}
  15522. * @readOnly
  15523. */
  15524. uid: null,
  15525. /**
  15526. * Support merge layout params.
  15527. * Only support 'box' now (left/right/top/bottom/width/height).
  15528. * @type {string|Object} Object can be {ignoreSize: true}
  15529. * @readOnly
  15530. */
  15531. layoutMode: null,
  15532. $constructor: function (option, parentModel, ecModel, extraOpt) {
  15533. Model.call(this, option, parentModel, ecModel, extraOpt);
  15534. this.uid = getUID('ec_cpt_model');
  15535. },
  15536. init: function (option, parentModel, ecModel, extraOpt) {
  15537. this.mergeDefaultAndTheme(option, ecModel);
  15538. },
  15539. mergeDefaultAndTheme: function (option, ecModel) {
  15540. var layoutMode = this.layoutMode;
  15541. var inputPositionParams = layoutMode
  15542. ? getLayoutParams(option) : {};
  15543. var themeModel = ecModel.getTheme();
  15544. merge(option, themeModel.get(this.mainType));
  15545. merge(option, this.getDefaultOption());
  15546. if (layoutMode) {
  15547. mergeLayoutParam(option, inputPositionParams, layoutMode);
  15548. }
  15549. },
  15550. mergeOption: function (option, extraOpt) {
  15551. merge(this.option, option, true);
  15552. var layoutMode = this.layoutMode;
  15553. if (layoutMode) {
  15554. mergeLayoutParam(this.option, option, layoutMode);
  15555. }
  15556. },
  15557. // Hooker after init or mergeOption
  15558. optionUpdated: function (newCptOption, isInit) {},
  15559. getDefaultOption: function () {
  15560. var fields = inner$1(this);
  15561. if (!fields.defaultOption) {
  15562. var optList = [];
  15563. var Class = this.constructor;
  15564. while (Class) {
  15565. var opt = Class.prototype.defaultOption;
  15566. opt && optList.push(opt);
  15567. Class = Class.superClass;
  15568. }
  15569. var defaultOption = {};
  15570. for (var i = optList.length - 1; i >= 0; i--) {
  15571. defaultOption = merge(defaultOption, optList[i], true);
  15572. }
  15573. fields.defaultOption = defaultOption;
  15574. }
  15575. return fields.defaultOption;
  15576. },
  15577. getReferringComponents: function (mainType) {
  15578. return this.ecModel.queryComponents({
  15579. mainType: mainType,
  15580. index: this.get(mainType + 'Index', true),
  15581. id: this.get(mainType + 'Id', true)
  15582. });
  15583. }
  15584. });
  15585. // Reset ComponentModel.extend, add preConstruct.
  15586. // clazzUtil.enableClassExtend(
  15587. // ComponentModel,
  15588. // function (option, parentModel, ecModel, extraOpt) {
  15589. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  15590. // zrUtil.extend(this, extraOpt);
  15591. // this.uid = componentUtil.getUID('componentModel');
  15592. // // this.setReadOnly([
  15593. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  15594. // // 'dependentModels', 'componentIndex'
  15595. // // ]);
  15596. // }
  15597. // );
  15598. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  15599. enableClassManagement(
  15600. ComponentModel, {registerWhenExtend: true}
  15601. );
  15602. enableSubTypeDefaulter(ComponentModel);
  15603. // Add capability of ComponentModel.topologicalTravel.
  15604. enableTopologicalTravel(ComponentModel, getDependencies);
  15605. function getDependencies(componentType) {
  15606. var deps = [];
  15607. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  15608. deps = deps.concat(Clazz.prototype.dependencies || []);
  15609. });
  15610. // Ensure main type.
  15611. deps = map(deps, function (type) {
  15612. return parseClassType$1(type).main;
  15613. });
  15614. // Hack dataset for convenience.
  15615. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  15616. deps.unshift('dataset');
  15617. }
  15618. return deps;
  15619. }
  15620. mixin(ComponentModel, boxLayoutMixin);
  15621. var platform = '';
  15622. // Navigator not exists in node
  15623. if (typeof navigator !== 'undefined') {
  15624. platform = navigator.platform || '';
  15625. }
  15626. var globalDefault = {
  15627. // 全图默认背景
  15628. // backgroundColor: 'rgba(0,0,0,0)',
  15629. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  15630. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  15631. // 浅色
  15632. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  15633. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  15634. // 深色
  15635. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  15636. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  15637. // 默认需要 Grid 配置项
  15638. // grid: {},
  15639. // 主题,主题
  15640. textStyle: {
  15641. // color: '#000',
  15642. // decoration: 'none',
  15643. // PENDING
  15644. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  15645. // fontFamily: 'Arial, Verdana, sans-serif',
  15646. fontSize: 12,
  15647. fontStyle: 'normal',
  15648. fontWeight: 'normal'
  15649. },
  15650. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  15651. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  15652. // Default is source-over
  15653. blendMode: null,
  15654. animation: 'auto',
  15655. animationDuration: 1000,
  15656. animationDurationUpdate: 300,
  15657. animationEasing: 'exponentialOut',
  15658. animationEasingUpdate: 'cubicOut',
  15659. animationThreshold: 2000,
  15660. // Configuration for progressive/incremental rendering
  15661. progressiveThreshold: 3000,
  15662. progressive: 400,
  15663. // Threshold of if use single hover layer to optimize.
  15664. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  15665. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  15666. // which is unexpected.
  15667. // see example <echarts/test/heatmap-large.html>.
  15668. hoverLayerThreshold: 3000,
  15669. // See: module:echarts/scale/Time
  15670. useUTC: false
  15671. };
  15672. var inner$2 = makeInner();
  15673. function getNearestColorPalette(colors, requestColorNum) {
  15674. var paletteNum = colors.length;
  15675. // TODO colors must be in order
  15676. for (var i = 0; i < paletteNum; i++) {
  15677. if (colors[i].length > requestColorNum) {
  15678. return colors[i];
  15679. }
  15680. }
  15681. return colors[paletteNum - 1];
  15682. }
  15683. var colorPaletteMixin = {
  15684. clearColorPalette: function () {
  15685. inner$2(this).colorIdx = 0;
  15686. inner$2(this).colorNameMap = {};
  15687. },
  15688. getColorFromPalette: function (name, scope, requestColorNum) {
  15689. scope = scope || this;
  15690. var scopeFields = inner$2(scope);
  15691. var colorIdx = scopeFields.colorIdx || 0;
  15692. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  15693. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  15694. if (colorNameMap.hasOwnProperty(name)) {
  15695. return colorNameMap[name];
  15696. }
  15697. var defaultColorPalette = normalizeToArray(this.get('color', true));
  15698. var layeredColorPalette = this.get('colorLayer', true);
  15699. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  15700. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  15701. // In case can't find in layered color palette.
  15702. colorPalette = colorPalette || defaultColorPalette;
  15703. if (!colorPalette || !colorPalette.length) {
  15704. return;
  15705. }
  15706. var color = colorPalette[colorIdx];
  15707. if (name) {
  15708. colorNameMap[name] = color;
  15709. }
  15710. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  15711. return color;
  15712. }
  15713. };
  15714. /**
  15715. * Helper for model references.
  15716. * There are many manners to refer axis/coordSys.
  15717. */
  15718. // TODO
  15719. // merge relevant logic to this file?
  15720. // check: "modelHelper" of tooltip and "BrushTargetManager".
  15721. /**
  15722. * @return {Object} For example:
  15723. * {
  15724. * coordSysName: 'cartesian2d',
  15725. * coordSysDims: ['x', 'y', ...],
  15726. * axisMap: HashMap({
  15727. * x: xAxisModel,
  15728. * y: yAxisModel
  15729. * }),
  15730. * categoryAxisMap: HashMap({
  15731. * x: xAxisModel,
  15732. * y: undefined
  15733. * }),
  15734. * // It also indicate that whether there is category axis.
  15735. * firstCategoryDimIndex: 1,
  15736. * // To replace user specified encode.
  15737. * }
  15738. */
  15739. function getCoordSysDefineBySeries(seriesModel) {
  15740. var coordSysName = seriesModel.get('coordinateSystem');
  15741. var result = {
  15742. coordSysName: coordSysName,
  15743. coordSysDims: [],
  15744. axisMap: createHashMap(),
  15745. categoryAxisMap: createHashMap()
  15746. };
  15747. var fetch = fetchers[coordSysName];
  15748. if (fetch) {
  15749. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  15750. return result;
  15751. }
  15752. }
  15753. var fetchers = {
  15754. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  15755. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  15756. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  15757. if (__DEV__) {
  15758. if (!xAxisModel) {
  15759. throw new Error('xAxis "' + retrieve(
  15760. seriesModel.get('xAxisIndex'),
  15761. seriesModel.get('xAxisId'),
  15762. 0
  15763. ) + '" not found');
  15764. }
  15765. if (!yAxisModel) {
  15766. throw new Error('yAxis "' + retrieve(
  15767. seriesModel.get('xAxisIndex'),
  15768. seriesModel.get('yAxisId'),
  15769. 0
  15770. ) + '" not found');
  15771. }
  15772. }
  15773. result.coordSysDims = ['x', 'y'];
  15774. axisMap.set('x', xAxisModel);
  15775. axisMap.set('y', yAxisModel);
  15776. if (isCategory(xAxisModel)) {
  15777. categoryAxisMap.set('x', xAxisModel);
  15778. result.firstCategoryDimIndex = 0;
  15779. }
  15780. if (isCategory(yAxisModel)) {
  15781. categoryAxisMap.set('y', yAxisModel);
  15782. result.firstCategoryDimIndex = 1;
  15783. }
  15784. },
  15785. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  15786. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  15787. if (__DEV__) {
  15788. if (!singleAxisModel) {
  15789. throw new Error('singleAxis should be specified.');
  15790. }
  15791. }
  15792. result.coordSysDims = ['single'];
  15793. axisMap.set('single', singleAxisModel);
  15794. if (isCategory(singleAxisModel)) {
  15795. categoryAxisMap.set('single', singleAxisModel);
  15796. result.firstCategoryDimIndex = 0;
  15797. }
  15798. },
  15799. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  15800. var polarModel = seriesModel.getReferringComponents('polar')[0];
  15801. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  15802. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  15803. if (__DEV__) {
  15804. if (!angleAxisModel) {
  15805. throw new Error('angleAxis option not found');
  15806. }
  15807. if (!radiusAxisModel) {
  15808. throw new Error('radiusAxis option not found');
  15809. }
  15810. }
  15811. result.coordSysDims = ['radius', 'angle'];
  15812. axisMap.set('radius', radiusAxisModel);
  15813. axisMap.set('angle', angleAxisModel);
  15814. if (isCategory(radiusAxisModel)) {
  15815. categoryAxisMap.set('radius', radiusAxisModel);
  15816. result.firstCategoryDimIndex = 0;
  15817. }
  15818. if (isCategory(angleAxisModel)) {
  15819. categoryAxisMap.set('angle', angleAxisModel);
  15820. result.firstCategoryDimIndex = 1;
  15821. }
  15822. },
  15823. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  15824. result.coordSysDims = ['lng', 'lat'];
  15825. },
  15826. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  15827. var ecModel = seriesModel.ecModel;
  15828. var parallelModel = ecModel.getComponent(
  15829. 'parallel', seriesModel.get('parallelIndex')
  15830. );
  15831. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  15832. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  15833. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  15834. var axisDim = coordSysDims[index];
  15835. axisMap.set(axisDim, axisModel);
  15836. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  15837. categoryAxisMap.set(axisDim, axisModel);
  15838. result.firstCategoryDimIndex = index;
  15839. }
  15840. });
  15841. }
  15842. };
  15843. function isCategory(axisModel) {
  15844. return axisModel.get('type') === 'category';
  15845. }
  15846. // Avoid typo.
  15847. var SOURCE_FORMAT_ORIGINAL = 'original';
  15848. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  15849. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  15850. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  15851. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  15852. // ??? CHANGE A NAME
  15853. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  15854. var SERIES_LAYOUT_BY_COLUMN = 'column';
  15855. var SERIES_LAYOUT_BY_ROW = 'row';
  15856. /**
  15857. * [sourceFormat]
  15858. *
  15859. * + "original":
  15860. * This format is only used in series.data, where
  15861. * itemStyle can be specified in data item.
  15862. *
  15863. * + "arrayRows":
  15864. * [
  15865. * ['product', 'score', 'amount'],
  15866. * ['Matcha Latte', 89.3, 95.8],
  15867. * ['Milk Tea', 92.1, 89.4],
  15868. * ['Cheese Cocoa', 94.4, 91.2],
  15869. * ['Walnut Brownie', 85.4, 76.9]
  15870. * ]
  15871. *
  15872. * + "objectRows":
  15873. * [
  15874. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  15875. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  15876. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  15877. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  15878. * ]
  15879. *
  15880. * + "keyedColumns":
  15881. * {
  15882. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  15883. * 'count': [823, 235, 1042, 988],
  15884. * 'score': [95.8, 81.4, 91.2, 76.9]
  15885. * }
  15886. *
  15887. * + "typedArray"
  15888. *
  15889. * + "unknown"
  15890. */
  15891. /**
  15892. * @constructor
  15893. * @param {Object} fields
  15894. * @param {string} fields.sourceFormat
  15895. * @param {Array|Object} fields.fromDataset
  15896. * @param {Array|Object} [fields.data]
  15897. * @param {string} [seriesLayoutBy='column']
  15898. * @param {Array.<Object|string>} [dimensionsDefine]
  15899. * @param {Objet|HashMap} [encodeDefine]
  15900. * @param {number} [startIndex=0]
  15901. * @param {number} [dimensionsDetectCount]
  15902. */
  15903. function Source(fields) {
  15904. /**
  15905. * @type {boolean}
  15906. */
  15907. this.fromDataset = fields.fromDataset;
  15908. /**
  15909. * Not null/undefined.
  15910. * @type {Array|Object}
  15911. */
  15912. this.data = fields.data || (
  15913. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  15914. );
  15915. /**
  15916. * See also "detectSourceFormat".
  15917. * Not null/undefined.
  15918. * @type {string}
  15919. */
  15920. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  15921. /**
  15922. * 'row' or 'column'
  15923. * Not null/undefined.
  15924. * @type {string} seriesLayoutBy
  15925. */
  15926. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  15927. /**
  15928. * dimensions definition in option.
  15929. * can be null/undefined.
  15930. * @type {Array.<Object|string>}
  15931. */
  15932. this.dimensionsDefine = fields.dimensionsDefine;
  15933. /**
  15934. * encode definition in option.
  15935. * can be null/undefined.
  15936. * @type {Objet|HashMap}
  15937. */
  15938. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  15939. /**
  15940. * Not null/undefined, uint.
  15941. * @type {number}
  15942. */
  15943. this.startIndex = fields.startIndex || 0;
  15944. /**
  15945. * Can be null/undefined (when unknown), uint.
  15946. * @type {number}
  15947. */
  15948. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  15949. }
  15950. /**
  15951. * Wrap original series data for some compatibility cases.
  15952. */
  15953. Source.seriesDataToSource = function (data) {
  15954. return new Source({
  15955. data: data,
  15956. sourceFormat: isTypedArray(data)
  15957. ? SOURCE_FORMAT_TYPED_ARRAY
  15958. : SOURCE_FORMAT_ORIGINAL,
  15959. fromDataset: false
  15960. });
  15961. };
  15962. enableClassCheck(Source);
  15963. var inner$3 = makeInner();
  15964. /**
  15965. * @see {module:echarts/data/Source}
  15966. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  15967. * @return {string} sourceFormat
  15968. */
  15969. function detectSourceFormat(datasetModel) {
  15970. var data = datasetModel.option.source;
  15971. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  15972. if (isTypedArray(data)) {
  15973. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  15974. }
  15975. else if (isArray(data)) {
  15976. // FIXME Whether tolerate null in top level array?
  15977. for (var i = 0, len = data.length; i < len; i++) {
  15978. var item = data[i];
  15979. if (item == null) {
  15980. continue;
  15981. }
  15982. else if (isArray(item)) {
  15983. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  15984. break;
  15985. }
  15986. else if (isObject$1(item)) {
  15987. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  15988. break;
  15989. }
  15990. }
  15991. }
  15992. else if (isObject$1(data)) {
  15993. for (var key in data) {
  15994. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  15995. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  15996. break;
  15997. }
  15998. }
  15999. }
  16000. else if (data != null) {
  16001. throw new Error('Invalid data');
  16002. }
  16003. inner$3(datasetModel).sourceFormat = sourceFormat;
  16004. }
  16005. /**
  16006. * [Scenarios]:
  16007. * (1) Provide source data directly:
  16008. * series: {
  16009. * encode: {...},
  16010. * dimensions: [...]
  16011. * seriesLayoutBy: 'row',
  16012. * data: [[...]]
  16013. * }
  16014. * (2) Refer to datasetModel.
  16015. * series: [{
  16016. * encode: {...}
  16017. * // Ignore datasetIndex means `datasetIndex: 0`
  16018. * // and the dimensions defination in dataset is used
  16019. * }, {
  16020. * encode: {...},
  16021. * seriesLayoutBy: 'column',
  16022. * datasetIndex: 1
  16023. * }]
  16024. *
  16025. * Get data from series itself or datset.
  16026. * @return {module:echarts/data/Source} source
  16027. */
  16028. function getSource(seriesModel) {
  16029. return inner$3(seriesModel).source;
  16030. }
  16031. /**
  16032. * MUST be called before mergeOption of all series.
  16033. * @param {module:echarts/model/Global} ecModel
  16034. */
  16035. function resetSourceDefaulter(ecModel) {
  16036. // `datasetMap` is used to make default encode.
  16037. inner$3(ecModel).datasetMap = createHashMap();
  16038. }
  16039. /**
  16040. * [Caution]:
  16041. * MUST be called after series option merged and
  16042. * before "series.getInitailData()" called.
  16043. *
  16044. * [The rule of making default encode]:
  16045. * Category axis (if exists) alway map to the first dimension.
  16046. * Each other axis occupies a subsequent dimension.
  16047. *
  16048. * [Why make default encode]:
  16049. * Simplify the typing of encode in option, avoiding the case like that:
  16050. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  16051. * where the "y" have to be manually typed as "1, 2, 3, ...".
  16052. *
  16053. * @param {module:echarts/model/Series} seriesModel
  16054. */
  16055. function prepareSource(seriesModel) {
  16056. var seriesOption = seriesModel.option;
  16057. var data = seriesOption.data;
  16058. var sourceFormat = isTypedArray(data)
  16059. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  16060. var fromDataset = false;
  16061. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  16062. var sourceHeader = seriesOption.sourceHeader;
  16063. var dimensionsDefine = seriesOption.dimensions;
  16064. var datasetModel = getDatasetModel(seriesModel);
  16065. if (datasetModel) {
  16066. var datasetOption = datasetModel.option;
  16067. data = datasetOption.source;
  16068. sourceFormat = inner$3(datasetModel).sourceFormat;
  16069. fromDataset = true;
  16070. // These settings from series has higher priority.
  16071. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  16072. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  16073. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  16074. }
  16075. var completeResult = completeBySourceData(
  16076. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  16077. );
  16078. // Note: dataset option does not have `encode`.
  16079. var encodeDefine = seriesOption.encode;
  16080. if (!encodeDefine && datasetModel) {
  16081. encodeDefine = makeDefaultEncode(
  16082. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16083. );
  16084. }
  16085. inner$3(seriesModel).source = new Source({
  16086. data: data,
  16087. fromDataset: fromDataset,
  16088. seriesLayoutBy: seriesLayoutBy,
  16089. sourceFormat: sourceFormat,
  16090. dimensionsDefine: completeResult.dimensionsDefine,
  16091. startIndex: completeResult.startIndex,
  16092. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  16093. encodeDefine: encodeDefine
  16094. });
  16095. }
  16096. // return {startIndex, dimensionsDefine, dimensionsCount}
  16097. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  16098. if (!data) {
  16099. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  16100. }
  16101. var dimensionsDetectCount;
  16102. var startIndex;
  16103. var findPotentialName;
  16104. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16105. // Rule: Most of the first line are string: it is header.
  16106. // Caution: consider a line with 5 string and 1 number,
  16107. // it still can not be sure it is a head, because the
  16108. // 5 string may be 5 values of category columns.
  16109. if (sourceHeader === 'auto' || sourceHeader == null) {
  16110. arrayRowsTravelFirst(function (val) {
  16111. // '-' is regarded as null/undefined.
  16112. if (val != null && val !== '-') {
  16113. if (isString(val)) {
  16114. startIndex == null && (startIndex = 1);
  16115. }
  16116. else {
  16117. startIndex = 0;
  16118. }
  16119. }
  16120. // 10 is an experience number, avoid long loop.
  16121. }, seriesLayoutBy, data, 10);
  16122. }
  16123. else {
  16124. startIndex = sourceHeader ? 1 : 0;
  16125. }
  16126. if (!dimensionsDefine && startIndex === 1) {
  16127. dimensionsDefine = [];
  16128. arrayRowsTravelFirst(function (val, index) {
  16129. dimensionsDefine[index] = val != null ? val : '';
  16130. }, seriesLayoutBy, data);
  16131. }
  16132. dimensionsDetectCount = dimensionsDefine
  16133. ? dimensionsDefine.length
  16134. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  16135. ? data.length
  16136. : data[0]
  16137. ? data[0].length
  16138. : null;
  16139. }
  16140. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16141. if (!dimensionsDefine) {
  16142. dimensionsDefine = objectRowsCollectDimensions(data);
  16143. findPotentialName = true;
  16144. }
  16145. }
  16146. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16147. if (!dimensionsDefine) {
  16148. dimensionsDefine = [];
  16149. findPotentialName = true;
  16150. each$1(data, function (colArr, key) {
  16151. dimensionsDefine.push(key);
  16152. });
  16153. }
  16154. }
  16155. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16156. var value0 = getDataItemValue(data[0]);
  16157. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  16158. }
  16159. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  16160. if (__DEV__) {
  16161. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  16162. }
  16163. }
  16164. var potentialNameDimIndex;
  16165. if (findPotentialName) {
  16166. each$1(dimensionsDefine, function (dim, idx) {
  16167. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  16168. potentialNameDimIndex = idx;
  16169. }
  16170. });
  16171. }
  16172. return {
  16173. startIndex: startIndex,
  16174. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  16175. dimensionsDetectCount: dimensionsDetectCount,
  16176. potentialNameDimIndex: potentialNameDimIndex
  16177. // TODO: potentialIdDimIdx
  16178. };
  16179. }
  16180. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  16181. // which is reasonable. But dimension name is duplicated.
  16182. // Returns undefined or an array contains only object without null/undefiend or string.
  16183. function normalizeDimensionsDefine(dimensionsDefine) {
  16184. if (!dimensionsDefine) {
  16185. // The meaning of null/undefined is different from empty array.
  16186. return;
  16187. }
  16188. var nameMap = createHashMap();
  16189. return map(dimensionsDefine, function (item, index) {
  16190. item = extend({}, isObject$1(item) ? item : {name: item});
  16191. // User can set null in dimensions.
  16192. // We dont auto specify name, othewise a given name may
  16193. // cause it be refered unexpectedly.
  16194. if (item.name == null) {
  16195. return item;
  16196. }
  16197. // Also consider number form like 2012.
  16198. item.name += '';
  16199. // User may also specify displayName.
  16200. // displayName will always exists except user not
  16201. // specified or dim name is not specified or detected.
  16202. // (A auto generated dim name will not be used as
  16203. // displayName).
  16204. if (item.displayName == null) {
  16205. item.displayName = item.name;
  16206. }
  16207. var exist = nameMap.get(item.name);
  16208. if (!exist) {
  16209. nameMap.set(item.name, {count: 1});
  16210. }
  16211. else {
  16212. item.name += '-' + exist.count++;
  16213. }
  16214. return item;
  16215. });
  16216. }
  16217. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  16218. maxLoop == null && (maxLoop = Infinity);
  16219. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16220. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16221. cb(data[i] ? data[i][0] : null, i);
  16222. }
  16223. }
  16224. else {
  16225. var value0 = data[0] || [];
  16226. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  16227. cb(value0[i], i);
  16228. }
  16229. }
  16230. }
  16231. function objectRowsCollectDimensions(data) {
  16232. var firstIndex = 0;
  16233. var obj;
  16234. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  16235. if (obj) {
  16236. var dimensions = [];
  16237. each$1(obj, function (value, key) {
  16238. dimensions.push(key);
  16239. });
  16240. return dimensions;
  16241. }
  16242. }
  16243. // ??? TODO merge to completedimensions, where also has
  16244. // default encode making logic. And the default rule
  16245. // should depends on series? consider 'map'.
  16246. function makeDefaultEncode(
  16247. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  16248. ) {
  16249. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  16250. var encode = {};
  16251. // var encodeTooltip = [];
  16252. // var encodeLabel = [];
  16253. var encodeItemName = [];
  16254. var encodeSeriesName = [];
  16255. var seriesType = seriesModel.subType;
  16256. // ??? TODO refactor: provide by series itself.
  16257. // Consider the case: 'map' series is based on geo coordSys,
  16258. // 'graph', 'heatmap' can be based on cartesian. But can not
  16259. // give default rule simply here.
  16260. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  16261. var cSeriesMap = createHashMap([
  16262. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  16263. ]);
  16264. // Usually in this case series will use the first data
  16265. // dimension as the "value" dimension, or other default
  16266. // processes respectively.
  16267. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  16268. var ecModel = seriesModel.ecModel;
  16269. var datasetMap = inner$3(ecModel).datasetMap;
  16270. var key = datasetModel.uid + '_' + seriesLayoutBy;
  16271. var datasetRecord = datasetMap.get(key)
  16272. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  16273. // TODO
  16274. // Auto detect first time axis and do arrangement.
  16275. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  16276. // In value way.
  16277. if (coordSysDefine.firstCategoryDimIndex == null) {
  16278. var dataDim = datasetRecord.valueWayDim++;
  16279. encode[coordDim] = dataDim;
  16280. // ??? TODO give a better default series name rule?
  16281. // especially when encode x y specified.
  16282. // consider: when mutiple series share one dimension
  16283. // category axis, series name should better use
  16284. // the other dimsion name. On the other hand, use
  16285. // both dimensions name.
  16286. encodeSeriesName.push(dataDim);
  16287. // encodeTooltip.push(dataDim);
  16288. // encodeLabel.push(dataDim);
  16289. }
  16290. // In category way, category axis.
  16291. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  16292. encode[coordDim] = 0;
  16293. encodeItemName.push(0);
  16294. }
  16295. // In category way, non-category axis.
  16296. else {
  16297. var dataDim = datasetRecord.categoryWayDim++;
  16298. encode[coordDim] = dataDim;
  16299. // encodeTooltip.push(dataDim);
  16300. // encodeLabel.push(dataDim);
  16301. encodeSeriesName.push(dataDim);
  16302. }
  16303. });
  16304. }
  16305. // Do not make a complex rule! Hard to code maintain and not necessary.
  16306. // ??? TODO refactor: provide by series itself.
  16307. // [{name: ..., value: ...}, ...] like:
  16308. else if (nSeriesMap.get(seriesType) != null) {
  16309. // Find the first not ordinal. (5 is an experience value)
  16310. var firstNotOrdinal;
  16311. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  16312. if (!doGuessOrdinal(
  16313. data, sourceFormat, seriesLayoutBy,
  16314. completeResult.dimensionsDefine, completeResult.startIndex, i
  16315. )) {
  16316. firstNotOrdinal = i;
  16317. }
  16318. }
  16319. if (firstNotOrdinal != null) {
  16320. encode.value = firstNotOrdinal;
  16321. var nameDimIndex = completeResult.potentialNameDimIndex
  16322. || Math.max(firstNotOrdinal - 1, 0);
  16323. // By default, label use itemName in charts.
  16324. // So we dont set encodeLabel here.
  16325. encodeSeriesName.push(nameDimIndex);
  16326. encodeItemName.push(nameDimIndex);
  16327. // encodeTooltip.push(firstNotOrdinal);
  16328. }
  16329. }
  16330. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  16331. // encodeLabel.length && (encode.label = encodeLabel);
  16332. encodeItemName.length && (encode.itemName = encodeItemName);
  16333. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16334. return encode;
  16335. }
  16336. /**
  16337. * If return null/undefined, indicate that should not use datasetModel.
  16338. */
  16339. function getDatasetModel(seriesModel) {
  16340. var option = seriesModel.option;
  16341. // Caution: consider the scenario:
  16342. // A dataset is declared and a series is not expected to use the dataset,
  16343. // and at the beginning `setOption({series: { noData })` (just prepare other
  16344. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16345. // the user should set an empty array to avoid that dataset is used by default.
  16346. var thisData = option.data;
  16347. if (!thisData) {
  16348. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  16349. }
  16350. }
  16351. /**
  16352. * The rule should not be complex, otherwise user might not
  16353. * be able to known where the data is wrong.
  16354. * The code is ugly, but how to make it neat?
  16355. *
  16356. * @param {module:echars/data/Source} source
  16357. * @param {number} dimIndex
  16358. * @return {boolean} Whether ordinal.
  16359. */
  16360. function guessOrdinal(source, dimIndex) {
  16361. return doGuessOrdinal(
  16362. source.data,
  16363. source.sourceFormat,
  16364. source.seriesLayoutBy,
  16365. source.dimensionsDefine,
  16366. source.startIndex,
  16367. dimIndex
  16368. );
  16369. }
  16370. // dimIndex may be overflow source data.
  16371. function doGuessOrdinal(
  16372. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  16373. ) {
  16374. var result;
  16375. // Experience value.
  16376. var maxLoop = 5;
  16377. if (isTypedArray(data)) {
  16378. return false;
  16379. }
  16380. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16381. // always exists in source.
  16382. var dimName;
  16383. if (dimensionsDefine) {
  16384. dimName = dimensionsDefine[dimIndex];
  16385. dimName = isObject$1(dimName) ? dimName.name : dimName;
  16386. }
  16387. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16388. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16389. var sample = data[dimIndex];
  16390. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16391. if ((result = detectValue(sample[startIndex + i])) != null) {
  16392. return result;
  16393. }
  16394. }
  16395. }
  16396. else {
  16397. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16398. var row = data[startIndex + i];
  16399. if (row && (result = detectValue(row[dimIndex])) != null) {
  16400. return result;
  16401. }
  16402. }
  16403. }
  16404. }
  16405. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16406. if (!dimName) {
  16407. return;
  16408. }
  16409. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16410. var item = data[i];
  16411. if (item && (result = detectValue(item[dimName])) != null) {
  16412. return result;
  16413. }
  16414. }
  16415. }
  16416. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16417. if (!dimName) {
  16418. return;
  16419. }
  16420. var sample = data[dimName];
  16421. if (!sample || isTypedArray(sample)) {
  16422. return false;
  16423. }
  16424. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16425. if ((result = detectValue(sample[i])) != null) {
  16426. return result;
  16427. }
  16428. }
  16429. }
  16430. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16431. for (var i = 0; i < data.length && i < maxLoop; i++) {
  16432. var item = data[i];
  16433. var val = getDataItemValue(item);
  16434. if (!isArray(val)) {
  16435. return false;
  16436. }
  16437. if ((result = detectValue(val[dimIndex])) != null) {
  16438. return result;
  16439. }
  16440. }
  16441. }
  16442. function detectValue(val) {
  16443. // Consider usage convenience, '1', '2' will be treated as "number".
  16444. // `isFinit('')` get `true`.
  16445. if (val != null && isFinite(val) && val !== '') {
  16446. return false;
  16447. }
  16448. else if (isString(val) && val !== '-') {
  16449. return true;
  16450. }
  16451. }
  16452. return false;
  16453. }
  16454. /**
  16455. * ECharts global model
  16456. *
  16457. * @module {echarts/model/Global}
  16458. */
  16459. /**
  16460. * Caution: If the mechanism should be changed some day, these cases
  16461. * should be considered:
  16462. *
  16463. * (1) In `merge option` mode, if using the same option to call `setOption`
  16464. * many times, the result should be the same (try our best to ensure that).
  16465. * (2) In `merge option` mode, if a component has no id/name specified, it
  16466. * will be merged by index, and the result sequence of the components is
  16467. * consistent to the original sequence.
  16468. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  16469. * `mergeOption` in module:echarts/model/OptionManager.
  16470. */
  16471. var OPTION_INNER_KEY = '\0_ec_inner';
  16472. /**
  16473. * @alias module:echarts/model/Global
  16474. *
  16475. * @param {Object} option
  16476. * @param {module:echarts/model/Model} parentModel
  16477. * @param {Object} theme
  16478. */
  16479. var GlobalModel = Model.extend({
  16480. constructor: GlobalModel,
  16481. init: function (option, parentModel, theme, optionManager) {
  16482. theme = theme || {};
  16483. this.option = null; // Mark as not initialized.
  16484. /**
  16485. * @type {module:echarts/model/Model}
  16486. * @private
  16487. */
  16488. this._theme = new Model(theme);
  16489. /**
  16490. * @type {module:echarts/model/OptionManager}
  16491. */
  16492. this._optionManager = optionManager;
  16493. },
  16494. setOption: function (option, optionPreprocessorFuncs) {
  16495. assert$1(
  16496. !(OPTION_INNER_KEY in option),
  16497. 'please use chart.getOption()'
  16498. );
  16499. this._optionManager.setOption(option, optionPreprocessorFuncs);
  16500. this.resetOption(null);
  16501. },
  16502. /**
  16503. * @param {string} type null/undefined: reset all.
  16504. * 'recreate': force recreate all.
  16505. * 'timeline': only reset timeline option
  16506. * 'media': only reset media query option
  16507. * @return {boolean} Whether option changed.
  16508. */
  16509. resetOption: function (type) {
  16510. var optionChanged = false;
  16511. var optionManager = this._optionManager;
  16512. if (!type || type === 'recreate') {
  16513. var baseOption = optionManager.mountOption(type === 'recreate');
  16514. if (!this.option || type === 'recreate') {
  16515. initBase.call(this, baseOption);
  16516. }
  16517. else {
  16518. this.restoreData();
  16519. this.mergeOption(baseOption);
  16520. }
  16521. optionChanged = true;
  16522. }
  16523. if (type === 'timeline' || type === 'media') {
  16524. this.restoreData();
  16525. }
  16526. if (!type || type === 'recreate' || type === 'timeline') {
  16527. var timelineOption = optionManager.getTimelineOption(this);
  16528. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  16529. }
  16530. if (!type || type === 'recreate' || type === 'media') {
  16531. var mediaOptions = optionManager.getMediaOption(this, this._api);
  16532. if (mediaOptions.length) {
  16533. each$1(mediaOptions, function (mediaOption) {
  16534. this.mergeOption(mediaOption, optionChanged = true);
  16535. }, this);
  16536. }
  16537. }
  16538. return optionChanged;
  16539. },
  16540. /**
  16541. * @protected
  16542. */
  16543. mergeOption: function (newOption) {
  16544. var option = this.option;
  16545. var componentsMap = this._componentsMap;
  16546. var newCptTypes = [];
  16547. resetSourceDefaulter(this);
  16548. // If no component class, merge directly.
  16549. // For example: color, animaiton options, etc.
  16550. each$1(newOption, function (componentOption, mainType) {
  16551. if (componentOption == null) {
  16552. return;
  16553. }
  16554. if (!ComponentModel.hasClass(mainType)) {
  16555. // globalSettingTask.dirty();
  16556. option[mainType] = option[mainType] == null
  16557. ? clone(componentOption)
  16558. : merge(option[mainType], componentOption, true);
  16559. }
  16560. else if (mainType) {
  16561. newCptTypes.push(mainType);
  16562. }
  16563. });
  16564. ComponentModel.topologicalTravel(
  16565. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  16566. );
  16567. function visitComponent(mainType, dependencies) {
  16568. var newCptOptionList = normalizeToArray(newOption[mainType]);
  16569. var mapResult = mappingToExists(
  16570. componentsMap.get(mainType), newCptOptionList
  16571. );
  16572. makeIdAndName(mapResult);
  16573. // Set mainType and complete subType.
  16574. each$1(mapResult, function (item, index) {
  16575. var opt = item.option;
  16576. if (isObject$1(opt)) {
  16577. item.keyInfo.mainType = mainType;
  16578. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  16579. }
  16580. });
  16581. var dependentModels = getComponentsByTypes(
  16582. componentsMap, dependencies
  16583. );
  16584. option[mainType] = [];
  16585. componentsMap.set(mainType, []);
  16586. each$1(mapResult, function (resultItem, index) {
  16587. var componentModel = resultItem.exist;
  16588. var newCptOption = resultItem.option;
  16589. assert$1(
  16590. isObject$1(newCptOption) || componentModel,
  16591. 'Empty component definition'
  16592. );
  16593. // Consider where is no new option and should be merged using {},
  16594. // see removeEdgeAndAdd in topologicalTravel and
  16595. // ComponentModel.getAllClassMainTypes.
  16596. if (!newCptOption) {
  16597. componentModel.mergeOption({}, this);
  16598. componentModel.optionUpdated({}, false);
  16599. }
  16600. else {
  16601. var ComponentModelClass = ComponentModel.getClass(
  16602. mainType, resultItem.keyInfo.subType, true
  16603. );
  16604. if (componentModel && componentModel instanceof ComponentModelClass) {
  16605. componentModel.name = resultItem.keyInfo.name;
  16606. // componentModel.settingTask && componentModel.settingTask.dirty();
  16607. componentModel.mergeOption(newCptOption, this);
  16608. componentModel.optionUpdated(newCptOption, false);
  16609. }
  16610. else {
  16611. // PENDING Global as parent ?
  16612. var extraOpt = extend(
  16613. {
  16614. dependentModels: dependentModels,
  16615. componentIndex: index
  16616. },
  16617. resultItem.keyInfo
  16618. );
  16619. componentModel = new ComponentModelClass(
  16620. newCptOption, this, this, extraOpt
  16621. );
  16622. extend(componentModel, extraOpt);
  16623. componentModel.init(newCptOption, this, this, extraOpt);
  16624. // Call optionUpdated after init.
  16625. // newCptOption has been used as componentModel.option
  16626. // and may be merged with theme and default, so pass null
  16627. // to avoid confusion.
  16628. componentModel.optionUpdated(null, true);
  16629. }
  16630. }
  16631. componentsMap.get(mainType)[index] = componentModel;
  16632. option[mainType][index] = componentModel.option;
  16633. }, this);
  16634. // Backup series for filtering.
  16635. if (mainType === 'series') {
  16636. createSeriesIndices(this, componentsMap.get('series'));
  16637. }
  16638. }
  16639. this._seriesIndicesMap = createHashMap(
  16640. this._seriesIndices = this._seriesIndices || []
  16641. );
  16642. },
  16643. /**
  16644. * Get option for output (cloned option and inner info removed)
  16645. * @public
  16646. * @return {Object}
  16647. */
  16648. getOption: function () {
  16649. var option = clone(this.option);
  16650. each$1(option, function (opts, mainType) {
  16651. if (ComponentModel.hasClass(mainType)) {
  16652. var opts = normalizeToArray(opts);
  16653. for (var i = opts.length - 1; i >= 0; i--) {
  16654. // Remove options with inner id.
  16655. if (isIdInner(opts[i])) {
  16656. opts.splice(i, 1);
  16657. }
  16658. }
  16659. option[mainType] = opts;
  16660. }
  16661. });
  16662. delete option[OPTION_INNER_KEY];
  16663. return option;
  16664. },
  16665. /**
  16666. * @return {module:echarts/model/Model}
  16667. */
  16668. getTheme: function () {
  16669. return this._theme;
  16670. },
  16671. /**
  16672. * @param {string} mainType
  16673. * @param {number} [idx=0]
  16674. * @return {module:echarts/model/Component}
  16675. */
  16676. getComponent: function (mainType, idx) {
  16677. var list = this._componentsMap.get(mainType);
  16678. if (list) {
  16679. return list[idx || 0];
  16680. }
  16681. },
  16682. /**
  16683. * If none of index and id and name used, return all components with mainType.
  16684. * @param {Object} condition
  16685. * @param {string} condition.mainType
  16686. * @param {string} [condition.subType] If ignore, only query by mainType
  16687. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  16688. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  16689. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  16690. * @return {Array.<module:echarts/model/Component>}
  16691. */
  16692. queryComponents: function (condition) {
  16693. var mainType = condition.mainType;
  16694. if (!mainType) {
  16695. return [];
  16696. }
  16697. var index = condition.index;
  16698. var id = condition.id;
  16699. var name = condition.name;
  16700. var cpts = this._componentsMap.get(mainType);
  16701. if (!cpts || !cpts.length) {
  16702. return [];
  16703. }
  16704. var result;
  16705. if (index != null) {
  16706. if (!isArray(index)) {
  16707. index = [index];
  16708. }
  16709. result = filter(map(index, function (idx) {
  16710. return cpts[idx];
  16711. }), function (val) {
  16712. return !!val;
  16713. });
  16714. }
  16715. else if (id != null) {
  16716. var isIdArray = isArray(id);
  16717. result = filter(cpts, function (cpt) {
  16718. return (isIdArray && indexOf(id, cpt.id) >= 0)
  16719. || (!isIdArray && cpt.id === id);
  16720. });
  16721. }
  16722. else if (name != null) {
  16723. var isNameArray = isArray(name);
  16724. result = filter(cpts, function (cpt) {
  16725. return (isNameArray && indexOf(name, cpt.name) >= 0)
  16726. || (!isNameArray && cpt.name === name);
  16727. });
  16728. }
  16729. else {
  16730. // Return all components with mainType
  16731. result = cpts.slice();
  16732. }
  16733. return filterBySubType(result, condition);
  16734. },
  16735. /**
  16736. * The interface is different from queryComponents,
  16737. * which is convenient for inner usage.
  16738. *
  16739. * @usage
  16740. * var result = findComponents(
  16741. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  16742. * );
  16743. * var result = findComponents(
  16744. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  16745. * );
  16746. * var result = findComponents(
  16747. * {mainType: 'series'},
  16748. * function (model, index) {...}
  16749. * );
  16750. * // result like [component0, componnet1, ...]
  16751. *
  16752. * @param {Object} condition
  16753. * @param {string} condition.mainType Mandatory.
  16754. * @param {string} [condition.subType] Optional.
  16755. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  16756. * where xxx is mainType.
  16757. * If query attribute is null/undefined or has no index/id/name,
  16758. * do not filtering by query conditions, which is convenient for
  16759. * no-payload situations or when target of action is global.
  16760. * @param {Function} [condition.filter] parameter: component, return boolean.
  16761. * @return {Array.<module:echarts/model/Component>}
  16762. */
  16763. findComponents: function (condition) {
  16764. var query = condition.query;
  16765. var mainType = condition.mainType;
  16766. var queryCond = getQueryCond(query);
  16767. var result = queryCond
  16768. ? this.queryComponents(queryCond)
  16769. : this._componentsMap.get(mainType);
  16770. return doFilter(filterBySubType(result, condition));
  16771. function getQueryCond(q) {
  16772. var indexAttr = mainType + 'Index';
  16773. var idAttr = mainType + 'Id';
  16774. var nameAttr = mainType + 'Name';
  16775. return q && (
  16776. q[indexAttr] != null
  16777. || q[idAttr] != null
  16778. || q[nameAttr] != null
  16779. )
  16780. ? {
  16781. mainType: mainType,
  16782. // subType will be filtered finally.
  16783. index: q[indexAttr],
  16784. id: q[idAttr],
  16785. name: q[nameAttr]
  16786. }
  16787. : null;
  16788. }
  16789. function doFilter(res) {
  16790. return condition.filter
  16791. ? filter(res, condition.filter)
  16792. : res;
  16793. }
  16794. },
  16795. /**
  16796. * @usage
  16797. * eachComponent('legend', function (legendModel, index) {
  16798. * ...
  16799. * });
  16800. * eachComponent(function (componentType, model, index) {
  16801. * // componentType does not include subType
  16802. * // (componentType is 'xxx' but not 'xxx.aa')
  16803. * });
  16804. * eachComponent(
  16805. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  16806. * function (model, index) {...}
  16807. * );
  16808. * eachComponent(
  16809. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  16810. * function (model, index) {...}
  16811. * );
  16812. *
  16813. * @param {string|Object=} mainType When mainType is object, the definition
  16814. * is the same as the method 'findComponents'.
  16815. * @param {Function} cb
  16816. * @param {*} context
  16817. */
  16818. eachComponent: function (mainType, cb, context) {
  16819. var componentsMap = this._componentsMap;
  16820. if (typeof mainType === 'function') {
  16821. context = cb;
  16822. cb = mainType;
  16823. componentsMap.each(function (components, componentType) {
  16824. each$1(components, function (component, index) {
  16825. cb.call(context, componentType, component, index);
  16826. });
  16827. });
  16828. }
  16829. else if (isString(mainType)) {
  16830. each$1(componentsMap.get(mainType), cb, context);
  16831. }
  16832. else if (isObject$1(mainType)) {
  16833. var queryResult = this.findComponents(mainType);
  16834. each$1(queryResult, cb, context);
  16835. }
  16836. },
  16837. /**
  16838. * @param {string} name
  16839. * @return {Array.<module:echarts/model/Series>}
  16840. */
  16841. getSeriesByName: function (name) {
  16842. var series = this._componentsMap.get('series');
  16843. return filter(series, function (oneSeries) {
  16844. return oneSeries.name === name;
  16845. });
  16846. },
  16847. /**
  16848. * @param {number} seriesIndex
  16849. * @return {module:echarts/model/Series}
  16850. */
  16851. getSeriesByIndex: function (seriesIndex) {
  16852. return this._componentsMap.get('series')[seriesIndex];
  16853. },
  16854. /**
  16855. * @param {string} subType
  16856. * @return {Array.<module:echarts/model/Series>}
  16857. */
  16858. getSeriesByType: function (subType) {
  16859. var series = this._componentsMap.get('series');
  16860. return filter(series, function (oneSeries) {
  16861. return oneSeries.subType === subType;
  16862. });
  16863. },
  16864. /**
  16865. * @return {Array.<module:echarts/model/Series>}
  16866. */
  16867. getSeries: function () {
  16868. return this._componentsMap.get('series').slice();
  16869. },
  16870. /**
  16871. * @return {number}
  16872. */
  16873. getSeriesCount: function () {
  16874. return this._componentsMap.get('series').length;
  16875. },
  16876. /**
  16877. * After filtering, series may be different
  16878. * frome raw series.
  16879. *
  16880. * @param {Function} cb
  16881. * @param {*} context
  16882. */
  16883. eachSeries: function (cb, context) {
  16884. assertSeriesInitialized(this);
  16885. each$1(this._seriesIndices, function (rawSeriesIndex) {
  16886. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16887. cb.call(context, series, rawSeriesIndex);
  16888. }, this);
  16889. },
  16890. /**
  16891. * Iterate raw series before filtered.
  16892. *
  16893. * @param {Function} cb
  16894. * @param {*} context
  16895. */
  16896. eachRawSeries: function (cb, context) {
  16897. each$1(this._componentsMap.get('series'), cb, context);
  16898. },
  16899. /**
  16900. * After filtering, series may be different.
  16901. * frome raw series.
  16902. *
  16903. * @parma {string} subType
  16904. * @param {Function} cb
  16905. * @param {*} context
  16906. */
  16907. eachSeriesByType: function (subType, cb, context) {
  16908. assertSeriesInitialized(this);
  16909. each$1(this._seriesIndices, function (rawSeriesIndex) {
  16910. var series = this._componentsMap.get('series')[rawSeriesIndex];
  16911. if (series.subType === subType) {
  16912. cb.call(context, series, rawSeriesIndex);
  16913. }
  16914. }, this);
  16915. },
  16916. /**
  16917. * Iterate raw series before filtered of given type.
  16918. *
  16919. * @parma {string} subType
  16920. * @param {Function} cb
  16921. * @param {*} context
  16922. */
  16923. eachRawSeriesByType: function (subType, cb, context) {
  16924. return each$1(this.getSeriesByType(subType), cb, context);
  16925. },
  16926. /**
  16927. * @param {module:echarts/model/Series} seriesModel
  16928. */
  16929. isSeriesFiltered: function (seriesModel) {
  16930. assertSeriesInitialized(this);
  16931. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  16932. },
  16933. /**
  16934. * @return {Array.<number>}
  16935. */
  16936. getCurrentSeriesIndices: function () {
  16937. return (this._seriesIndices || []).slice();
  16938. },
  16939. /**
  16940. * @param {Function} cb
  16941. * @param {*} context
  16942. */
  16943. filterSeries: function (cb, context) {
  16944. assertSeriesInitialized(this);
  16945. var filteredSeries = filter(
  16946. this._componentsMap.get('series'), cb, context
  16947. );
  16948. createSeriesIndices(this, filteredSeries);
  16949. },
  16950. restoreData: function (payload) {
  16951. var componentsMap = this._componentsMap;
  16952. createSeriesIndices(this, componentsMap.get('series'));
  16953. var componentTypes = [];
  16954. componentsMap.each(function (components, componentType) {
  16955. componentTypes.push(componentType);
  16956. });
  16957. ComponentModel.topologicalTravel(
  16958. componentTypes,
  16959. ComponentModel.getAllClassMainTypes(),
  16960. function (componentType, dependencies) {
  16961. each$1(componentsMap.get(componentType), function (component) {
  16962. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  16963. && component.restoreData();
  16964. });
  16965. }
  16966. );
  16967. }
  16968. });
  16969. function isNotTargetSeries(seriesModel, payload) {
  16970. if (payload) {
  16971. var index = payload.seiresIndex;
  16972. var id = payload.seriesId;
  16973. var name = payload.seriesName;
  16974. return (index != null && seriesModel.componentIndex !== index)
  16975. || (id != null && seriesModel.id !== id)
  16976. || (name != null && seriesModel.name !== name);
  16977. }
  16978. }
  16979. /**
  16980. * @inner
  16981. */
  16982. function mergeTheme(option, theme) {
  16983. each$1(theme, function (themeItem, name) {
  16984. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  16985. if (!ComponentModel.hasClass(name)) {
  16986. if (typeof themeItem === 'object') {
  16987. option[name] = !option[name]
  16988. ? clone(themeItem)
  16989. : merge(option[name], themeItem, false);
  16990. }
  16991. else {
  16992. if (option[name] == null) {
  16993. option[name] = themeItem;
  16994. }
  16995. }
  16996. }
  16997. });
  16998. }
  16999. function initBase(baseOption) {
  17000. baseOption = baseOption;
  17001. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17002. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17003. this.option = {};
  17004. this.option[OPTION_INNER_KEY] = 1;
  17005. /**
  17006. * Init with series: [], in case of calling findSeries method
  17007. * before series initialized.
  17008. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17009. * @private
  17010. */
  17011. this._componentsMap = createHashMap({series: []});
  17012. /**
  17013. * Mapping between filtered series list and raw series list.
  17014. * key: filtered series indices, value: raw series indices.
  17015. * @type {Array.<nubmer>}
  17016. * @private
  17017. */
  17018. this._seriesIndices;
  17019. this._seriesIndicesMap;
  17020. mergeTheme(baseOption, this._theme.option);
  17021. // TODO Needs clone when merging to the unexisted property
  17022. merge(baseOption, globalDefault, false);
  17023. this.mergeOption(baseOption);
  17024. }
  17025. /**
  17026. * @inner
  17027. * @param {Array.<string>|string} types model types
  17028. * @return {Object} key: {string} type, value: {Array.<Object>} models
  17029. */
  17030. function getComponentsByTypes(componentsMap, types) {
  17031. if (!isArray(types)) {
  17032. types = types ? [types] : [];
  17033. }
  17034. var ret = {};
  17035. each$1(types, function (type) {
  17036. ret[type] = (componentsMap.get(type) || []).slice();
  17037. });
  17038. return ret;
  17039. }
  17040. /**
  17041. * @inner
  17042. */
  17043. function determineSubType(mainType, newCptOption, existComponent) {
  17044. var subType = newCptOption.type
  17045. ? newCptOption.type
  17046. : existComponent
  17047. ? existComponent.subType
  17048. // Use determineSubType only when there is no existComponent.
  17049. : ComponentModel.determineSubType(mainType, newCptOption);
  17050. // tooltip, markline, markpoint may always has no subType
  17051. return subType;
  17052. }
  17053. /**
  17054. * @inner
  17055. */
  17056. function createSeriesIndices(ecModel, seriesModels) {
  17057. ecModel._seriesIndicesMap = createHashMap(
  17058. ecModel._seriesIndices = map(seriesModels, function (series) {
  17059. return series.componentIndex;
  17060. }) || []
  17061. );
  17062. }
  17063. /**
  17064. * @inner
  17065. */
  17066. function filterBySubType(components, condition) {
  17067. // Using hasOwnProperty for restrict. Consider
  17068. // subType is undefined in user payload.
  17069. return condition.hasOwnProperty('subType')
  17070. ? filter(components, function (cpt) {
  17071. return cpt.subType === condition.subType;
  17072. })
  17073. : components;
  17074. }
  17075. /**
  17076. * @inner
  17077. */
  17078. function assertSeriesInitialized(ecModel) {
  17079. // Components that use _seriesIndices should depends on series component,
  17080. // which make sure that their initialization is after series.
  17081. if (__DEV__) {
  17082. if (!ecModel._seriesIndices) {
  17083. throw new Error('Option should contains series.');
  17084. }
  17085. }
  17086. }
  17087. mixin(GlobalModel, colorPaletteMixin);
  17088. var echartsAPIList = [
  17089. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  17090. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  17091. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  17092. ];
  17093. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  17094. function ExtensionAPI(chartInstance) {
  17095. each$1(echartsAPIList, function (name) {
  17096. this[name] = bind(chartInstance[name], chartInstance);
  17097. }, this);
  17098. }
  17099. var coordinateSystemCreators = {};
  17100. function CoordinateSystemManager() {
  17101. this._coordinateSystems = [];
  17102. }
  17103. CoordinateSystemManager.prototype = {
  17104. constructor: CoordinateSystemManager,
  17105. create: function (ecModel, api) {
  17106. var coordinateSystems = [];
  17107. each$1(coordinateSystemCreators, function (creater, type) {
  17108. var list = creater.create(ecModel, api);
  17109. coordinateSystems = coordinateSystems.concat(list || []);
  17110. });
  17111. this._coordinateSystems = coordinateSystems;
  17112. },
  17113. update: function (ecModel, api) {
  17114. each$1(this._coordinateSystems, function (coordSys) {
  17115. coordSys.update && coordSys.update(ecModel, api);
  17116. });
  17117. },
  17118. getCoordinateSystems: function () {
  17119. return this._coordinateSystems.slice();
  17120. }
  17121. };
  17122. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  17123. coordinateSystemCreators[type] = coordinateSystemCreator;
  17124. };
  17125. CoordinateSystemManager.get = function (type) {
  17126. return coordinateSystemCreators[type];
  17127. };
  17128. /**
  17129. * ECharts option manager
  17130. *
  17131. * @module {echarts/model/OptionManager}
  17132. */
  17133. var each$4 = each$1;
  17134. var clone$3 = clone;
  17135. var map$1 = map;
  17136. var merge$1 = merge;
  17137. var QUERY_REG = /^(min|max)?(.+)$/;
  17138. /**
  17139. * TERM EXPLANATIONS:
  17140. *
  17141. * [option]:
  17142. *
  17143. * An object that contains definitions of components. For example:
  17144. * var option = {
  17145. * title: {...},
  17146. * legend: {...},
  17147. * visualMap: {...},
  17148. * series: [
  17149. * {data: [...]},
  17150. * {data: [...]},
  17151. * ...
  17152. * ]
  17153. * };
  17154. *
  17155. * [rawOption]:
  17156. *
  17157. * An object input to echarts.setOption. 'rawOption' may be an
  17158. * 'option', or may be an object contains multi-options. For example:
  17159. * var option = {
  17160. * baseOption: {
  17161. * title: {...},
  17162. * legend: {...},
  17163. * series: [
  17164. * {data: [...]},
  17165. * {data: [...]},
  17166. * ...
  17167. * ]
  17168. * },
  17169. * timeline: {...},
  17170. * options: [
  17171. * {title: {...}, series: {data: [...]}},
  17172. * {title: {...}, series: {data: [...]}},
  17173. * ...
  17174. * ],
  17175. * media: [
  17176. * {
  17177. * query: {maxWidth: 320},
  17178. * option: {series: {x: 20}, visualMap: {show: false}}
  17179. * },
  17180. * {
  17181. * query: {minWidth: 320, maxWidth: 720},
  17182. * option: {series: {x: 500}, visualMap: {show: true}}
  17183. * },
  17184. * {
  17185. * option: {series: {x: 1200}, visualMap: {show: true}}
  17186. * }
  17187. * ]
  17188. * };
  17189. *
  17190. * @alias module:echarts/model/OptionManager
  17191. * @param {module:echarts/ExtensionAPI} api
  17192. */
  17193. function OptionManager(api) {
  17194. /**
  17195. * @private
  17196. * @type {module:echarts/ExtensionAPI}
  17197. */
  17198. this._api = api;
  17199. /**
  17200. * @private
  17201. * @type {Array.<number>}
  17202. */
  17203. this._timelineOptions = [];
  17204. /**
  17205. * @private
  17206. * @type {Array.<Object>}
  17207. */
  17208. this._mediaList = [];
  17209. /**
  17210. * @private
  17211. * @type {Object}
  17212. */
  17213. this._mediaDefault;
  17214. /**
  17215. * -1, means default.
  17216. * empty means no media.
  17217. * @private
  17218. * @type {Array.<number>}
  17219. */
  17220. this._currentMediaIndices = [];
  17221. /**
  17222. * @private
  17223. * @type {Object}
  17224. */
  17225. this._optionBackup;
  17226. /**
  17227. * @private
  17228. * @type {Object}
  17229. */
  17230. this._newBaseOption;
  17231. }
  17232. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17233. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17234. // rawOption cloned and backuped when timeline changed, which does no
  17235. // good to performance. What's more, that both timeline and setOption
  17236. // method supply 'notMerge' brings complex and some problems.
  17237. // Consider this case:
  17238. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17239. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17240. OptionManager.prototype = {
  17241. constructor: OptionManager,
  17242. /**
  17243. * @public
  17244. * @param {Object} rawOption Raw option.
  17245. * @param {module:echarts/model/Global} ecModel
  17246. * @param {Array.<Function>} optionPreprocessorFuncs
  17247. * @return {Object} Init option
  17248. */
  17249. setOption: function (rawOption, optionPreprocessorFuncs) {
  17250. if (rawOption) {
  17251. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17252. each$1(normalizeToArray(rawOption.series), function (series) {
  17253. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17254. });
  17255. }
  17256. // Caution: some series modify option data, if do not clone,
  17257. // it should ensure that the repeat modify correctly
  17258. // (create a new object when modify itself).
  17259. rawOption = clone$3(rawOption, true);
  17260. // FIXME
  17261. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  17262. var oldOptionBackup = this._optionBackup;
  17263. var newParsedOption = parseRawOption.call(
  17264. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  17265. );
  17266. this._newBaseOption = newParsedOption.baseOption;
  17267. // For setOption at second time (using merge mode);
  17268. if (oldOptionBackup) {
  17269. // Only baseOption can be merged.
  17270. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  17271. // For simplicity, timeline options and media options do not support merge,
  17272. // that is, if you `setOption` twice and both has timeline options, the latter
  17273. // timeline opitons will not be merged to the formers, but just substitude them.
  17274. if (newParsedOption.timelineOptions.length) {
  17275. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  17276. }
  17277. if (newParsedOption.mediaList.length) {
  17278. oldOptionBackup.mediaList = newParsedOption.mediaList;
  17279. }
  17280. if (newParsedOption.mediaDefault) {
  17281. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  17282. }
  17283. }
  17284. else {
  17285. this._optionBackup = newParsedOption;
  17286. }
  17287. },
  17288. /**
  17289. * @param {boolean} isRecreate
  17290. * @return {Object}
  17291. */
  17292. mountOption: function (isRecreate) {
  17293. var optionBackup = this._optionBackup;
  17294. // TODO
  17295. // 如果没有reset功能则不clone。
  17296. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  17297. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  17298. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  17299. this._currentMediaIndices = [];
  17300. return clone$3(isRecreate
  17301. // this._optionBackup.baseOption, which is created at the first `setOption`
  17302. // called, and is merged into every new option by inner method `mergeOption`
  17303. // each time `setOption` called, can be only used in `isRecreate`, because
  17304. // its reliability is under suspicion. In other cases option merge is
  17305. // performed by `model.mergeOption`.
  17306. ? optionBackup.baseOption : this._newBaseOption
  17307. );
  17308. },
  17309. /**
  17310. * @param {module:echarts/model/Global} ecModel
  17311. * @return {Object}
  17312. */
  17313. getTimelineOption: function (ecModel) {
  17314. var option;
  17315. var timelineOptions = this._timelineOptions;
  17316. if (timelineOptions.length) {
  17317. // getTimelineOption can only be called after ecModel inited,
  17318. // so we can get currentIndex from timelineModel.
  17319. var timelineModel = ecModel.getComponent('timeline');
  17320. if (timelineModel) {
  17321. option = clone$3(
  17322. timelineOptions[timelineModel.getCurrentIndex()],
  17323. true
  17324. );
  17325. }
  17326. }
  17327. return option;
  17328. },
  17329. /**
  17330. * @param {module:echarts/model/Global} ecModel
  17331. * @return {Array.<Object>}
  17332. */
  17333. getMediaOption: function (ecModel) {
  17334. var ecWidth = this._api.getWidth();
  17335. var ecHeight = this._api.getHeight();
  17336. var mediaList = this._mediaList;
  17337. var mediaDefault = this._mediaDefault;
  17338. var indices = [];
  17339. var result = [];
  17340. // No media defined.
  17341. if (!mediaList.length && !mediaDefault) {
  17342. return result;
  17343. }
  17344. // Multi media may be applied, the latter defined media has higher priority.
  17345. for (var i = 0, len = mediaList.length; i < len; i++) {
  17346. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17347. indices.push(i);
  17348. }
  17349. }
  17350. // FIXME
  17351. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  17352. if (!indices.length && mediaDefault) {
  17353. indices = [-1];
  17354. }
  17355. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17356. result = map$1(indices, function (index) {
  17357. return clone$3(
  17358. index === -1 ? mediaDefault.option : mediaList[index].option
  17359. );
  17360. });
  17361. }
  17362. // Otherwise return nothing.
  17363. this._currentMediaIndices = indices;
  17364. return result;
  17365. }
  17366. };
  17367. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  17368. var timelineOptions = [];
  17369. var mediaList = [];
  17370. var mediaDefault;
  17371. var baseOption;
  17372. // Compatible with ec2.
  17373. var timelineOpt = rawOption.timeline;
  17374. if (rawOption.baseOption) {
  17375. baseOption = rawOption.baseOption;
  17376. }
  17377. // For timeline
  17378. if (timelineOpt || rawOption.options) {
  17379. baseOption = baseOption || {};
  17380. timelineOptions = (rawOption.options || []).slice();
  17381. }
  17382. // For media query
  17383. if (rawOption.media) {
  17384. baseOption = baseOption || {};
  17385. var media = rawOption.media;
  17386. each$4(media, function (singleMedia) {
  17387. if (singleMedia && singleMedia.option) {
  17388. if (singleMedia.query) {
  17389. mediaList.push(singleMedia);
  17390. }
  17391. else if (!mediaDefault) {
  17392. // Use the first media default.
  17393. mediaDefault = singleMedia;
  17394. }
  17395. }
  17396. });
  17397. }
  17398. // For normal option
  17399. if (!baseOption) {
  17400. baseOption = rawOption;
  17401. }
  17402. // Set timelineOpt to baseOption in ec3,
  17403. // which is convenient for merge option.
  17404. if (!baseOption.timeline) {
  17405. baseOption.timeline = timelineOpt;
  17406. }
  17407. // Preprocess.
  17408. each$4([baseOption].concat(timelineOptions)
  17409. .concat(map(mediaList, function (media) {
  17410. return media.option;
  17411. })),
  17412. function (option) {
  17413. each$4(optionPreprocessorFuncs, function (preProcess) {
  17414. preProcess(option, isNew);
  17415. });
  17416. }
  17417. );
  17418. return {
  17419. baseOption: baseOption,
  17420. timelineOptions: timelineOptions,
  17421. mediaDefault: mediaDefault,
  17422. mediaList: mediaList
  17423. };
  17424. }
  17425. /**
  17426. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17427. * Support: width, height, aspectRatio
  17428. * Can use max or min as prefix.
  17429. */
  17430. function applyMediaQuery(query, ecWidth, ecHeight) {
  17431. var realMap = {
  17432. width: ecWidth,
  17433. height: ecHeight,
  17434. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17435. };
  17436. var applicatable = true;
  17437. each$1(query, function (value, attr) {
  17438. var matched = attr.match(QUERY_REG);
  17439. if (!matched || !matched[1] || !matched[2]) {
  17440. return;
  17441. }
  17442. var operator = matched[1];
  17443. var realAttr = matched[2].toLowerCase();
  17444. if (!compare(realMap[realAttr], value, operator)) {
  17445. applicatable = false;
  17446. }
  17447. });
  17448. return applicatable;
  17449. }
  17450. function compare(real, expect, operator) {
  17451. if (operator === 'min') {
  17452. return real >= expect;
  17453. }
  17454. else if (operator === 'max') {
  17455. return real <= expect;
  17456. }
  17457. else { // Equals
  17458. return real === expect;
  17459. }
  17460. }
  17461. function indicesEquals(indices1, indices2) {
  17462. // indices is always order by asc and has only finite number.
  17463. return indices1.join(',') === indices2.join(',');
  17464. }
  17465. /**
  17466. * Consider case:
  17467. * `chart.setOption(opt1);`
  17468. * Then user do some interaction like dataZoom, dataView changing.
  17469. * `chart.setOption(opt2);`
  17470. * Then user press 'reset button' in toolbox.
  17471. *
  17472. * After doing that all of the interaction effects should be reset, the
  17473. * chart should be the same as the result of invoke
  17474. * `chart.setOption(opt1); chart.setOption(opt2);`.
  17475. *
  17476. * Although it is not able ensure that
  17477. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  17478. * `chart.setOption(merge(opt1, opt2));` exactly,
  17479. * this might be the only simple way to implement that feature.
  17480. *
  17481. * MEMO: We've considered some other approaches:
  17482. * 1. Each model handle its self restoration but not uniform treatment.
  17483. * (Too complex in logic and error-prone)
  17484. * 2. Use a shadow ecModel. (Performace expensive)
  17485. */
  17486. function mergeOption(oldOption, newOption) {
  17487. newOption = newOption || {};
  17488. each$4(newOption, function (newCptOpt, mainType) {
  17489. if (newCptOpt == null) {
  17490. return;
  17491. }
  17492. var oldCptOpt = oldOption[mainType];
  17493. if (!ComponentModel.hasClass(mainType)) {
  17494. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  17495. }
  17496. else {
  17497. newCptOpt = normalizeToArray(newCptOpt);
  17498. oldCptOpt = normalizeToArray(oldCptOpt);
  17499. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  17500. oldOption[mainType] = map$1(mapResult, function (item) {
  17501. return (item.option && item.exist)
  17502. ? merge$1(item.exist, item.option, true)
  17503. : (item.exist || item.option);
  17504. });
  17505. }
  17506. });
  17507. }
  17508. var each$5 = each$1;
  17509. var isObject$3 = isObject$1;
  17510. var POSSIBLE_STYLES = [
  17511. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  17512. 'chordStyle', 'label', 'labelLine'
  17513. ];
  17514. function compatEC2ItemStyle(opt) {
  17515. var itemStyleOpt = opt && opt.itemStyle;
  17516. if (!itemStyleOpt) {
  17517. return;
  17518. }
  17519. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17520. var styleName = POSSIBLE_STYLES[i];
  17521. var normalItemStyleOpt = itemStyleOpt.normal;
  17522. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17523. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17524. opt[styleName] = opt[styleName] || {};
  17525. if (!opt[styleName].normal) {
  17526. opt[styleName].normal = normalItemStyleOpt[styleName];
  17527. }
  17528. else {
  17529. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17530. }
  17531. normalItemStyleOpt[styleName] = null;
  17532. }
  17533. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17534. opt[styleName] = opt[styleName] || {};
  17535. if (!opt[styleName].emphasis) {
  17536. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17537. }
  17538. else {
  17539. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17540. }
  17541. emphasisItemStyleOpt[styleName] = null;
  17542. }
  17543. }
  17544. }
  17545. function convertNormalEmphasis(opt, optType, useExtend) {
  17546. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  17547. var normalOpt = opt[optType].normal;
  17548. var emphasisOpt = opt[optType].emphasis;
  17549. if (normalOpt) {
  17550. // Timeline controlStyle has other properties besides normal and emphasis
  17551. if (useExtend) {
  17552. opt[optType].normal = opt[optType].emphasis = null;
  17553. defaults(opt[optType], normalOpt);
  17554. }
  17555. else {
  17556. opt[optType] = normalOpt;
  17557. }
  17558. }
  17559. if (emphasisOpt) {
  17560. opt.emphasis = opt.emphasis || {};
  17561. opt.emphasis[optType] = emphasisOpt;
  17562. }
  17563. }
  17564. }
  17565. function removeEC3NormalStatus(opt) {
  17566. convertNormalEmphasis(opt, 'itemStyle');
  17567. convertNormalEmphasis(opt, 'lineStyle');
  17568. convertNormalEmphasis(opt, 'areaStyle');
  17569. convertNormalEmphasis(opt, 'label');
  17570. convertNormalEmphasis(opt, 'labelLine');
  17571. // treemap
  17572. convertNormalEmphasis(opt, 'upperLabel');
  17573. // graph
  17574. convertNormalEmphasis(opt, 'edgeLabel');
  17575. }
  17576. function compatTextStyle(labelOpt) {
  17577. var textStyle = isObject$3(labelOpt) && labelOpt.textStyle;
  17578. if (textStyle) {
  17579. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17580. var propName = TEXT_STYLE_OPTIONS[i];
  17581. if (textStyle.hasOwnProperty(propName)) {
  17582. labelOpt[propName] = textStyle[propName];
  17583. }
  17584. }
  17585. }
  17586. }
  17587. function compatEC3CommonStyles(opt) {
  17588. if (opt) {
  17589. removeEC3NormalStatus(opt);
  17590. compatTextStyle(opt.label);
  17591. opt.emphasis && compatTextStyle(opt.emphasis.label);
  17592. }
  17593. }
  17594. function processSeries(seriesOpt) {
  17595. if (!isObject$3(seriesOpt)) {
  17596. return;
  17597. }
  17598. compatEC2ItemStyle(seriesOpt);
  17599. removeEC3NormalStatus(seriesOpt);
  17600. compatTextStyle(seriesOpt.label);
  17601. // treemap
  17602. compatTextStyle(seriesOpt.upperLabel);
  17603. // graph
  17604. compatTextStyle(seriesOpt.edgeLabel);
  17605. if (seriesOpt.emphasis) {
  17606. compatTextStyle(seriesOpt.emphasis.label);
  17607. // treemap
  17608. compatTextStyle(seriesOpt.emphasis.upperLabel);
  17609. // graph
  17610. compatTextStyle(seriesOpt.emphasis.edgeLabel);
  17611. }
  17612. var markPoint = seriesOpt.markPoint;
  17613. if (markPoint) {
  17614. compatEC2ItemStyle(markPoint);
  17615. compatEC3CommonStyles(markPoint);
  17616. }
  17617. var markLine = seriesOpt.markLine;
  17618. if (markLine) {
  17619. compatEC2ItemStyle(markLine);
  17620. compatEC3CommonStyles(markLine);
  17621. }
  17622. var markArea = seriesOpt.markArea;
  17623. if (markArea) {
  17624. compatEC3CommonStyles(markArea);
  17625. }
  17626. var data = seriesOpt.data;
  17627. // Break with ec3: if `setOption` again, there may be no `type` in option,
  17628. // then the backward compat based on option type will not be performed.
  17629. if (seriesOpt.type === 'graph') {
  17630. data = data || seriesOpt.nodes;
  17631. var edgeData = seriesOpt.links || seriesOpt.edges;
  17632. if (edgeData && !isTypedArray(edgeData)) {
  17633. for (var i = 0; i < edgeData.length; i++) {
  17634. compatEC3CommonStyles(edgeData[i]);
  17635. }
  17636. }
  17637. each$1(seriesOpt.categories, function (opt) {
  17638. removeEC3NormalStatus(opt);
  17639. });
  17640. }
  17641. if (data && !isTypedArray(data)) {
  17642. for (var i = 0; i < data.length; i++) {
  17643. compatEC3CommonStyles(data[i]);
  17644. }
  17645. }
  17646. // mark point data
  17647. var markPoint = seriesOpt.markPoint;
  17648. if (markPoint && markPoint.data) {
  17649. var mpData = markPoint.data;
  17650. for (var i = 0; i < mpData.length; i++) {
  17651. compatEC3CommonStyles(mpData[i]);
  17652. }
  17653. }
  17654. // mark line data
  17655. var markLine = seriesOpt.markLine;
  17656. if (markLine && markLine.data) {
  17657. var mlData = markLine.data;
  17658. for (var i = 0; i < mlData.length; i++) {
  17659. if (isArray(mlData[i])) {
  17660. compatEC3CommonStyles(mlData[i][0]);
  17661. compatEC3CommonStyles(mlData[i][1]);
  17662. }
  17663. else {
  17664. compatEC3CommonStyles(mlData[i]);
  17665. }
  17666. }
  17667. }
  17668. // Series
  17669. if (seriesOpt.type === 'gauge') {
  17670. compatTextStyle(seriesOpt, 'axisLabel');
  17671. compatTextStyle(seriesOpt, 'title');
  17672. compatTextStyle(seriesOpt, 'detail');
  17673. }
  17674. else if (seriesOpt.type === 'treemap') {
  17675. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  17676. each$1(seriesOpt.levels, function (opt) {
  17677. removeEC3NormalStatus(opt);
  17678. });
  17679. }
  17680. // sunburst starts from ec4, so it does not need to compat levels.
  17681. }
  17682. function toArr(o) {
  17683. return isArray(o) ? o : o ? [o] : [];
  17684. }
  17685. function toObj(o) {
  17686. return (isArray(o) ? o[0] : o) || {};
  17687. }
  17688. var compatStyle = function (option, isTheme) {
  17689. each$5(toArr(option.series), function (seriesOpt) {
  17690. isObject$3(seriesOpt) && processSeries(seriesOpt);
  17691. });
  17692. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17693. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17694. each$5(
  17695. axes,
  17696. function (axisName) {
  17697. each$5(toArr(option[axisName]), function (axisOpt) {
  17698. if (axisOpt) {
  17699. compatTextStyle(axisOpt, 'axisLabel');
  17700. compatTextStyle(axisOpt.axisPointer, 'label');
  17701. }
  17702. });
  17703. }
  17704. );
  17705. each$5(toArr(option.parallel), function (parallelOpt) {
  17706. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17707. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17708. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17709. });
  17710. each$5(toArr(option.calendar), function (calendarOpt) {
  17711. convertNormalEmphasis(calendarOpt, 'itemStyle');
  17712. compatTextStyle(calendarOpt, 'dayLabel');
  17713. compatTextStyle(calendarOpt, 'monthLabel');
  17714. compatTextStyle(calendarOpt, 'yearLabel');
  17715. });
  17716. // radar.name.textStyle
  17717. each$5(toArr(option.radar), function (radarOpt) {
  17718. compatTextStyle(radarOpt, 'name');
  17719. });
  17720. each$5(toArr(option.geo), function (geoOpt) {
  17721. if (isObject$3(geoOpt)) {
  17722. compatEC3CommonStyles(geoOpt);
  17723. each$5(toArr(geoOpt.regions), function (regionObj) {
  17724. compatEC3CommonStyles(regionObj);
  17725. });
  17726. }
  17727. });
  17728. each$5(toArr(option.timeline), function (timelineOpt) {
  17729. compatEC3CommonStyles(timelineOpt);
  17730. convertNormalEmphasis(timelineOpt, 'label');
  17731. convertNormalEmphasis(timelineOpt, 'itemStyle');
  17732. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  17733. convertNormalEmphasis(timelineOpt, 'checkpointStyle');
  17734. var data = timelineOpt.data;
  17735. isArray(data) && each$1(data, function (item) {
  17736. if (isObject$1(item)) {
  17737. convertNormalEmphasis(item, 'label');
  17738. convertNormalEmphasis(item, 'itemStyle');
  17739. }
  17740. });
  17741. });
  17742. each$5(toArr(option.toolbox), function (toolboxOpt) {
  17743. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  17744. each$5(toolboxOpt.feature, function (featureOpt) {
  17745. convertNormalEmphasis(featureOpt, 'iconStyle');
  17746. });
  17747. });
  17748. compatTextStyle(toObj(option.axisPointer), 'label');
  17749. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  17750. };
  17751. // Compatitable with 2.0
  17752. function get(opt, path) {
  17753. path = path.split(',');
  17754. var obj = opt;
  17755. for (var i = 0; i < path.length; i++) {
  17756. obj = obj && obj[path[i]];
  17757. if (obj == null) {
  17758. break;
  17759. }
  17760. }
  17761. return obj;
  17762. }
  17763. function set$1(opt, path, val, overwrite) {
  17764. path = path.split(',');
  17765. var obj = opt;
  17766. var key;
  17767. for (var i = 0; i < path.length - 1; i++) {
  17768. key = path[i];
  17769. if (obj[key] == null) {
  17770. obj[key] = {};
  17771. }
  17772. obj = obj[key];
  17773. }
  17774. if (overwrite || obj[path[i]] == null) {
  17775. obj[path[i]] = val;
  17776. }
  17777. }
  17778. function compatLayoutProperties(option) {
  17779. each$1(LAYOUT_PROPERTIES, function (prop) {
  17780. if (prop[0] in option && !(prop[1] in option)) {
  17781. option[prop[1]] = option[prop[0]];
  17782. }
  17783. });
  17784. }
  17785. var LAYOUT_PROPERTIES = [
  17786. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  17787. ];
  17788. var COMPATITABLE_COMPONENTS = [
  17789. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  17790. ];
  17791. var backwardCompat = function (option, isTheme) {
  17792. compatStyle(option, isTheme);
  17793. // Make sure series array for model initialization.
  17794. option.series = normalizeToArray(option.series);
  17795. each$1(option.series, function (seriesOpt) {
  17796. if (!isObject$1(seriesOpt)) {
  17797. return;
  17798. }
  17799. var seriesType = seriesOpt.type;
  17800. if (seriesType === 'pie' || seriesType === 'gauge') {
  17801. if (seriesOpt.clockWise != null) {
  17802. seriesOpt.clockwise = seriesOpt.clockWise;
  17803. }
  17804. }
  17805. if (seriesType === 'gauge') {
  17806. var pointerColor = get(seriesOpt, 'pointer.color');
  17807. pointerColor != null
  17808. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  17809. }
  17810. compatLayoutProperties(seriesOpt);
  17811. });
  17812. // dataRange has changed to visualMap
  17813. if (option.dataRange) {
  17814. option.visualMap = option.dataRange;
  17815. }
  17816. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  17817. var options = option[componentName];
  17818. if (options) {
  17819. if (!isArray(options)) {
  17820. options = [options];
  17821. }
  17822. each$1(options, function (option) {
  17823. compatLayoutProperties(option);
  17824. });
  17825. }
  17826. });
  17827. };
  17828. // TODO
  17829. // ??? refactor? check the outer usage of data provider.
  17830. // merge with defaultDimValueGetter?
  17831. /**
  17832. * If normal array used, mutable chunk size is supported.
  17833. * If typed array used, chunk size must be fixed.
  17834. */
  17835. function DefaultDataProvider(source, dimSize) {
  17836. if (!Source.isInstance(source)) {
  17837. source = Source.seriesDataToSource(source);
  17838. }
  17839. this._source = source;
  17840. var data = this._data = source.data;
  17841. var sourceFormat = source.sourceFormat;
  17842. // Typed array. TODO IE10+?
  17843. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17844. if (__DEV__) {
  17845. if (dimSize == null) {
  17846. throw new Error('Typed array data must specify dimension size');
  17847. }
  17848. }
  17849. this._offset = 0;
  17850. this._dimSize = dimSize;
  17851. this._data = data;
  17852. }
  17853. var methods = providerMethods[
  17854. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  17855. ? sourceFormat + '_' + source.seriesLayoutBy
  17856. : sourceFormat
  17857. ];
  17858. if (__DEV__) {
  17859. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  17860. }
  17861. extend(this, methods);
  17862. }
  17863. var providerProto = DefaultDataProvider.prototype;
  17864. // If data is pure without style configuration
  17865. providerProto.pure = false;
  17866. // If data is persistent and will not be released after use.
  17867. providerProto.persistent = true;
  17868. // ???! FIXME legacy data provider do not has method getSource
  17869. providerProto.getSource = function () {
  17870. return this._source;
  17871. };
  17872. var providerMethods = {
  17873. 'arrayRows_column': {
  17874. pure: true,
  17875. count: function () {
  17876. return Math.max(0, this._data.length - this._source.startIndex);
  17877. },
  17878. getItem: function (idx) {
  17879. return this._data[idx + this._source.startIndex];
  17880. },
  17881. appendData: appendDataSimply
  17882. },
  17883. 'arrayRows_row': {
  17884. pure: true,
  17885. count: function () {
  17886. var row = this._data[0];
  17887. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  17888. },
  17889. getItem: function (idx) {
  17890. idx += this._source.startIndex;
  17891. var item = [];
  17892. var data = this._data;
  17893. for (var i = 0; i < data.length; i++) {
  17894. var row = data[i];
  17895. item.push(row ? row[idx] : null);
  17896. }
  17897. return item;
  17898. },
  17899. appendData: function () {
  17900. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  17901. }
  17902. },
  17903. 'objectRows': {
  17904. pure: true,
  17905. count: countSimply,
  17906. getItem: getItemSimply,
  17907. appendData: appendDataSimply
  17908. },
  17909. 'keyedColumns': {
  17910. pure: true,
  17911. count: function () {
  17912. var dimName = this._source.dimensionsDefine[0].name;
  17913. var col = this._data[dimName];
  17914. return col ? col.length : 0;
  17915. },
  17916. getItem: function (idx) {
  17917. var item = [];
  17918. var dims = this._source.dimensionsDefine;
  17919. for (var i = 0; i < dims.length; i++) {
  17920. var col = this._data[dims[i].name];
  17921. item.push(col ? col[idx] : null);
  17922. }
  17923. return item;
  17924. },
  17925. appendData: function (newData) {
  17926. var data = this._data;
  17927. each$1(newData, function (newCol, key) {
  17928. var oldCol = data[key] || (data[key] = []);
  17929. for (var i = 0; i < (newCol || []).length; i++) {
  17930. oldCol.push(newCol[i]);
  17931. }
  17932. });
  17933. }
  17934. },
  17935. 'original': {
  17936. count: countSimply,
  17937. getItem: getItemSimply,
  17938. appendData: appendDataSimply
  17939. },
  17940. 'typedArray': {
  17941. persistent: false,
  17942. pure: true,
  17943. count: function () {
  17944. return this._data ? (this._data.length / this._dimSize) : 0;
  17945. },
  17946. getItem: function (idx) {
  17947. idx = idx - this._offset;
  17948. var item = [];
  17949. var offset = this._dimSize * idx;
  17950. for (var i = 0; i < this._dimSize; i++) {
  17951. item[i] = this._data[offset + i];
  17952. }
  17953. return item;
  17954. },
  17955. appendData: function (newData) {
  17956. if (__DEV__) {
  17957. assert$1(
  17958. isTypedArray(newData),
  17959. 'Added data must be TypedArray if data in initialization is TypedArray'
  17960. );
  17961. }
  17962. this._data = newData;
  17963. },
  17964. // Clean self if data is already used.
  17965. clean: function () {
  17966. // PENDING
  17967. this._offset += this.count();
  17968. this._data = null;
  17969. }
  17970. }
  17971. };
  17972. function countSimply() {
  17973. return this._data.length;
  17974. }
  17975. function getItemSimply(idx) {
  17976. return this._data[idx];
  17977. }
  17978. function appendDataSimply(newData) {
  17979. for (var i = 0; i < newData.length; i++) {
  17980. this._data.push(newData[i]);
  17981. }
  17982. }
  17983. var rawValueGetters = {
  17984. arrayRows: getRawValueSimply,
  17985. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  17986. return dimIndex != null ? dataItem[dimName] : dataItem;
  17987. },
  17988. keyedColumns: getRawValueSimply,
  17989. original: function (dataItem, dataIndex, dimIndex, dimName) {
  17990. // FIXME
  17991. // In some case (markpoint in geo (geo-map.html)), dataItem
  17992. // is {coord: [...]}
  17993. var value = getDataItemValue(dataItem);
  17994. return (dimIndex == null || !(value instanceof Array))
  17995. ? value
  17996. : value[dimIndex];
  17997. },
  17998. typedArray: getRawValueSimply
  17999. };
  18000. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  18001. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18002. }
  18003. var defaultDimValueGetters = {
  18004. arrayRows: getDimValueSimply,
  18005. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  18006. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  18007. },
  18008. keyedColumns: getDimValueSimply,
  18009. original: function (dataItem, dimName, dataIndex, dimIndex) {
  18010. // Performance sensitive, do not use modelUtil.getDataItemValue.
  18011. // If dataItem is an plain object with no value field, the var `value`
  18012. // will be assigned with the object, but it will be tread correctly
  18013. // in the `convertDataValue`.
  18014. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  18015. // If any dataItem is like { value: 10 }
  18016. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  18017. this.hasItemOption = true;
  18018. }
  18019. return converDataValue(
  18020. (value instanceof Array)
  18021. ? value[dimIndex]
  18022. // If value is a single number or something else not array.
  18023. : value,
  18024. this._dimensionInfos[dimName]
  18025. );
  18026. },
  18027. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  18028. return dataItem[dimIndex];
  18029. }
  18030. };
  18031. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  18032. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  18033. }
  18034. /**
  18035. * This helper method convert value in data.
  18036. * @param {string|number|Date} value
  18037. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  18038. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  18039. */
  18040. function converDataValue(value, dimInfo) {
  18041. // Performance sensitive.
  18042. var dimType = dimInfo && dimInfo.type;
  18043. if (dimType === 'ordinal') {
  18044. // If given value is a category string
  18045. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  18046. return ordinalMeta
  18047. ? ordinalMeta.parseAndCollect(value)
  18048. : value;
  18049. }
  18050. if (dimType === 'time'
  18051. // spead up when using timestamp
  18052. && typeof value !== 'number'
  18053. && value != null
  18054. && value !== '-'
  18055. ) {
  18056. value = +parseDate(value);
  18057. }
  18058. // dimType defaults 'number'.
  18059. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  18060. // parse to NaN.
  18061. return (value == null || value === '')
  18062. ? NaN
  18063. // If string (like '-'), using '+' parse to NaN
  18064. // If object, also parse to NaN
  18065. : +value;
  18066. }
  18067. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18068. // Consider persistent.
  18069. // Caution: why use raw value to display on label or tooltip?
  18070. // A reason is to avoid format. For example time value we do not know
  18071. // how to format is expected. More over, if stack is used, calculated
  18072. // value may be 0.91000000001, which have brings trouble to display.
  18073. // TODO: consider how to treat null/undefined/NaN when display?
  18074. /**
  18075. * @param {module:echarts/data/List} data
  18076. * @param {number} dataIndex
  18077. * @param {string|number} [dim] dimName or dimIndex
  18078. * @return {Array.<number>|string|number} can be null/undefined.
  18079. */
  18080. function retrieveRawValue(data, dataIndex, dim) {
  18081. if (!data) {
  18082. return;
  18083. }
  18084. // Consider data may be not persistent.
  18085. var dataItem = data.getRawDataItem(dataIndex);
  18086. if (dataItem == null) {
  18087. return;
  18088. }
  18089. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18090. var dimName;
  18091. var dimIndex;
  18092. var dimInfo = data.getDimensionInfo(dim);
  18093. if (dimInfo) {
  18094. dimName = dimInfo.name;
  18095. dimIndex = dimInfo.index;
  18096. }
  18097. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  18098. }
  18099. /**
  18100. * Compatible with some cases (in pie, map) like:
  18101. * data: [{name: 'xx', value: 5, selected: true}, ...]
  18102. * where only sourceFormat is 'original' and 'objectRows' supported.
  18103. *
  18104. * ??? TODO
  18105. * Supported detail options in data item when using 'arrayRows'.
  18106. *
  18107. * @param {module:echarts/data/List} data
  18108. * @param {number} dataIndex
  18109. * @param {string} attr like 'selected'
  18110. */
  18111. function retrieveRawAttr(data, dataIndex, attr) {
  18112. if (!data) {
  18113. return;
  18114. }
  18115. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18116. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  18117. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  18118. ) {
  18119. return;
  18120. }
  18121. var dataItem = data.getRawDataItem(dataIndex);
  18122. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  18123. dataItem = null;
  18124. }
  18125. if (dataItem) {
  18126. return dataItem[attr];
  18127. }
  18128. }
  18129. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18130. // PENDING A little ugly
  18131. var dataFormatMixin = {
  18132. /**
  18133. * Get params for formatter
  18134. * @param {number} dataIndex
  18135. * @param {string} [dataType]
  18136. * @return {Object}
  18137. */
  18138. getDataParams: function (dataIndex, dataType) {
  18139. var data = this.getData(dataType);
  18140. var rawValue = this.getRawValue(dataIndex, dataType);
  18141. var rawDataIndex = data.getRawIndex(dataIndex);
  18142. var name = data.getName(dataIndex, true);
  18143. var itemOpt = data.getRawDataItem(dataIndex);
  18144. var color = data.getItemVisual(dataIndex, 'color');
  18145. return {
  18146. componentType: this.mainType,
  18147. componentSubType: this.subType,
  18148. seriesType: this.mainType === 'series' ? this.subType : null,
  18149. seriesIndex: this.seriesIndex,
  18150. seriesId: this.id,
  18151. seriesName: this.name,
  18152. name: name,
  18153. dataIndex: rawDataIndex,
  18154. data: itemOpt,
  18155. dataType: dataType,
  18156. value: rawValue,
  18157. color: color,
  18158. marker: getTooltipMarker(color),
  18159. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18160. $vars: ['seriesName', 'name', 'value']
  18161. };
  18162. },
  18163. /**
  18164. * Format label
  18165. * @param {number} dataIndex
  18166. * @param {string} [status='normal'] 'normal' or 'emphasis'
  18167. * @param {string} [dataType]
  18168. * @param {number} [dimIndex]
  18169. * @param {string} [labelProp='label']
  18170. * @return {string} If not formatter, return null/undefined
  18171. */
  18172. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  18173. status = status || 'normal';
  18174. var data = this.getData(dataType);
  18175. var itemModel = data.getItemModel(dataIndex);
  18176. var params = this.getDataParams(dataIndex, dataType);
  18177. if (dimIndex != null && (params.value instanceof Array)) {
  18178. params.value = params.value[dimIndex];
  18179. }
  18180. var formatter = itemModel.get(
  18181. status === 'normal'
  18182. ? [labelProp || 'label', 'formatter']
  18183. : [status, labelProp || 'label', 'formatter']
  18184. );
  18185. if (typeof formatter === 'function') {
  18186. params.status = status;
  18187. return formatter(params);
  18188. }
  18189. else if (typeof formatter === 'string') {
  18190. var str = formatTpl(formatter, params);
  18191. // Support 'aaa{@[3]}bbb{@product}ccc'.
  18192. // Do not support '}' in dim name util have to.
  18193. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  18194. var len = dim.length;
  18195. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  18196. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  18197. }
  18198. return retrieveRawValue(data, dataIndex, dim);
  18199. });
  18200. }
  18201. },
  18202. /**
  18203. * Get raw value in option
  18204. * @param {number} idx
  18205. * @param {string} [dataType]
  18206. * @return {Array|number|string}
  18207. */
  18208. getRawValue: function (idx, dataType) {
  18209. return retrieveRawValue(this.getData(dataType), idx);
  18210. },
  18211. /**
  18212. * Should be implemented.
  18213. * @param {number} dataIndex
  18214. * @param {boolean} [multipleSeries=false]
  18215. * @param {number} [dataType]
  18216. * @return {string} tooltip string
  18217. */
  18218. formatTooltip: function () {
  18219. // Empty function
  18220. }
  18221. };
  18222. /**
  18223. * @param {Object} define
  18224. * @return See the return of `createTask`.
  18225. */
  18226. function createTask(define) {
  18227. return new Task(define);
  18228. }
  18229. /**
  18230. * @constructor
  18231. * @param {Object} define
  18232. * @param {Function} define.reset Custom reset
  18233. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  18234. * @param {Function} [define.count] count is used to determin data task.
  18235. * @param {Function} [define.onDirty] count is used to determin data task.
  18236. */
  18237. function Task(define) {
  18238. define = define || {};
  18239. this._reset = define.reset;
  18240. this._plan = define.plan;
  18241. this._count = define.count;
  18242. this._onDirty = define.onDirty;
  18243. this._dirty = true;
  18244. // Context must be specified implicitly, to
  18245. // avoid miss update context when model changed.
  18246. this.context;
  18247. }
  18248. var taskProto = Task.prototype;
  18249. /**
  18250. * @param {Object} performArgs
  18251. * @param {number} [performArgs.step] Specified step.
  18252. * @param {number} [performArgs.skip] Skip customer perform call.
  18253. */
  18254. taskProto.perform = function (performArgs) {
  18255. var upTask = this._upstream;
  18256. var skip = performArgs && performArgs.skip;
  18257. // TODO some refactor.
  18258. // Pull data. Must pull data each time, because context.data
  18259. // may be updated by Series.setData.
  18260. if (this._dirty && upTask) {
  18261. var context = this.context;
  18262. context.data = context.outputData = upTask.context.outputData;
  18263. }
  18264. if (this.__pipeline) {
  18265. this.__pipeline.currentTask = this;
  18266. }
  18267. var planResult;
  18268. if (this._plan && !skip) {
  18269. planResult = this._plan(this.context);
  18270. }
  18271. if (this._dirty || planResult === 'reset') {
  18272. this._dirty = false;
  18273. reset(this, skip);
  18274. }
  18275. var step = performArgs && performArgs.step;
  18276. if (upTask) {
  18277. if (__DEV__) {
  18278. assert$1(upTask._outputDueEnd != null);
  18279. }
  18280. // ??? FIXME move to schedueler?
  18281. // this._dueEnd = Math.max(upTask._outputDueEnd, this._dueEnd);
  18282. this._dueEnd = upTask._outputDueEnd;
  18283. }
  18284. // DataTask or overallTask
  18285. else {
  18286. if (__DEV__) {
  18287. assert$1(!this._progress || this._count);
  18288. }
  18289. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18290. }
  18291. // Note: Stubs, that its host overall task let it has progress, has progress.
  18292. // If no progress, pass index from upstream to downstream each time plan called.
  18293. if (this._progress) {
  18294. var start = this._dueIndex;
  18295. var end = Math.min(
  18296. step != null ? this._dueIndex + step : Infinity,
  18297. this._dueEnd
  18298. );
  18299. !skip && start < end && (
  18300. this._progress({start: start, end: end}, this.context)
  18301. );
  18302. this._dueIndex = end;
  18303. // If no `outputDueEnd`, assume that output data and
  18304. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  18305. var outputDueEnd = this._settedOutputEnd != null
  18306. ? this._settedOutputEnd : end;
  18307. if (__DEV__) {
  18308. // ??? Can not rollback.
  18309. assert$1(outputDueEnd >= this._outputDueEnd);
  18310. }
  18311. this._outputDueEnd = outputDueEnd;
  18312. }
  18313. else {
  18314. // (1) Some overall task has no progress.
  18315. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  18316. // This should always be performed so it can be passed to downstream.
  18317. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  18318. ? this._settedOutputEnd : this._dueEnd;
  18319. }
  18320. return this.unfinished();
  18321. };
  18322. taskProto.dirty = function () {
  18323. this._dirty = true;
  18324. this._onDirty && this._onDirty(this.context);
  18325. };
  18326. /**
  18327. * @param {Object} [params]
  18328. */
  18329. function reset(taskIns, skip) {
  18330. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  18331. taskIns._settedOutputEnd = null;
  18332. taskIns._progress = !skip && taskIns._reset && taskIns._reset(
  18333. taskIns.context
  18334. );
  18335. var downstream = taskIns._downstream;
  18336. downstream && downstream.dirty();
  18337. }
  18338. /**
  18339. * @return {boolean}
  18340. */
  18341. taskProto.unfinished = function () {
  18342. return this._progress && this._dueIndex < this._dueEnd;
  18343. };
  18344. /**
  18345. * @param {Object} downTask The downstream task.
  18346. * @return {Object} The downstream task.
  18347. */
  18348. taskProto.pipe = function (downTask) {
  18349. if (__DEV__) {
  18350. assert$1(downTask && !downTask._disposed && downTask !== this);
  18351. }
  18352. // If already downstream, do not dirty downTask.
  18353. if (this._downstream !== downTask || this._dirty) {
  18354. this._downstream = downTask;
  18355. downTask._upstream = this;
  18356. downTask.dirty();
  18357. }
  18358. };
  18359. taskProto.dispose = function () {
  18360. if (this._disposed) {
  18361. return;
  18362. }
  18363. this._upstream && (this._upstream._downstream = null);
  18364. this._downstream && (this._downstream._upstream = null);
  18365. this._dirty = false;
  18366. this._disposed = true;
  18367. };
  18368. taskProto.getUpstream = function () {
  18369. return this._upstream;
  18370. };
  18371. taskProto.getDownstream = function () {
  18372. return this._downstream;
  18373. };
  18374. taskProto.setOutputEnd = function (end) {
  18375. // ??? FIXME: check
  18376. // This only happend in dataTask, dataZoom, map, currently.
  18377. // where dataZoom do not set end each time, but only set
  18378. // when reset. So we should record the setted end, in case
  18379. // that the stub of dataZoom perform again and earse the
  18380. // setted end by upstream.
  18381. this._outputDueEnd = this._settedOutputEnd = end;
  18382. // this._outputDueEnd = end;
  18383. };
  18384. var inner$4 = makeInner();
  18385. var SeriesModel = ComponentModel.extend({
  18386. type: 'series.__base__',
  18387. /**
  18388. * @readOnly
  18389. */
  18390. seriesIndex: 0,
  18391. // coodinateSystem will be injected in the echarts/CoordinateSystem
  18392. coordinateSystem: null,
  18393. /**
  18394. * @type {Object}
  18395. * @protected
  18396. */
  18397. defaultOption: null,
  18398. /**
  18399. * Data provided for legend
  18400. * @type {Function}
  18401. */
  18402. // PENDING
  18403. legendDataProvider: null,
  18404. /**
  18405. * Access path of color for visual
  18406. */
  18407. visualColorAccessPath: 'itemStyle.color',
  18408. /**
  18409. * Support merge layout params.
  18410. * Only support 'box' now (left/right/top/bottom/width/height).
  18411. * @type {string|Object} Object can be {ignoreSize: true}
  18412. * @readOnly
  18413. */
  18414. layoutMode: null,
  18415. init: function (option, parentModel, ecModel, extraOpt) {
  18416. /**
  18417. * @type {number}
  18418. * @readOnly
  18419. */
  18420. this.seriesIndex = this.componentIndex;
  18421. this.dataTask = createTask({
  18422. count: dataTaskCount,
  18423. reset: dataTaskReset
  18424. });
  18425. this.dataTask.context = {model: this};
  18426. this.mergeDefaultAndTheme(option, ecModel);
  18427. prepareSource(this);
  18428. var data = this.getInitialData(option, ecModel);
  18429. wrapData(data, this);
  18430. this.dataTask.context.data = data;
  18431. if (__DEV__) {
  18432. assert$1(data, 'getInitialData returned invalid data.');
  18433. }
  18434. /**
  18435. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  18436. * @private
  18437. */
  18438. inner$4(this).dataBeforeProcessed = data;
  18439. // If we reverse the order (make data firstly, and then make
  18440. // dataBeforeProcessed by cloneShallow), cloneShallow will
  18441. // cause data.graph.data !== data when using
  18442. // module:echarts/data/Graph or module:echarts/data/Tree.
  18443. // See module:echarts/data/helper/linkList
  18444. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  18445. // init or merge stage, because the data can be restored. So we do not `restoreData`
  18446. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  18447. // Call `seriesModel.getRawData()` instead.
  18448. // this.restoreData();
  18449. autoSeriesName(this);
  18450. },
  18451. /**
  18452. * Util for merge default and theme to option
  18453. * @param {Object} option
  18454. * @param {module:echarts/model/Global} ecModel
  18455. */
  18456. mergeDefaultAndTheme: function (option, ecModel) {
  18457. var layoutMode = this.layoutMode;
  18458. var inputPositionParams = layoutMode
  18459. ? getLayoutParams(option) : {};
  18460. // Backward compat: using subType on theme.
  18461. // But if name duplicate between series subType
  18462. // (for example: parallel) add component mainType,
  18463. // add suffix 'Series'.
  18464. var themeSubType = this.subType;
  18465. if (ComponentModel.hasClass(themeSubType)) {
  18466. themeSubType += 'Series';
  18467. }
  18468. merge(
  18469. option,
  18470. ecModel.getTheme().get(this.subType)
  18471. );
  18472. merge(option, this.getDefaultOption());
  18473. // Default label emphasis `show`
  18474. defaultEmphasis(option, 'label', ['show']);
  18475. this.fillDataTextStyle(option.data);
  18476. if (layoutMode) {
  18477. mergeLayoutParam(option, inputPositionParams, layoutMode);
  18478. }
  18479. },
  18480. mergeOption: function (newSeriesOption, ecModel) {
  18481. // this.settingTask.dirty();
  18482. newSeriesOption = merge(this.option, newSeriesOption, true);
  18483. this.fillDataTextStyle(newSeriesOption.data);
  18484. var layoutMode = this.layoutMode;
  18485. if (layoutMode) {
  18486. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  18487. }
  18488. prepareSource(this);
  18489. var data = this.getInitialData(newSeriesOption, ecModel);
  18490. wrapData(data, this);
  18491. this.dataTask.dirty();
  18492. this.dataTask.context.data = data;
  18493. inner$4(this).dataBeforeProcessed = data;
  18494. autoSeriesName(this);
  18495. },
  18496. fillDataTextStyle: function (data) {
  18497. // Default data label emphasis `show`
  18498. // FIXME Tree structure data ?
  18499. // FIXME Performance ?
  18500. if (data) {
  18501. var props = ['show'];
  18502. for (var i = 0; i < data.length; i++) {
  18503. if (data[i] && data[i].label) {
  18504. defaultEmphasis(data[i], 'label', props);
  18505. }
  18506. }
  18507. }
  18508. },
  18509. /**
  18510. * Init a data structure from data related option in series
  18511. * Must be overwritten
  18512. */
  18513. getInitialData: function () {},
  18514. /**
  18515. * Append data to list
  18516. * @param {Object} params
  18517. * @param {Array|TypedArray} params.data
  18518. */
  18519. appendData: function (params) {
  18520. // FIXME ???
  18521. // (1) If data from dataset, forbidden append.
  18522. // (2) support append data of dataset.
  18523. var data = this.getRawData();
  18524. data.appendData(params.data);
  18525. },
  18526. /**
  18527. * Consider some method like `filter`, `map` need make new data,
  18528. * We should make sure that `seriesModel.getData()` get correct
  18529. * data in the stream procedure. So we fetch data from upstream
  18530. * each time `task.perform` called.
  18531. * @param {string} [dataType]
  18532. * @return {module:echarts/data/List}
  18533. */
  18534. getData: function (dataType) {
  18535. var task = getCurrentTask(this);
  18536. if (task) {
  18537. var data = task.context.data;
  18538. return dataType == null ? data : data.getLinkedData(dataType);
  18539. }
  18540. else {
  18541. // When series is not alive (that may happen when click toolbox
  18542. // restore or setOption with not merge mode), series data may
  18543. // be still need to judge animation or something when graphic
  18544. // elements want to know whether fade out.
  18545. return inner$4(this).data;
  18546. }
  18547. },
  18548. /**
  18549. * @param {module:echarts/data/List} data
  18550. */
  18551. setData: function (data) {
  18552. var task = getCurrentTask(this);
  18553. if (task) {
  18554. var context = task.context;
  18555. // Consider case: filter, data sample.
  18556. if (context.data !== data && task.isOverallFilter) {
  18557. task.setOutputEnd(data.count());
  18558. }
  18559. context.outputData = data;
  18560. // Caution: setData should update context.data,
  18561. // Because getData may be called multiply in a
  18562. // single stage and expect to get the data just
  18563. // set. (For example, AxisProxy, x y both call
  18564. // getData and setDate sequentially).
  18565. // So the context.data should be fetched from
  18566. // upstream each time when a stage starts to be
  18567. // performed.
  18568. if (task !== this.dataTask) {
  18569. context.data = data;
  18570. }
  18571. }
  18572. inner$4(this).data = data;
  18573. },
  18574. /**
  18575. * @see {module:echarts/data/helper/sourceHelper#getSource}
  18576. * @return {module:echarts/data/Source} source
  18577. */
  18578. getSource: function () {
  18579. return getSource(this);
  18580. },
  18581. /**
  18582. * Get data before processed
  18583. * @return {module:echarts/data/List}
  18584. */
  18585. getRawData: function () {
  18586. return inner$4(this).dataBeforeProcessed;
  18587. },
  18588. /**
  18589. * Get base axis if has coordinate system and has axis.
  18590. * By default use coordSys.getBaseAxis();
  18591. * Can be overrided for some chart.
  18592. * @return {type} description
  18593. */
  18594. getBaseAxis: function () {
  18595. var coordSys = this.coordinateSystem;
  18596. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  18597. },
  18598. // FIXME
  18599. /**
  18600. * Default tooltip formatter
  18601. *
  18602. * @param {number} dataIndex
  18603. * @param {boolean} [multipleSeries=false]
  18604. * @param {number} [dataType]
  18605. */
  18606. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  18607. function formatArrayValue(value) {
  18608. // ??? TODO refactor these logic.
  18609. // check: category-no-encode-has-axis-data in dataset.html
  18610. var vertially = reduce(value, function (vertially, val, idx) {
  18611. var dimItem = data.getDimensionInfo(idx);
  18612. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  18613. }, 0);
  18614. var result = [];
  18615. tooltipDims.length
  18616. ? each$1(tooltipDims, function (dim) {
  18617. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  18618. })
  18619. // By default, all dims is used on tooltip.
  18620. : each$1(value, setEachItem);
  18621. function setEachItem(val, dim) {
  18622. var dimInfo = data.getDimensionInfo(dim);
  18623. // If `dimInfo.tooltip` is not set, show tooltip.
  18624. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  18625. return;
  18626. }
  18627. var dimType = dimInfo.type;
  18628. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  18629. var valStr = (vertially
  18630. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  18631. : ''
  18632. )
  18633. // FIXME should not format time for raw data?
  18634. + encodeHTML(dimType === 'ordinal'
  18635. ? val + ''
  18636. : dimType === 'time'
  18637. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  18638. : addCommas(val)
  18639. );
  18640. valStr && result.push(valStr);
  18641. }
  18642. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  18643. }
  18644. function formatSingleValue(val) {
  18645. return encodeHTML(addCommas(val));
  18646. }
  18647. var data = this.getData();
  18648. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  18649. var tooltipDimLen = tooltipDims.length;
  18650. var value = this.getRawValue(dataIndex);
  18651. var isValueArr = isArray(value);
  18652. var color = data.getItemVisual(dataIndex, 'color');
  18653. if (isObject$1(color) && color.colorStops) {
  18654. color = (color.colorStops[0] || {}).color;
  18655. }
  18656. color = color || 'transparent';
  18657. // Complicated rule for pretty tooltip.
  18658. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  18659. ? formatArrayValue(value)
  18660. : tooltipDimLen
  18661. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  18662. : formatSingleValue(isValueArr ? value[0] : value);
  18663. var colorEl = getTooltipMarker(color);
  18664. var name = data.getName(dataIndex);
  18665. var seriesName = this.name;
  18666. if (seriesName === DEFAULT_COMPONENT_NAME) {
  18667. // Not show '-'
  18668. seriesName = '';
  18669. }
  18670. seriesName = seriesName
  18671. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  18672. : '';
  18673. return !multipleSeries
  18674. ? seriesName + colorEl
  18675. + (name
  18676. ? encodeHTML(name) + ': ' + formattedValue
  18677. : formattedValue
  18678. )
  18679. : colorEl + seriesName + formattedValue;
  18680. },
  18681. /**
  18682. * @return {boolean}
  18683. */
  18684. isAnimationEnabled: function () {
  18685. if (env$1.node) {
  18686. return false;
  18687. }
  18688. var animationEnabled = this.getShallow('animation');
  18689. if (animationEnabled) {
  18690. if (this.getData().count() > this.getShallow('animationThreshold')) {
  18691. animationEnabled = false;
  18692. }
  18693. }
  18694. return animationEnabled;
  18695. },
  18696. restoreData: function () {
  18697. this.dataTask.dirty();
  18698. },
  18699. getColorFromPalette: function (name, scope, requestColorNum) {
  18700. var ecModel = this.ecModel;
  18701. // PENDING
  18702. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  18703. if (!color) {
  18704. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  18705. }
  18706. return color;
  18707. },
  18708. /**
  18709. * Use `data.mapDimension(coordDim, true)` instead.
  18710. * @deprecated
  18711. */
  18712. coordDimToDataDim: function (coordDim) {
  18713. return this.getRawData().mapDimension(coordDim, true);
  18714. },
  18715. /**
  18716. * Get progressive rendering count each step
  18717. * @return {number}
  18718. */
  18719. getProgressive: function () {
  18720. return this.get('progressive');
  18721. },
  18722. /**
  18723. * Get progressive rendering count each step
  18724. * @return {number}
  18725. */
  18726. getProgressiveThreshold: function () {
  18727. return this.get('progressiveThreshold');
  18728. },
  18729. /**
  18730. * Get data indices for show tooltip content. See tooltip.
  18731. * @abstract
  18732. * @param {Array.<string>|string} dim
  18733. * @param {Array.<number>} value
  18734. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  18735. * @return {Object} {dataIndices, nestestValue}.
  18736. */
  18737. getAxisTooltipData: null,
  18738. /**
  18739. * See tooltip.
  18740. * @abstract
  18741. * @param {number} dataIndex
  18742. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  18743. */
  18744. getTooltipPosition: null,
  18745. /**
  18746. * @see {module:echarts/stream/Scheduler}
  18747. */
  18748. pipeTask: null,
  18749. /**
  18750. * Convinient for override in extended class.
  18751. * @protected
  18752. * @type {Function}
  18753. */
  18754. preventIncremental: null,
  18755. /**
  18756. * @public
  18757. * @readOnly
  18758. * @type {Object}
  18759. */
  18760. pipelineContext: null
  18761. });
  18762. mixin(SeriesModel, dataFormatMixin);
  18763. mixin(SeriesModel, colorPaletteMixin);
  18764. /**
  18765. * MUST be called after `prepareSource` called
  18766. * Here we need to make auto series, especially for auto legend. But we
  18767. * do not modify series.name in option to avoid side effects.
  18768. */
  18769. function autoSeriesName(seriesModel) {
  18770. // User specified name has higher priority, otherwise it may cause
  18771. // series can not be queried unexpectedly.
  18772. var name = seriesModel.name;
  18773. if (DEFAULT_COMPONENT_NAME === name) {
  18774. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  18775. }
  18776. }
  18777. function getSeriesAutoName(seriesModel) {
  18778. var data = seriesModel.getRawData();
  18779. var dataDims = data.mapDimension('seriesName', true);
  18780. var nameArr = [];
  18781. each$1(dataDims, function (dataDim) {
  18782. var dimInfo = data.getDimensionInfo(dataDim);
  18783. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  18784. });
  18785. return nameArr.join(' ');
  18786. }
  18787. function dataTaskCount(context) {
  18788. return context.model.getRawData().count();
  18789. }
  18790. function dataTaskReset(context) {
  18791. var seriesModel = context.model;
  18792. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  18793. return dataTaskProgress;
  18794. }
  18795. function dataTaskProgress(param, context) {
  18796. // Avoid repead cloneShallow when data just created in reset.
  18797. if (param.end > context.outputData.count()) {
  18798. context.model.getRawData().cloneShallow(context.outputData);
  18799. }
  18800. }
  18801. // TODO refactor
  18802. function wrapData(data, seriesModel) {
  18803. each$1(data.CHANGABLE_METHODS, function (methodName) {
  18804. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  18805. });
  18806. }
  18807. function onDataSelfChange(seriesModel) {
  18808. var task = getCurrentTask(seriesModel);
  18809. if (task) {
  18810. // Consider case: filter, selectRange
  18811. task.setOutputEnd(this.count());
  18812. }
  18813. }
  18814. function getCurrentTask(seriesModel) {
  18815. var scheduler = (seriesModel.ecModel || {}).scheduler;
  18816. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  18817. if (pipeline) {
  18818. // When pipline finished, the currrentTask keep the last
  18819. // task (renderTask).
  18820. var task = pipeline.currentTask;
  18821. if (task) {
  18822. var agentStubMap = task.agentStubMap;
  18823. if (agentStubMap) {
  18824. task = agentStubMap.get(seriesModel.uid);
  18825. }
  18826. }
  18827. return task;
  18828. }
  18829. }
  18830. var Component = function () {
  18831. /**
  18832. * @type {module:zrender/container/Group}
  18833. * @readOnly
  18834. */
  18835. this.group = new Group();
  18836. /**
  18837. * @type {string}
  18838. * @readOnly
  18839. */
  18840. this.uid = getUID('viewComponent');
  18841. };
  18842. Component.prototype = {
  18843. constructor: Component,
  18844. init: function (ecModel, api) {},
  18845. render: function (componentModel, ecModel, api, payload) {},
  18846. dispose: function () {}
  18847. };
  18848. var componentProto = Component.prototype;
  18849. componentProto.updateView
  18850. = componentProto.updateLayout
  18851. = componentProto.updateVisual
  18852. = function (seriesModel, ecModel, api, payload) {
  18853. // Do nothing;
  18854. };
  18855. // Enable Component.extend.
  18856. enableClassExtend(Component);
  18857. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  18858. enableClassManagement(Component, {registerWhenExtend: true});
  18859. /**
  18860. * @return {string} If large mode changed, return string 'reset';
  18861. */
  18862. var createRenderPlanner = function () {
  18863. var inner = makeInner();
  18864. return function (seriesModel) {
  18865. var fields = inner(seriesModel);
  18866. var pipelineContext = seriesModel.pipelineContext;
  18867. var originalLarge = fields.large;
  18868. var originalIncremental = fields.incrementalRender;
  18869. var large = fields.large = pipelineContext.large;
  18870. var incremental = fields.incrementalRender = pipelineContext.incrementalRender;
  18871. return ((originalLarge ^ large) || (originalIncremental ^ incremental)) && 'reset';
  18872. };
  18873. };
  18874. var inner$5 = makeInner();
  18875. var renderPlanner = createRenderPlanner();
  18876. function Chart() {
  18877. /**
  18878. * @type {module:zrender/container/Group}
  18879. * @readOnly
  18880. */
  18881. this.group = new Group();
  18882. /**
  18883. * @type {string}
  18884. * @readOnly
  18885. */
  18886. this.uid = getUID('viewChart');
  18887. this.renderTask = createTask({
  18888. plan: renderTaskPlan,
  18889. reset: renderTaskReset
  18890. });
  18891. this.renderTask.context = {view: this};
  18892. }
  18893. Chart.prototype = {
  18894. type: 'chart',
  18895. /**
  18896. * Init the chart.
  18897. * @param {module:echarts/model/Global} ecModel
  18898. * @param {module:echarts/ExtensionAPI} api
  18899. */
  18900. init: function (ecModel, api) {},
  18901. /**
  18902. * Render the chart.
  18903. * @param {module:echarts/model/Series} seriesModel
  18904. * @param {module:echarts/model/Global} ecModel
  18905. * @param {module:echarts/ExtensionAPI} api
  18906. * @param {Object} payload
  18907. */
  18908. render: function (seriesModel, ecModel, api, payload) {},
  18909. /**
  18910. * Highlight series or specified data item.
  18911. * @param {module:echarts/model/Series} seriesModel
  18912. * @param {module:echarts/model/Global} ecModel
  18913. * @param {module:echarts/ExtensionAPI} api
  18914. * @param {Object} payload
  18915. */
  18916. highlight: function (seriesModel, ecModel, api, payload) {
  18917. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  18918. },
  18919. /**
  18920. * Downplay series or specified data item.
  18921. * @param {module:echarts/model/Series} seriesModel
  18922. * @param {module:echarts/model/Global} ecModel
  18923. * @param {module:echarts/ExtensionAPI} api
  18924. * @param {Object} payload
  18925. */
  18926. downplay: function (seriesModel, ecModel, api, payload) {
  18927. toggleHighlight(seriesModel.getData(), payload, 'normal');
  18928. },
  18929. /**
  18930. * Remove self.
  18931. * @param {module:echarts/model/Global} ecModel
  18932. * @param {module:echarts/ExtensionAPI} api
  18933. */
  18934. remove: function (ecModel, api) {
  18935. this.group.removeAll();
  18936. },
  18937. /**
  18938. * Dispose self.
  18939. * @param {module:echarts/model/Global} ecModel
  18940. * @param {module:echarts/ExtensionAPI} api
  18941. */
  18942. dispose: function () {},
  18943. /**
  18944. * Rendering preparation in progressive mode.
  18945. * @param {module:echarts/model/Series} seriesModel
  18946. * @param {module:echarts/model/Global} ecModel
  18947. * @param {module:echarts/ExtensionAPI} api
  18948. * @param {Object} payload
  18949. */
  18950. incrementalPrepareRender: null,
  18951. /**
  18952. * Render in progressive mode.
  18953. * @param {module:echarts/model/Series} seriesModel
  18954. * @param {module:echarts/model/Global} ecModel
  18955. * @param {module:echarts/ExtensionAPI} api
  18956. * @param {Object} payload
  18957. */
  18958. incrementalRender: null,
  18959. /**
  18960. * Update transform directly.
  18961. * @param {module:echarts/model/Series} seriesModel
  18962. * @param {module:echarts/model/Global} ecModel
  18963. * @param {module:echarts/ExtensionAPI} api
  18964. * @param {Object} payload
  18965. * @return {Object} {update: true}
  18966. */
  18967. updateTransform: null
  18968. /**
  18969. * The view contains the given point.
  18970. * @interface
  18971. * @param {Array.<number>} point
  18972. * @return {boolean}
  18973. */
  18974. // containPoint: function () {}
  18975. };
  18976. var chartProto = Chart.prototype;
  18977. chartProto.updateView
  18978. = chartProto.updateLayout
  18979. = chartProto.updateVisual
  18980. = function (seriesModel, ecModel, api, payload) {
  18981. this.render(seriesModel, ecModel, api, payload);
  18982. };
  18983. /**
  18984. * Set state of single element
  18985. * @param {module:zrender/Element} el
  18986. * @param {string} state
  18987. */
  18988. function elSetState(el, state) {
  18989. if (el) {
  18990. el.trigger(state);
  18991. if (el.type === 'group') {
  18992. for (var i = 0; i < el.childCount(); i++) {
  18993. elSetState(el.childAt(i), state);
  18994. }
  18995. }
  18996. }
  18997. }
  18998. /**
  18999. * @param {module:echarts/data/List} data
  19000. * @param {Object} payload
  19001. * @param {string} state 'normal'|'emphasis'
  19002. */
  19003. function toggleHighlight(data, payload, state) {
  19004. var dataIndex = queryDataIndex(data, payload);
  19005. if (dataIndex != null) {
  19006. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  19007. elSetState(data.getItemGraphicEl(dataIdx), state);
  19008. });
  19009. }
  19010. else {
  19011. data.eachItemGraphicEl(function (el) {
  19012. elSetState(el, state);
  19013. });
  19014. }
  19015. }
  19016. // Enable Chart.extend.
  19017. enableClassExtend(Chart, ['dispose']);
  19018. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  19019. enableClassManagement(Chart, {registerWhenExtend: true});
  19020. Chart.markUpdateMethod = function (payload, methodName) {
  19021. inner$5(payload).updateMethod = methodName;
  19022. };
  19023. function renderTaskPlan(context) {
  19024. return renderPlanner(context.model);
  19025. }
  19026. function renderTaskReset(context) {
  19027. var seriesModel = context.model;
  19028. var ecModel = context.ecModel;
  19029. var api = context.api;
  19030. var payload = context.payload;
  19031. // ???! remove updateView updateVisual
  19032. var incremental = seriesModel.pipelineContext.incrementalRender;
  19033. var view = context.view;
  19034. var updateMethod = payload && inner$5(payload).updateMethod;
  19035. var methodName = (incremental && view.incrementalPrepareRender)
  19036. ? 'incrementalPrepareRender'
  19037. : (updateMethod && view[updateMethod])
  19038. ? updateMethod
  19039. : 'render';
  19040. view[methodName](seriesModel, ecModel, api, payload);
  19041. return incremental ? renderTaskProgress : null;
  19042. }
  19043. function renderTaskProgress(params, context) {
  19044. context.view.incrementalRender(
  19045. params, context.model, context.ecModel, context.api, context.payload
  19046. );
  19047. }
  19048. /**
  19049. * @public
  19050. * @param {(Function)} fn
  19051. * @param {number} [delay=0] Unit: ms.
  19052. * @param {boolean} [debounce=false]
  19053. * true: If call interval less than `delay`, only the last call works.
  19054. * false: If call interval less than `delay, call works on fixed rate.
  19055. * @return {(Function)} throttled fn.
  19056. */
  19057. function throttle(fn, delay, debounce) {
  19058. var currCall;
  19059. var lastCall = 0;
  19060. var lastExec = 0;
  19061. var timer = null;
  19062. var diff;
  19063. var scope;
  19064. var args;
  19065. var debounceNextCall;
  19066. delay = delay || 0;
  19067. function exec() {
  19068. lastExec = (new Date()).getTime();
  19069. timer = null;
  19070. fn.apply(scope, args || []);
  19071. }
  19072. var cb = function () {
  19073. currCall = (new Date()).getTime();
  19074. scope = this;
  19075. args = arguments;
  19076. var thisDelay = debounceNextCall || delay;
  19077. var thisDebounce = debounceNextCall || debounce;
  19078. debounceNextCall = null;
  19079. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  19080. clearTimeout(timer);
  19081. if (thisDebounce) {
  19082. timer = setTimeout(exec, thisDelay);
  19083. }
  19084. else {
  19085. if (diff >= 0) {
  19086. exec();
  19087. }
  19088. else {
  19089. timer = setTimeout(exec, -diff);
  19090. }
  19091. }
  19092. lastCall = currCall;
  19093. };
  19094. /**
  19095. * Clear throttle.
  19096. * @public
  19097. */
  19098. cb.clear = function () {
  19099. if (timer) {
  19100. clearTimeout(timer);
  19101. timer = null;
  19102. }
  19103. };
  19104. /**
  19105. * Enable debounce once.
  19106. */
  19107. cb.debounceNextCall = function (debounceDelay) {
  19108. debounceNextCall = debounceDelay;
  19109. };
  19110. return cb;
  19111. }
  19112. /**
  19113. * Create throttle method or update throttle rate.
  19114. *
  19115. * @example
  19116. * ComponentView.prototype.render = function () {
  19117. * ...
  19118. * throttle.createOrUpdate(
  19119. * this,
  19120. * '_dispatchAction',
  19121. * this.model.get('throttle'),
  19122. * 'fixRate'
  19123. * );
  19124. * };
  19125. * ComponentView.prototype.remove = function () {
  19126. * throttle.clear(this, '_dispatchAction');
  19127. * };
  19128. * ComponentView.prototype.dispose = function () {
  19129. * throttle.clear(this, '_dispatchAction');
  19130. * };
  19131. *
  19132. * @public
  19133. * @param {Object} obj
  19134. * @param {string} fnAttr
  19135. * @param {number} [rate]
  19136. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  19137. * @return {Function} throttled function.
  19138. */
  19139. /**
  19140. * Clear throttle. Example see throttle.createOrUpdate.
  19141. *
  19142. * @public
  19143. * @param {Object} obj
  19144. * @param {string} fnAttr
  19145. */
  19146. var seriesColor = {
  19147. createOnAllSeries: true,
  19148. performRawSeries: true,
  19149. reset: function (seriesModel, ecModel) {
  19150. var data = seriesModel.getData();
  19151. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  19152. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  19153. || seriesModel.getColorFromPalette(
  19154. // TODO series count changed.
  19155. seriesModel.get('name'), null, ecModel.getSeriesCount()
  19156. ); // Default color
  19157. // FIXME Set color function or use the platte color
  19158. data.setVisual('color', color);
  19159. // Only visible series has each data be visual encoded
  19160. if (!ecModel.isSeriesFiltered(seriesModel)) {
  19161. if (typeof color === 'function' && !(color instanceof Gradient)) {
  19162. data.each(function (idx) {
  19163. data.setItemVisual(
  19164. idx, 'color', color(seriesModel.getDataParams(idx))
  19165. );
  19166. });
  19167. }
  19168. // itemStyle in each data item
  19169. var dataEach = function (data, idx) {
  19170. var itemModel = data.getItemModel(idx);
  19171. var color = itemModel.get(colorAccessPath, true);
  19172. if (color != null) {
  19173. data.setItemVisual(idx, 'color', color);
  19174. }
  19175. };
  19176. return { dataEach: data.hasItemOption ? dataEach : null };
  19177. }
  19178. }
  19179. };
  19180. var lang = {
  19181. toolbox: {
  19182. brush: {
  19183. title: {
  19184. rect: '矩形选择',
  19185. polygon: '圈选',
  19186. lineX: '横向选择',
  19187. lineY: '纵向选择',
  19188. keep: '保持选择',
  19189. clear: '清除选择'
  19190. }
  19191. },
  19192. dataView: {
  19193. title: '数据视图',
  19194. lang: ['数据视图', '关闭', '刷新']
  19195. },
  19196. dataZoom: {
  19197. title: {
  19198. zoom: '区域缩放',
  19199. back: '区域缩放还原'
  19200. }
  19201. },
  19202. magicType: {
  19203. title: {
  19204. line: '切换为折线图',
  19205. bar: '切换为柱状图',
  19206. stack: '切换为堆叠',
  19207. tiled: '切换为平铺'
  19208. }
  19209. },
  19210. restore: {
  19211. title: '还原'
  19212. },
  19213. saveAsImage: {
  19214. title: '保存为图片',
  19215. lang: ['右键另存为图片']
  19216. }
  19217. },
  19218. series: {
  19219. typeNames: {
  19220. pie: '饼图',
  19221. bar: '柱状图',
  19222. line: '折线图',
  19223. scatter: '散点图',
  19224. effectScatter: '涟漪散点图',
  19225. radar: '雷达图',
  19226. tree: '树图',
  19227. treemap: '矩形树图',
  19228. boxplot: '箱型图',
  19229. candlestick: 'K线图',
  19230. k: 'K线图',
  19231. heatmap: '热力图',
  19232. map: '地图',
  19233. parallel: '平行坐标图',
  19234. lines: '线图',
  19235. graph: '关系图',
  19236. sankey: '桑基图',
  19237. funnel: '漏斗图',
  19238. gauge: '仪表盘图',
  19239. pictorialBar: '象形柱图',
  19240. themeRiver: '主题河流图',
  19241. sunburst: '旭日图'
  19242. }
  19243. },
  19244. aria: {
  19245. general: {
  19246. withTitle: '这是一个关于“{title}”的图表。',
  19247. withoutTitle: '这是一个图表,'
  19248. },
  19249. series: {
  19250. single: {
  19251. prefix: '',
  19252. withName: '图表类型是{seriesType},表示{seriesName}。',
  19253. withoutName: '图表类型是{seriesType}。'
  19254. },
  19255. multiple: {
  19256. prefix: '它由{seriesCount}个图表系列组成。',
  19257. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  19258. withoutName: '第{seriesId}个系列是一个{seriesType},',
  19259. separator: {
  19260. middle: ';',
  19261. end: '。'
  19262. }
  19263. }
  19264. },
  19265. data: {
  19266. allData: '其数据是——',
  19267. partialData: '其中,前{displayCnt}项是——',
  19268. withName: '{name}的数据是{value}',
  19269. withoutName: '{value}',
  19270. separator: {
  19271. middle: ',',
  19272. end: ''
  19273. }
  19274. }
  19275. }
  19276. };
  19277. var aria = function (dom, ecModel) {
  19278. var ariaModel = ecModel.getModel('aria');
  19279. if (!ariaModel.get('show')) {
  19280. return;
  19281. }
  19282. else if (ariaModel.get('description')) {
  19283. dom.setAttribute('aria-label', ariaModel.get('description'));
  19284. return;
  19285. }
  19286. var seriesCnt = 0;
  19287. ecModel.eachSeries(function (seriesModel, idx) {
  19288. ++seriesCnt;
  19289. }, this);
  19290. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  19291. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  19292. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  19293. var ariaLabel;
  19294. if (seriesCnt < 1) {
  19295. // No series, no aria label
  19296. return;
  19297. }
  19298. else {
  19299. var title = getTitle();
  19300. if (title) {
  19301. ariaLabel = replace(getConfig('general.withTitle'), {
  19302. title: title
  19303. });
  19304. }
  19305. else {
  19306. ariaLabel = getConfig('general.withoutTitle');
  19307. }
  19308. var seriesLabels = [];
  19309. var prefix = seriesCnt > 1
  19310. ? 'series.multiple.prefix'
  19311. : 'series.single.prefix';
  19312. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  19313. ecModel.eachSeries(function (seriesModel, idx) {
  19314. if (idx < displaySeriesCnt) {
  19315. var seriesLabel;
  19316. var seriesName = seriesModel.get('name');
  19317. var seriesTpl = 'series.'
  19318. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  19319. seriesLabel = getConfig(seriesName
  19320. ? seriesTpl + 'withName'
  19321. : seriesTpl + 'withoutName');
  19322. seriesLabel = replace(seriesLabel, {
  19323. seriesId: seriesModel.seriesIndex,
  19324. seriesName: seriesModel.get('name'),
  19325. seriesType: getSeriesTypeName(seriesModel.subType)
  19326. });
  19327. var data = seriesModel.getData();
  19328. window.data = data;
  19329. if (data.count() > maxDataCnt) {
  19330. // Show part of data
  19331. seriesLabel += replace(getConfig('data.partialData'), {
  19332. displayCnt: maxDataCnt
  19333. });
  19334. }
  19335. else {
  19336. seriesLabel += getConfig('data.allData');
  19337. }
  19338. var dataLabels = [];
  19339. for (var i = 0; i < data.count(); i++) {
  19340. if (i < maxDataCnt) {
  19341. var name = data.getName(i);
  19342. var value = retrieveRawValue(data, i);
  19343. dataLabels.push(
  19344. replace(
  19345. name
  19346. ? getConfig('data.withName')
  19347. : getConfig('data.withoutName'),
  19348. {
  19349. name: name,
  19350. value: value
  19351. }
  19352. )
  19353. );
  19354. }
  19355. }
  19356. seriesLabel += dataLabels
  19357. .join(getConfig('data.separator.middle'))
  19358. + getConfig('data.separator.end');
  19359. seriesLabels.push(seriesLabel);
  19360. }
  19361. });
  19362. ariaLabel += seriesLabels
  19363. .join(getConfig('series.multiple.separator.middle'))
  19364. + getConfig('series.multiple.separator.end');
  19365. dom.setAttribute('aria-label', ariaLabel);
  19366. }
  19367. function replace(str, keyValues) {
  19368. if (typeof str !== 'string') {
  19369. return str;
  19370. }
  19371. var result = str;
  19372. each$1(keyValues, function (value, key) {
  19373. result = result.replace(
  19374. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  19375. value
  19376. );
  19377. });
  19378. return result;
  19379. }
  19380. function getConfig(path) {
  19381. var userConfig = ariaModel.get(path);
  19382. if (userConfig == null) {
  19383. var pathArr = path.split('.');
  19384. var result = lang.aria;
  19385. for (var i = 0; i < pathArr.length; ++i) {
  19386. result = result[pathArr[i]];
  19387. }
  19388. return result;
  19389. }
  19390. else {
  19391. return userConfig;
  19392. }
  19393. }
  19394. function getTitle() {
  19395. var title = ecModel.getModel('title').option;
  19396. if (title && title.length) {
  19397. title = title[0];
  19398. }
  19399. return title && title.text;
  19400. }
  19401. function getSeriesTypeName(type) {
  19402. return lang.series.typeNames[type] || '自定义图';
  19403. }
  19404. };
  19405. var PI$1 = Math.PI;
  19406. /**
  19407. * @param {module:echarts/ExtensionAPI} api
  19408. * @param {Object} [opts]
  19409. * @param {string} [opts.text]
  19410. * @param {string} [opts.color]
  19411. * @param {string} [opts.textColor]
  19412. * @return {module:zrender/Element}
  19413. */
  19414. var loadingDefault = function (api, opts) {
  19415. opts = opts || {};
  19416. defaults(opts, {
  19417. text: 'loading',
  19418. color: '#c23531',
  19419. textColor: '#000',
  19420. maskColor: 'rgba(255, 255, 255, 0.8)',
  19421. zlevel: 0
  19422. });
  19423. var mask = new Rect({
  19424. style: {
  19425. fill: opts.maskColor
  19426. },
  19427. zlevel: opts.zlevel,
  19428. z: 10000
  19429. });
  19430. var arc = new Arc({
  19431. shape: {
  19432. startAngle: -PI$1 / 2,
  19433. endAngle: -PI$1 / 2 + 0.1,
  19434. r: 10
  19435. },
  19436. style: {
  19437. stroke: opts.color,
  19438. lineCap: 'round',
  19439. lineWidth: 5
  19440. },
  19441. zlevel: opts.zlevel,
  19442. z: 10001
  19443. });
  19444. var labelRect = new Rect({
  19445. style: {
  19446. fill: 'none',
  19447. text: opts.text,
  19448. textPosition: 'right',
  19449. textDistance: 10,
  19450. textFill: opts.textColor
  19451. },
  19452. zlevel: opts.zlevel,
  19453. z: 10001
  19454. });
  19455. arc.animateShape(true)
  19456. .when(1000, {
  19457. endAngle: PI$1 * 3 / 2
  19458. })
  19459. .start('circularInOut');
  19460. arc.animateShape(true)
  19461. .when(1000, {
  19462. startAngle: PI$1 * 3 / 2
  19463. })
  19464. .delay(300)
  19465. .start('circularInOut');
  19466. var group = new Group();
  19467. group.add(arc);
  19468. group.add(labelRect);
  19469. group.add(mask);
  19470. // Inject resize
  19471. group.resize = function () {
  19472. var cx = api.getWidth() / 2;
  19473. var cy = api.getHeight() / 2;
  19474. arc.setShape({
  19475. cx: cx,
  19476. cy: cy
  19477. });
  19478. var r = arc.shape.r;
  19479. labelRect.setShape({
  19480. x: cx - r,
  19481. y: cy - r,
  19482. width: r * 2,
  19483. height: r * 2
  19484. });
  19485. mask.setShape({
  19486. x: 0,
  19487. y: 0,
  19488. width: api.getWidth(),
  19489. height: api.getHeight()
  19490. });
  19491. };
  19492. group.resize();
  19493. return group;
  19494. };
  19495. /**
  19496. * @module echarts/stream/Scheduler
  19497. */
  19498. /**
  19499. * @constructor
  19500. */
  19501. function Scheduler(ecInstance, api) {
  19502. // this._pipelineMap = createHashMap();
  19503. this.ecInstance = ecInstance;
  19504. this.api = api;
  19505. this.unfinished;
  19506. /**
  19507. * @private
  19508. * @type {
  19509. * [handlerUID: string]: {
  19510. * seriesTaskMap?: {
  19511. * [seriesUID: string]: Task
  19512. * },
  19513. * overallTask?: Task
  19514. * }
  19515. * }
  19516. */
  19517. this._stageTaskMap = createHashMap();
  19518. }
  19519. var proto = Scheduler.prototype;
  19520. // If seriesModel provided, incremental threshold is check by series data.
  19521. proto.getPerformArgs = function (task, isBlock) {
  19522. // For overall task
  19523. if (!task.__pipeline) {
  19524. return;
  19525. }
  19526. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  19527. var pCtx = pipeline.context;
  19528. var incremental = !isBlock
  19529. && pipeline.progressiveEnabled
  19530. && (!pCtx || pCtx.incrementalRender)
  19531. && task.__idxInPipeline > pipeline.bockIndex;
  19532. return {step: incremental ? pipeline.step : null};
  19533. };
  19534. proto.getPipeline = function (pipelineId) {
  19535. return this._pipelineMap.get(pipelineId);
  19536. };
  19537. /**
  19538. * Current, progressive rendering starts from visual and layout.
  19539. * Always detect render mode in the same stage, avoiding that incorrect
  19540. * detection caused by data filtering.
  19541. * Caution:
  19542. * `updateStreamModes` use `seriesModel.getData()`.
  19543. */
  19544. proto.updateStreamModes = function (seriesModel, view) {
  19545. var pipeline = this._pipelineMap.get(seriesModel.uid);
  19546. var data = seriesModel.getData();
  19547. var dataLen = data.count();
  19548. var incrementalRender = pipeline.progressiveEnabled
  19549. && view.incrementalPrepareRender
  19550. && dataLen >= pipeline.threshold;
  19551. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  19552. seriesModel.pipelineContext = pipeline.context = {
  19553. incrementalRender: incrementalRender,
  19554. large: large
  19555. };
  19556. };
  19557. proto.restorePipelines = function (ecModel) {
  19558. var scheduler = this;
  19559. var pipelineMap = scheduler._pipelineMap = createHashMap();
  19560. ecModel.eachSeries(function (seriesModel) {
  19561. var progressive = seriesModel.getProgressive();
  19562. var pipelineId = seriesModel.uid;
  19563. pipelineMap.set(pipelineId, {
  19564. id: pipelineId,
  19565. head: null,
  19566. tail: null,
  19567. threshold: seriesModel.getProgressiveThreshold(),
  19568. progressiveEnabled: progressive
  19569. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  19570. bockIndex: -1,
  19571. step: progressive || 700, // ??? Temporarily number
  19572. count: 0
  19573. });
  19574. pipe(scheduler, seriesModel, seriesModel.dataTask);
  19575. });
  19576. };
  19577. proto.prepareStageTasks = function (stageHandlers, useClearVisual) {
  19578. var stageTaskMap = this._stageTaskMap;
  19579. var ecModel = this.ecInstance.getModel();
  19580. var api = this.api;
  19581. each$1(stageHandlers, function (handler) {
  19582. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  19583. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  19584. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  19585. }, this);
  19586. };
  19587. proto.prepareView = function (view, model, ecModel, api) {
  19588. var renderTask = view.renderTask;
  19589. var context = renderTask.context;
  19590. context.model = model;
  19591. context.ecModel = ecModel;
  19592. context.api = api;
  19593. renderTask.__block = !view.incrementalPrepareRender;
  19594. pipe(this, model, renderTask);
  19595. };
  19596. proto.performDataProcessorTasks = function (stageHandlers, ecModel, payload) {
  19597. // If we do not use `block` here, it should be considered when to update modes.
  19598. performStageTasks(this, stageHandlers, ecModel, payload, {block: true});
  19599. };
  19600. // opt
  19601. // opt.visualType: 'visual' or 'layout'
  19602. // opt.setDirty
  19603. proto.performVisualTasks = function (stageHandlers, ecModel, payload, opt) {
  19604. performStageTasks(this, stageHandlers, ecModel, payload, opt);
  19605. };
  19606. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  19607. opt = opt || {};
  19608. var unfinished;
  19609. each$1(stageHandlers, function (stageHandler, idx) {
  19610. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  19611. return;
  19612. }
  19613. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  19614. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  19615. var overallTask = stageHandlerRecord.overallTask;
  19616. if (overallTask) {
  19617. var overallNeedDirty;
  19618. var agentStubMap = overallTask.agentStubMap;
  19619. agentStubMap.each(function (stub) {
  19620. if (needSetDirty(opt, stub)) {
  19621. stub.dirty();
  19622. overallNeedDirty = true;
  19623. }
  19624. });
  19625. overallNeedDirty && overallTask.dirty();
  19626. updatePayload(overallTask, payload);
  19627. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  19628. // Execute stubs firstly, which may set the overall task dirty,
  19629. // then execute the overall task. And stub will call seriesModel.setData,
  19630. // which ensures that in the overallTask seriesModel.getData() will not
  19631. // return incorrect data.
  19632. agentStubMap.each(function (stub) {
  19633. stub.perform(performArgs);
  19634. });
  19635. unfinished |= overallTask.perform(performArgs);
  19636. }
  19637. else if (seriesTaskMap) {
  19638. seriesTaskMap.each(function (task, pipelineId) {
  19639. if (needSetDirty(opt, task)) {
  19640. task.dirty();
  19641. }
  19642. var performArgs = scheduler.getPerformArgs(task, opt.block);
  19643. performArgs.skip = !stageHandler.performRawSeries
  19644. && ecModel.isSeriesFiltered(task.context.model);
  19645. updatePayload(task, payload);
  19646. unfinished |= task.perform(performArgs);
  19647. });
  19648. }
  19649. });
  19650. function needSetDirty(opt, task) {
  19651. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  19652. }
  19653. scheduler.unfinished |= unfinished;
  19654. }
  19655. proto.performSeriesTasks = function (ecModel) {
  19656. var unfinished;
  19657. ecModel.eachSeries(function (seriesModel) {
  19658. // Progress to the end for dataInit and dataRestore.
  19659. unfinished |= seriesModel.dataTask.perform();
  19660. });
  19661. this.unfinished |= unfinished;
  19662. };
  19663. proto.plan = function () {
  19664. // Travel pipelines, check block.
  19665. this._pipelineMap.each(function (pipeline) {
  19666. var task = pipeline.tail;
  19667. do {
  19668. if (task.__block) {
  19669. pipeline.bockIndex = task.__idxInPipeline;
  19670. break;
  19671. }
  19672. task = task.getUpstream();
  19673. }
  19674. while (task);
  19675. });
  19676. };
  19677. var updatePayload = proto.updatePayload = function (task, payload) {
  19678. payload !== 'remain' && (task.context.payload = payload);
  19679. };
  19680. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  19681. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  19682. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  19683. var seriesType = stageHandler.seriesType;
  19684. var getTargetSeries = stageHandler.getTargetSeries;
  19685. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  19686. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  19687. // it works but it may cause other irrelevant charts blocked.
  19688. if (stageHandler.createOnAllSeries) {
  19689. ecModel.eachRawSeries(create);
  19690. }
  19691. else if (seriesType) {
  19692. ecModel.eachRawSeriesByType(seriesType, create);
  19693. }
  19694. else if (getTargetSeries) {
  19695. getTargetSeries(ecModel, api).each(create);
  19696. }
  19697. function create(seriesModel) {
  19698. var pipelineId = seriesModel.uid;
  19699. // Init tasks for each seriesModel only once.
  19700. // Reuse original task instance.
  19701. var task = seriesTaskMap.get(pipelineId)
  19702. || seriesTaskMap.set(pipelineId, createTask({
  19703. plan: seriesTaskPlan,
  19704. reset: seriesTaskReset,
  19705. count: seriesTaskCount
  19706. }));
  19707. task.context = {
  19708. model: seriesModel,
  19709. ecModel: ecModel,
  19710. api: api,
  19711. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  19712. plan: stageHandler.plan,
  19713. reset: stageHandler.reset,
  19714. scheduler: scheduler
  19715. };
  19716. pipe(scheduler, seriesModel, task);
  19717. }
  19718. // Clear unused series tasks.
  19719. var pipelineMap = scheduler._pipelineMap;
  19720. seriesTaskMap.each(function (task, pipelineId) {
  19721. if (!pipelineMap.get(pipelineId)) {
  19722. task.dispose();
  19723. seriesTaskMap.removeKey(pipelineId);
  19724. }
  19725. });
  19726. }
  19727. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  19728. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  19729. // For overall task, the function only be called on reset stage.
  19730. || createTask({reset: overallTaskReset});
  19731. overallTask.context = {
  19732. ecModel: ecModel,
  19733. api: api,
  19734. overallReset: stageHandler.overallReset,
  19735. scheduler: scheduler
  19736. };
  19737. // Reuse orignal stubs.
  19738. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  19739. var seriesType = stageHandler.seriesType;
  19740. var getTargetSeries = stageHandler.getTargetSeries;
  19741. var overallProgress = true;
  19742. var isOverallFilter = stageHandler.isOverallFilter;
  19743. // An overall task with seriesType detected or has `getTargetSeries`, we add
  19744. // stub in each pipelines, it will set the overall task dirty when the pipeline
  19745. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  19746. // we set the pipeline block.
  19747. if (seriesType) {
  19748. ecModel.eachRawSeriesByType(seriesType, createStub);
  19749. }
  19750. else if (getTargetSeries) {
  19751. getTargetSeries(ecModel, api).each(createStub);
  19752. }
  19753. // Otherwise, (usually it is legancy case), the overall task will only be
  19754. // executed when upstream dirty. Otherwise the progressive rendering of all
  19755. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  19756. // dirty info from upsteam.
  19757. else {
  19758. overallProgress = false;
  19759. each$1(ecModel.getSeries(), createStub);
  19760. }
  19761. function createStub(seriesModel) {
  19762. var pipelineId = seriesModel.uid;
  19763. var stub = agentStubMap.get(pipelineId) || agentStubMap.set(pipelineId, createTask(
  19764. {reset: stubReset, onDirty: stubOnDirty}
  19765. ));
  19766. stub.context = {
  19767. model: seriesModel,
  19768. overallProgress: overallProgress,
  19769. isOverallFilter: isOverallFilter
  19770. };
  19771. stub.agent = overallTask;
  19772. stub.__block = overallProgress;
  19773. pipe(scheduler, seriesModel, stub);
  19774. }
  19775. // Clear unused stubs.
  19776. var pipelineMap = scheduler._pipelineMap;
  19777. agentStubMap.each(function (stub, pipelineId) {
  19778. if (!pipelineMap.get(pipelineId)) {
  19779. stub.dispose();
  19780. agentStubMap.removeKey(pipelineId);
  19781. }
  19782. });
  19783. }
  19784. function overallTaskReset(context) {
  19785. context.overallReset(
  19786. context.ecModel, context.api, context.payload
  19787. );
  19788. }
  19789. function stubReset(context, upstreamContext) {
  19790. return context.overallProgress && stubProgress;
  19791. }
  19792. function stubProgress() {
  19793. this.agent.dirty();
  19794. this.getDownstream().dirty();
  19795. }
  19796. function stubOnDirty() {
  19797. this.agent && this.agent.dirty();
  19798. }
  19799. function seriesTaskPlan(context) {
  19800. return context.plan && context.plan(
  19801. context.model, context.ecModel, context.api, context.payload
  19802. );
  19803. }
  19804. function seriesTaskReset(context) {
  19805. if (context.useClearVisual) {
  19806. context.data.clearAllVisual();
  19807. }
  19808. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  19809. context.model, context.ecModel, context.api, context.payload
  19810. ));
  19811. if (resetDefines.length) {
  19812. return seriesTaskProgress;
  19813. }
  19814. }
  19815. function seriesTaskProgress(params, context) {
  19816. var data = context.data;
  19817. var resetDefines = context.resetDefines;
  19818. for (var k = 0; k < resetDefines.length; k++) {
  19819. var resetDefine = resetDefines[k];
  19820. if (resetDefine && resetDefine.dataEach) {
  19821. for (var i = params.start; i < params.end; i++) {
  19822. resetDefine.dataEach(data, i);
  19823. }
  19824. }
  19825. else if (resetDefine && resetDefine.progress) {
  19826. resetDefine.progress(params, data);
  19827. }
  19828. }
  19829. }
  19830. function seriesTaskCount(context) {
  19831. return context.data.count();
  19832. }
  19833. function pipe(scheduler, seriesModel, task) {
  19834. var pipelineId = seriesModel.uid;
  19835. var pipeline = scheduler._pipelineMap.get(pipelineId);
  19836. !pipeline.head && (pipeline.head = task);
  19837. pipeline.tail && pipeline.tail.pipe(task);
  19838. pipeline.tail = task;
  19839. task.__idxInPipeline = pipeline.count++;
  19840. task.__pipeline = pipeline;
  19841. }
  19842. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  19843. if (isFunction$1(stageHandler)) {
  19844. stageHandler = {
  19845. overallReset: stageHandler,
  19846. seriesType: detectSeriseType(stageHandler)
  19847. };
  19848. }
  19849. stageHandler.uid = getUID('stageHandler');
  19850. visualType && (stageHandler.visualType = visualType);
  19851. return stageHandler;
  19852. };
  19853. /**
  19854. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  19855. * To ensure that they can work normally, they should work in block mode, that is,
  19856. * they should not be started util the previous tasks finished. So they cause the
  19857. * progressive rendering disabled. We try to detect the series type, to narrow down
  19858. * the block range to only the series type they concern, but not all series.
  19859. */
  19860. function detectSeriseType(legacyFunc) {
  19861. seriesType = null;
  19862. try {
  19863. // Assume there is no async when calling `eachSeriesByType`.
  19864. legacyFunc(ecModelMock, apiMock);
  19865. }
  19866. catch (e) {
  19867. }
  19868. return seriesType;
  19869. }
  19870. var ecModelMock = {};
  19871. var apiMock = {};
  19872. var seriesType;
  19873. mockMethods(ecModelMock, GlobalModel);
  19874. mockMethods(apiMock, ExtensionAPI);
  19875. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  19876. seriesType = type;
  19877. };
  19878. ecModelMock.eachComponent = function (cond) {
  19879. if (cond.mainType === 'series' && cond.subType) {
  19880. seriesType = cond.subType;
  19881. }
  19882. };
  19883. function mockMethods(target, Clz) {
  19884. for (var name in Clz.prototype) {
  19885. // Do not use hasOwnProperty
  19886. target[name] = noop;
  19887. }
  19888. }
  19889. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  19890. var lightTheme = {
  19891. color: colorAll,
  19892. colorLayer: [
  19893. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  19894. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  19895. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  19896. colorAll
  19897. ]
  19898. };
  19899. var contrastColor = '#eee';
  19900. var axisCommon = function () {
  19901. return {
  19902. axisLine: {
  19903. lineStyle: {
  19904. color: contrastColor
  19905. }
  19906. },
  19907. axisTick: {
  19908. lineStyle: {
  19909. color: contrastColor
  19910. }
  19911. },
  19912. axisLabel: {
  19913. textStyle: {
  19914. color: contrastColor
  19915. }
  19916. },
  19917. splitLine: {
  19918. lineStyle: {
  19919. type: 'dashed',
  19920. color: '#aaa'
  19921. }
  19922. },
  19923. splitArea: {
  19924. areaStyle: {
  19925. color: contrastColor
  19926. }
  19927. }
  19928. };
  19929. };
  19930. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  19931. var theme = {
  19932. color: colorPalette,
  19933. backgroundColor: '#333',
  19934. tooltip: {
  19935. axisPointer: {
  19936. lineStyle: {
  19937. color: contrastColor
  19938. },
  19939. crossStyle: {
  19940. color: contrastColor
  19941. }
  19942. }
  19943. },
  19944. legend: {
  19945. textStyle: {
  19946. color: contrastColor
  19947. }
  19948. },
  19949. textStyle: {
  19950. color: contrastColor
  19951. },
  19952. title: {
  19953. textStyle: {
  19954. color: contrastColor
  19955. }
  19956. },
  19957. toolbox: {
  19958. iconStyle: {
  19959. normal: {
  19960. borderColor: contrastColor
  19961. }
  19962. }
  19963. },
  19964. dataZoom: {
  19965. textStyle: {
  19966. color: contrastColor
  19967. }
  19968. },
  19969. visualMap: {
  19970. textStyle: {
  19971. color: contrastColor
  19972. }
  19973. },
  19974. timeline: {
  19975. lineStyle: {
  19976. color: contrastColor
  19977. },
  19978. itemStyle: {
  19979. normal: {
  19980. color: colorPalette[1]
  19981. }
  19982. },
  19983. label: {
  19984. normal: {
  19985. textStyle: {
  19986. color: contrastColor
  19987. }
  19988. }
  19989. },
  19990. controlStyle: {
  19991. normal: {
  19992. color: contrastColor,
  19993. borderColor: contrastColor
  19994. }
  19995. }
  19996. },
  19997. timeAxis: axisCommon(),
  19998. logAxis: axisCommon(),
  19999. valueAxis: axisCommon(),
  20000. categoryAxis: axisCommon(),
  20001. line: {
  20002. symbol: 'circle'
  20003. },
  20004. graph: {
  20005. color: colorPalette
  20006. },
  20007. gauge: {
  20008. title: {
  20009. textStyle: {
  20010. color: contrastColor
  20011. }
  20012. }
  20013. },
  20014. candlestick: {
  20015. itemStyle: {
  20016. normal: {
  20017. color: '#FD1050',
  20018. color0: '#0CF49B',
  20019. borderColor: '#FD1050',
  20020. borderColor0: '#0CF49B'
  20021. }
  20022. }
  20023. }
  20024. };
  20025. theme.categoryAxis.splitLine.show = false;
  20026. /*!
  20027. * ECharts, a free, powerful charting and visualization library.
  20028. *
  20029. * Copyright (c) 2017, Baidu Inc.
  20030. * All rights reserved.
  20031. *
  20032. * LICENSE
  20033. * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt
  20034. */
  20035. var assert = assert$1;
  20036. var each = each$1;
  20037. var isFunction = isFunction$1;
  20038. var isObject = isObject$1;
  20039. var parseClassType = ComponentModel.parseClassType;
  20040. var version = '4.0.2';
  20041. var dependencies = {
  20042. zrender: '4.0.1'
  20043. };
  20044. var TEST_FRAME_REMAIN_TIME = 1;
  20045. var PRIORITY_PROCESSOR_FILTER = 1000;
  20046. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  20047. var PRIORITY_VISUAL_LAYOUT = 1000;
  20048. var PRIORITY_VISUAL_GLOBAL = 2000;
  20049. var PRIORITY_VISUAL_CHART = 3000;
  20050. var PRIORITY_VISUAL_COMPONENT = 4000;
  20051. // FIXME
  20052. // necessary?
  20053. var PRIORITY_VISUAL_BRUSH = 5000;
  20054. var PRIORITY = {
  20055. PROCESSOR: {
  20056. FILTER: PRIORITY_PROCESSOR_FILTER,
  20057. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  20058. },
  20059. VISUAL: {
  20060. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  20061. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  20062. CHART: PRIORITY_VISUAL_CHART,
  20063. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  20064. BRUSH: PRIORITY_VISUAL_BRUSH
  20065. }
  20066. };
  20067. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  20068. // where they must not be invoked nestedly, except the only case: invoke
  20069. // dispatchAction with updateMethod "none" in main process.
  20070. // This flag is used to carry out this rule.
  20071. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  20072. var IN_MAIN_PROCESS = '__flagInMainProcess';
  20073. var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg';
  20074. var OPTION_UPDATED = '__optionUpdated';
  20075. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  20076. function createRegisterEventWithLowercaseName(method) {
  20077. return function (eventName, handler, context) {
  20078. // Event name is all lowercase
  20079. eventName = eventName && eventName.toLowerCase();
  20080. Eventful.prototype[method].call(this, eventName, handler, context);
  20081. };
  20082. }
  20083. /**
  20084. * @module echarts~MessageCenter
  20085. */
  20086. function MessageCenter() {
  20087. Eventful.call(this);
  20088. }
  20089. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  20090. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  20091. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  20092. mixin(MessageCenter, Eventful);
  20093. /**
  20094. * @module echarts~ECharts
  20095. */
  20096. function ECharts(dom, theme$$1, opts) {
  20097. opts = opts || {};
  20098. // Get theme by name
  20099. if (typeof theme$$1 === 'string') {
  20100. theme$$1 = themeStorage[theme$$1];
  20101. }
  20102. /**
  20103. * @type {string}
  20104. */
  20105. this.id;
  20106. /**
  20107. * Group id
  20108. * @type {string}
  20109. */
  20110. this.group;
  20111. /**
  20112. * @type {HTMLElement}
  20113. * @private
  20114. */
  20115. this._dom = dom;
  20116. var defaultRenderer = 'canvas';
  20117. if (__DEV__) {
  20118. defaultRenderer = (
  20119. typeof window === 'undefined' ? global : window
  20120. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  20121. }
  20122. /**
  20123. * @type {module:zrender/ZRender}
  20124. * @private
  20125. */
  20126. var zr = this._zr = init$1(dom, {
  20127. renderer: opts.renderer || defaultRenderer,
  20128. devicePixelRatio: opts.devicePixelRatio,
  20129. width: opts.width,
  20130. height: opts.height
  20131. });
  20132. /**
  20133. * Expect 60 pfs.
  20134. * @type {Function}
  20135. * @private
  20136. */
  20137. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  20138. var theme$$1 = clone(theme$$1);
  20139. theme$$1 && backwardCompat(theme$$1, true);
  20140. /**
  20141. * @type {Object}
  20142. * @private
  20143. */
  20144. this._theme = theme$$1;
  20145. /**
  20146. * @type {Array.<module:echarts/view/Chart>}
  20147. * @private
  20148. */
  20149. this._chartsViews = [];
  20150. /**
  20151. * @type {Object.<string, module:echarts/view/Chart>}
  20152. * @private
  20153. */
  20154. this._chartsMap = {};
  20155. /**
  20156. * @type {Array.<module:echarts/view/Component>}
  20157. * @private
  20158. */
  20159. this._componentsViews = [];
  20160. /**
  20161. * @type {Object.<string, module:echarts/view/Component>}
  20162. * @private
  20163. */
  20164. this._componentsMap = {};
  20165. /**
  20166. * @type {module:echarts/CoordinateSystem}
  20167. * @private
  20168. */
  20169. this._coordSysMgr = new CoordinateSystemManager();
  20170. /**
  20171. * @type {module:echarts/ExtensionAPI}
  20172. * @private
  20173. */
  20174. var api = this._api = createExtensionAPI(this);
  20175. /**
  20176. * @type {module:echarts/stream/Scheduler}
  20177. */
  20178. this._scheduler = new Scheduler(this, api);
  20179. Eventful.call(this);
  20180. /**
  20181. * @type {module:echarts~MessageCenter}
  20182. * @private
  20183. */
  20184. this._messageCenter = new MessageCenter();
  20185. // this._scheduler = new Scheduler();
  20186. // Init mouse events
  20187. this._initEvents();
  20188. // In case some people write `window.onresize = chart.resize`
  20189. this.resize = bind(this.resize, this);
  20190. // Can't dispatch action during rendering procedure
  20191. this._pendingActions = [];
  20192. // Sort on demand
  20193. function prioritySortFunc(a, b) {
  20194. return a.__prio - b.__prio;
  20195. }
  20196. sort(visualFuncs, prioritySortFunc);
  20197. sort(dataProcessorFuncs, prioritySortFunc);
  20198. zr.animation.on('frame', this._onframe, this);
  20199. // ECharts instance can be used as value.
  20200. setAsPrimitive(this);
  20201. }
  20202. var echartsProto = ECharts.prototype;
  20203. echartsProto._onframe = function () {
  20204. if (this._disposed) {
  20205. return;
  20206. }
  20207. var scheduler = this._scheduler;
  20208. // Lazy update
  20209. if (this[OPTION_UPDATED]) {
  20210. var silent = this[OPTION_UPDATED].silent;
  20211. this[IN_MAIN_PROCESS] = true;
  20212. prepare(this);
  20213. updateMethods.update.call(this);
  20214. this[IN_MAIN_PROCESS] = false;
  20215. this[OPTION_UPDATED] = false;
  20216. flushPendingActions.call(this, silent);
  20217. triggerUpdatedEvent.call(this, silent);
  20218. }
  20219. // Avoid do both lazy update and progress in one frame.
  20220. else if (scheduler.unfinished) {
  20221. // Stream progress.
  20222. var remainTime = TEST_FRAME_REMAIN_TIME;
  20223. var ecModel = this._model;
  20224. var api = this._api;
  20225. scheduler.unfinished = false;
  20226. do {
  20227. var startTime = +new Date();
  20228. scheduler.performSeriesTasks(ecModel);
  20229. // Currently dataProcessorFuncs do not check threshold.
  20230. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel);
  20231. updateStreamModes(this, ecModel);
  20232. // Do not update coordinate system here. Because that coord system update in
  20233. // each frame is not a good user experience. So we follow the rule that
  20234. // the extent of the coordinate system is determin in the first frame (the
  20235. // frame is executed immedietely after task reset.
  20236. // this._coordSysMgr.update(ecModel, api);
  20237. // console.log('--- ec frame visual ---', remainTime);
  20238. scheduler.performVisualTasks(visualFuncs, ecModel);
  20239. renderSeries(this, this._model, api, 'remain');
  20240. remainTime -= (+new Date() - startTime);
  20241. }
  20242. while (remainTime > 0 && scheduler.unfinished);
  20243. if (!scheduler.unfinished) {
  20244. this._zr && this._zr.flush();
  20245. this.trigger('finished');
  20246. }
  20247. // Else, zr flushing be ensue within the same frame,
  20248. // because zr flushing is after onframe event.
  20249. }
  20250. };
  20251. /**
  20252. * @return {HTMLElement}
  20253. */
  20254. echartsProto.getDom = function () {
  20255. return this._dom;
  20256. };
  20257. /**
  20258. * @return {module:zrender~ZRender}
  20259. */
  20260. echartsProto.getZr = function () {
  20261. return this._zr;
  20262. };
  20263. /**
  20264. * Usage:
  20265. * chart.setOption(option, notMerge, lazyUpdate);
  20266. * chart.setOption(option, {
  20267. * notMerge: ...,
  20268. * lazyUpdate: ...,
  20269. * silent: ...
  20270. * });
  20271. *
  20272. * @param {Object} option
  20273. * @param {Object|boolean} [opts] opts or notMerge.
  20274. * @param {boolean} [opts.notMerge=false]
  20275. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  20276. */
  20277. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  20278. if (__DEV__) {
  20279. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  20280. }
  20281. var silent;
  20282. if (isObject(notMerge)) {
  20283. lazyUpdate = notMerge.lazyUpdate;
  20284. silent = notMerge.silent;
  20285. notMerge = notMerge.notMerge;
  20286. }
  20287. this[IN_MAIN_PROCESS] = true;
  20288. if (!this._model || notMerge) {
  20289. var optionManager = new OptionManager(this._api);
  20290. var theme$$1 = this._theme;
  20291. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  20292. ecModel.scheduler = this._scheduler;
  20293. ecModel.init(null, null, theme$$1, optionManager);
  20294. }
  20295. this._model.setOption(option, optionPreprocessorFuncs);
  20296. if (lazyUpdate) {
  20297. this[OPTION_UPDATED] = {silent: silent};
  20298. this[IN_MAIN_PROCESS] = false;
  20299. }
  20300. else {
  20301. prepare(this);
  20302. updateMethods.update.call(this);
  20303. // Ensure zr refresh sychronously, and then pixel in canvas can be
  20304. // fetched after `setOption`.
  20305. this._zr.flush();
  20306. this[OPTION_UPDATED] = false;
  20307. this[IN_MAIN_PROCESS] = false;
  20308. flushPendingActions.call(this, silent);
  20309. triggerUpdatedEvent.call(this, silent);
  20310. }
  20311. };
  20312. /**
  20313. * @DEPRECATED
  20314. */
  20315. echartsProto.setTheme = function () {
  20316. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  20317. };
  20318. /**
  20319. * @return {module:echarts/model/Global}
  20320. */
  20321. echartsProto.getModel = function () {
  20322. return this._model;
  20323. };
  20324. /**
  20325. * @return {Object}
  20326. */
  20327. echartsProto.getOption = function () {
  20328. return this._model && this._model.getOption();
  20329. };
  20330. /**
  20331. * @return {number}
  20332. */
  20333. echartsProto.getWidth = function () {
  20334. return this._zr.getWidth();
  20335. };
  20336. /**
  20337. * @return {number}
  20338. */
  20339. echartsProto.getHeight = function () {
  20340. return this._zr.getHeight();
  20341. };
  20342. /**
  20343. * @return {number}
  20344. */
  20345. echartsProto.getDevicePixelRatio = function () {
  20346. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  20347. };
  20348. /**
  20349. * Get canvas which has all thing rendered
  20350. * @param {Object} opts
  20351. * @param {string} [opts.backgroundColor]
  20352. * @return {string}
  20353. */
  20354. echartsProto.getRenderedCanvas = function (opts) {
  20355. if (!env$1.canvasSupported) {
  20356. return;
  20357. }
  20358. opts = opts || {};
  20359. opts.pixelRatio = opts.pixelRatio || 1;
  20360. opts.backgroundColor = opts.backgroundColor
  20361. || this._model.get('backgroundColor');
  20362. var zr = this._zr;
  20363. var list = zr.storage.getDisplayList();
  20364. // Stop animations
  20365. each$1(list, function (el) {
  20366. el.stopAnimation(true);
  20367. });
  20368. return zr.painter.getRenderedCanvas(opts);
  20369. };
  20370. /**
  20371. * Get svg data url
  20372. * @return {string}
  20373. */
  20374. echartsProto.getSvgDataUrl = function () {
  20375. if (!env$1.svgSupported) {
  20376. return;
  20377. }
  20378. var zr = this._zr;
  20379. var list = zr.storage.getDisplayList();
  20380. // Stop animations
  20381. each$1(list, function (el) {
  20382. el.stopAnimation(true);
  20383. });
  20384. return zr.painter.pathToSvg();
  20385. };
  20386. /**
  20387. * @return {string}
  20388. * @param {Object} opts
  20389. * @param {string} [opts.type='png']
  20390. * @param {string} [opts.pixelRatio=1]
  20391. * @param {string} [opts.backgroundColor]
  20392. * @param {string} [opts.excludeComponents]
  20393. */
  20394. echartsProto.getDataURL = function (opts) {
  20395. opts = opts || {};
  20396. var excludeComponents = opts.excludeComponents;
  20397. var ecModel = this._model;
  20398. var excludesComponentViews = [];
  20399. var self = this;
  20400. each(excludeComponents, function (componentType) {
  20401. ecModel.eachComponent({
  20402. mainType: componentType
  20403. }, function (component) {
  20404. var view = self._componentsMap[component.__viewId];
  20405. if (!view.group.ignore) {
  20406. excludesComponentViews.push(view);
  20407. view.group.ignore = true;
  20408. }
  20409. });
  20410. });
  20411. var url = this._zr.painter.getType() === 'svg'
  20412. ? this.getSvgDataUrl()
  20413. : this.getRenderedCanvas(opts).toDataURL(
  20414. 'image/' + (opts && opts.type || 'png')
  20415. );
  20416. each(excludesComponentViews, function (view) {
  20417. view.group.ignore = false;
  20418. });
  20419. return url;
  20420. };
  20421. /**
  20422. * @return {string}
  20423. * @param {Object} opts
  20424. * @param {string} [opts.type='png']
  20425. * @param {string} [opts.pixelRatio=1]
  20426. * @param {string} [opts.backgroundColor]
  20427. */
  20428. echartsProto.getConnectedDataURL = function (opts) {
  20429. if (!env$1.canvasSupported) {
  20430. return;
  20431. }
  20432. var groupId = this.group;
  20433. var mathMin = Math.min;
  20434. var mathMax = Math.max;
  20435. var MAX_NUMBER = Infinity;
  20436. if (connectedGroups[groupId]) {
  20437. var left = MAX_NUMBER;
  20438. var top = MAX_NUMBER;
  20439. var right = -MAX_NUMBER;
  20440. var bottom = -MAX_NUMBER;
  20441. var canvasList = [];
  20442. var dpr = (opts && opts.pixelRatio) || 1;
  20443. each$1(instances, function (chart, id) {
  20444. if (chart.group === groupId) {
  20445. var canvas = chart.getRenderedCanvas(
  20446. clone(opts)
  20447. );
  20448. var boundingRect = chart.getDom().getBoundingClientRect();
  20449. left = mathMin(boundingRect.left, left);
  20450. top = mathMin(boundingRect.top, top);
  20451. right = mathMax(boundingRect.right, right);
  20452. bottom = mathMax(boundingRect.bottom, bottom);
  20453. canvasList.push({
  20454. dom: canvas,
  20455. left: boundingRect.left,
  20456. top: boundingRect.top
  20457. });
  20458. }
  20459. });
  20460. left *= dpr;
  20461. top *= dpr;
  20462. right *= dpr;
  20463. bottom *= dpr;
  20464. var width = right - left;
  20465. var height = bottom - top;
  20466. var targetCanvas = createCanvas();
  20467. targetCanvas.width = width;
  20468. targetCanvas.height = height;
  20469. var zr = init$1(targetCanvas);
  20470. each(canvasList, function (item) {
  20471. var img = new ZImage({
  20472. style: {
  20473. x: item.left * dpr - left,
  20474. y: item.top * dpr - top,
  20475. image: item.dom
  20476. }
  20477. });
  20478. zr.add(img);
  20479. });
  20480. zr.refreshImmediately();
  20481. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  20482. }
  20483. else {
  20484. return this.getDataURL(opts);
  20485. }
  20486. };
  20487. /**
  20488. * Convert from logical coordinate system to pixel coordinate system.
  20489. * See CoordinateSystem#convertToPixel.
  20490. * @param {string|Object} finder
  20491. * If string, e.g., 'geo', means {geoIndex: 0}.
  20492. * If Object, could contain some of these properties below:
  20493. * {
  20494. * seriesIndex / seriesId / seriesName,
  20495. * geoIndex / geoId, geoName,
  20496. * bmapIndex / bmapId / bmapName,
  20497. * xAxisIndex / xAxisId / xAxisName,
  20498. * yAxisIndex / yAxisId / yAxisName,
  20499. * gridIndex / gridId / gridName,
  20500. * ... (can be extended)
  20501. * }
  20502. * @param {Array|number} value
  20503. * @return {Array|number} result
  20504. */
  20505. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  20506. /**
  20507. * Convert from pixel coordinate system to logical coordinate system.
  20508. * See CoordinateSystem#convertFromPixel.
  20509. * @param {string|Object} finder
  20510. * If string, e.g., 'geo', means {geoIndex: 0}.
  20511. * If Object, could contain some of these properties below:
  20512. * {
  20513. * seriesIndex / seriesId / seriesName,
  20514. * geoIndex / geoId / geoName,
  20515. * bmapIndex / bmapId / bmapName,
  20516. * xAxisIndex / xAxisId / xAxisName,
  20517. * yAxisIndex / yAxisId / yAxisName
  20518. * gridIndex / gridId / gridName,
  20519. * ... (can be extended)
  20520. * }
  20521. * @param {Array|number} value
  20522. * @return {Array|number} result
  20523. */
  20524. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  20525. function doConvertPixel(methodName, finder, value) {
  20526. var ecModel = this._model;
  20527. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  20528. var result;
  20529. finder = parseFinder(ecModel, finder);
  20530. for (var i = 0; i < coordSysList.length; i++) {
  20531. var coordSys = coordSysList[i];
  20532. if (coordSys[methodName]
  20533. && (result = coordSys[methodName](ecModel, finder, value)) != null
  20534. ) {
  20535. return result;
  20536. }
  20537. }
  20538. if (__DEV__) {
  20539. console.warn(
  20540. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  20541. );
  20542. }
  20543. }
  20544. /**
  20545. * Is the specified coordinate systems or components contain the given pixel point.
  20546. * @param {string|Object} finder
  20547. * If string, e.g., 'geo', means {geoIndex: 0}.
  20548. * If Object, could contain some of these properties below:
  20549. * {
  20550. * seriesIndex / seriesId / seriesName,
  20551. * geoIndex / geoId / geoName,
  20552. * bmapIndex / bmapId / bmapName,
  20553. * xAxisIndex / xAxisId / xAxisName,
  20554. * yAxisIndex / yAxisId / yAxisName,
  20555. * gridIndex / gridId / gridName,
  20556. * ... (can be extended)
  20557. * }
  20558. * @param {Array|number} value
  20559. * @return {boolean} result
  20560. */
  20561. echartsProto.containPixel = function (finder, value) {
  20562. var ecModel = this._model;
  20563. var result;
  20564. finder = parseFinder(ecModel, finder);
  20565. each$1(finder, function (models, key) {
  20566. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  20567. var coordSys = model.coordinateSystem;
  20568. if (coordSys && coordSys.containPoint) {
  20569. result |= !!coordSys.containPoint(value);
  20570. }
  20571. else if (key === 'seriesModels') {
  20572. var view = this._chartsMap[model.__viewId];
  20573. if (view && view.containPoint) {
  20574. result |= view.containPoint(value, model);
  20575. }
  20576. else {
  20577. if (__DEV__) {
  20578. console.warn(key + ': ' + (view
  20579. ? 'The found component do not support containPoint.'
  20580. : 'No view mapping to the found component.'
  20581. ));
  20582. }
  20583. }
  20584. }
  20585. else {
  20586. if (__DEV__) {
  20587. console.warn(key + ': containPoint is not supported');
  20588. }
  20589. }
  20590. }, this);
  20591. }, this);
  20592. return !!result;
  20593. };
  20594. /**
  20595. * Get visual from series or data.
  20596. * @param {string|Object} finder
  20597. * If string, e.g., 'series', means {seriesIndex: 0}.
  20598. * If Object, could contain some of these properties below:
  20599. * {
  20600. * seriesIndex / seriesId / seriesName,
  20601. * dataIndex / dataIndexInside
  20602. * }
  20603. * If dataIndex is not specified, series visual will be fetched,
  20604. * but not data item visual.
  20605. * If all of seriesIndex, seriesId, seriesName are not specified,
  20606. * visual will be fetched from first series.
  20607. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  20608. */
  20609. echartsProto.getVisual = function (finder, visualType) {
  20610. var ecModel = this._model;
  20611. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  20612. var seriesModel = finder.seriesModel;
  20613. if (__DEV__) {
  20614. if (!seriesModel) {
  20615. console.warn('There is no specified seires model');
  20616. }
  20617. }
  20618. var data = seriesModel.getData();
  20619. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  20620. ? finder.dataIndexInside
  20621. : finder.hasOwnProperty('dataIndex')
  20622. ? data.indexOfRawIndex(finder.dataIndex)
  20623. : null;
  20624. return dataIndexInside != null
  20625. ? data.getItemVisual(dataIndexInside, visualType)
  20626. : data.getVisual(visualType);
  20627. };
  20628. /**
  20629. * Get view of corresponding component model
  20630. * @param {module:echarts/model/Component} componentModel
  20631. * @return {module:echarts/view/Component}
  20632. */
  20633. echartsProto.getViewOfComponentModel = function (componentModel) {
  20634. return this._componentsMap[componentModel.__viewId];
  20635. };
  20636. /**
  20637. * Get view of corresponding series model
  20638. * @param {module:echarts/model/Series} seriesModel
  20639. * @return {module:echarts/view/Chart}
  20640. */
  20641. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  20642. return this._chartsMap[seriesModel.__viewId];
  20643. };
  20644. var updateMethods = {
  20645. prepareAndUpdate: function (payload) {
  20646. prepare(this);
  20647. updateMethods.update.call(this, payload);
  20648. },
  20649. /**
  20650. * @param {Object} payload
  20651. * @private
  20652. */
  20653. update: function (payload) {
  20654. // console.profile && console.profile('update');
  20655. var ecModel = this._model;
  20656. var api = this._api;
  20657. var zr = this._zr;
  20658. var coordSysMgr = this._coordSysMgr;
  20659. var scheduler = this._scheduler;
  20660. // update before setOption
  20661. if (!ecModel) {
  20662. return;
  20663. }
  20664. ecModel.restoreData(payload);
  20665. scheduler.performSeriesTasks(ecModel);
  20666. // TODO
  20667. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  20668. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  20669. // Create new coordinate system each update
  20670. // In LineView may save the old coordinate system and use it to get the orignal point
  20671. coordSysMgr.create(ecModel, api);
  20672. scheduler.performDataProcessorTasks(dataProcessorFuncs, ecModel, payload);
  20673. // Current stream render is not supported in data process. So we can update
  20674. // stream modes after data processing, where the filtered data is used to
  20675. // deteming whether use progressive rendering.
  20676. updateStreamModes(this, ecModel);
  20677. stackSeriesData(ecModel);
  20678. coordSysMgr.update(ecModel, api);
  20679. clearColorPalette(ecModel);
  20680. scheduler.performVisualTasks(visualFuncs, ecModel, payload);
  20681. render(this, ecModel, api, payload);
  20682. // Set background
  20683. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  20684. var painter = zr.painter;
  20685. // TODO all use clearColor ?
  20686. if (painter.isSingleCanvas && painter.isSingleCanvas()) {
  20687. zr.configLayer(0, {
  20688. clearColor: backgroundColor
  20689. });
  20690. }
  20691. else {
  20692. // In IE8
  20693. if (!env$1.canvasSupported) {
  20694. var colorArr = parse(backgroundColor);
  20695. backgroundColor = stringify(colorArr, 'rgb');
  20696. if (colorArr[3] === 0) {
  20697. backgroundColor = 'transparent';
  20698. }
  20699. }
  20700. if (backgroundColor.colorStops || backgroundColor.image) {
  20701. // Gradient background
  20702. // FIXME Fixed layer?
  20703. zr.configLayer(0, {
  20704. clearColor: backgroundColor
  20705. });
  20706. this[HAS_GRADIENT_OR_PATTERN_BG] = true;
  20707. this._dom.style.background = 'transparent';
  20708. }
  20709. else {
  20710. if (this[HAS_GRADIENT_OR_PATTERN_BG]) {
  20711. zr.configLayer(0, {
  20712. clearColor: null
  20713. });
  20714. }
  20715. this[HAS_GRADIENT_OR_PATTERN_BG] = false;
  20716. this._dom.style.background = backgroundColor;
  20717. }
  20718. }
  20719. performPostUpdateFuncs(ecModel, api);
  20720. // console.profile && console.profileEnd('update');
  20721. },
  20722. /**
  20723. * @param {Object} payload
  20724. * @private
  20725. */
  20726. updateTransform: function (payload) {
  20727. var ecModel = this._model;
  20728. var ecIns = this;
  20729. var api = this._api;
  20730. // update before setOption
  20731. if (!ecModel) {
  20732. return;
  20733. }
  20734. // ChartView.markUpdateMethod(payload, 'updateTransform');
  20735. var componentDirtyList = [];
  20736. ecModel.eachComponent(function (componentType, componentModel) {
  20737. var componentView = ecIns.getViewOfComponentModel(componentModel);
  20738. if (componentView && componentView.__alive) {
  20739. if (componentView.updateTransform) {
  20740. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  20741. result && result.update && componentDirtyList.push(componentView);
  20742. }
  20743. else {
  20744. componentDirtyList.push(componentView);
  20745. }
  20746. }
  20747. });
  20748. var seriesDirtyMap = createHashMap();
  20749. ecModel.eachSeries(function (seriesModel) {
  20750. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  20751. if (chartView.updateTransform) {
  20752. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  20753. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  20754. }
  20755. else {
  20756. seriesDirtyMap.set(seriesModel.uid, 1);
  20757. }
  20758. });
  20759. clearColorPalette(ecModel);
  20760. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  20761. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  20762. this._scheduler.performVisualTasks(
  20763. visualFuncs, ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  20764. );
  20765. // Currently, not call render of components. Geo render cost a lot.
  20766. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  20767. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  20768. performPostUpdateFuncs(ecModel, this._api);
  20769. },
  20770. /**
  20771. * @param {Object} payload
  20772. * @private
  20773. */
  20774. updateView: function (payload) {
  20775. var ecModel = this._model;
  20776. // update before setOption
  20777. if (!ecModel) {
  20778. return;
  20779. }
  20780. Chart.markUpdateMethod(payload, 'updateView');
  20781. clearColorPalette(ecModel);
  20782. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  20783. this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  20784. render(this, this._model, this._api, payload);
  20785. performPostUpdateFuncs(ecModel, this._api);
  20786. },
  20787. /**
  20788. * @param {Object} payload
  20789. * @private
  20790. */
  20791. updateVisual: function (payload) {
  20792. updateMethods.update.call(this, payload);
  20793. // var ecModel = this._model;
  20794. // // update before setOption
  20795. // if (!ecModel) {
  20796. // return;
  20797. // }
  20798. // ChartView.markUpdateMethod(payload, 'updateVisual');
  20799. // clearColorPalette(ecModel);
  20800. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  20801. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {visualType: 'visual', setDirty: true});
  20802. // render(this, this._model, this._api, payload);
  20803. // performPostUpdateFuncs(ecModel, this._api);
  20804. },
  20805. /**
  20806. * @param {Object} payload
  20807. * @private
  20808. */
  20809. updateLayout: function (payload) {
  20810. updateMethods.update.call(this, payload);
  20811. // var ecModel = this._model;
  20812. // // update before setOption
  20813. // if (!ecModel) {
  20814. // return;
  20815. // }
  20816. // ChartView.markUpdateMethod(payload, 'updateLayout');
  20817. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  20818. // // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, 'layout', true);
  20819. // this._scheduler.performVisualTasks(visualFuncs, ecModel, payload, {setDirty: true});
  20820. // render(this, this._model, this._api, payload);
  20821. // performPostUpdateFuncs(ecModel, this._api);
  20822. }
  20823. };
  20824. function prepare(ecIns) {
  20825. var ecModel = ecIns._model;
  20826. var scheduler = ecIns._scheduler;
  20827. scheduler.restorePipelines(ecModel);
  20828. scheduler.prepareStageTasks(dataProcessorFuncs);
  20829. scheduler.prepareStageTasks(visualFuncs);
  20830. prepareView(ecIns, 'component', ecModel, scheduler);
  20831. prepareView(ecIns, 'chart', ecModel, scheduler);
  20832. scheduler.plan();
  20833. }
  20834. /**
  20835. * @private
  20836. */
  20837. function updateDirectly(ecIns, method, payload, mainType, subType) {
  20838. var ecModel = ecIns._model;
  20839. // broadcast
  20840. if (!mainType) {
  20841. // FIXME
  20842. // Chart will not be update directly here, except set dirty.
  20843. // But there is no such scenario now.
  20844. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  20845. return;
  20846. }
  20847. var query = {};
  20848. query[mainType + 'Id'] = payload[mainType + 'Id'];
  20849. query[mainType + 'Index'] = payload[mainType + 'Index'];
  20850. query[mainType + 'Name'] = payload[mainType + 'Name'];
  20851. var condition = {mainType: mainType, query: query};
  20852. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  20853. // If dispatchAction before setOption, do nothing.
  20854. ecModel && ecModel.eachComponent(condition, function (model, index) {
  20855. callView(ecIns[
  20856. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  20857. ][model.__viewId]);
  20858. }, ecIns);
  20859. function callView(view) {
  20860. view && view.__alive && view[method] && view[method](
  20861. view.__model, ecModel, ecIns._api, payload
  20862. );
  20863. }
  20864. }
  20865. /**
  20866. * Resize the chart
  20867. * @param {Object} opts
  20868. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  20869. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  20870. * @param {boolean} [opts.silent=false]
  20871. */
  20872. echartsProto.resize = function (opts) {
  20873. if (__DEV__) {
  20874. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  20875. }
  20876. this._zr.resize(opts);
  20877. var ecModel = this._model;
  20878. // Resize loading effect
  20879. this._loadingFX && this._loadingFX.resize();
  20880. if (!ecModel) {
  20881. return;
  20882. }
  20883. var optionChanged = ecModel.resetOption('media');
  20884. refresh(this, optionChanged, opts && opts.silent);
  20885. };
  20886. function refresh(ecIns, needPrepare, silent) {
  20887. ecIns[IN_MAIN_PROCESS] = true;
  20888. needPrepare && prepare(ecIns);
  20889. updateMethods.update.call(ecIns);
  20890. ecIns[IN_MAIN_PROCESS] = false;
  20891. flushPendingActions.call(ecIns, silent);
  20892. triggerUpdatedEvent.call(ecIns, silent);
  20893. }
  20894. function updateStreamModes(ecIns, ecModel) {
  20895. var chartsMap = ecIns._chartsMap;
  20896. var scheduler = ecIns._scheduler;
  20897. ecModel.eachSeries(function (seriesModel) {
  20898. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  20899. });
  20900. }
  20901. /**
  20902. * Show loading effect
  20903. * @param {string} [name='default']
  20904. * @param {Object} [cfg]
  20905. */
  20906. echartsProto.showLoading = function (name, cfg) {
  20907. if (isObject(name)) {
  20908. cfg = name;
  20909. name = '';
  20910. }
  20911. name = name || 'default';
  20912. this.hideLoading();
  20913. if (!loadingEffects[name]) {
  20914. if (__DEV__) {
  20915. console.warn('Loading effects ' + name + ' not exists.');
  20916. }
  20917. return;
  20918. }
  20919. var el = loadingEffects[name](this._api, cfg);
  20920. var zr = this._zr;
  20921. this._loadingFX = el;
  20922. zr.add(el);
  20923. };
  20924. /**
  20925. * Hide loading effect
  20926. */
  20927. echartsProto.hideLoading = function () {
  20928. this._loadingFX && this._zr.remove(this._loadingFX);
  20929. this._loadingFX = null;
  20930. };
  20931. /**
  20932. * @param {Object} eventObj
  20933. * @return {Object}
  20934. */
  20935. echartsProto.makeActionFromEvent = function (eventObj) {
  20936. var payload = extend({}, eventObj);
  20937. payload.type = eventActionMap[eventObj.type];
  20938. return payload;
  20939. };
  20940. /**
  20941. * @pubilc
  20942. * @param {Object} payload
  20943. * @param {string} [payload.type] Action type
  20944. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  20945. * @param {boolean} [opt.silent=false] Whether trigger events.
  20946. * @param {boolean} [opt.flush=undefined]
  20947. * true: Flush immediately, and then pixel in canvas can be fetched
  20948. * immediately. Caution: it might affect performance.
  20949. * false: Not not flush.
  20950. * undefined: Auto decide whether perform flush.
  20951. */
  20952. echartsProto.dispatchAction = function (payload, opt) {
  20953. if (!isObject(opt)) {
  20954. opt = {silent: !!opt};
  20955. }
  20956. if (!actions[payload.type]) {
  20957. return;
  20958. }
  20959. // Avoid dispatch action before setOption. Especially in `connect`.
  20960. if (!this._model) {
  20961. return;
  20962. }
  20963. // May dispatchAction in rendering procedure
  20964. if (this[IN_MAIN_PROCESS]) {
  20965. this._pendingActions.push(payload);
  20966. return;
  20967. }
  20968. doDispatchAction.call(this, payload, opt.silent);
  20969. if (opt.flush) {
  20970. this._zr.flush(true);
  20971. }
  20972. else if (opt.flush !== false && env$1.browser.weChat) {
  20973. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  20974. // hang when sliding page (on touch event), which cause that zr does not
  20975. // refresh util user interaction finished, which is not expected.
  20976. // But `dispatchAction` may be called too frequently when pan on touch
  20977. // screen, which impacts performance if do not throttle them.
  20978. this._throttledZrFlush();
  20979. }
  20980. flushPendingActions.call(this, opt.silent);
  20981. triggerUpdatedEvent.call(this, opt.silent);
  20982. };
  20983. function doDispatchAction(payload, silent) {
  20984. var payloadType = payload.type;
  20985. var escapeConnect = payload.escapeConnect;
  20986. var actionWrap = actions[payloadType];
  20987. var actionInfo = actionWrap.actionInfo;
  20988. var cptType = (actionInfo.update || 'update').split(':');
  20989. var updateMethod = cptType.pop();
  20990. cptType = cptType[0] != null && parseClassType(cptType[0]);
  20991. this[IN_MAIN_PROCESS] = true;
  20992. var payloads = [payload];
  20993. var batched = false;
  20994. // Batch action
  20995. if (payload.batch) {
  20996. batched = true;
  20997. payloads = map(payload.batch, function (item) {
  20998. item = defaults(extend({}, item), payload);
  20999. item.batch = null;
  21000. return item;
  21001. });
  21002. }
  21003. var eventObjBatch = [];
  21004. var eventObj;
  21005. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  21006. each(payloads, function (batchItem) {
  21007. // Action can specify the event by return it.
  21008. eventObj = actionWrap.action(batchItem, this._model, this._api);
  21009. // Emit event outside
  21010. eventObj = eventObj || extend({}, batchItem);
  21011. // Convert type to eventType
  21012. eventObj.type = actionInfo.event || eventObj.type;
  21013. eventObjBatch.push(eventObj);
  21014. // light update does not perform data process, layout and visual.
  21015. if (isHighDown) {
  21016. // method, payload, mainType, subType
  21017. updateDirectly(this, updateMethod, batchItem, 'series');
  21018. }
  21019. else if (cptType) {
  21020. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  21021. }
  21022. }, this);
  21023. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  21024. // Still dirty
  21025. if (this[OPTION_UPDATED]) {
  21026. // FIXME Pass payload ?
  21027. prepare(this);
  21028. updateMethods.update.call(this, payload);
  21029. this[OPTION_UPDATED] = false;
  21030. }
  21031. else {
  21032. updateMethods[updateMethod].call(this, payload);
  21033. }
  21034. }
  21035. // Follow the rule of action batch
  21036. if (batched) {
  21037. eventObj = {
  21038. type: actionInfo.event || payloadType,
  21039. escapeConnect: escapeConnect,
  21040. batch: eventObjBatch
  21041. };
  21042. }
  21043. else {
  21044. eventObj = eventObjBatch[0];
  21045. }
  21046. this[IN_MAIN_PROCESS] = false;
  21047. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  21048. }
  21049. function flushPendingActions(silent) {
  21050. var pendingActions = this._pendingActions;
  21051. while (pendingActions.length) {
  21052. var payload = pendingActions.shift();
  21053. doDispatchAction.call(this, payload, silent);
  21054. }
  21055. }
  21056. function triggerUpdatedEvent(silent) {
  21057. !silent && this.trigger('updated');
  21058. }
  21059. /**
  21060. * @param {Object} params
  21061. * @param {number} params.seriesIndex
  21062. * @param {Array|TypedArray} params.data
  21063. */
  21064. echartsProto.appendData = function (params) {
  21065. var seriesIndex = params.seriesIndex;
  21066. var ecModel = this.getModel();
  21067. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  21068. if (__DEV__) {
  21069. assert(params.data && seriesModel);
  21070. }
  21071. seriesModel.appendData(params);
  21072. this._scheduler.unfinished = true;
  21073. };
  21074. /**
  21075. * Register event
  21076. * @method
  21077. */
  21078. echartsProto.on = createRegisterEventWithLowercaseName('on');
  21079. echartsProto.off = createRegisterEventWithLowercaseName('off');
  21080. echartsProto.one = createRegisterEventWithLowercaseName('one');
  21081. /**
  21082. * Prepare view instances of charts and components
  21083. * @param {module:echarts/model/Global} ecModel
  21084. * @private
  21085. */
  21086. function prepareView(ecIns, type, ecModel, scheduler) {
  21087. var isComponent = type === 'component';
  21088. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  21089. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  21090. var zr = ecIns._zr;
  21091. var api = ecIns._api;
  21092. for (var i = 0; i < viewList.length; i++) {
  21093. viewList[i].__alive = false;
  21094. }
  21095. isComponent
  21096. ? ecModel.eachComponent(function (componentType, model) {
  21097. componentType !== 'series' && doPrepare(model);
  21098. })
  21099. : ecModel.eachSeries(doPrepare);
  21100. function doPrepare(model) {
  21101. // Consider: id same and type changed.
  21102. var viewId = '_ec_' + model.id + '_' + model.type;
  21103. var view = viewMap[viewId];
  21104. if (!view) {
  21105. var classType = parseClassType(model.type);
  21106. var Clazz = isComponent
  21107. ? Component.getClass(classType.main, classType.sub)
  21108. : Chart.getClass(classType.sub);
  21109. if (__DEV__) {
  21110. assert(Clazz, classType.sub + ' does not exist.');
  21111. }
  21112. view = new Clazz();
  21113. view.init(ecModel, api);
  21114. viewMap[viewId] = view;
  21115. viewList.push(view);
  21116. zr.add(view.group);
  21117. }
  21118. model.__viewId = view.__id = viewId;
  21119. view.__alive = true;
  21120. view.__model = model;
  21121. view.group.__ecComponentInfo = {
  21122. mainType: model.mainType,
  21123. index: model.componentIndex
  21124. };
  21125. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  21126. }
  21127. for (var i = 0; i < viewList.length;) {
  21128. var view = viewList[i];
  21129. if (!view.__alive) {
  21130. !isComponent && view.renderTask.dispose();
  21131. zr.remove(view.group);
  21132. view.dispose(ecModel, api);
  21133. viewList.splice(i, 1);
  21134. delete viewMap[view.__id];
  21135. view.__id = view.group.__ecComponentInfo = null;
  21136. }
  21137. else {
  21138. i++;
  21139. }
  21140. }
  21141. }
  21142. /**
  21143. * @private
  21144. */
  21145. function stackSeriesData(ecModel) {
  21146. var stackedDataMap = {};
  21147. ecModel.eachSeries(function (series) {
  21148. var stack = series.get('stack');
  21149. var data = series.getData();
  21150. if (stack && data.type === 'list') {
  21151. var previousStack = stackedDataMap[stack];
  21152. // Avoid conflict with Object.prototype
  21153. if (stackedDataMap.hasOwnProperty(stack) && previousStack) {
  21154. data.stackedOn = previousStack;
  21155. }
  21156. stackedDataMap[stack] = data;
  21157. }
  21158. });
  21159. }
  21160. // /**
  21161. // * Encode visual infomation from data after data processing
  21162. // *
  21163. // * @param {module:echarts/model/Global} ecModel
  21164. // * @param {object} layout
  21165. // * @param {boolean} [layoutFilter] `true`: only layout,
  21166. // * `false`: only not layout,
  21167. // * `null`/`undefined`: all.
  21168. // * @param {string} taskBaseTag
  21169. // * @private
  21170. // */
  21171. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  21172. // each(visualFuncs, function (visual, index) {
  21173. // var isLayout = visual.isLayout;
  21174. // if (layoutFilter == null
  21175. // || (layoutFilter === false && !isLayout)
  21176. // || (layoutFilter === true && isLayout)
  21177. // ) {
  21178. // visual.func(ecModel, api, payload);
  21179. // }
  21180. // });
  21181. // }
  21182. function clearColorPalette(ecModel) {
  21183. ecModel.clearColorPalette();
  21184. ecModel.eachSeries(function (seriesModel) {
  21185. seriesModel.clearColorPalette();
  21186. });
  21187. }
  21188. function render(ecIns, ecModel, api, payload) {
  21189. renderComponents(ecIns, ecModel, api, payload);
  21190. each(ecIns._chartsViews, function (chart) {
  21191. chart.__alive = false;
  21192. });
  21193. renderSeries(ecIns, ecModel, api, payload);
  21194. // Remove groups of unrendered charts
  21195. each(ecIns._chartsViews, function (chart) {
  21196. if (!chart.__alive) {
  21197. chart.remove(ecModel, api);
  21198. }
  21199. });
  21200. }
  21201. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  21202. each(dirtyList || ecIns._componentsViews, function (componentView) {
  21203. var componentModel = componentView.__model;
  21204. componentView.render(componentModel, ecModel, api, payload);
  21205. updateZ(componentModel, componentView);
  21206. });
  21207. }
  21208. /**
  21209. * Render each chart and component
  21210. * @private
  21211. */
  21212. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  21213. // Render all charts
  21214. var scheduler = ecIns._scheduler;
  21215. var unfinished;
  21216. ecModel.eachSeries(function (seriesModel) {
  21217. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  21218. chartView.__alive = true;
  21219. var renderTask = chartView.renderTask;
  21220. scheduler.updatePayload(renderTask, payload);
  21221. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  21222. renderTask.dirty();
  21223. }
  21224. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  21225. chartView.group.silent = !!seriesModel.get('silent');
  21226. updateZ(seriesModel, chartView);
  21227. updateBlend(seriesModel, chartView);
  21228. });
  21229. scheduler.unfinished |= unfinished;
  21230. // If use hover layer
  21231. updateHoverLayerStatus(ecIns._zr, ecModel);
  21232. // Add aria
  21233. aria(ecIns._zr.dom, ecModel);
  21234. }
  21235. function performPostUpdateFuncs(ecModel, api) {
  21236. each(postUpdateFuncs, function (func) {
  21237. func(ecModel, api);
  21238. });
  21239. }
  21240. var MOUSE_EVENT_NAMES = [
  21241. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  21242. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  21243. ];
  21244. /**
  21245. * @private
  21246. */
  21247. echartsProto._initEvents = function () {
  21248. each(MOUSE_EVENT_NAMES, function (eveName) {
  21249. this._zr.on(eveName, function (e) {
  21250. var ecModel = this.getModel();
  21251. var el = e.target;
  21252. var params;
  21253. // no e.target when 'globalout'.
  21254. if (eveName === 'globalout') {
  21255. params = {};
  21256. }
  21257. else if (el && el.dataIndex != null) {
  21258. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  21259. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  21260. }
  21261. // If element has custom eventData of components
  21262. else if (el && el.eventData) {
  21263. params = extend({}, el.eventData);
  21264. }
  21265. if (params) {
  21266. params.event = e;
  21267. params.type = eveName;
  21268. this.trigger(eveName, params);
  21269. }
  21270. }, this);
  21271. }, this);
  21272. each(eventActionMap, function (actionType, eventType) {
  21273. this._messageCenter.on(eventType, function (event) {
  21274. this.trigger(eventType, event);
  21275. }, this);
  21276. }, this);
  21277. };
  21278. /**
  21279. * @return {boolean}
  21280. */
  21281. echartsProto.isDisposed = function () {
  21282. return this._disposed;
  21283. };
  21284. /**
  21285. * Clear
  21286. */
  21287. echartsProto.clear = function () {
  21288. this.setOption({ series: [] }, true);
  21289. };
  21290. /**
  21291. * Dispose instance
  21292. */
  21293. echartsProto.dispose = function () {
  21294. if (this._disposed) {
  21295. if (__DEV__) {
  21296. console.warn('Instance ' + this.id + ' has been disposed');
  21297. }
  21298. return;
  21299. }
  21300. this._disposed = true;
  21301. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  21302. var api = this._api;
  21303. var ecModel = this._model;
  21304. each(this._componentsViews, function (component) {
  21305. component.dispose(ecModel, api);
  21306. });
  21307. each(this._chartsViews, function (chart) {
  21308. chart.dispose(ecModel, api);
  21309. });
  21310. // Dispose after all views disposed
  21311. this._zr.dispose();
  21312. delete instances[this.id];
  21313. };
  21314. mixin(ECharts, Eventful);
  21315. function updateHoverLayerStatus(zr, ecModel) {
  21316. var storage = zr.storage;
  21317. var elCount = 0;
  21318. storage.traverse(function (el) {
  21319. if (!el.isGroup) {
  21320. elCount++;
  21321. }
  21322. });
  21323. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  21324. storage.traverse(function (el) {
  21325. if (!el.isGroup) {
  21326. // Don't switch back.
  21327. el.useHoverLayer = true;
  21328. }
  21329. });
  21330. }
  21331. }
  21332. /**
  21333. * Update chart progressive and blend.
  21334. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21335. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21336. */
  21337. function updateBlend(seriesModel, chartView) {
  21338. var blendMode = seriesModel.get('blendMode') || null;
  21339. if (__DEV__) {
  21340. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  21341. console.warn('Only canvas support blendMode');
  21342. }
  21343. }
  21344. chartView.group.traverse(function (el) {
  21345. // FIXME marker and other components
  21346. if (!el.isGroup) {
  21347. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  21348. if (el.style.blend !== blendMode) {
  21349. el.setStyle('blend', blendMode);
  21350. }
  21351. }
  21352. if (el.eachPendingDisplayable) {
  21353. el.eachPendingDisplayable(function (displayable) {
  21354. displayable.setStyle('blend', blendMode);
  21355. });
  21356. }
  21357. });
  21358. }
  21359. /**
  21360. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  21361. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  21362. */
  21363. function updateZ(model, view) {
  21364. var z = model.get('z');
  21365. var zlevel = model.get('zlevel');
  21366. // Set z and zlevel
  21367. view.group.traverse(function (el) {
  21368. if (el.type !== 'group') {
  21369. z != null && (el.z = z);
  21370. zlevel != null && (el.zlevel = zlevel);
  21371. }
  21372. });
  21373. }
  21374. function createExtensionAPI(ecInstance) {
  21375. var coordSysMgr = ecInstance._coordSysMgr;
  21376. return extend(new ExtensionAPI(ecInstance), {
  21377. // Inject methods
  21378. getCoordinateSystems: bind(
  21379. coordSysMgr.getCoordinateSystems, coordSysMgr
  21380. ),
  21381. getComponentByElement: function (el) {
  21382. while (el) {
  21383. var modelInfo = el.__ecComponentInfo;
  21384. if (modelInfo != null) {
  21385. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  21386. }
  21387. el = el.parent;
  21388. }
  21389. }
  21390. });
  21391. }
  21392. /**
  21393. * @type {Object} key: actionType.
  21394. * @inner
  21395. */
  21396. var actions = {};
  21397. /**
  21398. * Map eventType to actionType
  21399. * @type {Object}
  21400. */
  21401. var eventActionMap = {};
  21402. /**
  21403. * Data processor functions of each stage
  21404. * @type {Array.<Object.<string, Function>>}
  21405. * @inner
  21406. */
  21407. var dataProcessorFuncs = [];
  21408. /**
  21409. * @type {Array.<Function>}
  21410. * @inner
  21411. */
  21412. var optionPreprocessorFuncs = [];
  21413. /**
  21414. * @type {Array.<Function>}
  21415. * @inner
  21416. */
  21417. var postUpdateFuncs = [];
  21418. /**
  21419. * Visual encoding functions of each stage
  21420. * @type {Array.<Object.<string, Function>>}
  21421. */
  21422. var visualFuncs = [];
  21423. /**
  21424. * Theme storage
  21425. * @type {Object.<key, Object>}
  21426. */
  21427. var themeStorage = {};
  21428. /**
  21429. * Loading effects
  21430. */
  21431. var loadingEffects = {};
  21432. var instances = {};
  21433. var connectedGroups = {};
  21434. var idBase = new Date() - 0;
  21435. var groupIdBase = new Date() - 0;
  21436. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  21437. var mapDataStores = {};
  21438. function enableConnect(chart) {
  21439. var STATUS_PENDING = 0;
  21440. var STATUS_UPDATING = 1;
  21441. var STATUS_UPDATED = 2;
  21442. var STATUS_KEY = '__connectUpdateStatus';
  21443. function updateConnectedChartsStatus(charts, status) {
  21444. for (var i = 0; i < charts.length; i++) {
  21445. var otherChart = charts[i];
  21446. otherChart[STATUS_KEY] = status;
  21447. }
  21448. }
  21449. each(eventActionMap, function (actionType, eventType) {
  21450. chart._messageCenter.on(eventType, function (event) {
  21451. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  21452. if (event && event.escapeConnect) {
  21453. return;
  21454. }
  21455. var action = chart.makeActionFromEvent(event);
  21456. var otherCharts = [];
  21457. each(instances, function (otherChart) {
  21458. if (otherChart !== chart && otherChart.group === chart.group) {
  21459. otherCharts.push(otherChart);
  21460. }
  21461. });
  21462. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  21463. each(otherCharts, function (otherChart) {
  21464. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  21465. otherChart.dispatchAction(action);
  21466. }
  21467. });
  21468. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  21469. }
  21470. });
  21471. });
  21472. }
  21473. /**
  21474. * @param {HTMLElement} dom
  21475. * @param {Object} [theme]
  21476. * @param {Object} opts
  21477. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  21478. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  21479. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  21480. * Can be 'auto' (the same as null/undefined)
  21481. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  21482. * Can be 'auto' (the same as null/undefined)
  21483. */
  21484. function init(dom, theme$$1, opts) {
  21485. if (__DEV__) {
  21486. // Check version
  21487. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  21488. throw new Error(
  21489. 'zrender/src ' + version$1
  21490. + ' is too old for ECharts ' + version
  21491. + '. Current version need ZRender '
  21492. + dependencies.zrender + '+'
  21493. );
  21494. }
  21495. if (!dom) {
  21496. throw new Error('Initialize failed: invalid dom.');
  21497. }
  21498. }
  21499. var existInstance = getInstanceByDom(dom);
  21500. if (existInstance) {
  21501. if (__DEV__) {
  21502. console.warn('There is a chart instance already initialized on the dom.');
  21503. }
  21504. return existInstance;
  21505. }
  21506. if (__DEV__) {
  21507. if (isDom(dom)
  21508. && dom.nodeName.toUpperCase() !== 'CANVAS'
  21509. && (
  21510. (!dom.clientWidth && (!opts || opts.width == null))
  21511. || (!dom.clientHeight && (!opts || opts.height == null))
  21512. )
  21513. ) {
  21514. console.warn('Can\'t get dom width or height');
  21515. }
  21516. }
  21517. var chart = new ECharts(dom, theme$$1, opts);
  21518. chart.id = 'ec_' + idBase++;
  21519. instances[chart.id] = chart;
  21520. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  21521. enableConnect(chart);
  21522. return chart;
  21523. }
  21524. /**
  21525. * @return {string|Array.<module:echarts~ECharts>} groupId
  21526. */
  21527. function connect(groupId) {
  21528. // Is array of charts
  21529. if (isArray(groupId)) {
  21530. var charts = groupId;
  21531. groupId = null;
  21532. // If any chart has group
  21533. each(charts, function (chart) {
  21534. if (chart.group != null) {
  21535. groupId = chart.group;
  21536. }
  21537. });
  21538. groupId = groupId || ('g_' + groupIdBase++);
  21539. each(charts, function (chart) {
  21540. chart.group = groupId;
  21541. });
  21542. }
  21543. connectedGroups[groupId] = true;
  21544. return groupId;
  21545. }
  21546. /**
  21547. * @DEPRECATED
  21548. * @return {string} groupId
  21549. */
  21550. function disConnect(groupId) {
  21551. connectedGroups[groupId] = false;
  21552. }
  21553. /**
  21554. * @return {string} groupId
  21555. */
  21556. var disconnect = disConnect;
  21557. /**
  21558. * Dispose a chart instance
  21559. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  21560. */
  21561. function dispose(chart) {
  21562. if (typeof chart === 'string') {
  21563. chart = instances[chart];
  21564. }
  21565. else if (!(chart instanceof ECharts)){
  21566. // Try to treat as dom
  21567. chart = getInstanceByDom(chart);
  21568. }
  21569. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  21570. chart.dispose();
  21571. }
  21572. }
  21573. /**
  21574. * @param {HTMLElement} dom
  21575. * @return {echarts~ECharts}
  21576. */
  21577. function getInstanceByDom(dom) {
  21578. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  21579. }
  21580. /**
  21581. * @param {string} key
  21582. * @return {echarts~ECharts}
  21583. */
  21584. function getInstanceById(key) {
  21585. return instances[key];
  21586. }
  21587. /**
  21588. * Register theme
  21589. */
  21590. function registerTheme(name, theme$$1) {
  21591. themeStorage[name] = theme$$1;
  21592. }
  21593. /**
  21594. * Register option preprocessor
  21595. * @param {Function} preprocessorFunc
  21596. */
  21597. function registerPreprocessor(preprocessorFunc) {
  21598. optionPreprocessorFuncs.push(preprocessorFunc);
  21599. }
  21600. /**
  21601. * @param {number} [priority=1000]
  21602. * @param {Object|Function} processor
  21603. */
  21604. function registerProcessor(priority, processor) {
  21605. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  21606. }
  21607. /**
  21608. * Register postUpdater
  21609. * @param {Function} postUpdateFunc
  21610. */
  21611. function registerPostUpdate(postUpdateFunc) {
  21612. postUpdateFuncs.push(postUpdateFunc);
  21613. }
  21614. /**
  21615. * Usage:
  21616. * registerAction('someAction', 'someEvent', function () { ... });
  21617. * registerAction('someAction', function () { ... });
  21618. * registerAction(
  21619. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  21620. * function () { ... }
  21621. * );
  21622. *
  21623. * @param {(string|Object)} actionInfo
  21624. * @param {string} actionInfo.type
  21625. * @param {string} [actionInfo.event]
  21626. * @param {string} [actionInfo.update]
  21627. * @param {string} [eventName]
  21628. * @param {Function} action
  21629. */
  21630. function registerAction(actionInfo, eventName, action) {
  21631. if (typeof eventName === 'function') {
  21632. action = eventName;
  21633. eventName = '';
  21634. }
  21635. var actionType = isObject(actionInfo)
  21636. ? actionInfo.type
  21637. : ([actionInfo, actionInfo = {
  21638. event: eventName
  21639. }][0]);
  21640. // Event name is all lowercase
  21641. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  21642. eventName = actionInfo.event;
  21643. // Validate action type and event name.
  21644. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  21645. if (!actions[actionType]) {
  21646. actions[actionType] = {action: action, actionInfo: actionInfo};
  21647. }
  21648. eventActionMap[eventName] = actionType;
  21649. }
  21650. /**
  21651. * @param {string} type
  21652. * @param {*} CoordinateSystem
  21653. */
  21654. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  21655. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  21656. }
  21657. /**
  21658. * Get dimensions of specified coordinate system.
  21659. * @param {string} type
  21660. * @return {Array.<string|Object>}
  21661. */
  21662. function getCoordinateSystemDimensions(type) {
  21663. var coordSysCreator = CoordinateSystemManager.get(type);
  21664. if (coordSysCreator) {
  21665. return coordSysCreator.getDimensionsInfo
  21666. ? coordSysCreator.getDimensionsInfo()
  21667. : coordSysCreator.dimensions.slice();
  21668. }
  21669. }
  21670. /**
  21671. * Layout is a special stage of visual encoding
  21672. * Most visual encoding like color are common for different chart
  21673. * But each chart has it's own layout algorithm
  21674. *
  21675. * @param {number} [priority=1000]
  21676. * @param {Function} layoutTask
  21677. */
  21678. function registerLayout(priority, layoutTask) {
  21679. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  21680. }
  21681. /**
  21682. * @param {number} [priority=3000]
  21683. * @param {module:echarts/stream/Task} visualTask
  21684. */
  21685. function registerVisual(priority, visualTask) {
  21686. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  21687. }
  21688. /**
  21689. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  21690. */
  21691. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  21692. if (isFunction(priority) || isObject(priority)) {
  21693. fn = priority;
  21694. priority = defaultPriority;
  21695. }
  21696. if (__DEV__) {
  21697. if (isNaN(priority) || priority == null) {
  21698. throw new Error('Illegal priority');
  21699. }
  21700. // Check duplicate
  21701. each(targetList, function (wrap) {
  21702. assert(wrap.__raw !== fn);
  21703. });
  21704. }
  21705. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  21706. stageHandler.__prio = priority;
  21707. stageHandler.__raw = fn;
  21708. targetList.push(stageHandler);
  21709. return stageHandler;
  21710. }
  21711. /**
  21712. * @param {string} name
  21713. */
  21714. function registerLoading(name, loadingFx) {
  21715. loadingEffects[name] = loadingFx;
  21716. }
  21717. /**
  21718. * @param {Object} opts
  21719. * @param {string} [superClass]
  21720. */
  21721. function extendComponentModel(opts/*, superClass*/) {
  21722. // var Clazz = ComponentModel;
  21723. // if (superClass) {
  21724. // var classType = parseClassType(superClass);
  21725. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  21726. // }
  21727. return ComponentModel.extend(opts);
  21728. }
  21729. /**
  21730. * @param {Object} opts
  21731. * @param {string} [superClass]
  21732. */
  21733. function extendComponentView(opts/*, superClass*/) {
  21734. // var Clazz = ComponentView;
  21735. // if (superClass) {
  21736. // var classType = parseClassType(superClass);
  21737. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  21738. // }
  21739. return Component.extend(opts);
  21740. }
  21741. /**
  21742. * @param {Object} opts
  21743. * @param {string} [superClass]
  21744. */
  21745. function extendSeriesModel(opts/*, superClass*/) {
  21746. // var Clazz = SeriesModel;
  21747. // if (superClass) {
  21748. // superClass = 'series.' + superClass.replace('series.', '');
  21749. // var classType = parseClassType(superClass);
  21750. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  21751. // }
  21752. return SeriesModel.extend(opts);
  21753. }
  21754. /**
  21755. * @param {Object} opts
  21756. * @param {string} [superClass]
  21757. */
  21758. function extendChartView(opts/*, superClass*/) {
  21759. // var Clazz = ChartView;
  21760. // if (superClass) {
  21761. // superClass = superClass.replace('series.', '');
  21762. // var classType = parseClassType(superClass);
  21763. // Clazz = ChartView.getClass(classType.main, true);
  21764. // }
  21765. return Chart.extend(opts);
  21766. }
  21767. /**
  21768. * ZRender need a canvas context to do measureText.
  21769. * But in node environment canvas may be created by node-canvas.
  21770. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  21771. *
  21772. * Be careful of using it in the browser.
  21773. *
  21774. * @param {Function} creator
  21775. * @example
  21776. * var Canvas = require('canvas');
  21777. * var echarts = require('echarts');
  21778. * echarts.setCanvasCreator(function () {
  21779. * // Small size is enough.
  21780. * return new Canvas(32, 32);
  21781. * });
  21782. */
  21783. function setCanvasCreator(creator) {
  21784. $override('createCanvas', creator);
  21785. }
  21786. /**
  21787. * @param {string} mapName
  21788. * @param {Object|string} geoJson
  21789. * @param {Object} [specialAreas]
  21790. *
  21791. * @example
  21792. * $.get('USA.json', function (geoJson) {
  21793. * echarts.registerMap('USA', geoJson);
  21794. * // Or
  21795. * echarts.registerMap('USA', {
  21796. * geoJson: geoJson,
  21797. * specialAreas: {}
  21798. * })
  21799. * });
  21800. */
  21801. function registerMap(mapName, geoJson, specialAreas) {
  21802. if (geoJson.geoJson && !geoJson.features) {
  21803. specialAreas = geoJson.specialAreas;
  21804. geoJson = geoJson.geoJson;
  21805. }
  21806. if (typeof geoJson === 'string') {
  21807. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  21808. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  21809. }
  21810. mapDataStores[mapName] = {
  21811. geoJson: geoJson,
  21812. specialAreas: specialAreas
  21813. };
  21814. }
  21815. /**
  21816. * @param {string} mapName
  21817. * @return {Object}
  21818. */
  21819. function getMap(mapName) {
  21820. return mapDataStores[mapName];
  21821. }
  21822. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  21823. registerPreprocessor(backwardCompat);
  21824. registerLoading('default', loadingDefault);
  21825. // Default actions
  21826. registerAction({
  21827. type: 'highlight',
  21828. event: 'highlight',
  21829. update: 'highlight'
  21830. }, noop);
  21831. registerAction({
  21832. type: 'downplay',
  21833. event: 'downplay',
  21834. update: 'downplay'
  21835. }, noop);
  21836. // Default theme
  21837. registerTheme('light', lightTheme);
  21838. registerTheme('dark', theme);
  21839. // For backward compatibility, where the namespace `dataTool` will
  21840. // be mounted on `echarts` is the extension `dataTool` is imported.
  21841. var dataTool = {};
  21842. var DatasetModel = extendComponentModel({
  21843. type: 'dataset',
  21844. /**
  21845. * @protected
  21846. */
  21847. defaultOption: {
  21848. // 'row', 'column'
  21849. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21850. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21851. sourceHeader: null,
  21852. dimensions: null,
  21853. source: null
  21854. },
  21855. optionUpdated: function () {
  21856. detectSourceFormat(this);
  21857. }
  21858. });
  21859. extendComponentView({type: 'dataset'});
  21860. function defaultKeyGetter(item) {
  21861. return item;
  21862. }
  21863. /**
  21864. * @param {Array} oldArr
  21865. * @param {Array} newArr
  21866. * @param {Function} oldKeyGetter
  21867. * @param {Function} newKeyGetter
  21868. * @param {Object} [context] Can be visited by this.context in callback.
  21869. */
  21870. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  21871. this._old = oldArr;
  21872. this._new = newArr;
  21873. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  21874. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  21875. this.context = context;
  21876. }
  21877. DataDiffer.prototype = {
  21878. constructor: DataDiffer,
  21879. /**
  21880. * Callback function when add a data
  21881. */
  21882. add: function (func) {
  21883. this._add = func;
  21884. return this;
  21885. },
  21886. /**
  21887. * Callback function when update a data
  21888. */
  21889. update: function (func) {
  21890. this._update = func;
  21891. return this;
  21892. },
  21893. /**
  21894. * Callback function when remove a data
  21895. */
  21896. remove: function (func) {
  21897. this._remove = func;
  21898. return this;
  21899. },
  21900. execute: function () {
  21901. var oldArr = this._old;
  21902. var newArr = this._new;
  21903. var oldDataIndexMap = {};
  21904. var newDataIndexMap = {};
  21905. var oldDataKeyArr = [];
  21906. var newDataKeyArr = [];
  21907. var i;
  21908. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  21909. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  21910. // Travel by inverted order to make sure order consistency
  21911. // when duplicate keys exists (consider newDataIndex.pop() below).
  21912. // For performance consideration, these code below do not look neat.
  21913. for (i = 0; i < oldArr.length; i++) {
  21914. var key = oldDataKeyArr[i];
  21915. var idx = newDataIndexMap[key];
  21916. // idx can never be empty array here. see 'set null' logic below.
  21917. if (idx != null) {
  21918. // Consider there is duplicate key (for example, use dataItem.name as key).
  21919. // We should make sure every item in newArr and oldArr can be visited.
  21920. var len = idx.length;
  21921. if (len) {
  21922. len === 1 && (newDataIndexMap[key] = null);
  21923. idx = idx.unshift();
  21924. }
  21925. else {
  21926. newDataIndexMap[key] = null;
  21927. }
  21928. this._update && this._update(idx, i);
  21929. }
  21930. else {
  21931. this._remove && this._remove(i);
  21932. }
  21933. }
  21934. for (var i = 0; i < newDataKeyArr.length; i++) {
  21935. var key = newDataKeyArr[i];
  21936. if (newDataIndexMap.hasOwnProperty(key)) {
  21937. var idx = newDataIndexMap[key];
  21938. if (idx == null) {
  21939. continue;
  21940. }
  21941. // idx can never be empty array here. see 'set null' logic above.
  21942. if (!idx.length) {
  21943. this._add && this._add(idx);
  21944. }
  21945. else {
  21946. for (var j = 0, len = idx.length; j < len; j++) {
  21947. this._add && this._add(idx[j]);
  21948. }
  21949. }
  21950. }
  21951. }
  21952. }
  21953. };
  21954. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  21955. for (var i = 0; i < arr.length; i++) {
  21956. // Add prefix to avoid conflict with Object.prototype.
  21957. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  21958. var existence = map[key];
  21959. if (existence == null) {
  21960. keyArr.push(key);
  21961. map[key] = i;
  21962. }
  21963. else {
  21964. if (!existence.length) {
  21965. map[key] = existence = [existence];
  21966. }
  21967. existence.push(i);
  21968. }
  21969. }
  21970. }
  21971. var OTHER_DIMENSIONS = createHashMap([
  21972. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  21973. ]);
  21974. function summarizeDimensions(data) {
  21975. var summary = {};
  21976. var encode = summary.encode = {};
  21977. var coordDimMap = summary.coordDimMap = createHashMap();
  21978. var defaultedLabel = [];
  21979. each$1(data.dimensions, function (dimName) {
  21980. var dimItem = data.getDimensionInfo(dimName);
  21981. var coordDim = dimItem.coordDim;
  21982. if (coordDim) {
  21983. if (__DEV__) {
  21984. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  21985. }
  21986. var coordDimArr = encode[coordDim];
  21987. if (!encode.hasOwnProperty(coordDim)) {
  21988. coordDimArr = encode[coordDim] = [];
  21989. }
  21990. coordDimArr[dimItem.coordDimIndex] = dimName;
  21991. if (dimItem.isSysCoord && mayLabelDimType(dimItem.type)) {
  21992. // Use the last coord dim (and label friendly) as default label,
  21993. // because both show x, y on label is not look good, and usually
  21994. // y axis is more focusd conventionally.
  21995. defaultedLabel[0] = dimName;
  21996. }
  21997. coordDimMap.set(coordDim, 1);
  21998. }
  21999. OTHER_DIMENSIONS.each(function (v, otherDim) {
  22000. var otherDimArr = encode[otherDim];
  22001. if (!encode.hasOwnProperty(otherDim)) {
  22002. otherDimArr = encode[otherDim] = [];
  22003. }
  22004. var dimIndex = dimItem.otherDims[otherDim];
  22005. if (dimIndex != null && dimIndex !== false) {
  22006. otherDimArr[dimIndex] = dimItem.name;
  22007. }
  22008. });
  22009. });
  22010. var dataDimsOnCoord = [];
  22011. coordDimMap.each(function (v, coordDim) {
  22012. dataDimsOnCoord = dataDimsOnCoord.concat(encode[coordDim]);
  22013. });
  22014. summary.dataDimsOnCoord = dataDimsOnCoord;
  22015. var encodeLabel = encode.label;
  22016. // FIXME `encode.label` is not recommanded, because formatter can not be set
  22017. // in this way. Use label.formatter instead. May be remove this approach someday.
  22018. if (encodeLabel && encodeLabel.length) {
  22019. defaultedLabel = encodeLabel.slice();
  22020. }
  22021. var defaultedTooltip = defaultedLabel.slice();
  22022. var encodeTooltip = encode.tooltip;
  22023. if (encodeTooltip && encodeTooltip.length) {
  22024. defaultedTooltip = encodeTooltip.slice();
  22025. }
  22026. encode.defaultedLabel = defaultedLabel;
  22027. encode.defaultedTooltip = defaultedTooltip;
  22028. return summary;
  22029. }
  22030. function getDimensionTypeByAxis(axisType) {
  22031. return axisType === 'category'
  22032. ? 'ordinal'
  22033. : axisType === 'time'
  22034. ? 'time'
  22035. : 'float';
  22036. }
  22037. function mayLabelDimType(dimType) {
  22038. // In most cases, ordinal and time do not suitable for label.
  22039. // Ordinal info can be displayed on axis. Time is too long.
  22040. return !(dimType === 'ordinal' || dimType === 'time');
  22041. }
  22042. // function findTheLastDimMayLabel(data) {
  22043. // // Get last value dim
  22044. // var dimensions = data.dimensions.slice();
  22045. // var valueType;
  22046. // var valueDim;
  22047. // while (dimensions.length && (
  22048. // valueDim = dimensions.pop(),
  22049. // valueType = data.getDimensionInfo(valueDim).type,
  22050. // valueType === 'ordinal' || valueType === 'time'
  22051. // )) {} // jshint ignore:line
  22052. // return valueDim;
  22053. // }
  22054. /**
  22055. * List for data storage
  22056. * @module echarts/data/List
  22057. */
  22058. var isObject$4 = isObject$1;
  22059. var UNDEFINED = 'undefined';
  22060. var globalObj = typeof window === UNDEFINED ? global : window;
  22061. // Use prefix to avoid index to be the same as otherIdList[idx],
  22062. // which will cause weird udpate animation.
  22063. var ID_PREFIX = 'e\0\0';
  22064. var dataCtors = {
  22065. 'float': typeof globalObj.Float64Array === UNDEFINED
  22066. ? Array : globalObj.Float64Array,
  22067. 'int': typeof globalObj.Int32Array === UNDEFINED
  22068. ? Array : globalObj.Int32Array,
  22069. // Ordinal data type can be string or int
  22070. 'ordinal': Array,
  22071. 'number': Array,
  22072. 'time': Array
  22073. };
  22074. function getIndicesCtor(list) {
  22075. var CtorUint32Array = typeof globalObj.Uint32Array === UNDEFINED ? Array : globalObj.Uint32Array;
  22076. var CtorUint16Array = typeof globalObj.Uint16Array === UNDEFINED ? Array : globalObj.Uint16Array;
  22077. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  22078. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  22079. }
  22080. function cloneChunk(originalChunk) {
  22081. var Ctor = originalChunk.constructor;
  22082. // Only shallow clone is enough when Array.
  22083. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  22084. }
  22085. var TRANSFERABLE_PROPERTIES = [
  22086. 'stackedOn', 'hasItemOption', '_nameList', '_idList',
  22087. '_rawData', '_rawExtent', '_chunkSize', '_chunkCount',
  22088. '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  22089. ];
  22090. function transferProperties(a, b) {
  22091. each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) {
  22092. if (b.hasOwnProperty(propName)) {
  22093. a[propName] = b[propName];
  22094. }
  22095. });
  22096. a.__wrappedMethods = b.__wrappedMethods;
  22097. }
  22098. /**
  22099. * @constructor
  22100. * @alias module:echarts/data/List
  22101. *
  22102. * @param {Array.<string|Object>} dimensions
  22103. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  22104. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  22105. * Spetial fields: {
  22106. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  22107. * }
  22108. * @param {module:echarts/model/Model} hostModel
  22109. */
  22110. var List = function (dimensions, hostModel) {
  22111. dimensions = dimensions || ['x', 'y'];
  22112. var dimensionInfos = {};
  22113. var dimensionNames = [];
  22114. for (var i = 0; i < dimensions.length; i++) {
  22115. var dimensionName;
  22116. var dimensionInfo = {};
  22117. if (typeof dimensions[i] === 'string') {
  22118. dimensionName = dimensions[i];
  22119. dimensionInfo = {
  22120. name: dimensionName,
  22121. coordDim: dimensionName,
  22122. coordDimIndex: 0,
  22123. stackable: false,
  22124. // Type can be 'float', 'int', 'number'
  22125. // Default is float64
  22126. type: 'float'
  22127. };
  22128. }
  22129. else {
  22130. dimensionInfo = dimensions[i];
  22131. dimensionName = dimensionInfo.name;
  22132. dimensionInfo.type = dimensionInfo.type || 'float';
  22133. if (!dimensionInfo.coordDim) {
  22134. dimensionInfo.coordDim = dimensionName;
  22135. dimensionInfo.coordDimIndex = 0;
  22136. }
  22137. }
  22138. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  22139. dimensionNames.push(dimensionName);
  22140. dimensionInfos[dimensionName] = dimensionInfo;
  22141. dimensionInfo.index = i;
  22142. }
  22143. /**
  22144. * @readOnly
  22145. * @type {Array.<string>}
  22146. */
  22147. this.dimensions = dimensionNames;
  22148. /**
  22149. * Infomation of each data dimension, like data type.
  22150. * @type {Object}
  22151. */
  22152. this._dimensionInfos = dimensionInfos;
  22153. /**
  22154. * @type {module:echarts/model/Model}
  22155. */
  22156. this.hostModel = hostModel;
  22157. /**
  22158. * @type {module:echarts/model/Model}
  22159. */
  22160. this.dataType;
  22161. /**
  22162. * Indices stores the indices of data subset after filtered.
  22163. * This data subset will be used in chart.
  22164. * @type {Array.<number>}
  22165. * @readOnly
  22166. */
  22167. this._indices = null;
  22168. this._count = 0;
  22169. this._rawCount = 0;
  22170. /**
  22171. * Data storage
  22172. * @type {Object.<key, Array.<TypedArray|Array>>}
  22173. * @private
  22174. */
  22175. this._storage = {};
  22176. /**
  22177. * @type {Array.<string>}
  22178. */
  22179. this._nameList = [];
  22180. /**
  22181. * @type {Array.<string>}
  22182. */
  22183. this._idList = [];
  22184. /**
  22185. * Models of data option is stored sparse for optimizing memory cost
  22186. * @type {Array.<module:echarts/model/Model>}
  22187. * @private
  22188. */
  22189. this._optionModels = [];
  22190. /**
  22191. * @param {module:echarts/data/List}
  22192. */
  22193. this.stackedOn = null;
  22194. /**
  22195. * Global visual properties after visual coding
  22196. * @type {Object}
  22197. * @private
  22198. */
  22199. this._visual = {};
  22200. /**
  22201. * Globel layout properties.
  22202. * @type {Object}
  22203. * @private
  22204. */
  22205. this._layout = {};
  22206. /**
  22207. * Item visual properties after visual coding
  22208. * @type {Array.<Object>}
  22209. * @private
  22210. */
  22211. this._itemVisuals = [];
  22212. /**
  22213. * Key: visual type, Value: boolean
  22214. * @type {Object}
  22215. * @readOnly
  22216. */
  22217. this.hasItemVisual = {};
  22218. /**
  22219. * Item layout properties after layout
  22220. * @type {Array.<Object>}
  22221. * @private
  22222. */
  22223. this._itemLayouts = [];
  22224. /**
  22225. * Graphic elemnents
  22226. * @type {Array.<module:zrender/Element>}
  22227. * @private
  22228. */
  22229. this._graphicEls = [];
  22230. /**
  22231. * Max size of each chunk.
  22232. * @type {number}
  22233. * @private
  22234. */
  22235. this._chunkSize = 1e5;
  22236. /**
  22237. * @type {number}
  22238. * @private
  22239. */
  22240. this._chunkCount = 0;
  22241. /**
  22242. * @type {Array.<Array|Object>}
  22243. * @private
  22244. */
  22245. this._rawData;
  22246. /**
  22247. * Raw extent will not be cloned, but only transfered.
  22248. * It will not be calculated util needed.
  22249. * key: dim,
  22250. * value: {end: number, extent: Array.<number>}
  22251. * @type {Object}
  22252. * @private
  22253. */
  22254. this._rawExtent = {};
  22255. /**
  22256. * @type {Object}
  22257. * @private
  22258. */
  22259. this._extent = {};
  22260. /**
  22261. * key: dim
  22262. * value: extent
  22263. * @type {Object}
  22264. * @private
  22265. */
  22266. this._approximateExtent = {};
  22267. /**
  22268. * Cache summary info for fast visit. See "dimensionHelper".
  22269. * @type {Object}
  22270. * @private
  22271. */
  22272. this._dimensionsSummary = summarizeDimensions(this);
  22273. };
  22274. var listProto = List.prototype;
  22275. listProto.type = 'list';
  22276. /**
  22277. * If each data item has it's own option
  22278. * @type {boolean}
  22279. */
  22280. listProto.hasItemOption = true;
  22281. /**
  22282. * Get dimension name
  22283. * @param {string|number} dim
  22284. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22285. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22286. * @return {string} Concrete dim name.
  22287. */
  22288. listProto.getDimension = function (dim) {
  22289. if (!isNaN(dim)) {
  22290. dim = this.dimensions[dim] || dim;
  22291. }
  22292. return dim;
  22293. };
  22294. /**
  22295. * Get type and stackable info of particular dimension
  22296. * @param {string|number} dim
  22297. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  22298. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  22299. */
  22300. listProto.getDimensionInfo = function (dim) {
  22301. // Do not clone, because there may be categories in dimInfo.
  22302. return this._dimensionInfos[this.getDimension(dim)];
  22303. };
  22304. /**
  22305. * @return {Array.<string>} concrete dimension name list on coord.
  22306. */
  22307. listProto.getDimensionsOnCoord = function () {
  22308. return this._dimensionsSummary.dataDimsOnCoord.slice();
  22309. };
  22310. /**
  22311. * @param {string} coordDim
  22312. * @param {number|Array} [idx=0] A coordDim may map to more than one data dim.
  22313. * If idx is `true`, return a array of all mapped dims.
  22314. * @return {string|Array.<string>} concrete data dim.
  22315. * If idx is number, and not found, return null/undefined.
  22316. * If idx is `true`, and not found, return empty array.
  22317. */
  22318. listProto.mapDimension = function (coordDim, idx) {
  22319. var dims = this._dimensionsSummary.encode[coordDim];
  22320. return idx === true
  22321. ? (dims && dims.slice() || [])
  22322. : dims
  22323. ? dims[idx || 0]
  22324. : null;
  22325. };
  22326. /**
  22327. * Initialize from data
  22328. * @param {Array.<Object|number|Array>} data source or data or data provider.
  22329. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  22330. * defualt label/tooltip.
  22331. * A name can be specified in encode.itemName,
  22332. * or dataItem.name (only for series option data),
  22333. * or provided in nameList from outside.
  22334. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  22335. */
  22336. listProto.initData = function (data, nameList, dimValueGetter) {
  22337. var notProvider = Source.isInstance(data) || isArrayLike(data);
  22338. if (notProvider) {
  22339. data = new DefaultDataProvider(data, this.dimensions.length);
  22340. }
  22341. if (__DEV__) {
  22342. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  22343. throw new Error('Inavlid data provider.');
  22344. }
  22345. }
  22346. this._rawData = data;
  22347. // Clear
  22348. this._storage = {};
  22349. this._indices = null;
  22350. this._nameList = nameList || [];
  22351. this._idList = [];
  22352. this._nameRepeatCount = {};
  22353. if (!dimValueGetter) {
  22354. this.hasItemOption = false;
  22355. }
  22356. /**
  22357. * @readOnly
  22358. */
  22359. this.defaultDimValueGetter = defaultDimValueGetters[
  22360. this._rawData.getSource().sourceFormat
  22361. ];
  22362. // Default dim value getter
  22363. this._dimValueGetter = dimValueGetter = dimValueGetter
  22364. || this.defaultDimValueGetter;
  22365. // Reset raw extent.
  22366. this._rawExtent = {};
  22367. this._initDataFromProvider(0, data.count());
  22368. // If data has no item option.
  22369. if (data.pure) {
  22370. this.hasItemOption = false;
  22371. }
  22372. };
  22373. listProto.getProvider = function () {
  22374. return this._rawData;
  22375. };
  22376. listProto.appendData = function (data) {
  22377. if (__DEV__) {
  22378. assert$1(!this._indices, 'appendData can only be called on raw data.');
  22379. }
  22380. var rawData = this._rawData;
  22381. var start = this.count();
  22382. rawData.appendData(data);
  22383. var end = rawData.count();
  22384. if (!rawData.persistent) {
  22385. end += start;
  22386. }
  22387. this._initDataFromProvider(start, end);
  22388. };
  22389. listProto._initDataFromProvider = function (start, end) {
  22390. // Optimize.
  22391. if (start >= end) {
  22392. return;
  22393. }
  22394. var chunkSize = this._chunkSize;
  22395. var rawData = this._rawData;
  22396. var storage = this._storage;
  22397. var dimensions = this.dimensions;
  22398. var dimensionInfoMap = this._dimensionInfos;
  22399. var nameList = this._nameList;
  22400. var idList = this._idList;
  22401. var rawExtent = this._rawExtent;
  22402. var nameRepeatCount = this._nameRepeatCount = {};
  22403. var nameDimIdx;
  22404. var chunkCount = this._chunkCount;
  22405. var lastChunkIndex = chunkCount - 1;
  22406. for (var i = 0; i < dimensions.length; i++) {
  22407. var dim = dimensions[i];
  22408. if (!rawExtent[dim]) {
  22409. rawExtent[dim] = [Infinity, -Infinity];
  22410. }
  22411. var dimInfo = dimensionInfoMap[dim];
  22412. if (dimInfo.otherDims.itemName === 0) {
  22413. nameDimIdx = this._nameDimIdx = i;
  22414. }
  22415. if (dimInfo.otherDims.itemId === 0) {
  22416. this._idDimIdx = i;
  22417. }
  22418. var DataCtor = dataCtors[dimInfo.type];
  22419. if (!storage[dim]) {
  22420. storage[dim] = [];
  22421. }
  22422. var resizeChunkArray = storage[dim][lastChunkIndex];
  22423. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  22424. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  22425. // The cost of the copy is probably inconsiderable
  22426. // within the initial chunkSize.
  22427. for (var j = 0; j < resizeChunkArray.length; j++) {
  22428. newStore[j] = resizeChunkArray[j];
  22429. }
  22430. storage[dim][lastChunkIndex] = newStore;
  22431. }
  22432. // Create new chunks.
  22433. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  22434. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  22435. }
  22436. this._chunkCount = storage[dim].length;
  22437. }
  22438. for (var idx = start; idx < end; idx++) {
  22439. // NOTICE: Try not to write things into dataItem
  22440. var dataItem = rawData.getItem(idx);
  22441. // Each data item is value
  22442. // [1, 2]
  22443. // 2
  22444. // Bar chart, line chart which uses category axis
  22445. // only gives the 'y' value. 'x' value is the indices of category
  22446. // Use a tempValue to normalize the value to be a (x, y) value
  22447. var chunkIndex = Math.floor(idx / chunkSize);
  22448. var chunkOffset = idx % chunkSize;
  22449. // Store the data by dimensions
  22450. for (var k = 0; k < dimensions.length; k++) {
  22451. var dim = dimensions[k];
  22452. var dimStorage = storage[dim][chunkIndex];
  22453. // PENDING NULL is empty or zero
  22454. var val = this._dimValueGetter(dataItem, dim, idx, k);
  22455. dimStorage[chunkOffset] = val;
  22456. if (val < rawExtent[dim][0]) {
  22457. rawExtent[dim][0] = val;
  22458. }
  22459. if (val > rawExtent[dim][1]) {
  22460. rawExtent[dim][1] = val;
  22461. }
  22462. }
  22463. // ??? FIXME not check by pure but sourceFormat?
  22464. // TODO refactor these logic.
  22465. if (!rawData.pure) {
  22466. var name = nameList[idx];
  22467. if (dataItem && !name) {
  22468. if (nameDimIdx != null) {
  22469. name = this._getNameFromStore(idx);
  22470. }
  22471. else if (dataItem.name != null) {
  22472. // There is no other place to persistent dataItem.name,
  22473. // so save it to nameList.
  22474. nameList[idx] = name = dataItem.name;
  22475. }
  22476. }
  22477. // Try using the id in option
  22478. // id or name is used on dynamical data, mapping old and new items.
  22479. var id = dataItem == null ? null : dataItem.id;
  22480. if (id == null && name != null) {
  22481. // Use name as id and add counter to avoid same name
  22482. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  22483. id = name;
  22484. if (nameRepeatCount[name] > 0) {
  22485. id += '__ec__' + nameRepeatCount[name];
  22486. }
  22487. nameRepeatCount[name]++;
  22488. }
  22489. id != null && (idList[idx] = id);
  22490. }
  22491. }
  22492. if (!rawData.persistent && rawData.clean) {
  22493. // Clean unused data if data source is typed array.
  22494. rawData.clean();
  22495. }
  22496. this._rawCount = this._count = end;
  22497. // Reset data extent
  22498. this._extent = {};
  22499. };
  22500. // TODO refactor
  22501. listProto._getNameFromStore = function (rawIndex) {
  22502. var nameDimIdx = this._nameDimIdx;
  22503. if (nameDimIdx != null) {
  22504. var chunkSize = this._chunkSize;
  22505. var chunkIndex = Math.floor(rawIndex / chunkSize);
  22506. var chunkOffset = rawIndex % chunkSize;
  22507. var dim = this.dimensions[nameDimIdx];
  22508. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  22509. if (ordinalMeta) {
  22510. return ordinalMeta.categories[rawIndex];
  22511. }
  22512. else {
  22513. var chunk = this._storage[dim][chunkIndex];
  22514. return chunk && chunk[chunkOffset];
  22515. }
  22516. }
  22517. };
  22518. // TODO refactor
  22519. listProto._getIdFromStore = function (rawIndex) {
  22520. var idDimIdx = this._idDimIdx;
  22521. if (idDimIdx != null) {
  22522. var chunkSize = this._chunkSize;
  22523. var chunkIndex = Math.floor(rawIndex / chunkSize);
  22524. var chunkOffset = rawIndex % chunkSize;
  22525. var dim = this.dimensions[idDimIdx];
  22526. var ordinalMeta = this._dimensionInfos[dim].ordinalMeta;
  22527. if (ordinalMeta) {
  22528. return ordinalMeta.categories[rawIndex];
  22529. }
  22530. else {
  22531. var chunk = this._storage[dim][chunkIndex];
  22532. return chunk && chunk[chunkOffset];
  22533. }
  22534. }
  22535. };
  22536. /**
  22537. * @return {number}
  22538. */
  22539. listProto.count = function () {
  22540. return this._count;
  22541. };
  22542. listProto.getIndices = function () {
  22543. if (this._indices) {
  22544. var Ctor = this._indices.constructor;
  22545. return new Ctor(this._indices.buffer, 0, this._count);
  22546. }
  22547. var Ctor = getIndicesCtor(this);
  22548. var arr = new Ctor(this.count());
  22549. for (var i = 0; i < arr.length; i++) {
  22550. arr[i] = i;
  22551. }
  22552. return arr;
  22553. };
  22554. /**
  22555. * Get value. Return NaN if idx is out of range.
  22556. * @param {string} dim Dim must be concrete name.
  22557. * @param {number} idx
  22558. * @param {boolean} stack
  22559. * @return {number}
  22560. */
  22561. listProto.get = function (dim, idx, stack) {
  22562. if (!(idx >= 0 && idx < this._count)) {
  22563. return NaN;
  22564. }
  22565. var storage = this._storage;
  22566. if (!storage[dim]) {
  22567. // TODO Warn ?
  22568. return NaN;
  22569. }
  22570. idx = this.getRawIndex(idx);
  22571. var chunkIndex = Math.floor(idx / this._chunkSize);
  22572. var chunkOffset = idx % this._chunkSize;
  22573. var chunkStore = storage[dim][chunkIndex];
  22574. var value = chunkStore[chunkOffset];
  22575. // FIXME ordinal data type is not stackable
  22576. if (stack) {
  22577. var dimensionInfo = this._dimensionInfos[dim];
  22578. if (dimensionInfo && dimensionInfo.stackable) {
  22579. var stackedOn = this.stackedOn;
  22580. while (stackedOn) {
  22581. // Get no stacked data of stacked on
  22582. var stackedValue = stackedOn.get(dim, idx);
  22583. // Considering positive stack, negative stack and empty data
  22584. if ((value >= 0 && stackedValue > 0) // Positive stack
  22585. || (value <= 0 && stackedValue < 0) // Negative stack
  22586. ) {
  22587. value += stackedValue;
  22588. }
  22589. stackedOn = stackedOn.stackedOn;
  22590. }
  22591. }
  22592. }
  22593. return value;
  22594. };
  22595. // FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  22596. // Hack a much simpler _getFast
  22597. listProto._getFast = function (dim, rawIdx) {
  22598. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  22599. var chunkOffset = rawIdx % this._chunkSize;
  22600. var chunkStore = this._storage[dim][chunkIndex];
  22601. return chunkStore[chunkOffset];
  22602. };
  22603. /**
  22604. * Get value for multi dimensions.
  22605. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  22606. * @param {number} idx
  22607. * @param {boolean} stack
  22608. * @return {number}
  22609. */
  22610. listProto.getValues = function (dimensions, idx, stack) {
  22611. var values = [];
  22612. if (!isArray(dimensions)) {
  22613. stack = idx;
  22614. idx = dimensions;
  22615. dimensions = this.dimensions;
  22616. }
  22617. for (var i = 0, len = dimensions.length; i < len; i++) {
  22618. values.push(this.get(dimensions[i], idx, stack));
  22619. }
  22620. return values;
  22621. };
  22622. /**
  22623. * If value is NaN. Inlcuding '-'
  22624. * Only check the coord dimensions.
  22625. * @param {string} dim
  22626. * @param {number} idx
  22627. * @return {number}
  22628. */
  22629. listProto.hasValue = function (idx) {
  22630. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  22631. var dimensionInfos = this._dimensionInfos;
  22632. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  22633. if (
  22634. // Ordinal type can be string or number
  22635. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  22636. // FIXME check ordinal when using index?
  22637. && isNaN(this.get(dataDimsOnCoord[i], idx))
  22638. ) {
  22639. return false;
  22640. }
  22641. }
  22642. return true;
  22643. };
  22644. /**
  22645. * Get extent of data in one dimension
  22646. * @param {string} dim
  22647. * @param {boolean} stack
  22648. */
  22649. listProto.getDataExtent = function (dim, stack) {
  22650. // Make sure use concrete dim as cache name.
  22651. dim = this.getDimension(dim);
  22652. var dimData = this._storage[dim];
  22653. var initialExtent = [Infinity, -Infinity];
  22654. stack = (stack || false) && this.isStacked(dim);
  22655. if (!dimData) {
  22656. return initialExtent;
  22657. }
  22658. // Make more strict checkings to ensure hitting cache.
  22659. var currEnd = this.count();
  22660. var cacheName = [dim, !!stack].join('_');
  22661. // Consider the most cases when using data zoom, `getDataExtent`
  22662. // happened before filtering. We cache raw extent, which is not
  22663. // necessary to be cleared and recalculated when restore data.
  22664. var useRaw = !this._indices && !stack;
  22665. var dimExtent;
  22666. if (useRaw) {
  22667. return this._rawExtent[dim].slice();
  22668. }
  22669. dimExtent = this._extent[cacheName];
  22670. if (dimExtent) {
  22671. return dimExtent.slice();
  22672. }
  22673. dimExtent = initialExtent;
  22674. var min = dimExtent[0];
  22675. var max = dimExtent[1];
  22676. for (var i = 0; i < currEnd; i++) {
  22677. var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  22678. value < min && (min = value);
  22679. value > max && (max = value);
  22680. }
  22681. dimExtent = [min, max];
  22682. this._extent[cacheName] = dimExtent;
  22683. return dimExtent;
  22684. };
  22685. /**
  22686. * Optimize for the scenario that data is filtered by a given extent.
  22687. * Consider that if data amount is more than hundreds of thousand,
  22688. * extent calculation will cost more than 10ms and the cache will
  22689. * be erased because of the filtering.
  22690. */
  22691. listProto.getApproximateExtent = function (dim, stack) {
  22692. dim = this.getDimension(dim);
  22693. return this._approximateExtent[dim] || this.getDataExtent(dim, stack);
  22694. };
  22695. listProto.setApproximateExtent = function (extent, dim, stack) {
  22696. dim = this.getDimension(dim);
  22697. this._approximateExtent[dim] = extent.slice();
  22698. };
  22699. listProto.isStacked = function (concreteDim) {
  22700. var dimensionInfo = this._dimensionInfos[concreteDim];
  22701. return dimensionInfo && dimensionInfo.stackable && this.stackedOn;
  22702. };
  22703. /**
  22704. * Get sum of data in one dimension
  22705. * @param {string} dim
  22706. * @param {boolean} stack
  22707. */
  22708. listProto.getSum = function (dim, stack) {
  22709. var dimData = this._storage[dim];
  22710. var sum = 0;
  22711. if (dimData) {
  22712. for (var i = 0, len = this.count(); i < len; i++) {
  22713. var value = this.get(dim, i, stack);
  22714. if (!isNaN(value)) {
  22715. sum += value;
  22716. }
  22717. }
  22718. }
  22719. return sum;
  22720. };
  22721. /**
  22722. * Retreive the index with given value
  22723. * @param {number} idx
  22724. * @param {number} value
  22725. * @return {number}
  22726. */
  22727. // FIXME Precision of float value
  22728. listProto.indexOf = function (dim, value) {
  22729. var storage = this._storage;
  22730. var dimData = storage[dim];
  22731. var chunkSize = this._chunkSize;
  22732. if (dimData) {
  22733. for (var i = 0, len = this.count(); i < len; i++) {
  22734. var chunkIndex = Math.floor(i / chunkSize);
  22735. var chunkOffset = i % chunkSize;
  22736. if (dimData[chunkIndex][chunkOffset] === value) {
  22737. return i;
  22738. }
  22739. }
  22740. }
  22741. return -1;
  22742. };
  22743. /**
  22744. * Retreive the index with given name
  22745. * @param {number} idx
  22746. * @param {number} name
  22747. * @return {number}
  22748. */
  22749. listProto.indexOfName = function (name) {
  22750. for (var i = 0, len = this.count(); i < len; i++) {
  22751. if (this.getName(i) === name) {
  22752. return i;
  22753. }
  22754. }
  22755. return -1;
  22756. };
  22757. /**
  22758. * Retreive the index with given raw data index
  22759. * @param {number} idx
  22760. * @param {number} name
  22761. * @return {number}
  22762. */
  22763. listProto.indexOfRawIndex = function (rawIndex) {
  22764. if (!this._indices) {
  22765. return rawIndex;
  22766. }
  22767. if (rawIndex >= this._rawCount || rawIndex < 0) {
  22768. return -1;
  22769. }
  22770. // Indices are ascending
  22771. var indices = this._indices;
  22772. // If rawIndex === dataIndex
  22773. var rawDataIndex = indices[rawIndex];
  22774. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  22775. return rawIndex;
  22776. }
  22777. var left = 0;
  22778. var right = this._count - 1;
  22779. while (left <= right) {
  22780. var mid = (left + right) / 2 | 0;
  22781. if (indices[mid] < rawIndex) {
  22782. left = mid + 1;
  22783. }
  22784. else if (indices[mid] > rawIndex) {
  22785. right = mid - 1;
  22786. }
  22787. else {
  22788. return mid;
  22789. }
  22790. }
  22791. return -1;
  22792. };
  22793. /**
  22794. * Retreive the index of nearest value
  22795. * @param {string} dim
  22796. * @param {number} value
  22797. * @param {boolean} stack If given value is after stacked
  22798. * @param {number} [maxDistance=Infinity]
  22799. * @return {Array.<number>} Considere multiple points has the same value.
  22800. */
  22801. listProto.indicesOfNearest = function (dim, value, stack, maxDistance) {
  22802. var storage = this._storage;
  22803. var dimData = storage[dim];
  22804. var nearestIndices = [];
  22805. if (!dimData) {
  22806. return nearestIndices;
  22807. }
  22808. if (maxDistance == null) {
  22809. maxDistance = Infinity;
  22810. }
  22811. var minDist = Number.MAX_VALUE;
  22812. var minDiff = -1;
  22813. for (var i = 0, len = this.count(); i < len; i++) {
  22814. var diff = value - this.get(dim, i, stack);
  22815. var dist = Math.abs(diff);
  22816. if (diff <= maxDistance && dist <= minDist) {
  22817. // For the case of two data are same on xAxis, which has sequence data.
  22818. // Show the nearest index
  22819. // https://github.com/ecomfe/echarts/issues/2869
  22820. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  22821. minDist = dist;
  22822. minDiff = diff;
  22823. nearestIndices.length = 0;
  22824. }
  22825. nearestIndices.push(i);
  22826. }
  22827. }
  22828. return nearestIndices;
  22829. };
  22830. /**
  22831. * Get raw data index
  22832. * @param {number} idx
  22833. * @return {number}
  22834. */
  22835. listProto.getRawIndex = getRawIndexWithoutIndices;
  22836. function getRawIndexWithoutIndices(idx) {
  22837. return idx;
  22838. }
  22839. function getRawIndexWithIndices(idx) {
  22840. if (idx < this._count && idx >= 0) {
  22841. return this._indices[idx];
  22842. }
  22843. return -1;
  22844. }
  22845. /**
  22846. * Get raw data item
  22847. * @param {number} idx
  22848. * @return {number}
  22849. */
  22850. listProto.getRawDataItem = function (idx) {
  22851. if (!this._rawData.persistent) {
  22852. var val = [];
  22853. for (var i = 0; i < this.dimensions.length; i++) {
  22854. var dim = this.dimensions[i];
  22855. val.push(this.get(dim, idx));
  22856. }
  22857. return val;
  22858. }
  22859. else {
  22860. return this._rawData.getItem(this.getRawIndex(idx));
  22861. }
  22862. };
  22863. /**
  22864. * @param {number} idx
  22865. * @param {boolean} [notDefaultIdx=false]
  22866. * @return {string}
  22867. */
  22868. listProto.getName = function (idx) {
  22869. var rawIndex = this.getRawIndex(idx);
  22870. return this._nameList[rawIndex]
  22871. || this._getNameFromStore(rawIndex)
  22872. || '';
  22873. };
  22874. /**
  22875. * @param {number} idx
  22876. * @param {boolean} [notDefaultIdx=false]
  22877. * @return {string}
  22878. */
  22879. listProto.getId = function (idx) {
  22880. return getId(this, this.getRawIndex(idx));
  22881. };
  22882. function getId(list, rawIndex) {
  22883. var id = list._idList[rawIndex];
  22884. if (id == null) {
  22885. id = list._getIdFromStore(rawIndex);
  22886. }
  22887. if (id == null) {
  22888. // FIXME Check the usage in graph, should not use prefix.
  22889. id = ID_PREFIX + rawIndex;
  22890. }
  22891. return id;
  22892. }
  22893. function normalizeDimensions(dimensions) {
  22894. if (!isArray(dimensions)) {
  22895. dimensions = [dimensions];
  22896. }
  22897. return dimensions;
  22898. }
  22899. function validateDimensions(list, dims) {
  22900. for (var i = 0; i < dims.length; i++) {
  22901. // stroage may be empty when no data, so use
  22902. // dimensionInfos to check.
  22903. if (!list._dimensionInfos[dims[i]]) {
  22904. console.error('Unkown dimension ' + dims[i]);
  22905. }
  22906. }
  22907. }
  22908. /**
  22909. * Data iteration
  22910. * @param {string|Array.<string>}
  22911. * @param {Function} cb
  22912. * @param {boolean} [stack=false]
  22913. * @param {*} [context=this]
  22914. *
  22915. * @example
  22916. * list.each('x', function (x, idx) {});
  22917. * list.each(['x', 'y'], function (x, y, idx) {});
  22918. * list.each(function (idx) {})
  22919. */
  22920. listProto.each = function (dims, cb, stack, context) {
  22921. 'use strict';
  22922. if (!this._count) {
  22923. return;
  22924. }
  22925. if (typeof dims === 'function') {
  22926. context = stack;
  22927. stack = cb;
  22928. cb = dims;
  22929. dims = [];
  22930. }
  22931. dims = map(normalizeDimensions(dims), this.getDimension, this);
  22932. if (__DEV__) {
  22933. validateDimensions(this, dims);
  22934. }
  22935. var dimSize = dims.length;
  22936. context = context || this;
  22937. for (var i = 0; i < this.count(); i++) {
  22938. // Simple optimization
  22939. switch (dimSize) {
  22940. case 0:
  22941. cb.call(context, i);
  22942. break;
  22943. case 1:
  22944. cb.call(context, this.get(dims[0], i, stack), i);
  22945. break;
  22946. case 2:
  22947. cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i);
  22948. break;
  22949. default:
  22950. var k = 0;
  22951. var value = [];
  22952. for (; k < dimSize; k++) {
  22953. value[k] = this.get(dims[k], i, stack);
  22954. }
  22955. // Index
  22956. value[k] = i;
  22957. cb.apply(context, value);
  22958. }
  22959. }
  22960. };
  22961. /**
  22962. * Data filter
  22963. * @param {string|Array.<string>}
  22964. * @param {Function} cb
  22965. * @param {boolean} [stack=false]
  22966. * @param {*} [context=this]
  22967. */
  22968. listProto.filterSelf = function (dimensions, cb, stack, context) {
  22969. 'use strict';
  22970. if (!this._count) {
  22971. return;
  22972. }
  22973. if (typeof dimensions === 'function') {
  22974. context = stack;
  22975. stack = cb;
  22976. cb = dimensions;
  22977. dimensions = [];
  22978. }
  22979. stack = stack || false;
  22980. context = context || this;
  22981. dimensions = map(
  22982. normalizeDimensions(dimensions), this.getDimension, this
  22983. );
  22984. if (__DEV__) {
  22985. validateDimensions(this, dimensions);
  22986. }
  22987. var count = this.count();
  22988. var Ctor = getIndicesCtor(this);
  22989. var newIndices = new Ctor(count);
  22990. var value = [];
  22991. var dimSize = dimensions.length;
  22992. var offset = 0;
  22993. var dim0 = dimensions[0];
  22994. for (var i = 0; i < count; i++) {
  22995. var keep;
  22996. var rawIdx = this.getRawIndex(i);
  22997. // Simple optimization
  22998. if (dimSize === 0) {
  22999. keep = cb.call(context, i);
  23000. }
  23001. else if (dimSize === 1) {
  23002. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIdx);
  23003. keep = cb.call(context, val, i);
  23004. }
  23005. else {
  23006. for (var k = 0; k < dimSize; k++) {
  23007. value[k] = stack ? this.get(dimensions[k], i, true) : this._getFast(dim0, rawIdx);
  23008. }
  23009. value[k] = i;
  23010. keep = cb.apply(context, value);
  23011. }
  23012. if (keep) {
  23013. newIndices[offset++] = rawIdx;
  23014. }
  23015. }
  23016. // Set indices after filtered.
  23017. if (offset < count) {
  23018. this._indices = newIndices;
  23019. }
  23020. this._count = offset;
  23021. // Reset data extent
  23022. this._extent = {};
  23023. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23024. return this;
  23025. };
  23026. /**
  23027. * Select data in range. (For optimization of filter)
  23028. * (Manually inline code, support 5 million data filtering in data zoom.)
  23029. */
  23030. listProto.selectRange = function (range, stack) {
  23031. 'use strict';
  23032. if (!this._count) {
  23033. return;
  23034. }
  23035. stack = stack || false;
  23036. var dimensions = [];
  23037. for (var dim in range) {
  23038. if (range.hasOwnProperty(dim)) {
  23039. dimensions.push(dim);
  23040. }
  23041. }
  23042. if (__DEV__) {
  23043. validateDimensions(this, dimensions);
  23044. }
  23045. var dimSize = dimensions.length;
  23046. if (!dimSize) {
  23047. return;
  23048. }
  23049. var originalCount = this.count();
  23050. var Ctor = getIndicesCtor(this);
  23051. var newIndices = new Ctor(originalCount);
  23052. var offset = 0;
  23053. var dim0 = dimensions[0];
  23054. var min = range[dim0][0];
  23055. var max = range[dim0][1];
  23056. var quickFinished = false;
  23057. if (!this._indices && !stack) {
  23058. // Extreme optimization for common case. About 2x faster in chrome.
  23059. var idx = 0;
  23060. if (dimSize === 1) {
  23061. var dimStorage = this._storage[dimensions[0]];
  23062. for (var k = 0; k < this._chunkCount; k++) {
  23063. var chunkStorage = dimStorage[k];
  23064. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23065. for (var i = 0; i < len; i++) {
  23066. var val = chunkStorage[i];
  23067. if (val >= min && val <= max) {
  23068. newIndices[offset++] = idx;
  23069. }
  23070. idx++;
  23071. }
  23072. }
  23073. quickFinished = true;
  23074. }
  23075. else if (dimSize === 2) {
  23076. var dimStorage = this._storage[dim0];
  23077. var dimStorage2 = this._storage[dimensions[1]];
  23078. var min2 = range[dimensions[1]][0];
  23079. var max2 = range[dimensions[1]][1];
  23080. for (var k = 0; k < this._chunkCount; k++) {
  23081. var chunkStorage = dimStorage[k];
  23082. var chunkStorage2= dimStorage2[k];
  23083. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  23084. for (var i = 0; i < len; i++) {
  23085. var val = chunkStorage[i];
  23086. var val2 = chunkStorage2[i];
  23087. if (val >= min && val <= max && val2 >= min2 && val2 <= max2) {
  23088. newIndices[offset++] = idx;
  23089. }
  23090. idx++;
  23091. }
  23092. }
  23093. quickFinished = true;
  23094. }
  23095. }
  23096. if (!quickFinished) {
  23097. if (dimSize === 1) {
  23098. stack = stack || this.isStacked(dim0);
  23099. for (var i = 0; i < originalCount; i++) {
  23100. var rawIndex = this.getRawIndex(i);
  23101. var val = stack ? this.get(dim0, i, true) : this._getFast(dim0, rawIndex);
  23102. if (val >= min && val <= max) {
  23103. newIndices[offset++] = rawIndex;
  23104. }
  23105. }
  23106. }
  23107. else {
  23108. for (var i = 0; i < originalCount; i++) {
  23109. var keep = true;
  23110. var rawIndex = this.getRawIndex(i);
  23111. for (var k = 0; k < dimSize; k++) {
  23112. var dimk = dimensions[k];
  23113. var val = stack ? this.get(dimk, i, true) : this._getFast(dim, rawIndex);
  23114. if (val < range[dimk][0] || val > range[dimk][1]) {
  23115. keep = false;
  23116. }
  23117. }
  23118. if (keep) {
  23119. newIndices[offset++] = this.getRawIndex(i);
  23120. }
  23121. }
  23122. }
  23123. }
  23124. // Set indices after filtered.
  23125. if (offset < originalCount) {
  23126. this._indices = newIndices;
  23127. }
  23128. this._count = offset;
  23129. // Reset data extent
  23130. this._extent = {};
  23131. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23132. return this;
  23133. };
  23134. /**
  23135. * Data mapping to a plain array
  23136. * @param {string|Array.<string>} [dimensions]
  23137. * @param {Function} cb
  23138. * @param {boolean} [stack=false]
  23139. * @param {*} [context=this]
  23140. * @return {Array}
  23141. */
  23142. listProto.mapArray = function (dimensions, cb, stack, context) {
  23143. 'use strict';
  23144. if (typeof dimensions === 'function') {
  23145. context = stack;
  23146. stack = cb;
  23147. cb = dimensions;
  23148. dimensions = [];
  23149. }
  23150. var result = [];
  23151. this.each(dimensions, function () {
  23152. result.push(cb && cb.apply(this, arguments));
  23153. }, stack, context);
  23154. return result;
  23155. };
  23156. // Data in excludeDimensions is copied, otherwise transfered.
  23157. function cloneListForMapAndSample(original, excludeDimensions) {
  23158. var allDimensions = original.dimensions;
  23159. var list = new List(
  23160. map(allDimensions, original.getDimensionInfo, original),
  23161. original.hostModel
  23162. );
  23163. // FIXME If needs stackedOn, value may already been stacked
  23164. transferProperties(list, original);
  23165. var storage = list._storage = {};
  23166. var originalStorage = original._storage;
  23167. // Init storage
  23168. for (var i = 0; i < allDimensions.length; i++) {
  23169. var dim = allDimensions[i];
  23170. if (originalStorage[dim]) {
  23171. storage[dim] = indexOf(excludeDimensions, dim) >= 0
  23172. ? cloneDimStore(originalStorage[dim])
  23173. // Direct reference for other dimensions
  23174. : originalStorage[dim];
  23175. }
  23176. }
  23177. return list;
  23178. }
  23179. function cloneDimStore(originalDimStore) {
  23180. var newDimStore = new Array(originalDimStore.length);
  23181. for (var j = 0; j < originalDimStore.length; j++) {
  23182. newDimStore[j] = cloneChunk(originalDimStore[j]);
  23183. }
  23184. return newDimStore;
  23185. }
  23186. /**
  23187. * Data mapping to a new List with given dimensions
  23188. * @param {string|Array.<string>} dimensions
  23189. * @param {Function} cb
  23190. * @param {boolean} [stack=false]
  23191. * @param {*} [context=this]
  23192. * @return {Array}
  23193. */
  23194. listProto.map = function (dimensions, cb, stack, context) {
  23195. 'use strict';
  23196. dimensions = map(
  23197. normalizeDimensions(dimensions), this.getDimension, this
  23198. );
  23199. if (__DEV__) {
  23200. validateDimensions(this, dimensions);
  23201. }
  23202. var list = cloneListForMapAndSample(this, dimensions);
  23203. // Following properties are all immutable.
  23204. // So we can reference to the same value
  23205. list._indices = this._indices;
  23206. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23207. var storage = list._storage;
  23208. var tmpRetValue = [];
  23209. var chunkSize = this._chunkSize;
  23210. var dimSize = dimensions.length;
  23211. var dataCount = this.count();
  23212. var values = [];
  23213. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  23214. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  23215. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex, stack);
  23216. }
  23217. values[dimSize] = dataIndex;
  23218. var retValue = cb && cb.apply(context, values);
  23219. if (retValue != null) {
  23220. // a number or string (in oridinal dimension)?
  23221. if (typeof retValue !== 'object') {
  23222. tmpRetValue[0] = retValue;
  23223. retValue = tmpRetValue;
  23224. }
  23225. var rawIndex = this.getRawIndex(dataIndex);
  23226. var chunkIndex = Math.floor(rawIndex / chunkSize);
  23227. var chunkOffset = rawIndex % chunkSize;
  23228. for (var i = 0; i < retValue.length; i++) {
  23229. var dim = dimensions[i];
  23230. var dimStore = storage[dim];
  23231. if (dimStore) {
  23232. dimStore[chunkIndex][chunkOffset] = retValue[i];
  23233. }
  23234. }
  23235. }
  23236. }
  23237. return list;
  23238. };
  23239. /**
  23240. * Large data down sampling on given dimension
  23241. * @param {string} dimension
  23242. * @param {number} rate
  23243. * @param {Function} sampleValue
  23244. * @param {Function} sampleIndex Sample index for name and id
  23245. */
  23246. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  23247. var list = cloneListForMapAndSample(this, [dimension]);
  23248. var targetStorage = list._storage;
  23249. var frameValues = [];
  23250. var frameSize = Math.floor(1 / rate);
  23251. var dimStore = targetStorage[dimension];
  23252. var len = this.count();
  23253. var chunkSize = this._chunkSize;
  23254. var newIndices = new (getIndicesCtor(this))(len);
  23255. var offset = 0;
  23256. for (var i = 0; i < len; i += frameSize) {
  23257. // Last frame
  23258. if (frameSize > len - i) {
  23259. frameSize = len - i;
  23260. frameValues.length = frameSize;
  23261. }
  23262. for (var k = 0; k < frameSize; k++) {
  23263. var dataIdx = this.getRawIndex(i + k);
  23264. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  23265. var originalChunkOffset = dataIdx % chunkSize;
  23266. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  23267. }
  23268. var value = sampleValue(frameValues);
  23269. var sampleFrameIdx = this.getRawIndex(
  23270. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  23271. );
  23272. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  23273. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  23274. // Only write value on the filtered data
  23275. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  23276. newIndices[offset++] = sampleFrameIdx;
  23277. }
  23278. list._count = offset;
  23279. list._indices = newIndices;
  23280. list.getRawIndex = getRawIndexWithIndices;
  23281. return list;
  23282. };
  23283. /**
  23284. * Get model of one data item.
  23285. *
  23286. * @param {number} idx
  23287. */
  23288. // FIXME Model proxy ?
  23289. listProto.getItemModel = function (idx) {
  23290. var hostModel = this.hostModel;
  23291. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  23292. };
  23293. /**
  23294. * Create a data differ
  23295. * @param {module:echarts/data/List} otherList
  23296. * @return {module:echarts/data/DataDiffer}
  23297. */
  23298. listProto.diff = function (otherList) {
  23299. var thisList = this;
  23300. return new DataDiffer(
  23301. otherList ? otherList.getIndices() : [],
  23302. this.getIndices(),
  23303. function (idx) {
  23304. return getId(otherList, idx);
  23305. },
  23306. function (idx) {
  23307. return getId(thisList, idx);
  23308. }
  23309. );
  23310. };
  23311. /**
  23312. * Get visual property.
  23313. * @param {string} key
  23314. */
  23315. listProto.getVisual = function (key) {
  23316. var visual = this._visual;
  23317. return visual && visual[key];
  23318. };
  23319. /**
  23320. * Set visual property
  23321. * @param {string|Object} key
  23322. * @param {*} [value]
  23323. *
  23324. * @example
  23325. * setVisual('color', color);
  23326. * setVisual({
  23327. * 'color': color
  23328. * });
  23329. */
  23330. listProto.setVisual = function (key, val) {
  23331. if (isObject$4(key)) {
  23332. for (var name in key) {
  23333. if (key.hasOwnProperty(name)) {
  23334. this.setVisual(name, key[name]);
  23335. }
  23336. }
  23337. return;
  23338. }
  23339. this._visual = this._visual || {};
  23340. this._visual[key] = val;
  23341. };
  23342. /**
  23343. * Set layout property.
  23344. * @param {string|Object} key
  23345. * @param {*} [val]
  23346. */
  23347. listProto.setLayout = function (key, val) {
  23348. if (isObject$4(key)) {
  23349. for (var name in key) {
  23350. if (key.hasOwnProperty(name)) {
  23351. this.setLayout(name, key[name]);
  23352. }
  23353. }
  23354. return;
  23355. }
  23356. this._layout[key] = val;
  23357. };
  23358. /**
  23359. * Get layout property.
  23360. * @param {string} key.
  23361. * @return {*}
  23362. */
  23363. listProto.getLayout = function (key) {
  23364. return this._layout[key];
  23365. };
  23366. /**
  23367. * Get layout of single data item
  23368. * @param {number} idx
  23369. */
  23370. listProto.getItemLayout = function (idx) {
  23371. return this._itemLayouts[idx];
  23372. };
  23373. /**
  23374. * Set layout of single data item
  23375. * @param {number} idx
  23376. * @param {Object} layout
  23377. * @param {boolean=} [merge=false]
  23378. */
  23379. listProto.setItemLayout = function (idx, layout, merge$$1) {
  23380. this._itemLayouts[idx] = merge$$1
  23381. ? extend(this._itemLayouts[idx] || {}, layout)
  23382. : layout;
  23383. };
  23384. /**
  23385. * Clear all layout of single data item
  23386. */
  23387. listProto.clearItemLayouts = function () {
  23388. this._itemLayouts.length = 0;
  23389. };
  23390. /**
  23391. * Get visual property of single data item
  23392. * @param {number} idx
  23393. * @param {string} key
  23394. * @param {boolean} [ignoreParent=false]
  23395. */
  23396. listProto.getItemVisual = function (idx, key, ignoreParent) {
  23397. var itemVisual = this._itemVisuals[idx];
  23398. var val = itemVisual && itemVisual[key];
  23399. if (val == null && !ignoreParent) {
  23400. // Use global visual property
  23401. return this.getVisual(key);
  23402. }
  23403. return val;
  23404. };
  23405. /**
  23406. * Set visual property of single data item
  23407. *
  23408. * @param {number} idx
  23409. * @param {string|Object} key
  23410. * @param {*} [value]
  23411. *
  23412. * @example
  23413. * setItemVisual(0, 'color', color);
  23414. * setItemVisual(0, {
  23415. * 'color': color
  23416. * });
  23417. */
  23418. listProto.setItemVisual = function (idx, key, value) {
  23419. var itemVisual = this._itemVisuals[idx] || {};
  23420. var hasItemVisual = this.hasItemVisual;
  23421. this._itemVisuals[idx] = itemVisual;
  23422. if (isObject$4(key)) {
  23423. for (var name in key) {
  23424. if (key.hasOwnProperty(name)) {
  23425. itemVisual[name] = key[name];
  23426. hasItemVisual[name] = true;
  23427. }
  23428. }
  23429. return;
  23430. }
  23431. itemVisual[key] = value;
  23432. hasItemVisual[key] = true;
  23433. };
  23434. /**
  23435. * Clear itemVisuals and list visual.
  23436. */
  23437. listProto.clearAllVisual = function () {
  23438. this._visual = {};
  23439. this._itemVisuals = [];
  23440. this.hasItemVisual = {};
  23441. };
  23442. var setItemDataAndSeriesIndex = function (child) {
  23443. child.seriesIndex = this.seriesIndex;
  23444. child.dataIndex = this.dataIndex;
  23445. child.dataType = this.dataType;
  23446. };
  23447. /**
  23448. * Set graphic element relative to data. It can be set as null
  23449. * @param {number} idx
  23450. * @param {module:zrender/Element} [el]
  23451. */
  23452. listProto.setItemGraphicEl = function (idx, el) {
  23453. var hostModel = this.hostModel;
  23454. if (el) {
  23455. // Add data index and series index for indexing the data by element
  23456. // Useful in tooltip
  23457. el.dataIndex = idx;
  23458. el.dataType = this.dataType;
  23459. el.seriesIndex = hostModel && hostModel.seriesIndex;
  23460. if (el.type === 'group') {
  23461. el.traverse(setItemDataAndSeriesIndex, el);
  23462. }
  23463. }
  23464. this._graphicEls[idx] = el;
  23465. };
  23466. /**
  23467. * @param {number} idx
  23468. * @return {module:zrender/Element}
  23469. */
  23470. listProto.getItemGraphicEl = function (idx) {
  23471. return this._graphicEls[idx];
  23472. };
  23473. /**
  23474. * @param {Function} cb
  23475. * @param {*} context
  23476. */
  23477. listProto.eachItemGraphicEl = function (cb, context) {
  23478. each$1(this._graphicEls, function (el, idx) {
  23479. if (el) {
  23480. cb && cb.call(context, el, idx);
  23481. }
  23482. });
  23483. };
  23484. /**
  23485. * Shallow clone a new list except visual and layout properties, and graph elements.
  23486. * New list only change the indices.
  23487. */
  23488. listProto.cloneShallow = function (list) {
  23489. if (!list) {
  23490. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  23491. list = new List(dimensionInfoList, this.hostModel);
  23492. }
  23493. // FIXME
  23494. list._storage = this._storage;
  23495. transferProperties(list, this);
  23496. // Clone will not change the data extent and indices
  23497. if (this._indices) {
  23498. var Ctor = this._indices.constructor;
  23499. list._indices = new Ctor(this._indices);
  23500. }
  23501. else {
  23502. list._indices = null;
  23503. }
  23504. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  23505. list._extent = clone(this._extent);
  23506. list._approximateExtent = clone(this._approximateExtent);
  23507. return list;
  23508. };
  23509. /**
  23510. * Wrap some method to add more feature
  23511. * @param {string} methodName
  23512. * @param {Function} injectFunction
  23513. */
  23514. listProto.wrapMethod = function (methodName, injectFunction) {
  23515. var originalMethod = this[methodName];
  23516. if (typeof originalMethod !== 'function') {
  23517. return;
  23518. }
  23519. this.__wrappedMethods = this.__wrappedMethods || [];
  23520. this.__wrappedMethods.push(methodName);
  23521. this[methodName] = function () {
  23522. var res = originalMethod.apply(this, arguments);
  23523. return injectFunction.apply(this, [res].concat(slice(arguments)));
  23524. };
  23525. };
  23526. // Methods that create a new list based on this list should be listed here.
  23527. // Notice that those method should `RETURN` the new list.
  23528. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  23529. // Methods that change indices of this list should be listed here.
  23530. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  23531. /**
  23532. * @deprecated
  23533. * Use `echarts/data/helper/createDimensions` instead.
  23534. */
  23535. /**
  23536. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  23537. *
  23538. * Complete the dimensions array, by user defined `dimension` and `encode`,
  23539. * and guessing from the data structure.
  23540. * If no 'value' dimension specified, the first no-named dimension will be
  23541. * named as 'value'.
  23542. *
  23543. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  23544. * provides not only dim template, but also default order.
  23545. * properties: 'name', 'type', 'displayName'.
  23546. * `name` of each item provides default coord name.
  23547. * [{dimsDef: [string...]}, ...] can be specified to give names.
  23548. * [{ordinalMeta}] can be specified.
  23549. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  23550. * @param {Object} [opt]
  23551. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  23552. * For example: ['asdf', {name, type}, ...].
  23553. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  23554. * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions.
  23555. * @param {string} [opt.extraFromZero] If specified, extra dim names will be:
  23556. * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ...
  23557. * If not specified, extra dim names will be:
  23558. * extraPrefix, extraPrefix + 0, extraPrefix + 1 ...
  23559. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  23560. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  23561. * @return {Array.<Object>} [{
  23562. * name: string mandatory,
  23563. * displayName: string, the origin name in dimsDef, see source helper.
  23564. * If displayName given, the tooltip will displayed vertically.
  23565. * coordDim: string mandatory,
  23566. * isSysCoord: boolean True if the coord is from sys dimension.
  23567. * coordDimIndex: number mandatory,
  23568. * type: string optional,
  23569. * otherDims: { never null/undefined
  23570. * tooltip: number optional,
  23571. * label: number optional,
  23572. * itemName: number optional,
  23573. * seriesName: number optional,
  23574. * },
  23575. * isExtraCoord: boolean true or undefined.
  23576. * other props ...
  23577. * }]
  23578. */
  23579. function completeDimensions(sysDims, source, opt) {
  23580. if (!Source.isInstance(source)) {
  23581. source = Source.seriesDataToSource(source);
  23582. }
  23583. opt = opt || {};
  23584. sysDims = (sysDims || []).slice();
  23585. var dimsDef = (opt.dimsDef || []).slice();
  23586. var encodeDef = createHashMap(opt.encodeDef);
  23587. var dataDimNameMap = createHashMap();
  23588. var coordDimNameMap = createHashMap();
  23589. // var valueCandidate;
  23590. var result = [];
  23591. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  23592. // Apply user defined dims (`name` and `type`) and init result.
  23593. for (var i = 0; i < dimCount; i++) {
  23594. var dimDefItem = dimsDef[i] = extend(
  23595. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  23596. );
  23597. var userDimName = dimDefItem.name;
  23598. var resultItem = result[i] = {otherDims: {}};
  23599. // Name will be applied later for avoiding duplication.
  23600. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  23601. // Only if `series.dimensions` is defined in option
  23602. // displayName, will be set, and dimension will be diplayed vertically in
  23603. // tooltip by default.
  23604. resultItem.name = resultItem.displayName = userDimName;
  23605. dataDimNameMap.set(userDimName, i);
  23606. }
  23607. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  23608. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  23609. }
  23610. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  23611. encodeDef.each(function (dataDims, coordDim) {
  23612. dataDims = normalizeToArray(dataDims).slice();
  23613. var validDataDims = encodeDef.set(coordDim, []);
  23614. each$1(dataDims, function (resultDimIdx, idx) {
  23615. // The input resultDimIdx can be dim name or index.
  23616. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  23617. if (resultDimIdx != null && resultDimIdx < dimCount) {
  23618. validDataDims[idx] = resultDimIdx;
  23619. applyDim(result[resultDimIdx], coordDim, idx);
  23620. }
  23621. });
  23622. });
  23623. // Apply templetes and default order from `sysDims`.
  23624. var availDimIdx = 0;
  23625. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  23626. var coordDim;
  23627. var sysDimItem;
  23628. var sysDimItemDimsDef;
  23629. var sysDimItemOtherDims;
  23630. if (isString(sysDimItem)) {
  23631. coordDim = sysDimItem;
  23632. sysDimItem = {};
  23633. }
  23634. else {
  23635. coordDim = sysDimItem.name;
  23636. var ordinalMeta = sysDimItem.ordinalMeta;
  23637. sysDimItem.ordinalMeta = null;
  23638. sysDimItem = clone(sysDimItem);
  23639. sysDimItem.ordinalMeta = ordinalMeta;
  23640. // `coordDimIndex` should not be set directly.
  23641. sysDimItemDimsDef = sysDimItem.dimsDef;
  23642. sysDimItemOtherDims = sysDimItem.otherDims;
  23643. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  23644. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  23645. }
  23646. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  23647. // dimensions provides default dim sequences.
  23648. if (!dataDims.length) {
  23649. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  23650. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  23651. availDimIdx++;
  23652. }
  23653. availDimIdx < result.length && dataDims.push(availDimIdx++);
  23654. }
  23655. }
  23656. // Apply templates.
  23657. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  23658. var resultItem = result[resultDimIdx];
  23659. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  23660. if (resultItem.name == null && sysDimItemDimsDef) {
  23661. resultItem.name = resultItem.displayName = sysDimItemDimsDef[coordDimIndex];
  23662. }
  23663. resultItem.isSysCoord = true;
  23664. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  23665. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  23666. });
  23667. });
  23668. function applyDim(resultItem, coordDim, coordDimIndex) {
  23669. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  23670. resultItem.otherDims[coordDim] = coordDimIndex;
  23671. }
  23672. else {
  23673. resultItem.coordDim = coordDim;
  23674. resultItem.coordDimIndex = coordDimIndex;
  23675. coordDimNameMap.set(coordDim, true);
  23676. }
  23677. }
  23678. // Make sure the first extra dim is 'value'.
  23679. var extra = opt.extraPrefix || 'value';
  23680. // Set dim `name` and other `coordDim` and other props.
  23681. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  23682. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  23683. var coordDim = resultItem.coordDim;
  23684. coordDim == null && (
  23685. resultItem.coordDim = genName(
  23686. extra, coordDimNameMap, opt.extraFromZero
  23687. ),
  23688. resultItem.coordDimIndex = 0,
  23689. resultItem.isExtraCoord = true
  23690. );
  23691. resultItem.name == null && (resultItem.name = genName(
  23692. resultItem.coordDim,
  23693. dataDimNameMap
  23694. ));
  23695. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  23696. resultItem.type = 'ordinal';
  23697. }
  23698. }
  23699. return result;
  23700. }
  23701. // ??? TODO
  23702. // Originally detect dimCount by data[0]. Should we
  23703. // optimize it to only by sysDims and dimensions and encode.
  23704. // So only necessary dims will be initialized.
  23705. // But
  23706. // (1) custom series should be considered. where other dims
  23707. // may be visited.
  23708. // (2) sometimes user need to calcualte bubble size or use visualMap
  23709. // on other dimensions besides coordSys needed.
  23710. function getDimCount(source, sysDims, dimsDef, dimCount) {
  23711. if (dimCount == null) {
  23712. dimCount = Math.max(
  23713. source.dimensionsDetectCount || 1,
  23714. sysDims.length,
  23715. dimsDef.length
  23716. );
  23717. each$1(sysDims, function (sysDimItem) {
  23718. var sysDimItemDimsDef = sysDimItem.dimsDef;
  23719. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  23720. });
  23721. }
  23722. return dimCount;
  23723. }
  23724. function genName(name, map$$1, fromZero) {
  23725. if (fromZero || map$$1.get(name) != null) {
  23726. var i = 0;
  23727. while (map$$1.get(name + i) != null) {
  23728. i++;
  23729. }
  23730. name += i;
  23731. }
  23732. map$$1.set(name, true);
  23733. return name;
  23734. }
  23735. /**
  23736. * Substitute `completeDimensions`.
  23737. * `completeDimensions` is to be deprecated.
  23738. */
  23739. /**
  23740. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  23741. * @param {Object|Array} [opt]
  23742. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  23743. * @param {number} [opt.dimensionsCount]
  23744. * @param {string} [opt.extraPrefix]
  23745. * @param {boolean} [opt.extraFromZero]
  23746. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  23747. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  23748. * @return {Array.<Object>} dimensionsInfo
  23749. */
  23750. var createDimensions = function (source, opt) {
  23751. opt = opt || {};
  23752. return completeDimensions(opt.coordDimensions || [], source, {
  23753. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  23754. encodeDef: opt.encodeDefine || source.encodeDefine,
  23755. dimCount: opt.dimensionsCount,
  23756. extraPrefix: opt.extraPrefix,
  23757. extraFromZero: opt.extraFromZero
  23758. });
  23759. };
  23760. /**
  23761. * @param {module:echarts/data/Source|Array} source Or raw data.
  23762. * @param {module:echarts/model/Series} seriesModel
  23763. */
  23764. function createListFromArray(source, seriesModel) {
  23765. if (!Source.isInstance(source)) {
  23766. source = Source.seriesDataToSource(source);
  23767. }
  23768. var coordSysName = seriesModel.get('coordinateSystem');
  23769. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  23770. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  23771. var coordSysDimDefs;
  23772. if (coordSysDefine) {
  23773. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  23774. var dimInfo = {name: dim};
  23775. var axisModel = coordSysDefine.axisMap.get(dim);
  23776. if (axisModel) {
  23777. var axisType = axisModel.get('type');
  23778. dimInfo.type = getDimensionTypeByAxis(axisType);
  23779. dimInfo.stackable = isStackable(axisType);
  23780. }
  23781. return dimInfo;
  23782. });
  23783. }
  23784. if (!coordSysDimDefs) {
  23785. // Get dimensions from registered coordinate system
  23786. coordSysDimDefs = (registeredCoordSys && (
  23787. registeredCoordSys.getDimensionsInfo
  23788. ? registeredCoordSys.getDimensionsInfo()
  23789. : registeredCoordSys.dimensions.slice()
  23790. )) || ['x', 'y'];
  23791. }
  23792. var dimInfoList = createDimensions(source, {
  23793. coordDimensions: coordSysDimDefs
  23794. });
  23795. var firstCategoryDimIndex;
  23796. var hasNameEncode;
  23797. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  23798. var coordDim = dimInfo.coordDim;
  23799. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  23800. if (categoryAxisModel) {
  23801. if (firstCategoryDimIndex == null) {
  23802. firstCategoryDimIndex = dimIndex;
  23803. }
  23804. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  23805. }
  23806. if (dimInfo.otherDims.itemName != null) {
  23807. hasNameEncode = true;
  23808. }
  23809. });
  23810. if (!hasNameEncode && firstCategoryDimIndex != null) {
  23811. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  23812. }
  23813. var list = new List(dimInfoList, seriesModel);
  23814. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  23815. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  23816. // Use dataIndex as ordinal value in categoryAxis
  23817. return dimIndex === firstCategoryDimIndex
  23818. ? dataIndex
  23819. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  23820. }
  23821. : null;
  23822. list.hasItemOption = false;
  23823. list.initData(source, null, dimValueGetter);
  23824. return list;
  23825. }
  23826. function isStackable(axisType) {
  23827. return axisType !== 'category' && axisType !== 'time';
  23828. }
  23829. function isNeedCompleteOrdinalData(source) {
  23830. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  23831. var sampleItem = firstDataNotNull(source.data || []);
  23832. return sampleItem != null
  23833. && !isArray(getDataItemValue(sampleItem));
  23834. }
  23835. }
  23836. function firstDataNotNull(data) {
  23837. var i = 0;
  23838. while (i < data.length && data[i] == null) {
  23839. i++;
  23840. }
  23841. return data[i];
  23842. }
  23843. SeriesModel.extend({
  23844. type: 'series.line',
  23845. dependencies: ['grid', 'polar'],
  23846. getInitialData: function (option, ecModel) {
  23847. if (__DEV__) {
  23848. var coordSys = option.coordinateSystem;
  23849. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  23850. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  23851. }
  23852. }
  23853. return createListFromArray(this.getSource(), this);
  23854. },
  23855. defaultOption: {
  23856. zlevel: 0, // 一级层叠
  23857. z: 2, // 二级层叠
  23858. coordinateSystem: 'cartesian2d',
  23859. legendHoverLink: true,
  23860. hoverAnimation: true,
  23861. // stack: null
  23862. // xAxisIndex: 0,
  23863. // yAxisIndex: 0,
  23864. // polarIndex: 0,
  23865. // If clip the overflow value
  23866. clipOverflow: true,
  23867. // cursor: null,
  23868. label: {
  23869. position: 'top'
  23870. },
  23871. // itemStyle: {
  23872. // },
  23873. lineStyle: {
  23874. width: 2,
  23875. type: 'solid'
  23876. },
  23877. // areaStyle: {origin: 'auto'},
  23878. // false, 'start', 'end', 'middle'
  23879. step: false,
  23880. // Disabled if step is true
  23881. smooth: false,
  23882. smoothMonotone: null,
  23883. // 拐点图形类型
  23884. symbol: 'emptyCircle',
  23885. // 拐点图形大小
  23886. symbolSize: 4,
  23887. // 拐点图形旋转控制
  23888. symbolRotate: null,
  23889. // 是否显示 symbol, 只有在 tooltip hover 的时候显示
  23890. showSymbol: true,
  23891. // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略)
  23892. showAllSymbol: false,
  23893. // 是否连接断点
  23894. connectNulls: false,
  23895. // 数据过滤,'average', 'max', 'min', 'sum'
  23896. sampling: 'none',
  23897. animationEasing: 'linear',
  23898. // Disable progressive
  23899. progressive: 0,
  23900. hoverLayerThreshold: Infinity
  23901. }
  23902. });
  23903. // Symbol factory
  23904. /**
  23905. * Triangle shape
  23906. * @inner
  23907. */
  23908. var Triangle = extendShape({
  23909. type: 'triangle',
  23910. shape: {
  23911. cx: 0,
  23912. cy: 0,
  23913. width: 0,
  23914. height: 0
  23915. },
  23916. buildPath: function (path, shape) {
  23917. var cx = shape.cx;
  23918. var cy = shape.cy;
  23919. var width = shape.width / 2;
  23920. var height = shape.height / 2;
  23921. path.moveTo(cx, cy - height);
  23922. path.lineTo(cx + width, cy + height);
  23923. path.lineTo(cx - width, cy + height);
  23924. path.closePath();
  23925. }
  23926. });
  23927. /**
  23928. * Diamond shape
  23929. * @inner
  23930. */
  23931. var Diamond = extendShape({
  23932. type: 'diamond',
  23933. shape: {
  23934. cx: 0,
  23935. cy: 0,
  23936. width: 0,
  23937. height: 0
  23938. },
  23939. buildPath: function (path, shape) {
  23940. var cx = shape.cx;
  23941. var cy = shape.cy;
  23942. var width = shape.width / 2;
  23943. var height = shape.height / 2;
  23944. path.moveTo(cx, cy - height);
  23945. path.lineTo(cx + width, cy);
  23946. path.lineTo(cx, cy + height);
  23947. path.lineTo(cx - width, cy);
  23948. path.closePath();
  23949. }
  23950. });
  23951. /**
  23952. * Pin shape
  23953. * @inner
  23954. */
  23955. var Pin = extendShape({
  23956. type: 'pin',
  23957. shape: {
  23958. // x, y on the cusp
  23959. x: 0,
  23960. y: 0,
  23961. width: 0,
  23962. height: 0
  23963. },
  23964. buildPath: function (path, shape) {
  23965. var x = shape.x;
  23966. var y = shape.y;
  23967. var w = shape.width / 5 * 3;
  23968. // Height must be larger than width
  23969. var h = Math.max(w, shape.height);
  23970. var r = w / 2;
  23971. // Dist on y with tangent point and circle center
  23972. var dy = r * r / (h - r);
  23973. var cy = y - h + r + dy;
  23974. var angle = Math.asin(dy / r);
  23975. // Dist on x with tangent point and circle center
  23976. var dx = Math.cos(angle) * r;
  23977. var tanX = Math.sin(angle);
  23978. var tanY = Math.cos(angle);
  23979. var cpLen = r * 0.6;
  23980. var cpLen2 = r * 0.7;
  23981. path.moveTo(x - dx, cy + dy);
  23982. path.arc(
  23983. x, cy, r,
  23984. Math.PI - angle,
  23985. Math.PI * 2 + angle
  23986. );
  23987. path.bezierCurveTo(
  23988. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  23989. x, y - cpLen2,
  23990. x, y
  23991. );
  23992. path.bezierCurveTo(
  23993. x, y - cpLen2,
  23994. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  23995. x - dx, cy + dy
  23996. );
  23997. path.closePath();
  23998. }
  23999. });
  24000. /**
  24001. * Arrow shape
  24002. * @inner
  24003. */
  24004. var Arrow = extendShape({
  24005. type: 'arrow',
  24006. shape: {
  24007. x: 0,
  24008. y: 0,
  24009. width: 0,
  24010. height: 0
  24011. },
  24012. buildPath: function (ctx, shape) {
  24013. var height = shape.height;
  24014. var width = shape.width;
  24015. var x = shape.x;
  24016. var y = shape.y;
  24017. var dx = width / 3 * 2;
  24018. ctx.moveTo(x, y);
  24019. ctx.lineTo(x + dx, y + height);
  24020. ctx.lineTo(x, y + height / 4 * 3);
  24021. ctx.lineTo(x - dx, y + height);
  24022. ctx.lineTo(x, y);
  24023. ctx.closePath();
  24024. }
  24025. });
  24026. /**
  24027. * Map of path contructors
  24028. * @type {Object.<string, module:zrender/graphic/Path>}
  24029. */
  24030. var symbolCtors = {
  24031. line: Line,
  24032. rect: Rect,
  24033. roundRect: Rect,
  24034. square: Rect,
  24035. circle: Circle,
  24036. diamond: Diamond,
  24037. pin: Pin,
  24038. arrow: Arrow,
  24039. triangle: Triangle
  24040. };
  24041. var symbolShapeMakers = {
  24042. line: function (x, y, w, h, shape) {
  24043. // FIXME
  24044. shape.x1 = x;
  24045. shape.y1 = y + h / 2;
  24046. shape.x2 = x + w;
  24047. shape.y2 = y + h / 2;
  24048. },
  24049. rect: function (x, y, w, h, shape) {
  24050. shape.x = x;
  24051. shape.y = y;
  24052. shape.width = w;
  24053. shape.height = h;
  24054. },
  24055. roundRect: function (x, y, w, h, shape) {
  24056. shape.x = x;
  24057. shape.y = y;
  24058. shape.width = w;
  24059. shape.height = h;
  24060. shape.r = Math.min(w, h) / 4;
  24061. },
  24062. square: function (x, y, w, h, shape) {
  24063. var size = Math.min(w, h);
  24064. shape.x = x;
  24065. shape.y = y;
  24066. shape.width = size;
  24067. shape.height = size;
  24068. },
  24069. circle: function (x, y, w, h, shape) {
  24070. // Put circle in the center of square
  24071. shape.cx = x + w / 2;
  24072. shape.cy = y + h / 2;
  24073. shape.r = Math.min(w, h) / 2;
  24074. },
  24075. diamond: function (x, y, w, h, shape) {
  24076. shape.cx = x + w / 2;
  24077. shape.cy = y + h / 2;
  24078. shape.width = w;
  24079. shape.height = h;
  24080. },
  24081. pin: function (x, y, w, h, shape) {
  24082. shape.x = x + w / 2;
  24083. shape.y = y + h / 2;
  24084. shape.width = w;
  24085. shape.height = h;
  24086. },
  24087. arrow: function (x, y, w, h, shape) {
  24088. shape.x = x + w / 2;
  24089. shape.y = y + h / 2;
  24090. shape.width = w;
  24091. shape.height = h;
  24092. },
  24093. triangle: function (x, y, w, h, shape) {
  24094. shape.cx = x + w / 2;
  24095. shape.cy = y + h / 2;
  24096. shape.width = w;
  24097. shape.height = h;
  24098. }
  24099. };
  24100. var symbolBuildProxies = {};
  24101. each$1(symbolCtors, function (Ctor, name) {
  24102. symbolBuildProxies[name] = new Ctor();
  24103. });
  24104. var SymbolClz$2 = extendShape({
  24105. type: 'symbol',
  24106. shape: {
  24107. symbolType: '',
  24108. x: 0,
  24109. y: 0,
  24110. width: 0,
  24111. height: 0
  24112. },
  24113. beforeBrush: function () {
  24114. var style = this.style;
  24115. var shape = this.shape;
  24116. // FIXME
  24117. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  24118. style.textPosition = ['50%', '40%'];
  24119. style.textAlign = 'center';
  24120. style.textVerticalAlign = 'middle';
  24121. }
  24122. },
  24123. buildPath: function (ctx, shape, inBundle) {
  24124. var symbolType = shape.symbolType;
  24125. var proxySymbol = symbolBuildProxies[symbolType];
  24126. if (shape.symbolType !== 'none') {
  24127. if (!proxySymbol) {
  24128. // Default rect
  24129. symbolType = 'rect';
  24130. proxySymbol = symbolBuildProxies[symbolType];
  24131. }
  24132. symbolShapeMakers[symbolType](
  24133. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  24134. );
  24135. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24136. }
  24137. }
  24138. });
  24139. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24140. function symbolPathSetColor(color, innerColor) {
  24141. if (this.type !== 'image') {
  24142. var symbolStyle = this.style;
  24143. var symbolShape = this.shape;
  24144. if (symbolShape && symbolShape.symbolType === 'line') {
  24145. symbolStyle.stroke = color;
  24146. }
  24147. else if (this.__isEmptyBrush) {
  24148. symbolStyle.stroke = color;
  24149. symbolStyle.fill = innerColor || '#fff';
  24150. }
  24151. else {
  24152. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  24153. symbolStyle.fill && (symbolStyle.fill = color);
  24154. symbolStyle.stroke && (symbolStyle.stroke = color);
  24155. }
  24156. this.dirty(false);
  24157. }
  24158. }
  24159. /**
  24160. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24161. * @param {string} symbolType
  24162. * @param {number} x
  24163. * @param {number} y
  24164. * @param {number} w
  24165. * @param {number} h
  24166. * @param {string} color
  24167. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  24168. * for path and image only.
  24169. */
  24170. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  24171. // TODO Support image object, DynamicImage.
  24172. var isEmpty = symbolType.indexOf('empty') === 0;
  24173. if (isEmpty) {
  24174. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24175. }
  24176. var symbolPath;
  24177. if (symbolType.indexOf('image://') === 0) {
  24178. symbolPath = makeImage(
  24179. symbolType.slice(8),
  24180. new BoundingRect(x, y, w, h),
  24181. keepAspect ? 'center' : 'cover'
  24182. );
  24183. }
  24184. else if (symbolType.indexOf('path://') === 0) {
  24185. symbolPath = makePath(
  24186. symbolType.slice(7),
  24187. {},
  24188. new BoundingRect(x, y, w, h),
  24189. keepAspect ? 'center' : 'cover'
  24190. );
  24191. }
  24192. else {
  24193. symbolPath = new SymbolClz$2({
  24194. shape: {
  24195. symbolType: symbolType,
  24196. x: x,
  24197. y: y,
  24198. width: w,
  24199. height: h
  24200. }
  24201. });
  24202. }
  24203. symbolPath.__isEmptyBrush = isEmpty;
  24204. symbolPath.setColor = symbolPathSetColor;
  24205. symbolPath.setColor(color);
  24206. return symbolPath;
  24207. }
  24208. /**
  24209. * @param {module:echarts/data/List} data
  24210. * @param {number} dataIndex
  24211. * @return {string} label string. Not null/undefined
  24212. */
  24213. function getDefaultLabel(data, dataIndex) {
  24214. var labelDims = data.mapDimension('defaultedLabel', true);
  24215. var len = labelDims.length;
  24216. // Simple optimization (in lots of cases, label dims length is 1)
  24217. if (len === 1) {
  24218. return retrieveRawValue(data, dataIndex, labelDims[0]);
  24219. }
  24220. else if (len) {
  24221. var vals = [];
  24222. for (var i = 0; i < labelDims.length; i++) {
  24223. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  24224. vals.push(val);
  24225. }
  24226. return vals.join(' ');
  24227. }
  24228. }
  24229. /**
  24230. * @module echarts/chart/helper/Symbol
  24231. */
  24232. function getSymbolSize(data, idx) {
  24233. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  24234. return symbolSize instanceof Array
  24235. ? symbolSize.slice()
  24236. : [+symbolSize, +symbolSize];
  24237. }
  24238. function getScale(symbolSize) {
  24239. return [symbolSize[0] / 2, symbolSize[1] / 2];
  24240. }
  24241. /**
  24242. * @constructor
  24243. * @alias {module:echarts/chart/helper/Symbol}
  24244. * @param {module:echarts/data/List} data
  24245. * @param {number} idx
  24246. * @extends {module:zrender/graphic/Group}
  24247. */
  24248. function SymbolClz(data, idx, seriesScope) {
  24249. Group.call(this);
  24250. this.updateData(data, idx, seriesScope);
  24251. }
  24252. var symbolProto = SymbolClz.prototype;
  24253. function driftSymbol(dx, dy) {
  24254. this.parent.drift(dx, dy);
  24255. }
  24256. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) {
  24257. // Remove paths created before
  24258. this.removeAll();
  24259. var color = data.getItemVisual(idx, 'color');
  24260. // var symbolPath = createSymbol(
  24261. // symbolType, -0.5, -0.5, 1, 1, color
  24262. // );
  24263. // If width/height are set too small (e.g., set to 1) on ios10
  24264. // and macOS Sierra, a circle stroke become a rect, no matter what
  24265. // the scale is set. So we set width/height as 2. See #4150.
  24266. var symbolPath = createSymbol(
  24267. symbolType, -1, -1, 2, 2, color
  24268. );
  24269. symbolPath.attr({
  24270. z2: 100,
  24271. culling: true,
  24272. scale: getScale(symbolSize)
  24273. });
  24274. // Rewrite drift method
  24275. symbolPath.drift = driftSymbol;
  24276. this._symbolType = symbolType;
  24277. this.add(symbolPath);
  24278. };
  24279. /**
  24280. * Stop animation
  24281. * @param {boolean} toLastFrame
  24282. */
  24283. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  24284. this.childAt(0).stopAnimation(toLastFrame);
  24285. };
  24286. /**
  24287. * FIXME:
  24288. * Caution: This method breaks the encapsulation of this module,
  24289. * but it indeed brings convenience. So do not use the method
  24290. * unless you detailedly know all the implements of `Symbol`,
  24291. * especially animation.
  24292. *
  24293. * Get symbol path element.
  24294. */
  24295. symbolProto.getSymbolPath = function () {
  24296. return this.childAt(0);
  24297. };
  24298. /**
  24299. * Get scale(aka, current symbol size).
  24300. * Including the change caused by animation
  24301. */
  24302. symbolProto.getScale = function () {
  24303. return this.childAt(0).scale;
  24304. };
  24305. /**
  24306. * Highlight symbol
  24307. */
  24308. symbolProto.highlight = function () {
  24309. this.childAt(0).trigger('emphasis');
  24310. };
  24311. /**
  24312. * Downplay symbol
  24313. */
  24314. symbolProto.downplay = function () {
  24315. this.childAt(0).trigger('normal');
  24316. };
  24317. /**
  24318. * @param {number} zlevel
  24319. * @param {number} z
  24320. */
  24321. symbolProto.setZ = function (zlevel, z) {
  24322. var symbolPath = this.childAt(0);
  24323. symbolPath.zlevel = zlevel;
  24324. symbolPath.z = z;
  24325. };
  24326. symbolProto.setDraggable = function (draggable) {
  24327. var symbolPath = this.childAt(0);
  24328. symbolPath.draggable = draggable;
  24329. symbolPath.cursor = draggable ? 'move' : 'pointer';
  24330. };
  24331. /**
  24332. * Update symbol properties
  24333. * @param {module:echarts/data/List} data
  24334. * @param {number} idx
  24335. * @param {Object} [seriesScope]
  24336. * @param {Object} [seriesScope.itemStyle]
  24337. * @param {Object} [seriesScope.hoverItemStyle]
  24338. * @param {Object} [seriesScope.symbolRotate]
  24339. * @param {Object} [seriesScope.symbolOffset]
  24340. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  24341. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  24342. * @param {boolean} [seriesScope.hoverAnimation]
  24343. * @param {Object} [seriesScope.cursorStyle]
  24344. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  24345. * @param {string} [seriesScope.symbolInnerColor]
  24346. * @param {Object} [seriesScope.fadeIn=false]
  24347. */
  24348. symbolProto.updateData = function (data, idx, seriesScope) {
  24349. this.silent = false;
  24350. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  24351. var seriesModel = data.hostModel;
  24352. var symbolSize = getSymbolSize(data, idx);
  24353. var isInit = symbolType !== this._symbolType;
  24354. if (isInit) {
  24355. this._createSymbol(symbolType, data, idx, symbolSize);
  24356. }
  24357. else {
  24358. var symbolPath = this.childAt(0);
  24359. symbolPath.silent = false;
  24360. updateProps(symbolPath, {
  24361. scale: getScale(symbolSize)
  24362. }, seriesModel, idx);
  24363. }
  24364. this._updateCommon(data, idx, symbolSize, seriesScope);
  24365. if (isInit) {
  24366. var symbolPath = this.childAt(0);
  24367. var fadeIn = seriesScope && seriesScope.fadeIn;
  24368. var target = {scale: symbolPath.scale.slice()};
  24369. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  24370. symbolPath.scale = [0, 0];
  24371. fadeIn && (symbolPath.style.opacity = 0);
  24372. initProps(symbolPath, target, seriesModel, idx);
  24373. }
  24374. this._seriesModel = seriesModel;
  24375. };
  24376. // Update common properties
  24377. var normalStyleAccessPath = ['itemStyle'];
  24378. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  24379. var normalLabelAccessPath = ['label'];
  24380. var emphasisLabelAccessPath = ['emphasis', 'label'];
  24381. /**
  24382. * @param {module:echarts/data/List} data
  24383. * @param {number} idx
  24384. * @param {Array.<number>} symbolSize
  24385. * @param {Object} [seriesScope]
  24386. */
  24387. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  24388. var symbolPath = this.childAt(0);
  24389. var seriesModel = data.hostModel;
  24390. var color = data.getItemVisual(idx, 'color');
  24391. // Reset style
  24392. if (symbolPath.type !== 'image') {
  24393. symbolPath.useStyle({
  24394. strokeNoScale: true
  24395. });
  24396. }
  24397. var itemStyle = seriesScope && seriesScope.itemStyle;
  24398. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  24399. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  24400. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  24401. var labelModel = seriesScope && seriesScope.labelModel;
  24402. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  24403. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  24404. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  24405. if (!seriesScope || data.hasItemOption) {
  24406. var itemModel = (seriesScope && seriesScope.itemModel)
  24407. ? seriesScope.itemModel : data.getItemModel(idx);
  24408. // Color must be excluded.
  24409. // Because symbol provide setColor individually to set fill and stroke
  24410. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  24411. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  24412. symbolRotate = itemModel.getShallow('symbolRotate');
  24413. symbolOffset = itemModel.getShallow('symbolOffset');
  24414. labelModel = itemModel.getModel(normalLabelAccessPath);
  24415. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  24416. hoverAnimation = itemModel.getShallow('hoverAnimation');
  24417. cursorStyle = itemModel.getShallow('cursor');
  24418. }
  24419. else {
  24420. hoverItemStyle = extend({}, hoverItemStyle);
  24421. }
  24422. var elStyle = symbolPath.style;
  24423. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  24424. if (symbolOffset) {
  24425. symbolPath.attr('position', [
  24426. parsePercent$1(symbolOffset[0], symbolSize[0]),
  24427. parsePercent$1(symbolOffset[1], symbolSize[1])
  24428. ]);
  24429. }
  24430. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  24431. // PENDING setColor before setStyle!!!
  24432. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  24433. symbolPath.setStyle(itemStyle);
  24434. var opacity = data.getItemVisual(idx, 'opacity');
  24435. if (opacity != null) {
  24436. elStyle.opacity = opacity;
  24437. }
  24438. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  24439. setLabelStyle(
  24440. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  24441. {
  24442. labelFetcher: seriesModel,
  24443. labelDataIndex: idx,
  24444. defaultText: getLabelDefaultText,
  24445. isRectText: true,
  24446. autoColor: color
  24447. }
  24448. );
  24449. // Do not execute util needed.
  24450. function getLabelDefaultText(idx, opt) {
  24451. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  24452. }
  24453. symbolPath.off('mouseover')
  24454. .off('mouseout')
  24455. .off('emphasis')
  24456. .off('normal');
  24457. symbolPath.hoverStyle = hoverItemStyle;
  24458. // FIXME
  24459. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  24460. setHoverStyle(symbolPath);
  24461. var scale = getScale(symbolSize);
  24462. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  24463. var onEmphasis = function() {
  24464. var ratio = scale[1] / scale[0];
  24465. this.animateTo({
  24466. scale: [
  24467. Math.max(scale[0] * 1.1, scale[0] + 3),
  24468. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  24469. ]
  24470. }, 400, 'elasticOut');
  24471. };
  24472. var onNormal = function() {
  24473. this.animateTo({
  24474. scale: scale
  24475. }, 400, 'elasticOut');
  24476. };
  24477. symbolPath.on('mouseover', onEmphasis)
  24478. .on('mouseout', onNormal)
  24479. .on('emphasis', onEmphasis)
  24480. .on('normal', onNormal);
  24481. }
  24482. };
  24483. /**
  24484. * @param {Function} cb
  24485. * @param {Object} [opt]
  24486. * @param {Object} [opt.keepLabel=true]
  24487. */
  24488. symbolProto.fadeOut = function (cb, opt) {
  24489. var symbolPath = this.childAt(0);
  24490. // Avoid mistaken hover when fading out
  24491. this.silent = symbolPath.silent = true;
  24492. // Not show text when animating
  24493. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  24494. updateProps(
  24495. symbolPath,
  24496. {
  24497. style: {opacity: 0},
  24498. scale: [0, 0]
  24499. },
  24500. this._seriesModel,
  24501. this.dataIndex,
  24502. cb
  24503. );
  24504. };
  24505. inherits(SymbolClz, Group);
  24506. /**
  24507. * @module echarts/chart/helper/SymbolDraw
  24508. */
  24509. /**
  24510. * @constructor
  24511. * @alias module:echarts/chart/helper/SymbolDraw
  24512. * @param {module:zrender/graphic/Group} [symbolCtor]
  24513. */
  24514. function SymbolDraw(symbolCtor) {
  24515. this.group = new Group();
  24516. this._symbolCtor = symbolCtor || SymbolClz;
  24517. }
  24518. var symbolDrawProto = SymbolDraw.prototype;
  24519. function symbolNeedsDraw(data, point, idx, isIgnore) {
  24520. return point && !isNaN(point[0]) && !isNaN(point[1])
  24521. && !(isIgnore && isIgnore(idx))
  24522. && data.getItemVisual(idx, 'symbol') !== 'none';
  24523. }
  24524. /**
  24525. * Update symbols draw by new data
  24526. * @param {module:echarts/data/List} data
  24527. * @param {Array.<boolean>} [isIgnore]
  24528. */
  24529. symbolDrawProto.updateData = function (data, isIgnore) {
  24530. var group = this.group;
  24531. var seriesModel = data.hostModel;
  24532. var oldData = this._data;
  24533. var SymbolCtor = this._symbolCtor;
  24534. var seriesScope = makeSeriesScope(data);
  24535. // There is no oldLineData only when first rendering or switching from
  24536. // stream mode to normal mode, where previous elements should be removed.
  24537. if (!oldData) {
  24538. group.removeAll();
  24539. }
  24540. data.diff(oldData)
  24541. .add(function (newIdx) {
  24542. var point = data.getItemLayout(newIdx);
  24543. if (symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  24544. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  24545. symbolEl.attr('position', point);
  24546. data.setItemGraphicEl(newIdx, symbolEl);
  24547. group.add(symbolEl);
  24548. }
  24549. })
  24550. .update(function (newIdx, oldIdx) {
  24551. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  24552. var point = data.getItemLayout(newIdx);
  24553. if (!symbolNeedsDraw(data, point, newIdx, isIgnore)) {
  24554. group.remove(symbolEl);
  24555. return;
  24556. }
  24557. if (!symbolEl) {
  24558. symbolEl = new SymbolCtor(data, newIdx);
  24559. symbolEl.attr('position', point);
  24560. }
  24561. else {
  24562. symbolEl.updateData(data, newIdx, seriesScope);
  24563. updateProps(symbolEl, {
  24564. position: point
  24565. }, seriesModel);
  24566. }
  24567. // Add back
  24568. group.add(symbolEl);
  24569. data.setItemGraphicEl(newIdx, symbolEl);
  24570. })
  24571. .remove(function (oldIdx) {
  24572. var el = oldData.getItemGraphicEl(oldIdx);
  24573. el && el.fadeOut(function () {
  24574. group.remove(el);
  24575. });
  24576. })
  24577. .execute();
  24578. this._data = data;
  24579. };
  24580. symbolDrawProto.isPersistent = function () {
  24581. return true;
  24582. };
  24583. symbolDrawProto.updateLayout = function () {
  24584. var data = this._data;
  24585. if (data) {
  24586. // Not use animation
  24587. data.eachItemGraphicEl(function (el, idx) {
  24588. var point = data.getItemLayout(idx);
  24589. el.attr('position', point);
  24590. });
  24591. }
  24592. };
  24593. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  24594. this._seriesScope = makeSeriesScope(data);
  24595. this._data = null;
  24596. this.group.removeAll();
  24597. };
  24598. symbolDrawProto.incrementalUpdate = function (taskParams, data, isIgnore) {
  24599. function updateIncrementalAndHover(el) {
  24600. if (!el.isGroup) {
  24601. el.incremental = el.useHoverLayer = true;
  24602. }
  24603. }
  24604. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  24605. var point = data.getItemLayout(idx);
  24606. if (symbolNeedsDraw(data, point, idx, isIgnore)) {
  24607. var el = new this._symbolCtor(data, idx, this._seriesScope);
  24608. el.traverse(updateIncrementalAndHover);
  24609. el.attr('position', point);
  24610. this.group.add(el);
  24611. data.setItemGraphicEl(idx, el);
  24612. }
  24613. }
  24614. };
  24615. symbolDrawProto.remove = function (enableAnimation) {
  24616. var group = this.group;
  24617. var data = this._data;
  24618. if (data) {
  24619. if (enableAnimation) {
  24620. data.eachItemGraphicEl(function (el) {
  24621. el.fadeOut(function () {
  24622. group.remove(el);
  24623. });
  24624. });
  24625. }
  24626. else {
  24627. group.removeAll();
  24628. }
  24629. }
  24630. };
  24631. function makeSeriesScope(data) {
  24632. var seriesModel = data.hostModel;
  24633. return {
  24634. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  24635. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  24636. symbolRotate: seriesModel.get('symbolRotate'),
  24637. symbolOffset: seriesModel.get('symbolOffset'),
  24638. hoverAnimation: seriesModel.get('hoverAnimation'),
  24639. labelModel: seriesModel.getModel('label'),
  24640. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  24641. cursorStyle: seriesModel.get('cursor')
  24642. };
  24643. }
  24644. // var arrayDiff = require('zrender/src/core/arrayDiff');
  24645. // 'zrender/src/core/arrayDiff' has been used before, but it did
  24646. // not do well in performance when roam with fixed dataZoom window.
  24647. function sign$1(val) {
  24648. return val >= 0 ? 1 : -1;
  24649. }
  24650. function getStackedOnPoint(coordSys, data, idx) {
  24651. var baseAxis = coordSys.getBaseAxis();
  24652. var valueAxis = coordSys.getOtherAxis(baseAxis);
  24653. var valueStart = baseAxis.onZero
  24654. ? 0 : valueAxis.scale.getExtent()[0];
  24655. var valueDim = valueAxis.dim;
  24656. var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0;
  24657. var stackedOnSameSign;
  24658. var stackedOn = data.stackedOn;
  24659. var val = data.get(valueDim, idx);
  24660. // Find first stacked value with same sign
  24661. while (stackedOn &&
  24662. sign$1(stackedOn.get(valueDim, idx)) === sign$1(val)
  24663. ) {
  24664. stackedOnSameSign = stackedOn;
  24665. break;
  24666. }
  24667. var stackedData = [];
  24668. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  24669. stackedData[1 - baseDataOffset] = stackedOnSameSign
  24670. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  24671. return coordSys.dataToPoint(stackedData);
  24672. }
  24673. // function convertToIntId(newIdList, oldIdList) {
  24674. // // Generate int id instead of string id.
  24675. // // Compare string maybe slow in score function of arrDiff
  24676. // // Assume id in idList are all unique
  24677. // var idIndicesMap = {};
  24678. // var idx = 0;
  24679. // for (var i = 0; i < newIdList.length; i++) {
  24680. // idIndicesMap[newIdList[i]] = idx;
  24681. // newIdList[i] = idx++;
  24682. // }
  24683. // for (var i = 0; i < oldIdList.length; i++) {
  24684. // var oldId = oldIdList[i];
  24685. // // Same with newIdList
  24686. // if (idIndicesMap[oldId]) {
  24687. // oldIdList[i] = idIndicesMap[oldId];
  24688. // }
  24689. // else {
  24690. // oldIdList[i] = idx++;
  24691. // }
  24692. // }
  24693. // }
  24694. function diffData(oldData, newData) {
  24695. var diffResult = [];
  24696. newData.diff(oldData)
  24697. .add(function (idx) {
  24698. diffResult.push({cmd: '+', idx: idx});
  24699. })
  24700. .update(function (newIdx, oldIdx) {
  24701. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  24702. })
  24703. .remove(function (idx) {
  24704. diffResult.push({cmd: '-', idx: idx});
  24705. })
  24706. .execute();
  24707. return diffResult;
  24708. }
  24709. var lineAnimationDiff = function (
  24710. oldData, newData,
  24711. oldStackedOnPoints, newStackedOnPoints,
  24712. oldCoordSys, newCoordSys
  24713. ) {
  24714. var diff = diffData(oldData, newData);
  24715. // var newIdList = newData.mapArray(newData.getId);
  24716. // var oldIdList = oldData.mapArray(oldData.getId);
  24717. // convertToIntId(newIdList, oldIdList);
  24718. // // FIXME One data ?
  24719. // diff = arrayDiff(oldIdList, newIdList);
  24720. var currPoints = [];
  24721. var nextPoints = [];
  24722. // Points for stacking base line
  24723. var currStackedPoints = [];
  24724. var nextStackedPoints = [];
  24725. var status = [];
  24726. var sortedIndices = [];
  24727. var rawIndices = [];
  24728. var dims = newCoordSys.dimensions;
  24729. for (var i = 0; i < diff.length; i++) {
  24730. var diffItem = diff[i];
  24731. var pointAdded = true;
  24732. // FIXME, animation is not so perfect when dataZoom window moves fast
  24733. // Which is in case remvoing or add more than one data in the tail or head
  24734. switch (diffItem.cmd) {
  24735. case '=':
  24736. var currentPt = oldData.getItemLayout(diffItem.idx);
  24737. var nextPt = newData.getItemLayout(diffItem.idx1);
  24738. // If previous data is NaN, use next point directly
  24739. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  24740. currentPt = nextPt.slice();
  24741. }
  24742. currPoints.push(currentPt);
  24743. nextPoints.push(nextPt);
  24744. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  24745. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  24746. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  24747. break;
  24748. case '+':
  24749. var idx = diffItem.idx;
  24750. currPoints.push(
  24751. oldCoordSys.dataToPoint([
  24752. newData.get(dims[0], idx, true), newData.get(dims[1], idx, true)
  24753. ])
  24754. );
  24755. nextPoints.push(newData.getItemLayout(idx).slice());
  24756. currStackedPoints.push(
  24757. getStackedOnPoint(oldCoordSys, newData, idx)
  24758. );
  24759. nextStackedPoints.push(newStackedOnPoints[idx]);
  24760. rawIndices.push(newData.getRawIndex(idx));
  24761. break;
  24762. case '-':
  24763. var idx = diffItem.idx;
  24764. var rawIndex = oldData.getRawIndex(idx);
  24765. // Data is replaced. In the case of dynamic data queue
  24766. // FIXME FIXME FIXME
  24767. if (rawIndex !== idx) {
  24768. currPoints.push(oldData.getItemLayout(idx));
  24769. nextPoints.push(newCoordSys.dataToPoint([
  24770. oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true)
  24771. ]));
  24772. currStackedPoints.push(oldStackedOnPoints[idx]);
  24773. nextStackedPoints.push(
  24774. getStackedOnPoint(
  24775. newCoordSys, oldData, idx
  24776. )
  24777. );
  24778. rawIndices.push(rawIndex);
  24779. }
  24780. else {
  24781. pointAdded = false;
  24782. }
  24783. }
  24784. // Original indices
  24785. if (pointAdded) {
  24786. status.push(diffItem);
  24787. sortedIndices.push(sortedIndices.length);
  24788. }
  24789. }
  24790. // Diff result may be crossed if all items are changed
  24791. // Sort by data index
  24792. sortedIndices.sort(function (a, b) {
  24793. return rawIndices[a] - rawIndices[b];
  24794. });
  24795. var sortedCurrPoints = [];
  24796. var sortedNextPoints = [];
  24797. var sortedCurrStackedPoints = [];
  24798. var sortedNextStackedPoints = [];
  24799. var sortedStatus = [];
  24800. for (var i = 0; i < sortedIndices.length; i++) {
  24801. var idx = sortedIndices[i];
  24802. sortedCurrPoints[i] = currPoints[idx];
  24803. sortedNextPoints[i] = nextPoints[idx];
  24804. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  24805. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  24806. sortedStatus[i] = status[idx];
  24807. }
  24808. return {
  24809. current: sortedCurrPoints,
  24810. next: sortedNextPoints,
  24811. stackedOnCurrent: sortedCurrStackedPoints,
  24812. stackedOnNext: sortedNextStackedPoints,
  24813. status: sortedStatus
  24814. };
  24815. };
  24816. // Poly path support NaN point
  24817. var vec2Min = min;
  24818. var vec2Max = max;
  24819. var scaleAndAdd$1 = scaleAndAdd;
  24820. var v2Copy = copy;
  24821. // Temporary variable
  24822. var v = [];
  24823. var cp0 = [];
  24824. var cp1 = [];
  24825. function isPointNull(p) {
  24826. return isNaN(p[0]) || isNaN(p[1]);
  24827. }
  24828. function drawSegment(
  24829. ctx, points, start, segLen, allLen,
  24830. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  24831. ) {
  24832. var prevIdx = 0;
  24833. var idx = start;
  24834. for (var k = 0; k < segLen; k++) {
  24835. var p = points[idx];
  24836. if (idx >= allLen || idx < 0) {
  24837. break;
  24838. }
  24839. if (isPointNull(p)) {
  24840. if (connectNulls) {
  24841. idx += dir;
  24842. continue;
  24843. }
  24844. break;
  24845. }
  24846. if (idx === start) {
  24847. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  24848. v2Copy(cp0, p);
  24849. }
  24850. else {
  24851. if (smooth > 0) {
  24852. var nextIdx = idx + dir;
  24853. var nextP = points[nextIdx];
  24854. if (connectNulls) {
  24855. // Find next point not null
  24856. while (nextP && isPointNull(points[nextIdx])) {
  24857. nextIdx += dir;
  24858. nextP = points[nextIdx];
  24859. }
  24860. }
  24861. var ratioNextSeg = 0.5;
  24862. var prevP = points[prevIdx];
  24863. var nextP = points[nextIdx];
  24864. // Last point
  24865. if (!nextP || isPointNull(nextP)) {
  24866. v2Copy(cp1, p);
  24867. }
  24868. else {
  24869. // If next data is null in not connect case
  24870. if (isPointNull(nextP) && !connectNulls) {
  24871. nextP = p;
  24872. }
  24873. sub(v, nextP, prevP);
  24874. var lenPrevSeg;
  24875. var lenNextSeg;
  24876. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  24877. var dim = smoothMonotone === 'x' ? 0 : 1;
  24878. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  24879. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  24880. }
  24881. else {
  24882. lenPrevSeg = dist(p, prevP);
  24883. lenNextSeg = dist(p, nextP);
  24884. }
  24885. // Use ratio of seg length
  24886. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  24887. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  24888. }
  24889. // Smooth constraint
  24890. vec2Min(cp0, cp0, smoothMax);
  24891. vec2Max(cp0, cp0, smoothMin);
  24892. vec2Min(cp1, cp1, smoothMax);
  24893. vec2Max(cp1, cp1, smoothMin);
  24894. ctx.bezierCurveTo(
  24895. cp0[0], cp0[1],
  24896. cp1[0], cp1[1],
  24897. p[0], p[1]
  24898. );
  24899. // cp0 of next segment
  24900. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  24901. }
  24902. else {
  24903. ctx.lineTo(p[0], p[1]);
  24904. }
  24905. }
  24906. prevIdx = idx;
  24907. idx += dir;
  24908. }
  24909. return k;
  24910. }
  24911. function getBoundingBox(points, smoothConstraint) {
  24912. var ptMin = [Infinity, Infinity];
  24913. var ptMax = [-Infinity, -Infinity];
  24914. if (smoothConstraint) {
  24915. for (var i = 0; i < points.length; i++) {
  24916. var pt = points[i];
  24917. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  24918. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  24919. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  24920. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  24921. }
  24922. }
  24923. return {
  24924. min: smoothConstraint ? ptMin : ptMax,
  24925. max: smoothConstraint ? ptMax : ptMin
  24926. };
  24927. }
  24928. var Polyline$1 = Path.extend({
  24929. type: 'ec-polyline',
  24930. shape: {
  24931. points: [],
  24932. smooth: 0,
  24933. smoothConstraint: true,
  24934. smoothMonotone: null,
  24935. connectNulls: false
  24936. },
  24937. style: {
  24938. fill: null,
  24939. stroke: '#000'
  24940. },
  24941. brush: fixClipWithShadow(Path.prototype.brush),
  24942. buildPath: function (ctx, shape) {
  24943. var points = shape.points;
  24944. var i = 0;
  24945. var len$$1 = points.length;
  24946. var result = getBoundingBox(points, shape.smoothConstraint);
  24947. if (shape.connectNulls) {
  24948. // Must remove first and last null values avoid draw error in polygon
  24949. for (; len$$1 > 0; len$$1--) {
  24950. if (!isPointNull(points[len$$1 - 1])) {
  24951. break;
  24952. }
  24953. }
  24954. for (; i < len$$1; i++) {
  24955. if (!isPointNull(points[i])) {
  24956. break;
  24957. }
  24958. }
  24959. }
  24960. while (i < len$$1) {
  24961. i += drawSegment(
  24962. ctx, points, i, len$$1, len$$1,
  24963. 1, result.min, result.max, shape.smooth,
  24964. shape.smoothMonotone, shape.connectNulls
  24965. ) + 1;
  24966. }
  24967. }
  24968. });
  24969. var Polygon$1 = Path.extend({
  24970. type: 'ec-polygon',
  24971. shape: {
  24972. points: [],
  24973. // Offset between stacked base points and points
  24974. stackedOnPoints: [],
  24975. smooth: 0,
  24976. stackedOnSmooth: 0,
  24977. smoothConstraint: true,
  24978. smoothMonotone: null,
  24979. connectNulls: false
  24980. },
  24981. brush: fixClipWithShadow(Path.prototype.brush),
  24982. buildPath: function (ctx, shape) {
  24983. var points = shape.points;
  24984. var stackedOnPoints = shape.stackedOnPoints;
  24985. var i = 0;
  24986. var len$$1 = points.length;
  24987. var smoothMonotone = shape.smoothMonotone;
  24988. var bbox = getBoundingBox(points, shape.smoothConstraint);
  24989. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  24990. if (shape.connectNulls) {
  24991. // Must remove first and last null values avoid draw error in polygon
  24992. for (; len$$1 > 0; len$$1--) {
  24993. if (!isPointNull(points[len$$1 - 1])) {
  24994. break;
  24995. }
  24996. }
  24997. for (; i < len$$1; i++) {
  24998. if (!isPointNull(points[i])) {
  24999. break;
  25000. }
  25001. }
  25002. }
  25003. while (i < len$$1) {
  25004. var k = drawSegment(
  25005. ctx, points, i, len$$1, len$$1,
  25006. 1, bbox.min, bbox.max, shape.smooth,
  25007. smoothMonotone, shape.connectNulls
  25008. );
  25009. drawSegment(
  25010. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  25011. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  25012. smoothMonotone, shape.connectNulls
  25013. );
  25014. i += k + 1;
  25015. ctx.closePath();
  25016. }
  25017. }
  25018. });
  25019. // FIXME step not support polar
  25020. function isPointsSame(points1, points2) {
  25021. if (points1.length !== points2.length) {
  25022. return;
  25023. }
  25024. for (var i = 0; i < points1.length; i++) {
  25025. var p1 = points1[i];
  25026. var p2 = points2[i];
  25027. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  25028. return;
  25029. }
  25030. }
  25031. return true;
  25032. }
  25033. function getSmooth(smooth) {
  25034. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0);
  25035. }
  25036. function getAxisExtentWithGap(axis) {
  25037. var extent = axis.getGlobalExtent();
  25038. if (axis.onBand) {
  25039. // Remove extra 1px to avoid line miter in clipped edge
  25040. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  25041. var dir = extent[1] > extent[0] ? 1 : -1;
  25042. extent[0] += dir * halfBandWidth;
  25043. extent[1] -= dir * halfBandWidth;
  25044. }
  25045. return extent;
  25046. }
  25047. function sign(val) {
  25048. return val >= 0 ? 1 : -1;
  25049. }
  25050. /**
  25051. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  25052. * @param {module:echarts/data/List} data
  25053. * @param {Array.<Array.<number>>} points
  25054. * @param {string} origin origin of areaStyle. Valid values: 'auto', 'start',
  25055. * 'end'.
  25056. * auto: from axisLine to data
  25057. * start: from min to data
  25058. * end: from data to max
  25059. * @private
  25060. */
  25061. function getStackedOnPoints(seriesModel, coordSys, data, origin) {
  25062. var baseAxis = coordSys.getBaseAxis();
  25063. var valueAxis = coordSys.getOtherAxis(baseAxis);
  25064. var valueStart = 0;
  25065. var extent = valueAxis.scale.getExtent();
  25066. if (origin === 'start') {
  25067. valueStart = extent[0];
  25068. }
  25069. else if (origin === 'end') {
  25070. valueStart = extent[1];
  25071. }
  25072. else {
  25073. // auto
  25074. var extent = valueAxis.scale.getExtent();
  25075. if (extent[0] > 0) {
  25076. // Both positive
  25077. valueStart = extent[0];
  25078. }
  25079. else if (extent[1] < 0) {
  25080. // Both negative
  25081. valueStart = extent[1];
  25082. }
  25083. // If is one positive, and one negative, onZero shall be true
  25084. }
  25085. var valueCoordDim = valueAxis.dim;
  25086. var baseDataOffset = valueCoordDim === 'x' || valueCoordDim === 'radius' ? 1 : 0;
  25087. var valueDim = data.mapDimension(valueCoordDim);
  25088. return data.mapArray(valueDim ? [valueDim] : [], function (val, idx) {
  25089. var stackedOnSameSign;
  25090. var stackedOn = data.stackedOn;
  25091. // Find first stacked value with same sign
  25092. while (stackedOn &&
  25093. sign(stackedOn.get(valueDim, idx)) === sign(val)
  25094. ) {
  25095. stackedOnSameSign = stackedOn;
  25096. break;
  25097. }
  25098. var stackedData = [];
  25099. stackedData[baseDataOffset] = data.get(baseAxis.dim, idx);
  25100. stackedData[1 - baseDataOffset] = stackedOnSameSign
  25101. ? stackedOnSameSign.get(valueDim, idx, true) : valueStart;
  25102. return coordSys.dataToPoint(stackedData);
  25103. }, true);
  25104. }
  25105. function createGridClipShape(cartesian, hasAnimation, seriesModel) {
  25106. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  25107. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  25108. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  25109. var x = Math.min(xExtent[0], xExtent[1]);
  25110. var y = Math.min(yExtent[0], yExtent[1]);
  25111. var width = Math.max(xExtent[0], xExtent[1]) - x;
  25112. var height = Math.max(yExtent[0], yExtent[1]) - y;
  25113. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  25114. // Expand clip shape to avoid clipping when line value exceeds axis
  25115. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  25116. if (isHorizontal) {
  25117. y -= expandSize;
  25118. height += expandSize * 2;
  25119. }
  25120. else {
  25121. x -= expandSize;
  25122. width += expandSize * 2;
  25123. }
  25124. var clipPath = new Rect({
  25125. shape: {
  25126. x: x,
  25127. y: y,
  25128. width: width,
  25129. height: height
  25130. }
  25131. });
  25132. if (hasAnimation) {
  25133. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  25134. initProps(clipPath, {
  25135. shape: {
  25136. width: width,
  25137. height: height
  25138. }
  25139. }, seriesModel);
  25140. }
  25141. return clipPath;
  25142. }
  25143. function createPolarClipShape(polar, hasAnimation, seriesModel) {
  25144. var angleAxis = polar.getAngleAxis();
  25145. var radiusAxis = polar.getRadiusAxis();
  25146. var radiusExtent = radiusAxis.getExtent();
  25147. var angleExtent = angleAxis.getExtent();
  25148. var RADIAN = Math.PI / 180;
  25149. var clipPath = new Sector({
  25150. shape: {
  25151. cx: polar.cx,
  25152. cy: polar.cy,
  25153. r0: radiusExtent[0],
  25154. r: radiusExtent[1],
  25155. startAngle: -angleExtent[0] * RADIAN,
  25156. endAngle: -angleExtent[1] * RADIAN,
  25157. clockwise: angleAxis.inverse
  25158. }
  25159. });
  25160. if (hasAnimation) {
  25161. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  25162. initProps(clipPath, {
  25163. shape: {
  25164. endAngle: -angleExtent[1] * RADIAN
  25165. }
  25166. }, seriesModel);
  25167. }
  25168. return clipPath;
  25169. }
  25170. function createClipShape(coordSys, hasAnimation, seriesModel) {
  25171. return coordSys.type === 'polar'
  25172. ? createPolarClipShape(coordSys, hasAnimation, seriesModel)
  25173. : createGridClipShape(coordSys, hasAnimation, seriesModel);
  25174. }
  25175. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  25176. var baseAxis = coordSys.getBaseAxis();
  25177. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  25178. var stepPoints = [];
  25179. for (var i = 0; i < points.length - 1; i++) {
  25180. var nextPt = points[i + 1];
  25181. var pt = points[i];
  25182. stepPoints.push(pt);
  25183. var stepPt = [];
  25184. switch (stepTurnAt) {
  25185. case 'end':
  25186. stepPt[baseIndex] = nextPt[baseIndex];
  25187. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  25188. // default is start
  25189. stepPoints.push(stepPt);
  25190. break;
  25191. case 'middle':
  25192. // default is start
  25193. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  25194. var stepPt2 = [];
  25195. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  25196. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  25197. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  25198. stepPoints.push(stepPt);
  25199. stepPoints.push(stepPt2);
  25200. break;
  25201. default:
  25202. stepPt[baseIndex] = pt[baseIndex];
  25203. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  25204. // default is start
  25205. stepPoints.push(stepPt);
  25206. }
  25207. }
  25208. // Last points
  25209. points[i] && stepPoints.push(points[i]);
  25210. return stepPoints;
  25211. }
  25212. function getVisualGradient(data, coordSys) {
  25213. var visualMetaList = data.getVisual('visualMeta');
  25214. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  25215. // When data.count() is 0, gradient range can not be calculated.
  25216. return;
  25217. }
  25218. var visualMeta;
  25219. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  25220. // Can only be x or y
  25221. if (visualMetaList[i].dimension < 2) {
  25222. visualMeta = visualMetaList[i];
  25223. break;
  25224. }
  25225. }
  25226. if (!visualMeta || coordSys.type !== 'cartesian2d') {
  25227. if (__DEV__) {
  25228. console.warn('Visual map on line style only support x or y dimension.');
  25229. }
  25230. return;
  25231. }
  25232. // If the area to be rendered is bigger than area defined by LinearGradient,
  25233. // the canvas spec prescribes that the color of the first stop and the last
  25234. // stop should be used. But if two stops are added at offset 0, in effect
  25235. // browsers use the color of the second stop to render area outside
  25236. // LinearGradient. So we can only infinitesimally extend area defined in
  25237. // LinearGradient to render `outerColors`.
  25238. var dimension = visualMeta.dimension;
  25239. var dimName = data.dimensions[dimension];
  25240. var axis = coordSys.getAxis(dimName);
  25241. // dataToCoor mapping may not be linear, but must be monotonic.
  25242. var colorStops = map(visualMeta.stops, function (stop) {
  25243. return {
  25244. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  25245. color: stop.color
  25246. };
  25247. });
  25248. var stopLen = colorStops.length;
  25249. var outerColors = visualMeta.outerColors.slice();
  25250. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  25251. colorStops.reverse();
  25252. outerColors.reverse();
  25253. }
  25254. var tinyExtent = 10; // Arbitrary value: 10px
  25255. var minCoord = colorStops[0].coord - tinyExtent;
  25256. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  25257. var coordSpan = maxCoord - minCoord;
  25258. if (coordSpan < 1e-3) {
  25259. return 'transparent';
  25260. }
  25261. each$1(colorStops, function (stop) {
  25262. stop.offset = (stop.coord - minCoord) / coordSpan;
  25263. });
  25264. colorStops.push({
  25265. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  25266. color: outerColors[1] || 'transparent'
  25267. });
  25268. colorStops.unshift({ // notice colorStops.length have been changed.
  25269. offset: stopLen ? colorStops[0].offset : 0.5,
  25270. color: outerColors[0] || 'transparent'
  25271. });
  25272. // zrUtil.each(colorStops, function (colorStop) {
  25273. // // Make sure each offset has rounded px to avoid not sharp edge
  25274. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  25275. // });
  25276. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  25277. gradient[dimName] = minCoord;
  25278. gradient[dimName + '2'] = maxCoord;
  25279. return gradient;
  25280. }
  25281. Chart.extend({
  25282. type: 'line',
  25283. init: function () {
  25284. var lineGroup = new Group();
  25285. var symbolDraw = new SymbolDraw();
  25286. this.group.add(symbolDraw.group);
  25287. this._symbolDraw = symbolDraw;
  25288. this._lineGroup = lineGroup;
  25289. },
  25290. render: function (seriesModel, ecModel, api) {
  25291. var coordSys = seriesModel.coordinateSystem;
  25292. var group = this.group;
  25293. var data = seriesModel.getData();
  25294. var lineStyleModel = seriesModel.getModel('lineStyle');
  25295. var areaStyleModel = seriesModel.getModel('areaStyle');
  25296. var points = data.mapArray(data.getItemLayout, true);
  25297. var isCoordSysPolar = coordSys.type === 'polar';
  25298. var prevCoordSys = this._coordSys;
  25299. var symbolDraw = this._symbolDraw;
  25300. var polyline = this._polyline;
  25301. var polygon = this._polygon;
  25302. var lineGroup = this._lineGroup;
  25303. var hasAnimation = seriesModel.get('animation');
  25304. var isAreaChart = !areaStyleModel.isEmpty();
  25305. var origin = areaStyleModel.get('origin');
  25306. var stackedOnPoints = getStackedOnPoints(seriesModel, coordSys, data, origin);
  25307. var showSymbol = seriesModel.get('showSymbol');
  25308. var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol')
  25309. && this._getSymbolIgnoreFunc(data, coordSys);
  25310. // Remove temporary symbols
  25311. var oldData = this._data;
  25312. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  25313. if (el.__temp) {
  25314. group.remove(el);
  25315. oldData.setItemGraphicEl(idx, null);
  25316. }
  25317. });
  25318. // Remove previous created symbols if showSymbol changed to false
  25319. if (!showSymbol) {
  25320. symbolDraw.remove();
  25321. }
  25322. group.add(lineGroup);
  25323. // FIXME step not support polar
  25324. var step = !isCoordSysPolar && seriesModel.get('step');
  25325. // Initialization animation or coordinate system changed
  25326. if (
  25327. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  25328. ) {
  25329. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  25330. if (step) {
  25331. // TODO If stacked series is not step
  25332. points = turnPointsIntoStep(points, coordSys, step);
  25333. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  25334. }
  25335. polyline = this._newPolyline(points, coordSys, hasAnimation);
  25336. if (isAreaChart) {
  25337. polygon = this._newPolygon(
  25338. points, stackedOnPoints,
  25339. coordSys, hasAnimation
  25340. );
  25341. }
  25342. lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel));
  25343. }
  25344. else {
  25345. if (isAreaChart && !polygon) {
  25346. // If areaStyle is added
  25347. polygon = this._newPolygon(
  25348. points, stackedOnPoints,
  25349. coordSys, hasAnimation
  25350. );
  25351. }
  25352. else if (polygon && !isAreaChart) {
  25353. // If areaStyle is removed
  25354. lineGroup.remove(polygon);
  25355. polygon = this._polygon = null;
  25356. }
  25357. // Update clipPath
  25358. lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel));
  25359. // Always update, or it is wrong in the case turning on legend
  25360. // because points are not changed
  25361. showSymbol && symbolDraw.updateData(data, isSymbolIgnore);
  25362. // Stop symbol animation and sync with line points
  25363. // FIXME performance?
  25364. data.eachItemGraphicEl(function (el) {
  25365. el.stopAnimation(true);
  25366. });
  25367. // In the case data zoom triggerred refreshing frequently
  25368. // Data may not change if line has a category axis. So it should animate nothing
  25369. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  25370. || !isPointsSame(this._points, points)
  25371. ) {
  25372. if (hasAnimation) {
  25373. this._updateAnimation(
  25374. data, stackedOnPoints, coordSys, api, step
  25375. );
  25376. }
  25377. else {
  25378. // Not do it in update with animation
  25379. if (step) {
  25380. // TODO If stacked series is not step
  25381. points = turnPointsIntoStep(points, coordSys, step);
  25382. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  25383. }
  25384. polyline.setShape({
  25385. points: points
  25386. });
  25387. polygon && polygon.setShape({
  25388. points: points,
  25389. stackedOnPoints: stackedOnPoints
  25390. });
  25391. }
  25392. }
  25393. }
  25394. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  25395. polyline.useStyle(defaults(
  25396. // Use color in lineStyle first
  25397. lineStyleModel.getLineStyle(),
  25398. {
  25399. fill: 'none',
  25400. stroke: visualColor,
  25401. lineJoin: 'bevel'
  25402. }
  25403. ));
  25404. var smooth = seriesModel.get('smooth');
  25405. smooth = getSmooth(seriesModel.get('smooth'));
  25406. polyline.setShape({
  25407. smooth: smooth,
  25408. smoothMonotone: seriesModel.get('smoothMonotone'),
  25409. connectNulls: seriesModel.get('connectNulls')
  25410. });
  25411. if (polygon) {
  25412. var stackedOn = data.stackedOn;
  25413. var stackedOnSmooth = 0;
  25414. polygon.useStyle(defaults(
  25415. areaStyleModel.getAreaStyle(),
  25416. {
  25417. fill: visualColor,
  25418. opacity: 0.7,
  25419. lineJoin: 'bevel'
  25420. }
  25421. ));
  25422. if (stackedOn) {
  25423. var stackedOnSeries = stackedOn.hostModel;
  25424. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  25425. }
  25426. polygon.setShape({
  25427. smooth: smooth,
  25428. stackedOnSmooth: stackedOnSmooth,
  25429. smoothMonotone: seriesModel.get('smoothMonotone'),
  25430. connectNulls: seriesModel.get('connectNulls')
  25431. });
  25432. }
  25433. this._data = data;
  25434. // Save the coordinate system for transition animation when data changed
  25435. this._coordSys = coordSys;
  25436. this._stackedOnPoints = stackedOnPoints;
  25437. this._points = points;
  25438. this._step = step;
  25439. },
  25440. dispose: function () {},
  25441. highlight: function (seriesModel, ecModel, api, payload) {
  25442. var data = seriesModel.getData();
  25443. var dataIndex = queryDataIndex(data, payload);
  25444. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  25445. var symbol = data.getItemGraphicEl(dataIndex);
  25446. if (!symbol) {
  25447. // Create a temporary symbol if it is not exists
  25448. var pt = data.getItemLayout(dataIndex);
  25449. if (!pt) {
  25450. // Null data
  25451. return;
  25452. }
  25453. symbol = new SymbolClz(data, dataIndex);
  25454. symbol.position = pt;
  25455. symbol.setZ(
  25456. seriesModel.get('zlevel'),
  25457. seriesModel.get('z')
  25458. );
  25459. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  25460. symbol.__temp = true;
  25461. data.setItemGraphicEl(dataIndex, symbol);
  25462. // Stop scale animation
  25463. symbol.stopSymbolAnimation(true);
  25464. this.group.add(symbol);
  25465. }
  25466. symbol.highlight();
  25467. }
  25468. else {
  25469. // Highlight whole series
  25470. Chart.prototype.highlight.call(
  25471. this, seriesModel, ecModel, api, payload
  25472. );
  25473. }
  25474. },
  25475. downplay: function (seriesModel, ecModel, api, payload) {
  25476. var data = seriesModel.getData();
  25477. var dataIndex = queryDataIndex(data, payload);
  25478. if (dataIndex != null && dataIndex >= 0) {
  25479. var symbol = data.getItemGraphicEl(dataIndex);
  25480. if (symbol) {
  25481. if (symbol.__temp) {
  25482. data.setItemGraphicEl(dataIndex, null);
  25483. this.group.remove(symbol);
  25484. }
  25485. else {
  25486. symbol.downplay();
  25487. }
  25488. }
  25489. }
  25490. else {
  25491. // FIXME
  25492. // can not downplay completely.
  25493. // Downplay whole series
  25494. Chart.prototype.downplay.call(
  25495. this, seriesModel, ecModel, api, payload
  25496. );
  25497. }
  25498. },
  25499. /**
  25500. * @param {module:zrender/container/Group} group
  25501. * @param {Array.<Array.<number>>} points
  25502. * @private
  25503. */
  25504. _newPolyline: function (points) {
  25505. var polyline = this._polyline;
  25506. // Remove previous created polyline
  25507. if (polyline) {
  25508. this._lineGroup.remove(polyline);
  25509. }
  25510. polyline = new Polyline$1({
  25511. shape: {
  25512. points: points
  25513. },
  25514. silent: true,
  25515. z2: 10
  25516. });
  25517. this._lineGroup.add(polyline);
  25518. this._polyline = polyline;
  25519. return polyline;
  25520. },
  25521. /**
  25522. * @param {module:zrender/container/Group} group
  25523. * @param {Array.<Array.<number>>} stackedOnPoints
  25524. * @param {Array.<Array.<number>>} points
  25525. * @private
  25526. */
  25527. _newPolygon: function (points, stackedOnPoints) {
  25528. var polygon = this._polygon;
  25529. // Remove previous created polygon
  25530. if (polygon) {
  25531. this._lineGroup.remove(polygon);
  25532. }
  25533. polygon = new Polygon$1({
  25534. shape: {
  25535. points: points,
  25536. stackedOnPoints: stackedOnPoints
  25537. },
  25538. silent: true
  25539. });
  25540. this._lineGroup.add(polygon);
  25541. this._polygon = polygon;
  25542. return polygon;
  25543. },
  25544. /**
  25545. * @private
  25546. */
  25547. _getSymbolIgnoreFunc: function (data, coordSys) {
  25548. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  25549. // `getLabelInterval` is provided by echarts/component/axis
  25550. if (categoryAxis && categoryAxis.isLabelIgnored) {
  25551. return bind(categoryAxis.isLabelIgnored, categoryAxis);
  25552. }
  25553. },
  25554. /**
  25555. * @private
  25556. */
  25557. // FIXME Two value axis
  25558. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) {
  25559. var polyline = this._polyline;
  25560. var polygon = this._polygon;
  25561. var seriesModel = data.hostModel;
  25562. var diff = lineAnimationDiff(
  25563. this._data, data,
  25564. this._stackedOnPoints, stackedOnPoints,
  25565. this._coordSys, coordSys
  25566. );
  25567. var current = diff.current;
  25568. var stackedOnCurrent = diff.stackedOnCurrent;
  25569. var next = diff.next;
  25570. var stackedOnNext = diff.stackedOnNext;
  25571. if (step) {
  25572. // TODO If stacked series is not step
  25573. current = turnPointsIntoStep(diff.current, coordSys, step);
  25574. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  25575. next = turnPointsIntoStep(diff.next, coordSys, step);
  25576. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  25577. }
  25578. // `diff.current` is subset of `current` (which should be ensured by
  25579. // turnPointsIntoStep), so points in `__points` can be updated when
  25580. // points in `current` are update during animation.
  25581. polyline.shape.__points = diff.current;
  25582. polyline.shape.points = current;
  25583. updateProps(polyline, {
  25584. shape: {
  25585. points: next
  25586. }
  25587. }, seriesModel);
  25588. if (polygon) {
  25589. polygon.setShape({
  25590. points: current,
  25591. stackedOnPoints: stackedOnCurrent
  25592. });
  25593. updateProps(polygon, {
  25594. shape: {
  25595. points: next,
  25596. stackedOnPoints: stackedOnNext
  25597. }
  25598. }, seriesModel);
  25599. }
  25600. var updatedDataInfo = [];
  25601. var diffStatus = diff.status;
  25602. for (var i = 0; i < diffStatus.length; i++) {
  25603. var cmd = diffStatus[i].cmd;
  25604. if (cmd === '=') {
  25605. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  25606. if (el) {
  25607. updatedDataInfo.push({
  25608. el: el,
  25609. ptIdx: i // Index of points
  25610. });
  25611. }
  25612. }
  25613. }
  25614. if (polyline.animators && polyline.animators.length) {
  25615. polyline.animators[0].during(function () {
  25616. for (var i = 0; i < updatedDataInfo.length; i++) {
  25617. var el = updatedDataInfo[i].el;
  25618. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  25619. }
  25620. });
  25621. }
  25622. },
  25623. remove: function (ecModel) {
  25624. var group = this.group;
  25625. var oldData = this._data;
  25626. this._lineGroup.removeAll();
  25627. this._symbolDraw.remove(true);
  25628. // Remove temporary created elements when highlighting
  25629. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  25630. if (el.__temp) {
  25631. group.remove(el);
  25632. oldData.setItemGraphicEl(idx, null);
  25633. }
  25634. });
  25635. this._polyline =
  25636. this._polygon =
  25637. this._coordSys =
  25638. this._points =
  25639. this._stackedOnPoints =
  25640. this._data = null;
  25641. }
  25642. });
  25643. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  25644. // Encoding visual for all series include which is filtered for legend drawing
  25645. return {
  25646. seriesType: seriesType,
  25647. performRawSeries: true,
  25648. reset: function (seriesModel, ecModel, api) {
  25649. var data = seriesModel.getData();
  25650. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  25651. var symbolSize = seriesModel.get('symbolSize');
  25652. data.setVisual({
  25653. legendSymbol: legendSymbol || symbolType,
  25654. symbol: symbolType,
  25655. symbolSize: symbolSize
  25656. });
  25657. // Only visible series has each data be visual encoded
  25658. if (ecModel.isSeriesFiltered(seriesModel)) {
  25659. return;
  25660. }
  25661. var hasCallback = typeof symbolSize === 'function';
  25662. function dataEach(data, idx) {
  25663. if (typeof symbolSize === 'function') {
  25664. var rawValue = seriesModel.getRawValue(idx);
  25665. // FIXME
  25666. var params = seriesModel.getDataParams(idx);
  25667. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  25668. }
  25669. if (data.hasItemOption) {
  25670. var itemModel = data.getItemModel(idx);
  25671. var itemSymbolType = itemModel.getShallow('symbol', true);
  25672. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  25673. // If has item symbol
  25674. if (itemSymbolType != null) {
  25675. data.setItemVisual(idx, 'symbol', itemSymbolType);
  25676. }
  25677. if (itemSymbolSize != null) {
  25678. // PENDING Transform symbolSize ?
  25679. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  25680. }
  25681. }
  25682. }
  25683. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  25684. }
  25685. };
  25686. };
  25687. var layoutPoints = function (seriesType) {
  25688. return {
  25689. seriesType: seriesType,
  25690. plan: createRenderPlanner(),
  25691. reset: function (seriesModel) {
  25692. var data = seriesModel.getData();
  25693. var coordSys = seriesModel.coordinateSystem;
  25694. var pipelineContext = seriesModel.pipelineContext;
  25695. var isLargeRender = pipelineContext.large;
  25696. if (!coordSys) {
  25697. return;
  25698. }
  25699. var dims = map(coordSys.dimensions, function (dim) {
  25700. return data.getDimension(data.mapDimension(dim));
  25701. }).slice(0, 2);
  25702. var dimLen = dims.length;
  25703. function progress(params, data) {
  25704. var segCount = params.end - params.start;
  25705. var points = isLargeRender && new Float32Array(segCount * dimLen);
  25706. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  25707. var point;
  25708. if (dimLen === 1) {
  25709. var x = data.get(dims[0], i, true);
  25710. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  25711. }
  25712. else {
  25713. var x = tmpIn[0] = data.get(dims[0], i, true);
  25714. var y = tmpIn[1] = data.get(dims[1], i, true);
  25715. // Also {Array.<number>}, not undefined to avoid if...else... statement
  25716. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  25717. }
  25718. if (isLargeRender) {
  25719. points[offset++] = point ? point[0] : NaN;
  25720. points[offset++] = point ? point[1] : NaN;
  25721. }
  25722. else {
  25723. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  25724. }
  25725. }
  25726. isLargeRender && data.setLayout('symbolPoints', points);
  25727. }
  25728. return dimLen && {progress: progress};
  25729. }
  25730. };
  25731. };
  25732. var samplers = {
  25733. average: function (frame) {
  25734. var sum = 0;
  25735. var count = 0;
  25736. for (var i = 0; i < frame.length; i++) {
  25737. if (!isNaN(frame[i])) {
  25738. sum += frame[i];
  25739. count++;
  25740. }
  25741. }
  25742. // Return NaN if count is 0
  25743. return count === 0 ? NaN : sum / count;
  25744. },
  25745. sum: function (frame) {
  25746. var sum = 0;
  25747. for (var i = 0; i < frame.length; i++) {
  25748. // Ignore NaN
  25749. sum += frame[i] || 0;
  25750. }
  25751. return sum;
  25752. },
  25753. max: function (frame) {
  25754. var max = -Infinity;
  25755. for (var i = 0; i < frame.length; i++) {
  25756. frame[i] > max && (max = frame[i]);
  25757. }
  25758. return max;
  25759. },
  25760. min: function (frame) {
  25761. var min = Infinity;
  25762. for (var i = 0; i < frame.length; i++) {
  25763. frame[i] < min && (min = frame[i]);
  25764. }
  25765. return min;
  25766. },
  25767. // TODO
  25768. // Median
  25769. nearest: function (frame) {
  25770. return frame[0];
  25771. }
  25772. };
  25773. var indexSampler = function (frame, value) {
  25774. return Math.round(frame.length / 2);
  25775. };
  25776. var dataSample = function (seriesType) {
  25777. return {
  25778. seriesType: seriesType,
  25779. reset: function (seriesModel, ecModel, api) {
  25780. var data = seriesModel.getData();
  25781. var sampling = seriesModel.get('sampling');
  25782. var coordSys = seriesModel.coordinateSystem;
  25783. // Only cartesian2d support down sampling
  25784. if (coordSys.type === 'cartesian2d' && sampling) {
  25785. var baseAxis = coordSys.getBaseAxis();
  25786. var valueAxis = coordSys.getOtherAxis(baseAxis);
  25787. var extent = baseAxis.getExtent();
  25788. // Coordinste system has been resized
  25789. var size = extent[1] - extent[0];
  25790. var rate = Math.round(data.count() / size);
  25791. if (rate > 1) {
  25792. var sampler;
  25793. if (typeof sampling === 'string') {
  25794. sampler = samplers[sampling];
  25795. }
  25796. else if (typeof sampling === 'function') {
  25797. sampler = sampling;
  25798. }
  25799. if (sampler) {
  25800. seriesModel.setData(data.downSample(
  25801. valueAxis.dim, 1 / rate, sampler, indexSampler
  25802. ));
  25803. }
  25804. }
  25805. }
  25806. }
  25807. };
  25808. };
  25809. /**
  25810. * // Scale class management
  25811. * @module echarts/scale/Scale
  25812. */
  25813. /**
  25814. * @param {Object} [setting]
  25815. */
  25816. function Scale(setting) {
  25817. this._setting = setting || {};
  25818. /**
  25819. * Extent
  25820. * @type {Array.<number>}
  25821. * @protected
  25822. */
  25823. this._extent = [Infinity, -Infinity];
  25824. /**
  25825. * Step is calculated in adjustExtent
  25826. * @type {Array.<number>}
  25827. * @protected
  25828. */
  25829. this._interval = 0;
  25830. this.init && this.init.apply(this, arguments);
  25831. }
  25832. /**
  25833. * Parse input val to valid inner number.
  25834. * @param {*} val
  25835. * @return {number}
  25836. */
  25837. Scale.prototype.parse = function (val) {
  25838. // Notice: This would be a trap here, If the implementation
  25839. // of this method depends on extent, and this method is used
  25840. // before extent set (like in dataZoom), it would be wrong.
  25841. // Nevertheless, parse does not depend on extent generally.
  25842. return val;
  25843. };
  25844. Scale.prototype.getSetting = function (name) {
  25845. return this._setting[name];
  25846. };
  25847. Scale.prototype.contain = function (val) {
  25848. var extent = this._extent;
  25849. return val >= extent[0] && val <= extent[1];
  25850. };
  25851. /**
  25852. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  25853. * @param {number} val
  25854. * @return {number}
  25855. */
  25856. Scale.prototype.normalize = function (val) {
  25857. var extent = this._extent;
  25858. if (extent[1] === extent[0]) {
  25859. return 0.5;
  25860. }
  25861. return (val - extent[0]) / (extent[1] - extent[0]);
  25862. };
  25863. /**
  25864. * Scale normalized value
  25865. * @param {number} val
  25866. * @return {number}
  25867. */
  25868. Scale.prototype.scale = function (val) {
  25869. var extent = this._extent;
  25870. return val * (extent[1] - extent[0]) + extent[0];
  25871. };
  25872. /**
  25873. * Set extent from data
  25874. * @param {Array.<number>} other
  25875. */
  25876. Scale.prototype.unionExtent = function (other) {
  25877. var extent = this._extent;
  25878. other[0] < extent[0] && (extent[0] = other[0]);
  25879. other[1] > extent[1] && (extent[1] = other[1]);
  25880. // not setExtent because in log axis it may transformed to power
  25881. // this.setExtent(extent[0], extent[1]);
  25882. };
  25883. /**
  25884. * Set extent from data
  25885. * @param {module:echarts/data/List} data
  25886. * @param {string} dim
  25887. */
  25888. Scale.prototype.unionExtentFromData = function (data, dim) {
  25889. this.unionExtent(data.getApproximateExtent(dim, true));
  25890. };
  25891. /**
  25892. * Get extent
  25893. * @return {Array.<number>}
  25894. */
  25895. Scale.prototype.getExtent = function () {
  25896. return this._extent.slice();
  25897. };
  25898. /**
  25899. * Set extent
  25900. * @param {number} start
  25901. * @param {number} end
  25902. */
  25903. Scale.prototype.setExtent = function (start, end) {
  25904. var thisExtent = this._extent;
  25905. if (!isNaN(start)) {
  25906. thisExtent[0] = start;
  25907. }
  25908. if (!isNaN(end)) {
  25909. thisExtent[1] = end;
  25910. }
  25911. };
  25912. /**
  25913. * @return {Array.<string>}
  25914. */
  25915. Scale.prototype.getTicksLabels = function () {
  25916. var labels = [];
  25917. var ticks = this.getTicks();
  25918. for (var i = 0; i < ticks.length; i++) {
  25919. labels.push(this.getLabel(ticks[i]));
  25920. }
  25921. return labels;
  25922. };
  25923. /**
  25924. * When axis extent depends on data and no data exists,
  25925. * axis ticks should not be drawn, which is named 'blank'.
  25926. */
  25927. Scale.prototype.isBlank = function () {
  25928. return this._isBlank;
  25929. },
  25930. /**
  25931. * When axis extent depends on data and no data exists,
  25932. * axis ticks should not be drawn, which is named 'blank'.
  25933. */
  25934. Scale.prototype.setBlank = function (isBlank) {
  25935. this._isBlank = isBlank;
  25936. };
  25937. enableClassExtend(Scale);
  25938. enableClassManagement(Scale, {
  25939. registerWhenExtend: true
  25940. });
  25941. /**
  25942. * @constructor
  25943. * @param {Object} [opt]
  25944. * @param {Object} [opt.categories=[]]
  25945. * @param {Object} [opt.needCollect=false]
  25946. * @param {Object} [opt.deduplication=false]
  25947. */
  25948. function OrdinalMeta(opt) {
  25949. /**
  25950. * @readOnly
  25951. * @type {Array.<string>}
  25952. */
  25953. this.categories = opt.categories || [];
  25954. /**
  25955. * @private
  25956. * @type {boolean}
  25957. */
  25958. this._needCollect = opt.needCollect;
  25959. /**
  25960. * @private
  25961. * @type {boolean}
  25962. */
  25963. this._deduplication = opt.deduplication;
  25964. /**
  25965. * @private
  25966. * @type {boolean}
  25967. */
  25968. this._map;
  25969. }
  25970. /**
  25971. * @param {module:echarts/model/Model} axisModel
  25972. * @return {module:echarts/data/OrdinalMeta}
  25973. */
  25974. OrdinalMeta.createByAxisModel = function (axisModel) {
  25975. var option = axisModel.option;
  25976. var data = option.data;
  25977. var categories = data && map(data, getName);
  25978. return new OrdinalMeta({
  25979. categories: categories,
  25980. needCollect: !categories,
  25981. // deduplication is default in axis.
  25982. deduplication: option.dedplication !== false
  25983. });
  25984. };
  25985. var proto$1 = OrdinalMeta.prototype;
  25986. /**
  25987. * @param {string} category
  25988. * @return {number} ordinal
  25989. */
  25990. proto$1.getOrdinal = function (category) {
  25991. return getOrCreateMap(this).get(category);
  25992. };
  25993. /**
  25994. * @param {*} category
  25995. * @return {number} The ordinal. If not found, return NaN.
  25996. */
  25997. proto$1.parseAndCollect = function (category) {
  25998. var index;
  25999. var needCollect = this._needCollect;
  26000. // The value of category dim can be the index of the given category set.
  26001. // This feature is only supported when !needCollect, because we should
  26002. // consider a common case: a value is 2017, which is a number but is
  26003. // expected to be tread as a category. This case usually happen in dataset,
  26004. // where it happent to be no need of the index feature.
  26005. if (typeof category !== 'string' && !needCollect) {
  26006. return category;
  26007. }
  26008. // Optimize for the scenario:
  26009. // category is ['2012-01-01', '2012-01-02', ...], where the input
  26010. // data has been ensured not duplicate and is large data.
  26011. // Notice, if a dataset dimension provide categroies, usually echarts
  26012. // should remove duplication except user tell echarts dont do that
  26013. // (set axis.deduplication = false), because echarts do not know whether
  26014. // the values in the category dimension has duplication (consider the
  26015. // parallel-aqi example)
  26016. if (needCollect && !this._deduplication) {
  26017. index = this.categories.length;
  26018. this.categories[index] = category;
  26019. return index;
  26020. }
  26021. var map$$1 = getOrCreateMap(this);
  26022. index = map$$1.get(category);
  26023. if (index == null) {
  26024. if (needCollect) {
  26025. index = this.categories.length;
  26026. this.categories[index] = category;
  26027. map$$1.set(category, index);
  26028. }
  26029. else {
  26030. index = NaN;
  26031. }
  26032. }
  26033. return index;
  26034. };
  26035. // Consider big data, do not create map until needed.
  26036. function getOrCreateMap(ordinalMeta) {
  26037. return ordinalMeta._map || (
  26038. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  26039. );
  26040. }
  26041. function getName(obj) {
  26042. if (isObject$1(obj) && obj.value != null) {
  26043. return obj.value;
  26044. }
  26045. else {
  26046. return obj + '';
  26047. }
  26048. }
  26049. /**
  26050. * Linear continuous scale
  26051. * @module echarts/coord/scale/Ordinal
  26052. *
  26053. * http://en.wikipedia.org/wiki/Level_of_measurement
  26054. */
  26055. // FIXME only one data
  26056. var scaleProto = Scale.prototype;
  26057. var OrdinalScale = Scale.extend({
  26058. type: 'ordinal',
  26059. /**
  26060. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  26061. */
  26062. init: function (ordinalMeta, extent) {
  26063. // Caution: Should not use instanceof, consider ec-extensions using
  26064. // import approach to get OrdinalMeta class.
  26065. if (!ordinalMeta || isArray(ordinalMeta)) {
  26066. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  26067. }
  26068. this._ordinalMeta = ordinalMeta;
  26069. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  26070. },
  26071. parse: function (val) {
  26072. return typeof val === 'string'
  26073. ? this._ordinalMeta.getOrdinal(val)
  26074. // val might be float.
  26075. : Math.round(val);
  26076. },
  26077. contain: function (rank) {
  26078. rank = this.parse(rank);
  26079. return scaleProto.contain.call(this, rank)
  26080. && this._ordinalMeta.categories[rank] != null;
  26081. },
  26082. /**
  26083. * Normalize given rank or name to linear [0, 1]
  26084. * @param {number|string} [val]
  26085. * @return {number}
  26086. */
  26087. normalize: function (val) {
  26088. return scaleProto.normalize.call(this, this.parse(val));
  26089. },
  26090. scale: function (val) {
  26091. return Math.round(scaleProto.scale.call(this, val));
  26092. },
  26093. /**
  26094. * @return {Array}
  26095. */
  26096. getTicks: function () {
  26097. var ticks = [];
  26098. var extent = this._extent;
  26099. var rank = extent[0];
  26100. while (rank <= extent[1]) {
  26101. ticks.push(rank);
  26102. rank++;
  26103. }
  26104. return ticks;
  26105. },
  26106. /**
  26107. * Get item on rank n
  26108. * @param {number} n
  26109. * @return {string}
  26110. */
  26111. getLabel: function (n) {
  26112. return this._ordinalMeta.categories[n];
  26113. },
  26114. /**
  26115. * @return {number}
  26116. */
  26117. count: function () {
  26118. return this._extent[1] - this._extent[0] + 1;
  26119. },
  26120. /**
  26121. * @override
  26122. */
  26123. unionExtentFromData: function (data, dim) {
  26124. this.unionExtent(data.getApproximateExtent(dim, false));
  26125. },
  26126. niceTicks: noop,
  26127. niceExtent: noop
  26128. });
  26129. /**
  26130. * @return {module:echarts/scale/Time}
  26131. */
  26132. OrdinalScale.create = function () {
  26133. return new OrdinalScale();
  26134. };
  26135. /**
  26136. * For testable.
  26137. */
  26138. var roundNumber$1 = round$1;
  26139. /**
  26140. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  26141. * Should be extent[0] < extent[1].
  26142. * @param {number} splitNumber splitNumber should be >= 1.
  26143. * @param {number} [minInterval]
  26144. * @param {number} [maxInterval]
  26145. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  26146. */
  26147. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  26148. var result = {};
  26149. var span = extent[1] - extent[0];
  26150. var interval = result.interval = nice(span / splitNumber, true);
  26151. if (minInterval != null && interval < minInterval) {
  26152. interval = result.interval = minInterval;
  26153. }
  26154. if (maxInterval != null && interval > maxInterval) {
  26155. interval = result.interval = maxInterval;
  26156. }
  26157. // Tow more digital for tick.
  26158. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  26159. // Niced extent inside original extent
  26160. var niceTickExtent = result.niceTickExtent = [
  26161. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  26162. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  26163. ];
  26164. fixExtent(niceTickExtent, extent);
  26165. return result;
  26166. }
  26167. /**
  26168. * @param {number} interval
  26169. * @return {number} interval precision
  26170. */
  26171. function getIntervalPrecision(interval) {
  26172. // Tow more digital for tick.
  26173. return getPrecisionSafe(interval) + 2;
  26174. }
  26175. function clamp(niceTickExtent, idx, extent) {
  26176. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  26177. }
  26178. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  26179. function fixExtent(niceTickExtent, extent) {
  26180. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  26181. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  26182. clamp(niceTickExtent, 0, extent);
  26183. clamp(niceTickExtent, 1, extent);
  26184. if (niceTickExtent[0] > niceTickExtent[1]) {
  26185. niceTickExtent[0] = niceTickExtent[1];
  26186. }
  26187. }
  26188. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  26189. var ticks = [];
  26190. // If interval is 0, return [];
  26191. if (!interval) {
  26192. return ticks;
  26193. }
  26194. // Consider this case: using dataZoom toolbox, zoom and zoom.
  26195. var safeLimit = 10000;
  26196. if (extent[0] < niceTickExtent[0]) {
  26197. ticks.push(extent[0]);
  26198. }
  26199. var tick = niceTickExtent[0];
  26200. while (tick <= niceTickExtent[1]) {
  26201. ticks.push(tick);
  26202. // Avoid rounding error
  26203. tick = roundNumber$1(tick + interval, intervalPrecision);
  26204. if (tick === ticks[ticks.length - 1]) {
  26205. // Consider out of safe float point, e.g.,
  26206. // -3711126.9907707 + 2e-10 === -3711126.9907707
  26207. break;
  26208. }
  26209. if (ticks.length > safeLimit) {
  26210. return [];
  26211. }
  26212. }
  26213. // Consider this case: the last item of ticks is smaller
  26214. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  26215. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  26216. ticks.push(extent[1]);
  26217. }
  26218. return ticks;
  26219. }
  26220. /**
  26221. * Interval scale
  26222. * @module echarts/scale/Interval
  26223. */
  26224. var roundNumber = round$1;
  26225. /**
  26226. * @alias module:echarts/coord/scale/Interval
  26227. * @constructor
  26228. */
  26229. var IntervalScale = Scale.extend({
  26230. type: 'interval',
  26231. _interval: 0,
  26232. _intervalPrecision: 2,
  26233. setExtent: function (start, end) {
  26234. var thisExtent = this._extent;
  26235. //start,end may be a Number like '25',so...
  26236. if (!isNaN(start)) {
  26237. thisExtent[0] = parseFloat(start);
  26238. }
  26239. if (!isNaN(end)) {
  26240. thisExtent[1] = parseFloat(end);
  26241. }
  26242. },
  26243. unionExtent: function (other) {
  26244. var extent = this._extent;
  26245. other[0] < extent[0] && (extent[0] = other[0]);
  26246. other[1] > extent[1] && (extent[1] = other[1]);
  26247. // unionExtent may called by it's sub classes
  26248. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  26249. },
  26250. /**
  26251. * Get interval
  26252. */
  26253. getInterval: function () {
  26254. return this._interval;
  26255. },
  26256. /**
  26257. * Set interval
  26258. */
  26259. setInterval: function (interval) {
  26260. this._interval = interval;
  26261. // Dropped auto calculated niceExtent and use user setted extent
  26262. // We assume user wan't to set both interval, min, max to get a better result
  26263. this._niceExtent = this._extent.slice();
  26264. this._intervalPrecision = getIntervalPrecision(interval);
  26265. },
  26266. /**
  26267. * @return {Array.<number>}
  26268. */
  26269. getTicks: function () {
  26270. return intervalScaleGetTicks(
  26271. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  26272. );
  26273. },
  26274. /**
  26275. * @return {Array.<string>}
  26276. */
  26277. getTicksLabels: function () {
  26278. var labels = [];
  26279. var ticks = this.getTicks();
  26280. for (var i = 0; i < ticks.length; i++) {
  26281. labels.push(this.getLabel(ticks[i]));
  26282. }
  26283. return labels;
  26284. },
  26285. /**
  26286. * @param {number} data
  26287. * @param {Object} [opt]
  26288. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  26289. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  26290. * @return {string}
  26291. */
  26292. getLabel: function (data, opt) {
  26293. if (data == null) {
  26294. return '';
  26295. }
  26296. var precision = opt && opt.precision;
  26297. if (precision == null) {
  26298. precision = getPrecisionSafe(data) || 0;
  26299. }
  26300. else if (precision === 'auto') {
  26301. // Should be more precise then tick.
  26302. precision = this._intervalPrecision;
  26303. }
  26304. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  26305. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  26306. data = roundNumber(data, precision, true);
  26307. return addCommas(data);
  26308. },
  26309. /**
  26310. * Update interval and extent of intervals for nice ticks
  26311. *
  26312. * @param {number} [splitNumber = 5] Desired number of ticks
  26313. * @param {number} [minInterval]
  26314. * @param {number} [maxInterval]
  26315. */
  26316. niceTicks: function (splitNumber, minInterval, maxInterval) {
  26317. splitNumber = splitNumber || 5;
  26318. var extent = this._extent;
  26319. var span = extent[1] - extent[0];
  26320. if (!isFinite(span)) {
  26321. return;
  26322. }
  26323. // User may set axis min 0 and data are all negative
  26324. // FIXME If it needs to reverse ?
  26325. if (span < 0) {
  26326. span = -span;
  26327. extent.reverse();
  26328. }
  26329. var result = intervalScaleNiceTicks(
  26330. extent, splitNumber, minInterval, maxInterval
  26331. );
  26332. this._intervalPrecision = result.intervalPrecision;
  26333. this._interval = result.interval;
  26334. this._niceExtent = result.niceTickExtent;
  26335. },
  26336. /**
  26337. * Nice extent.
  26338. * @param {Object} opt
  26339. * @param {number} [opt.splitNumber = 5] Given approx tick number
  26340. * @param {boolean} [opt.fixMin=false]
  26341. * @param {boolean} [opt.fixMax=false]
  26342. * @param {boolean} [opt.minInterval]
  26343. * @param {boolean} [opt.maxInterval]
  26344. */
  26345. niceExtent: function (opt) {
  26346. var extent = this._extent;
  26347. // If extent start and end are same, expand them
  26348. if (extent[0] === extent[1]) {
  26349. if (extent[0] !== 0) {
  26350. // Expand extent
  26351. var expandSize = extent[0];
  26352. // In the fowllowing case
  26353. // Axis has been fixed max 100
  26354. // Plus data are all 100 and axis extent are [100, 100].
  26355. // Extend to the both side will cause expanded max is larger than fixed max.
  26356. // So only expand to the smaller side.
  26357. if (!opt.fixMax) {
  26358. extent[1] += expandSize / 2;
  26359. extent[0] -= expandSize / 2;
  26360. }
  26361. else {
  26362. extent[0] -= expandSize / 2;
  26363. }
  26364. }
  26365. else {
  26366. extent[1] = 1;
  26367. }
  26368. }
  26369. var span = extent[1] - extent[0];
  26370. // If there are no data and extent are [Infinity, -Infinity]
  26371. if (!isFinite(span)) {
  26372. extent[0] = 0;
  26373. extent[1] = 1;
  26374. }
  26375. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  26376. // var extent = this._extent;
  26377. var interval = this._interval;
  26378. if (!opt.fixMin) {
  26379. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  26380. }
  26381. if (!opt.fixMax) {
  26382. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  26383. }
  26384. }
  26385. });
  26386. /**
  26387. * @return {module:echarts/scale/Time}
  26388. */
  26389. IntervalScale.create = function () {
  26390. return new IntervalScale();
  26391. };
  26392. var STACK_PREFIX = '__ec_stack_';
  26393. function getSeriesStackId(seriesModel) {
  26394. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  26395. }
  26396. function getAxisKey(axis) {
  26397. return axis.dim + axis.index;
  26398. }
  26399. /**
  26400. * @param {Object} opt
  26401. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  26402. * @param {number} opt.count Positive interger.
  26403. * @param {number} [opt.barWidth]
  26404. * @param {number} [opt.barMaxWidth]
  26405. * @param {number} [opt.barGap]
  26406. * @param {number} [opt.barCategoryGap]
  26407. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  26408. */
  26409. function calBarWidthAndOffset(barSeries, api) {
  26410. var seriesInfoList = map(barSeries, function (seriesModel) {
  26411. var data = seriesModel.getData();
  26412. var cartesian = seriesModel.coordinateSystem;
  26413. var baseAxis = cartesian.getBaseAxis();
  26414. var axisExtent = baseAxis.getExtent();
  26415. var bandWidth = baseAxis.type === 'category'
  26416. ? baseAxis.getBandWidth()
  26417. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  26418. var barWidth = parsePercent$1(
  26419. seriesModel.get('barWidth'), bandWidth
  26420. );
  26421. var barMaxWidth = parsePercent$1(
  26422. seriesModel.get('barMaxWidth'), bandWidth
  26423. );
  26424. var barGap = seriesModel.get('barGap');
  26425. var barCategoryGap = seriesModel.get('barCategoryGap');
  26426. return {
  26427. bandWidth: bandWidth,
  26428. barWidth: barWidth,
  26429. barMaxWidth: barMaxWidth,
  26430. barGap: barGap,
  26431. barCategoryGap: barCategoryGap,
  26432. axisKey: getAxisKey(baseAxis),
  26433. stackId: getSeriesStackId(seriesModel)
  26434. };
  26435. });
  26436. return doCalBarWidthAndOffset(seriesInfoList, api);
  26437. }
  26438. function doCalBarWidthAndOffset(seriesInfoList, api) {
  26439. // Columns info on each category axis. Key is cartesian name
  26440. var columnsMap = {};
  26441. each$1(seriesInfoList, function (seriesInfo, idx) {
  26442. var axisKey = seriesInfo.axisKey;
  26443. var bandWidth = seriesInfo.bandWidth;
  26444. var columnsOnAxis = columnsMap[axisKey] || {
  26445. bandWidth: bandWidth,
  26446. remainedWidth: bandWidth,
  26447. autoWidthCount: 0,
  26448. categoryGap: '20%',
  26449. gap: '30%',
  26450. stacks: {}
  26451. };
  26452. var stacks = columnsOnAxis.stacks;
  26453. columnsMap[axisKey] = columnsOnAxis;
  26454. var stackId = seriesInfo.stackId;
  26455. if (!stacks[stackId]) {
  26456. columnsOnAxis.autoWidthCount++;
  26457. }
  26458. stacks[stackId] = stacks[stackId] || {
  26459. width: 0,
  26460. maxWidth: 0
  26461. };
  26462. // Caution: In a single coordinate system, these barGrid attributes
  26463. // will be shared by series. Consider that they have default values,
  26464. // only the attributes set on the last series will work.
  26465. // Do not change this fact unless there will be a break change.
  26466. // TODO
  26467. var barWidth = seriesInfo.barWidth;
  26468. if (barWidth && !stacks[stackId].width) {
  26469. // See #6312, do not restrict width.
  26470. stacks[stackId].width = barWidth;
  26471. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  26472. columnsOnAxis.remainedWidth -= barWidth;
  26473. }
  26474. var barMaxWidth = seriesInfo.barMaxWidth;
  26475. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  26476. var barGap = seriesInfo.barGap;
  26477. (barGap != null) && (columnsOnAxis.gap = barGap);
  26478. var barCategoryGap = seriesInfo.barCategoryGap;
  26479. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  26480. });
  26481. var result = {};
  26482. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  26483. result[coordSysName] = {};
  26484. var stacks = columnsOnAxis.stacks;
  26485. var bandWidth = columnsOnAxis.bandWidth;
  26486. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  26487. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  26488. var remainedWidth = columnsOnAxis.remainedWidth;
  26489. var autoWidthCount = columnsOnAxis.autoWidthCount;
  26490. var autoWidth = (remainedWidth - categoryGap)
  26491. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26492. autoWidth = Math.max(autoWidth, 0);
  26493. // Find if any auto calculated bar exceeded maxBarWidth
  26494. each$1(stacks, function (column, stack) {
  26495. var maxWidth = column.maxWidth;
  26496. if (maxWidth && maxWidth < autoWidth) {
  26497. maxWidth = Math.min(maxWidth, remainedWidth);
  26498. if (column.width) {
  26499. maxWidth = Math.min(maxWidth, column.width);
  26500. }
  26501. remainedWidth -= maxWidth;
  26502. column.width = maxWidth;
  26503. autoWidthCount--;
  26504. }
  26505. });
  26506. // Recalculate width again
  26507. autoWidth = (remainedWidth - categoryGap)
  26508. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26509. autoWidth = Math.max(autoWidth, 0);
  26510. var widthSum = 0;
  26511. var lastColumn;
  26512. each$1(stacks, function (column, idx) {
  26513. if (!column.width) {
  26514. column.width = autoWidth;
  26515. }
  26516. lastColumn = column;
  26517. widthSum += column.width * (1 + barGapPercent);
  26518. });
  26519. if (lastColumn) {
  26520. widthSum -= lastColumn.width * barGapPercent;
  26521. }
  26522. var offset = -widthSum / 2;
  26523. each$1(stacks, function (column, stackId) {
  26524. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  26525. offset: offset,
  26526. width: column.width
  26527. };
  26528. offset += column.width * (1 + barGapPercent);
  26529. });
  26530. });
  26531. return result;
  26532. }
  26533. /**
  26534. * @param {string} seriesType
  26535. * @param {module:echarts/model/Global} ecModel
  26536. * @param {module:echarts/ExtensionAPI} api
  26537. */
  26538. function layout(seriesType, ecModel, api) {
  26539. var barWidthAndOffset = calBarWidthAndOffset(
  26540. filter(
  26541. ecModel.getSeriesByType(seriesType),
  26542. function (seriesModel) {
  26543. return !ecModel.isSeriesFiltered(seriesModel)
  26544. && seriesModel.coordinateSystem
  26545. && seriesModel.coordinateSystem.type === 'cartesian2d';
  26546. }
  26547. )
  26548. );
  26549. var lastStackCoords = {};
  26550. var lastStackCoordsOrigin = {};
  26551. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  26552. // Check series coordinate, do layout for cartesian2d only
  26553. if (seriesModel.coordinateSystem.type !== 'cartesian2d') {
  26554. return;
  26555. }
  26556. var data = seriesModel.getData();
  26557. var cartesian = seriesModel.coordinateSystem;
  26558. var baseAxis = cartesian.getBaseAxis();
  26559. var stackId = getSeriesStackId(seriesModel);
  26560. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  26561. var columnOffset = columnLayoutInfo.offset;
  26562. var columnWidth = columnLayoutInfo.width;
  26563. var valueAxis = cartesian.getOtherAxis(baseAxis);
  26564. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  26565. var valueAxisStart = baseAxis.onZero
  26566. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  26567. : valueAxis.getGlobalExtent()[0];
  26568. var coordDims = [
  26569. data.mapDimension('x'),
  26570. data.mapDimension('y')
  26571. ];
  26572. var coords = data.mapArray(coordDims, function (x, y) {
  26573. return cartesian.dataToPoint([x, y]);
  26574. }, true);
  26575. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  26576. lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243
  26577. data.setLayout({
  26578. offset: columnOffset,
  26579. size: columnWidth
  26580. });
  26581. data.each(data.mapDimension(valueAxis.dim), function (value, idx) {
  26582. if (isNaN(value)) {
  26583. return;
  26584. }
  26585. if (!lastStackCoords[stackId][idx]) {
  26586. lastStackCoords[stackId][idx] = {
  26587. p: valueAxisStart, // Positive stack
  26588. n: valueAxisStart // Negative stack
  26589. };
  26590. lastStackCoordsOrigin[stackId][idx] = {
  26591. p: valueAxisStart, // Positive stack
  26592. n: valueAxisStart // Negative stack
  26593. };
  26594. }
  26595. var sign = value >= 0 ? 'p' : 'n';
  26596. var coord = coords[idx];
  26597. var lastCoord = lastStackCoords[stackId][idx][sign];
  26598. var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign];
  26599. var x;
  26600. var y;
  26601. var width;
  26602. var height;
  26603. if (valueAxis.isHorizontal()) {
  26604. x = lastCoord;
  26605. y = coord[1] + columnOffset;
  26606. width = coord[0] - lastCoordOrigin;
  26607. height = columnWidth;
  26608. lastStackCoordsOrigin[stackId][idx][sign] += width;
  26609. if (Math.abs(width) < barMinHeight) {
  26610. width = (width < 0 ? -1 : 1) * barMinHeight;
  26611. }
  26612. lastStackCoords[stackId][idx][sign] += width;
  26613. }
  26614. else {
  26615. x = coord[0] + columnOffset;
  26616. y = lastCoord;
  26617. width = columnWidth;
  26618. height = coord[1] - lastCoordOrigin;
  26619. lastStackCoordsOrigin[stackId][idx][sign] += height;
  26620. if (Math.abs(height) < barMinHeight) {
  26621. // Include zero to has a positive bar
  26622. height = (height <= 0 ? -1 : 1) * barMinHeight;
  26623. }
  26624. lastStackCoords[stackId][idx][sign] += height;
  26625. }
  26626. data.setItemLayout(idx, {
  26627. x: x,
  26628. y: y,
  26629. width: width,
  26630. height: height
  26631. });
  26632. }, true);
  26633. }, this);
  26634. }
  26635. // [About UTC and local time zone]:
  26636. // In most cases, `number.parseDate` will treat input data string as local time
  26637. // (except time zone is specified in time string). And `format.formateTime` returns
  26638. // local time by default. option.useUTC is false by default. This design have
  26639. // concidered these common case:
  26640. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  26641. // in local time by default.
  26642. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  26643. // as its original time, without any time difference.
  26644. var intervalScaleProto = IntervalScale.prototype;
  26645. var mathCeil = Math.ceil;
  26646. var mathFloor = Math.floor;
  26647. var ONE_SECOND = 1000;
  26648. var ONE_MINUTE = ONE_SECOND * 60;
  26649. var ONE_HOUR = ONE_MINUTE * 60;
  26650. var ONE_DAY = ONE_HOUR * 24;
  26651. // FIXME 公用?
  26652. var bisect = function (a, x, lo, hi) {
  26653. while (lo < hi) {
  26654. var mid = lo + hi >>> 1;
  26655. if (a[mid][1] < x) {
  26656. lo = mid + 1;
  26657. }
  26658. else {
  26659. hi = mid;
  26660. }
  26661. }
  26662. return lo;
  26663. };
  26664. /**
  26665. * @alias module:echarts/coord/scale/Time
  26666. * @constructor
  26667. */
  26668. var TimeScale = IntervalScale.extend({
  26669. type: 'time',
  26670. /**
  26671. * @override
  26672. */
  26673. getLabel: function (val) {
  26674. var stepLvl = this._stepLvl;
  26675. var date = new Date(val);
  26676. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  26677. },
  26678. /**
  26679. * @override
  26680. */
  26681. niceExtent: function (opt) {
  26682. var extent = this._extent;
  26683. // If extent start and end are same, expand them
  26684. if (extent[0] === extent[1]) {
  26685. // Expand extent
  26686. extent[0] -= ONE_DAY;
  26687. extent[1] += ONE_DAY;
  26688. }
  26689. // If there are no data and extent are [Infinity, -Infinity]
  26690. if (extent[1] === -Infinity && extent[0] === Infinity) {
  26691. var d = new Date();
  26692. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  26693. extent[0] = extent[1] - ONE_DAY;
  26694. }
  26695. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  26696. // var extent = this._extent;
  26697. var interval = this._interval;
  26698. if (!opt.fixMin) {
  26699. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  26700. }
  26701. if (!opt.fixMax) {
  26702. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  26703. }
  26704. },
  26705. /**
  26706. * @override
  26707. */
  26708. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  26709. approxTickNum = approxTickNum || 10;
  26710. var extent = this._extent;
  26711. var span = extent[1] - extent[0];
  26712. var approxInterval = span / approxTickNum;
  26713. if (minInterval != null && approxInterval < minInterval) {
  26714. approxInterval = minInterval;
  26715. }
  26716. if (maxInterval != null && approxInterval > maxInterval) {
  26717. approxInterval = maxInterval;
  26718. }
  26719. var scaleLevelsLen = scaleLevels.length;
  26720. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  26721. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  26722. var interval = level[1];
  26723. // Same with interval scale if span is much larger than 1 year
  26724. if (level[0] === 'year') {
  26725. var yearSpan = span / interval;
  26726. // From "Nice Numbers for Graph Labels" of Graphic Gems
  26727. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  26728. var yearStep = nice(yearSpan / approxTickNum, true);
  26729. interval *= yearStep;
  26730. }
  26731. var timezoneOffset = this.getSetting('useUTC')
  26732. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  26733. var niceExtent = [
  26734. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  26735. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  26736. ];
  26737. fixExtent(niceExtent, extent);
  26738. this._stepLvl = level;
  26739. // Interval will be used in getTicks
  26740. this._interval = interval;
  26741. this._niceExtent = niceExtent;
  26742. },
  26743. parse: function (val) {
  26744. // val might be float.
  26745. return +parseDate(val);
  26746. }
  26747. });
  26748. each$1(['contain', 'normalize'], function (methodName) {
  26749. TimeScale.prototype[methodName] = function (val) {
  26750. return intervalScaleProto[methodName].call(this, this.parse(val));
  26751. };
  26752. });
  26753. // Steps from d3
  26754. var scaleLevels = [
  26755. // Format interval
  26756. ['hh:mm:ss', ONE_SECOND], // 1s
  26757. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  26758. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  26759. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  26760. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  26761. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  26762. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  26763. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  26764. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  26765. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  26766. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  26767. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  26768. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  26769. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  26770. ['MM-dd\nyyyy', ONE_DAY], // 1d
  26771. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  26772. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  26773. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  26774. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  26775. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  26776. ['week', ONE_DAY * 7], // 7d
  26777. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  26778. ['week', ONE_DAY * 14], // 2w
  26779. ['week', ONE_DAY * 21], // 3w
  26780. ['month', ONE_DAY * 31], // 1M
  26781. ['week', ONE_DAY * 42], // 6w
  26782. ['month', ONE_DAY * 62], // 2M
  26783. ['week', ONE_DAY * 42], // 10w
  26784. ['quarter', ONE_DAY * 380 / 4], // 3M
  26785. ['month', ONE_DAY * 31 * 4], // 4M
  26786. ['month', ONE_DAY * 31 * 5], // 5M
  26787. ['half-year', ONE_DAY * 380 / 2], // 6M
  26788. ['month', ONE_DAY * 31 * 8], // 8M
  26789. ['month', ONE_DAY * 31 * 10], // 10M
  26790. ['year', ONE_DAY * 380] // 1Y
  26791. ];
  26792. /**
  26793. * @param {module:echarts/model/Model}
  26794. * @return {module:echarts/scale/Time}
  26795. */
  26796. TimeScale.create = function (model) {
  26797. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  26798. };
  26799. /**
  26800. * Log scale
  26801. * @module echarts/scale/Log
  26802. */
  26803. // Use some method of IntervalScale
  26804. var scaleProto$1 = Scale.prototype;
  26805. var intervalScaleProto$1 = IntervalScale.prototype;
  26806. var getPrecisionSafe$1 = getPrecisionSafe;
  26807. var roundingErrorFix = round$1;
  26808. var mathFloor$1 = Math.floor;
  26809. var mathCeil$1 = Math.ceil;
  26810. var mathPow$1 = Math.pow;
  26811. var mathLog = Math.log;
  26812. var LogScale = Scale.extend({
  26813. type: 'log',
  26814. base: 10,
  26815. $constructor: function () {
  26816. Scale.apply(this, arguments);
  26817. this._originalScale = new IntervalScale();
  26818. },
  26819. /**
  26820. * @return {Array.<number>}
  26821. */
  26822. getTicks: function () {
  26823. var originalScale = this._originalScale;
  26824. var extent = this._extent;
  26825. var originalExtent = originalScale.getExtent();
  26826. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  26827. var powVal = round$1(mathPow$1(this.base, val));
  26828. // Fix #4158
  26829. powVal = (val === extent[0] && originalScale.__fixMin)
  26830. ? fixRoundingError(powVal, originalExtent[0])
  26831. : powVal;
  26832. powVal = (val === extent[1] && originalScale.__fixMax)
  26833. ? fixRoundingError(powVal, originalExtent[1])
  26834. : powVal;
  26835. return powVal;
  26836. }, this);
  26837. },
  26838. /**
  26839. * @param {number} val
  26840. * @return {string}
  26841. */
  26842. getLabel: intervalScaleProto$1.getLabel,
  26843. /**
  26844. * @param {number} val
  26845. * @return {number}
  26846. */
  26847. scale: function (val) {
  26848. val = scaleProto$1.scale.call(this, val);
  26849. return mathPow$1(this.base, val);
  26850. },
  26851. /**
  26852. * @param {number} start
  26853. * @param {number} end
  26854. */
  26855. setExtent: function (start, end) {
  26856. var base = this.base;
  26857. start = mathLog(start) / mathLog(base);
  26858. end = mathLog(end) / mathLog(base);
  26859. intervalScaleProto$1.setExtent.call(this, start, end);
  26860. },
  26861. /**
  26862. * @return {number} end
  26863. */
  26864. getExtent: function () {
  26865. var base = this.base;
  26866. var extent = scaleProto$1.getExtent.call(this);
  26867. extent[0] = mathPow$1(base, extent[0]);
  26868. extent[1] = mathPow$1(base, extent[1]);
  26869. // Fix #4158
  26870. var originalScale = this._originalScale;
  26871. var originalExtent = originalScale.getExtent();
  26872. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  26873. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  26874. return extent;
  26875. },
  26876. /**
  26877. * @param {Array.<number>} extent
  26878. */
  26879. unionExtent: function (extent) {
  26880. this._originalScale.unionExtent(extent);
  26881. var base = this.base;
  26882. extent[0] = mathLog(extent[0]) / mathLog(base);
  26883. extent[1] = mathLog(extent[1]) / mathLog(base);
  26884. scaleProto$1.unionExtent.call(this, extent);
  26885. },
  26886. /**
  26887. * @override
  26888. */
  26889. unionExtentFromData: function (data, dim) {
  26890. this.unionExtent(data.getApproximateExtent(dim, true, function (val) {
  26891. return val > 0;
  26892. }));
  26893. },
  26894. /**
  26895. * Update interval and extent of intervals for nice ticks
  26896. * @param {number} [approxTickNum = 10] Given approx tick number
  26897. */
  26898. niceTicks: function (approxTickNum) {
  26899. approxTickNum = approxTickNum || 10;
  26900. var extent = this._extent;
  26901. var span = extent[1] - extent[0];
  26902. if (span === Infinity || span <= 0) {
  26903. return;
  26904. }
  26905. var interval = quantity(span);
  26906. var err = approxTickNum / span * interval;
  26907. // Filter ticks to get closer to the desired count.
  26908. if (err <= 0.5) {
  26909. interval *= 10;
  26910. }
  26911. // Interval should be integer
  26912. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  26913. interval *= 10;
  26914. }
  26915. var niceExtent = [
  26916. round$1(mathCeil$1(extent[0] / interval) * interval),
  26917. round$1(mathFloor$1(extent[1] / interval) * interval)
  26918. ];
  26919. this._interval = interval;
  26920. this._niceExtent = niceExtent;
  26921. },
  26922. /**
  26923. * Nice extent.
  26924. * @override
  26925. */
  26926. niceExtent: function (opt) {
  26927. intervalScaleProto$1.niceExtent.call(this, opt);
  26928. var originalScale = this._originalScale;
  26929. originalScale.__fixMin = opt.fixMin;
  26930. originalScale.__fixMax = opt.fixMax;
  26931. }
  26932. });
  26933. each$1(['contain', 'normalize'], function (methodName) {
  26934. LogScale.prototype[methodName] = function (val) {
  26935. val = mathLog(val) / mathLog(this.base);
  26936. return scaleProto$1[methodName].call(this, val);
  26937. };
  26938. });
  26939. LogScale.create = function () {
  26940. return new LogScale();
  26941. };
  26942. function fixRoundingError(val, originalVal) {
  26943. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  26944. }
  26945. /**
  26946. * Get axis scale extent before niced.
  26947. * Item of returned array can only be number (including Infinity and NaN).
  26948. */
  26949. function getScaleExtent(scale, model) {
  26950. var scaleType = scale.type;
  26951. var min = model.getMin();
  26952. var max = model.getMax();
  26953. var fixMin = min != null;
  26954. var fixMax = max != null;
  26955. var originalExtent = scale.getExtent();
  26956. var axisDataLen;
  26957. var boundaryGap;
  26958. var span;
  26959. if (scaleType === 'ordinal') {
  26960. axisDataLen = model.getCategories().length;
  26961. }
  26962. else {
  26963. boundaryGap = model.get('boundaryGap');
  26964. if (!isArray(boundaryGap)) {
  26965. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  26966. }
  26967. if (typeof boundaryGap[0] === 'boolean') {
  26968. if (__DEV__) {
  26969. console.warn('Boolean type for boundaryGap is only '
  26970. + 'allowed for ordinal axis. Please use string in '
  26971. + 'percentage instead, e.g., "20%". Currently, '
  26972. + 'boundaryGap is set to be 0.');
  26973. }
  26974. boundaryGap = [0, 0];
  26975. }
  26976. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  26977. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  26978. span = (originalExtent[1] - originalExtent[0])
  26979. || Math.abs(originalExtent[0]);
  26980. }
  26981. // Notice: When min/max is not set (that is, when there are null/undefined,
  26982. // which is the most common case), these cases should be ensured:
  26983. // (1) For 'ordinal', show all axis.data.
  26984. // (2) For others:
  26985. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  26986. // disabled).
  26987. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  26988. // be the result that originalExtent enlarged by boundaryGap.
  26989. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  26990. // FIXME
  26991. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  26992. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  26993. // that the results processed by boundaryGap are positive/negative?
  26994. if (min == null) {
  26995. min = scaleType === 'ordinal'
  26996. ? (axisDataLen ? 0 : NaN)
  26997. : originalExtent[0] - boundaryGap[0] * span;
  26998. }
  26999. if (max == null) {
  27000. max = scaleType === 'ordinal'
  27001. ? (axisDataLen ? axisDataLen - 1 : NaN)
  27002. : originalExtent[1] + boundaryGap[1] * span;
  27003. }
  27004. if (min === 'dataMin') {
  27005. min = originalExtent[0];
  27006. }
  27007. else if (typeof min === 'function') {
  27008. min = min({
  27009. min: originalExtent[0],
  27010. max: originalExtent[1]
  27011. });
  27012. }
  27013. if (max === 'dataMax') {
  27014. max = originalExtent[1];
  27015. }
  27016. else if (typeof max === 'function') {
  27017. max = max({
  27018. min: originalExtent[0],
  27019. max: originalExtent[1]
  27020. });
  27021. }
  27022. (min == null || !isFinite(min)) && (min = NaN);
  27023. (max == null || !isFinite(max)) && (max = NaN);
  27024. scale.setBlank(eqNaN(min) || eqNaN(max));
  27025. // Evaluate if axis needs cross zero
  27026. if (model.getNeedCrossZero()) {
  27027. // Axis is over zero and min is not set
  27028. if (min > 0 && max > 0 && !fixMin) {
  27029. min = 0;
  27030. }
  27031. // Axis is under zero and max is not set
  27032. if (min < 0 && max < 0 && !fixMax) {
  27033. max = 0;
  27034. }
  27035. }
  27036. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  27037. // is base axis
  27038. var ecModel = model.ecModel;
  27039. if (ecModel) {
  27040. var isBaseAxisAndHasBarSeries = filter(ecModel.getSeriesByType('bar'), function (seriesModel) {
  27041. return seriesModel.getBaseAxis() === model.axis;
  27042. }).length > 0;
  27043. if ((scaleType === 'time' || scaleType === 'interval') && isBaseAxisAndHasBarSeries) {
  27044. // Adjust axis min and max to account for overflow
  27045. var adjustedScale = adjustScaleForOverflow(min, max, model);
  27046. min = adjustedScale.min;
  27047. max = adjustedScale.max;
  27048. }
  27049. }
  27050. return [min, max];
  27051. }
  27052. function adjustScaleForOverflow(min, max, model) {
  27053. var ecModel = model.ecModel;
  27054. // Get Axis Length
  27055. var axisExtent = model.axis.getExtent();
  27056. var axisLength = axisExtent[1] - axisExtent[0];
  27057. // Calculate placement of bars on axis
  27058. var barWidthAndOffset = calBarWidthAndOffset(filter(
  27059. ecModel.getSeriesByType('bar'),
  27060. function (seriesModel) {
  27061. return !ecModel.isSeriesFiltered(seriesModel)
  27062. && seriesModel.coordinateSystem
  27063. && seriesModel.coordinateSystem.type === 'cartesian2d';
  27064. }
  27065. ));
  27066. // Get bars on current base axis and calculate min and max overflow
  27067. var baseAxisKey = model.axis.dim + model.axis.index;
  27068. var barsOnCurrentAxis = barWidthAndOffset[baseAxisKey];
  27069. if (barsOnCurrentAxis === undefined) {
  27070. return {min: min, max: max};
  27071. }
  27072. var minOverflow = Infinity;
  27073. each$1(barsOnCurrentAxis, function (item) {
  27074. minOverflow = Math.min(item.offset, minOverflow);
  27075. });
  27076. var maxOverflow = -Infinity;
  27077. each$1(barsOnCurrentAxis, function (item) {
  27078. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  27079. });
  27080. var totalOverFlow = Math.abs(minOverflow) + maxOverflow;
  27081. // Calulate required buffer based on old range and overflow
  27082. var oldRange = max - min;
  27083. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  27084. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  27085. max += overflowBuffer * (maxOverflow / totalOverFlow);
  27086. min -= overflowBuffer * (minOverflow / totalOverFlow);
  27087. return {min: min, max: max};
  27088. }
  27089. function niceScaleExtent$1(scale, model) {
  27090. var extent = getScaleExtent(scale, model);
  27091. var fixMin = model.getMin() != null;
  27092. var fixMax = model.getMax() != null;
  27093. var splitNumber = model.get('splitNumber');
  27094. if (scale.type === 'log') {
  27095. scale.base = model.get('logBase');
  27096. }
  27097. var scaleType = scale.type;
  27098. scale.setExtent(extent[0], extent[1]);
  27099. scale.niceExtent({
  27100. splitNumber: splitNumber,
  27101. fixMin: fixMin,
  27102. fixMax: fixMax,
  27103. minInterval: (scaleType === 'interval' || scaleType === 'time')
  27104. ? model.get('minInterval') : null,
  27105. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  27106. ? model.get('maxInterval') : null
  27107. });
  27108. // If some one specified the min, max. And the default calculated interval
  27109. // is not good enough. He can specify the interval. It is often appeared
  27110. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  27111. // to be 60.
  27112. // FIXME
  27113. var interval = model.get('interval');
  27114. if (interval != null) {
  27115. scale.setInterval && scale.setInterval(interval);
  27116. }
  27117. }
  27118. /**
  27119. * @param {module:echarts/model/Model} model
  27120. * @param {string} [axisType] Default retrieve from model.type
  27121. * @return {module:echarts/scale/*}
  27122. */
  27123. function createScaleByModel(model, axisType) {
  27124. axisType = axisType || model.get('type');
  27125. if (axisType) {
  27126. switch (axisType) {
  27127. // Buildin scale
  27128. case 'category':
  27129. return new OrdinalScale(
  27130. model.getOrdinalMeta
  27131. ? model.getOrdinalMeta()
  27132. : model.getCategories(),
  27133. [Infinity, -Infinity]
  27134. );
  27135. case 'value':
  27136. return new IntervalScale();
  27137. // Extended scale, like time and log
  27138. default:
  27139. return (Scale.getClass(axisType) || IntervalScale).create(model);
  27140. }
  27141. }
  27142. }
  27143. /**
  27144. * Check if the axis corss 0
  27145. */
  27146. function ifAxisCrossZero$1(axis) {
  27147. var dataExtent = axis.scale.getExtent();
  27148. var min = dataExtent[0];
  27149. var max = dataExtent[1];
  27150. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  27151. }
  27152. /**
  27153. * @param {Array.<number>} tickCoords In axis self coordinate.
  27154. * @param {Array.<string>} labels
  27155. * @param {string} font
  27156. * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative.
  27157. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative.
  27158. * @return {number}
  27159. */
  27160. function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) {
  27161. var textSpaceTakenRect;
  27162. var autoLabelInterval = 0;
  27163. var accumulatedLabelInterval = 0;
  27164. var rotation = (axisRotate - labelRotate) / 180 * Math.PI;
  27165. var step = 1;
  27166. if (labels.length > 40) {
  27167. // Simple optimization for large amount of labels
  27168. step = Math.floor(labels.length / 40);
  27169. }
  27170. for (var i = 0; i < tickCoords.length; i += step) {
  27171. var tickCoord = tickCoords[i];
  27172. // Not precise, do not consider align and vertical align
  27173. // and each distance from axis line yet.
  27174. var rect = getBoundingRect(
  27175. labels[i], font, 'center', 'top'
  27176. );
  27177. rect.x += tickCoord * Math.cos(rotation);
  27178. rect.y += tickCoord * Math.sin(rotation);
  27179. // Magic number
  27180. rect.width *= 1.3;
  27181. rect.height *= 1.3;
  27182. if (!textSpaceTakenRect) {
  27183. textSpaceTakenRect = rect.clone();
  27184. }
  27185. // There is no space for current label;
  27186. else if (textSpaceTakenRect.intersect(rect)) {
  27187. accumulatedLabelInterval++;
  27188. autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval);
  27189. }
  27190. else {
  27191. textSpaceTakenRect.union(rect);
  27192. // Reset
  27193. accumulatedLabelInterval = 0;
  27194. }
  27195. }
  27196. if (autoLabelInterval === 0 && step > 1) {
  27197. return step;
  27198. }
  27199. return (autoLabelInterval + 1) * step - 1;
  27200. }
  27201. /**
  27202. * @param {Object} axis
  27203. * @param {Function} labelFormatter
  27204. * @return {Array.<string>}
  27205. */
  27206. function getFormattedLabels(axis, labelFormatter) {
  27207. var scale = axis.scale;
  27208. var labels = scale.getTicksLabels();
  27209. var ticks = scale.getTicks();
  27210. if (typeof labelFormatter === 'string') {
  27211. labelFormatter = (function (tpl) {
  27212. return function (val) {
  27213. return tpl.replace('{value}', val != null ? val : '');
  27214. };
  27215. })(labelFormatter);
  27216. // Consider empty array
  27217. return map(labels, labelFormatter);
  27218. }
  27219. else if (typeof labelFormatter === 'function') {
  27220. return map(ticks, function (tick, idx) {
  27221. return labelFormatter(
  27222. getAxisRawValue(axis, tick),
  27223. idx
  27224. );
  27225. }, this);
  27226. }
  27227. else {
  27228. return labels;
  27229. }
  27230. }
  27231. function getAxisRawValue(axis, value) {
  27232. // In category axis with data zoom, tick is not the original
  27233. // index of axis.data. So tick should not be exposed to user
  27234. // in category axis.
  27235. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  27236. }
  27237. /**
  27238. * Cartesian coordinate system
  27239. * @module echarts/coord/Cartesian
  27240. *
  27241. */
  27242. function dimAxisMapper(dim) {
  27243. return this._axes[dim];
  27244. }
  27245. /**
  27246. * @alias module:echarts/coord/Cartesian
  27247. * @constructor
  27248. */
  27249. var Cartesian = function (name) {
  27250. this._axes = {};
  27251. this._dimList = [];
  27252. /**
  27253. * @type {string}
  27254. */
  27255. this.name = name || '';
  27256. };
  27257. Cartesian.prototype = {
  27258. constructor: Cartesian,
  27259. type: 'cartesian',
  27260. /**
  27261. * Get axis
  27262. * @param {number|string} dim
  27263. * @return {module:echarts/coord/Cartesian~Axis}
  27264. */
  27265. getAxis: function (dim) {
  27266. return this._axes[dim];
  27267. },
  27268. /**
  27269. * Get axes list
  27270. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  27271. */
  27272. getAxes: function () {
  27273. return map(this._dimList, dimAxisMapper, this);
  27274. },
  27275. /**
  27276. * Get axes list by given scale type
  27277. */
  27278. getAxesByScale: function (scaleType) {
  27279. scaleType = scaleType.toLowerCase();
  27280. return filter(
  27281. this.getAxes(),
  27282. function (axis) {
  27283. return axis.scale.type === scaleType;
  27284. }
  27285. );
  27286. },
  27287. /**
  27288. * Add axis
  27289. * @param {module:echarts/coord/Cartesian.Axis}
  27290. */
  27291. addAxis: function (axis) {
  27292. var dim = axis.dim;
  27293. this._axes[dim] = axis;
  27294. this._dimList.push(dim);
  27295. },
  27296. /**
  27297. * Convert data to coord in nd space
  27298. * @param {Array.<number>|Object.<string, number>} val
  27299. * @return {Array.<number>|Object.<string, number>}
  27300. */
  27301. dataToCoord: function (val) {
  27302. return this._dataCoordConvert(val, 'dataToCoord');
  27303. },
  27304. /**
  27305. * Convert coord in nd space to data
  27306. * @param {Array.<number>|Object.<string, number>} val
  27307. * @return {Array.<number>|Object.<string, number>}
  27308. */
  27309. coordToData: function (val) {
  27310. return this._dataCoordConvert(val, 'coordToData');
  27311. },
  27312. _dataCoordConvert: function (input, method) {
  27313. var dimList = this._dimList;
  27314. var output = input instanceof Array ? [] : {};
  27315. for (var i = 0; i < dimList.length; i++) {
  27316. var dim = dimList[i];
  27317. var axis = this._axes[dim];
  27318. output[dim] = axis[method](input[dim]);
  27319. }
  27320. return output;
  27321. }
  27322. };
  27323. function Cartesian2D(name) {
  27324. Cartesian.call(this, name);
  27325. }
  27326. Cartesian2D.prototype = {
  27327. constructor: Cartesian2D,
  27328. type: 'cartesian2d',
  27329. /**
  27330. * @type {Array.<string>}
  27331. * @readOnly
  27332. */
  27333. dimensions: ['x', 'y'],
  27334. /**
  27335. * Base axis will be used on stacking.
  27336. *
  27337. * @return {module:echarts/coord/cartesian/Axis2D}
  27338. */
  27339. getBaseAxis: function () {
  27340. return this.getAxesByScale('ordinal')[0]
  27341. || this.getAxesByScale('time')[0]
  27342. || this.getAxis('x');
  27343. },
  27344. /**
  27345. * If contain point
  27346. * @param {Array.<number>} point
  27347. * @return {boolean}
  27348. */
  27349. containPoint: function (point) {
  27350. var axisX = this.getAxis('x');
  27351. var axisY = this.getAxis('y');
  27352. return axisX.contain(axisX.toLocalCoord(point[0]))
  27353. && axisY.contain(axisY.toLocalCoord(point[1]));
  27354. },
  27355. /**
  27356. * If contain data
  27357. * @param {Array.<number>} data
  27358. * @return {boolean}
  27359. */
  27360. containData: function (data) {
  27361. return this.getAxis('x').containData(data[0])
  27362. && this.getAxis('y').containData(data[1]);
  27363. },
  27364. /**
  27365. * @param {Array.<number>} data
  27366. * @param {Array.<number>} out
  27367. * @return {Array.<number>}
  27368. */
  27369. dataToPoint: function (data, reserved, out) {
  27370. var xAxis = this.getAxis('x');
  27371. var yAxis = this.getAxis('y');
  27372. out = out || [];
  27373. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  27374. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  27375. return out;
  27376. },
  27377. /**
  27378. * @param {Array.<number>} data
  27379. * @param {Array.<number>} out
  27380. * @return {Array.<number>}
  27381. */
  27382. clampData: function (data, out) {
  27383. var xAxisExtent = this.getAxis('x').scale.getExtent();
  27384. var yAxisExtent = this.getAxis('y').scale.getExtent();
  27385. out = out || [];
  27386. out[0] = Math.min(
  27387. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), data[0]),
  27388. Math.max(xAxisExtent[0], xAxisExtent[1])
  27389. );
  27390. out[1] = Math.min(
  27391. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), data[1]),
  27392. Math.max(yAxisExtent[0], yAxisExtent[1])
  27393. );
  27394. return out;
  27395. },
  27396. /**
  27397. * @param {Array.<number>} point
  27398. * @param {Array.<number>} out
  27399. * @return {Array.<number>}
  27400. */
  27401. pointToData: function (point, out) {
  27402. var xAxis = this.getAxis('x');
  27403. var yAxis = this.getAxis('y');
  27404. out = out || [];
  27405. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  27406. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  27407. return out;
  27408. },
  27409. /**
  27410. * Get other axis
  27411. * @param {module:echarts/coord/cartesian/Axis2D} axis
  27412. */
  27413. getOtherAxis: function (axis) {
  27414. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  27415. }
  27416. };
  27417. inherits(Cartesian2D, Cartesian);
  27418. var linearMap$1 = linearMap;
  27419. function fixExtentWithBands(extent, nTick) {
  27420. var size = extent[1] - extent[0];
  27421. var len = nTick;
  27422. var margin = size / len / 2;
  27423. extent[0] += margin;
  27424. extent[1] -= margin;
  27425. }
  27426. var normalizedExtent = [0, 1];
  27427. /**
  27428. * @name module:echarts/coord/CartesianAxis
  27429. * @constructor
  27430. */
  27431. var Axis = function (dim, scale, extent) {
  27432. /**
  27433. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'
  27434. * @type {string}
  27435. */
  27436. this.dim = dim;
  27437. /**
  27438. * Axis scale
  27439. * @type {module:echarts/coord/scale/*}
  27440. */
  27441. this.scale = scale;
  27442. /**
  27443. * @type {Array.<number>}
  27444. * @private
  27445. */
  27446. this._extent = extent || [0, 0];
  27447. /**
  27448. * @type {boolean}
  27449. */
  27450. this.inverse = false;
  27451. /**
  27452. * Usually true when axis has a ordinal scale
  27453. * @type {boolean}
  27454. */
  27455. this.onBand = false;
  27456. /**
  27457. * @private
  27458. * @type {number}
  27459. */
  27460. this._labelInterval;
  27461. };
  27462. Axis.prototype = {
  27463. constructor: Axis,
  27464. /**
  27465. * If axis extent contain given coord
  27466. * @param {number} coord
  27467. * @return {boolean}
  27468. */
  27469. contain: function (coord) {
  27470. var extent = this._extent;
  27471. var min = Math.min(extent[0], extent[1]);
  27472. var max = Math.max(extent[0], extent[1]);
  27473. return coord >= min && coord <= max;
  27474. },
  27475. /**
  27476. * If axis extent contain given data
  27477. * @param {number} data
  27478. * @return {boolean}
  27479. */
  27480. containData: function (data) {
  27481. return this.contain(this.dataToCoord(data));
  27482. },
  27483. /**
  27484. * Get coord extent.
  27485. * @return {Array.<number>}
  27486. */
  27487. getExtent: function () {
  27488. return this._extent.slice();
  27489. },
  27490. /**
  27491. * Get precision used for formatting
  27492. * @param {Array.<number>} [dataExtent]
  27493. * @return {number}
  27494. */
  27495. getPixelPrecision: function (dataExtent) {
  27496. return getPixelPrecision(
  27497. dataExtent || this.scale.getExtent(),
  27498. this._extent
  27499. );
  27500. },
  27501. /**
  27502. * Set coord extent
  27503. * @param {number} start
  27504. * @param {number} end
  27505. */
  27506. setExtent: function (start, end) {
  27507. var extent = this._extent;
  27508. extent[0] = start;
  27509. extent[1] = end;
  27510. },
  27511. /**
  27512. * Convert data to coord. Data is the rank if it has a ordinal scale
  27513. * @param {number} data
  27514. * @param {boolean} clamp
  27515. * @return {number}
  27516. */
  27517. dataToCoord: function (data, clamp) {
  27518. var extent = this._extent;
  27519. var scale = this.scale;
  27520. data = scale.normalize(data);
  27521. if (this.onBand && scale.type === 'ordinal') {
  27522. extent = extent.slice();
  27523. fixExtentWithBands(extent, scale.count());
  27524. }
  27525. return linearMap$1(data, normalizedExtent, extent, clamp);
  27526. },
  27527. /**
  27528. * Convert coord to data. Data is the rank if it has a ordinal scale
  27529. * @param {number} coord
  27530. * @param {boolean} clamp
  27531. * @return {number}
  27532. */
  27533. coordToData: function (coord, clamp) {
  27534. var extent = this._extent;
  27535. var scale = this.scale;
  27536. if (this.onBand && scale.type === 'ordinal') {
  27537. extent = extent.slice();
  27538. fixExtentWithBands(extent, scale.count());
  27539. }
  27540. var t = linearMap$1(coord, extent, normalizedExtent, clamp);
  27541. return this.scale.scale(t);
  27542. },
  27543. /**
  27544. * Convert pixel point to data in axis
  27545. * @param {Array.<number>} point
  27546. * @param {boolean} clamp
  27547. * @return {number} data
  27548. */
  27549. pointToData: function (point, clamp) {
  27550. // Should be implemented in derived class if necessary.
  27551. },
  27552. /**
  27553. * @return {Array.<number>}
  27554. */
  27555. getTicksCoords: function (alignWithLabel) {
  27556. if (this.onBand && !alignWithLabel) {
  27557. var bands = this.getBands();
  27558. var coords = [];
  27559. for (var i = 0; i < bands.length; i++) {
  27560. coords.push(bands[i][0]);
  27561. }
  27562. if (bands[i - 1]) {
  27563. coords.push(bands[i - 1][1]);
  27564. }
  27565. return coords;
  27566. }
  27567. else {
  27568. return map(this.scale.getTicks(), this.dataToCoord, this);
  27569. }
  27570. },
  27571. /**
  27572. * Coords of labels are on the ticks or on the middle of bands
  27573. * @return {Array.<number>}
  27574. */
  27575. getLabelsCoords: function () {
  27576. return map(this.scale.getTicks(), this.dataToCoord, this);
  27577. },
  27578. /**
  27579. * Get bands.
  27580. *
  27581. * If axis has labels [1, 2, 3, 4]. Bands on the axis are
  27582. * |---1---|---2---|---3---|---4---|.
  27583. *
  27584. * @return {Array}
  27585. */
  27586. // FIXME Situation when labels is on ticks
  27587. getBands: function () {
  27588. var extent = this.getExtent();
  27589. var bands = [];
  27590. var len = this.scale.count();
  27591. var start = extent[0];
  27592. var end = extent[1];
  27593. var span = end - start;
  27594. for (var i = 0; i < len; i++) {
  27595. bands.push([
  27596. span * i / len + start,
  27597. span * (i + 1) / len + start
  27598. ]);
  27599. }
  27600. return bands;
  27601. },
  27602. /**
  27603. * Get width of band
  27604. * @return {number}
  27605. */
  27606. getBandWidth: function () {
  27607. var axisExtent = this._extent;
  27608. var dataExtent = this.scale.getExtent();
  27609. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  27610. // Fix #2728, avoid NaN when only one data.
  27611. len === 0 && (len = 1);
  27612. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  27613. return Math.abs(size) / len;
  27614. },
  27615. /**
  27616. * @abstract
  27617. * @return {boolean} Is horizontal
  27618. */
  27619. isHorizontal: null,
  27620. /**
  27621. * @abstract
  27622. * @return {number} Get axis rotate, by degree.
  27623. */
  27624. getRotate: null,
  27625. /**
  27626. * Get interval of the axis label.
  27627. * To get precise result, at least one of `getRotate` and `isHorizontal`
  27628. * should be implemented.
  27629. * @return {number}
  27630. */
  27631. getLabelInterval: function () {
  27632. var labelInterval = this._labelInterval;
  27633. if (!labelInterval) {
  27634. var axisModel = this.model;
  27635. var labelModel = axisModel.getModel('axisLabel');
  27636. labelInterval = labelModel.get('interval');
  27637. if (this.type === 'category'
  27638. && (labelInterval == null || labelInterval === 'auto')
  27639. ) {
  27640. labelInterval = getAxisLabelInterval(
  27641. map(this.scale.getTicks(), this.dataToCoord, this),
  27642. axisModel.getFormattedLabels(),
  27643. labelModel.getFont(),
  27644. this.getRotate
  27645. ? this.getRotate()
  27646. : (this.isHorizontal && !this.isHorizontal())
  27647. ? 90
  27648. : 0,
  27649. labelModel.get('rotate')
  27650. );
  27651. }
  27652. this._labelInterval = labelInterval;
  27653. }
  27654. return labelInterval;
  27655. }
  27656. };
  27657. /**
  27658. * Extend axis 2d
  27659. * @constructor module:echarts/coord/cartesian/Axis2D
  27660. * @extends {module:echarts/coord/cartesian/Axis}
  27661. * @param {string} dim
  27662. * @param {*} scale
  27663. * @param {Array.<number>} coordExtent
  27664. * @param {string} axisType
  27665. * @param {string} position
  27666. */
  27667. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  27668. Axis.call(this, dim, scale, coordExtent);
  27669. /**
  27670. * Axis type
  27671. * - 'category'
  27672. * - 'value'
  27673. * - 'time'
  27674. * - 'log'
  27675. * @type {string}
  27676. */
  27677. this.type = axisType || 'value';
  27678. /**
  27679. * Axis position
  27680. * - 'top'
  27681. * - 'bottom'
  27682. * - 'left'
  27683. * - 'right'
  27684. */
  27685. this.position = position || 'bottom';
  27686. };
  27687. Axis2D.prototype = {
  27688. constructor: Axis2D,
  27689. /**
  27690. * Index of axis, can be used as key
  27691. */
  27692. index: 0,
  27693. /**
  27694. * If axis is on the zero position of the other axis
  27695. * @type {boolean}
  27696. */
  27697. onZero: false,
  27698. /**
  27699. * Axis model
  27700. * @param {module:echarts/coord/cartesian/AxisModel}
  27701. */
  27702. model: null,
  27703. isHorizontal: function () {
  27704. var position = this.position;
  27705. return position === 'top' || position === 'bottom';
  27706. },
  27707. /**
  27708. * Each item cooresponds to this.getExtent(), which
  27709. * means globalExtent[0] may greater than globalExtent[1],
  27710. * unless `asc` is input.
  27711. *
  27712. * @param {boolean} [asc]
  27713. * @return {Array.<number>}
  27714. */
  27715. getGlobalExtent: function (asc) {
  27716. var ret = this.getExtent();
  27717. ret[0] = this.toGlobalCoord(ret[0]);
  27718. ret[1] = this.toGlobalCoord(ret[1]);
  27719. asc && ret[0] > ret[1] && ret.reverse();
  27720. return ret;
  27721. },
  27722. getOtherAxis: function () {
  27723. this.grid.getOtherAxis();
  27724. },
  27725. /**
  27726. * If label is ignored.
  27727. * Automatically used when axis is category and label can not be all shown
  27728. * @param {number} idx
  27729. * @return {boolean}
  27730. */
  27731. isLabelIgnored: function (idx) {
  27732. if (this.type === 'category') {
  27733. var labelInterval = this.getLabelInterval();
  27734. return ((typeof labelInterval === 'function')
  27735. && !labelInterval(idx, this.scale.getLabel(idx)))
  27736. || idx % (labelInterval + 1);
  27737. }
  27738. },
  27739. /**
  27740. * @override
  27741. */
  27742. pointToData: function (point, clamp) {
  27743. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  27744. },
  27745. /**
  27746. * Transform global coord to local coord,
  27747. * i.e. var localCoord = axis.toLocalCoord(80);
  27748. * designate by module:echarts/coord/cartesian/Grid.
  27749. * @type {Function}
  27750. */
  27751. toLocalCoord: null,
  27752. /**
  27753. * Transform global coord to local coord,
  27754. * i.e. var globalCoord = axis.toLocalCoord(40);
  27755. * designate by module:echarts/coord/cartesian/Grid.
  27756. * @type {Function}
  27757. */
  27758. toGlobalCoord: null
  27759. };
  27760. inherits(Axis2D, Axis);
  27761. var defaultOption = {
  27762. show: true,
  27763. zlevel: 0, // 一级层叠
  27764. z: 0, // 二级层叠
  27765. // 反向坐标轴
  27766. inverse: false,
  27767. // 坐标轴名字,默认为空
  27768. name: '',
  27769. // 坐标轴名字位置,支持'start' | 'middle' | 'end'
  27770. nameLocation: 'end',
  27771. // 坐标轴名字旋转,degree。
  27772. nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'.
  27773. nameTruncate: {
  27774. maxWidth: null,
  27775. ellipsis: '...',
  27776. placeholder: '.'
  27777. },
  27778. // 坐标轴文字样式,默认取全局样式
  27779. nameTextStyle: {},
  27780. // 文字与轴线距离
  27781. nameGap: 15,
  27782. silent: false, // Default false to support tooltip.
  27783. triggerEvent: false, // Default false to avoid legacy user event listener fail.
  27784. tooltip: {
  27785. show: false
  27786. },
  27787. axisPointer: {},
  27788. // 坐标轴线
  27789. axisLine: {
  27790. // 默认显示,属性show控制显示与否
  27791. show: true,
  27792. onZero: true,
  27793. onZeroAxisIndex: null,
  27794. // 属性lineStyle控制线条样式
  27795. lineStyle: {
  27796. color: '#333',
  27797. width: 1,
  27798. type: 'solid'
  27799. },
  27800. // 坐标轴两端的箭头
  27801. symbol: ['none', 'none'],
  27802. symbolSize: [10, 15]
  27803. },
  27804. // 坐标轴小标记
  27805. axisTick: {
  27806. // 属性show控制显示与否,默认显示
  27807. show: true,
  27808. // 控制小标记是否在grid里
  27809. inside: false,
  27810. // 属性length控制线长
  27811. length: 5,
  27812. // 属性lineStyle控制线条样式
  27813. lineStyle: {
  27814. width: 1
  27815. }
  27816. },
  27817. // 坐标轴文本标签,详见axis.axisLabel
  27818. axisLabel: {
  27819. show: true,
  27820. // 控制文本标签是否在grid里
  27821. inside: false,
  27822. rotate: 0,
  27823. showMinLabel: null, // true | false | null (auto)
  27824. showMaxLabel: null, // true | false | null (auto)
  27825. margin: 8,
  27826. // formatter: null,
  27827. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  27828. fontSize: 12
  27829. },
  27830. // 分隔线
  27831. splitLine: {
  27832. // 默认显示,属性show控制显示与否
  27833. show: true,
  27834. // 属性lineStyle(详见lineStyle)控制线条样式
  27835. lineStyle: {
  27836. color: ['#ccc'],
  27837. width: 1,
  27838. type: 'solid'
  27839. }
  27840. },
  27841. // 分隔区域
  27842. splitArea: {
  27843. // 默认不显示,属性show控制显示与否
  27844. show: false,
  27845. // 属性areaStyle(详见areaStyle)控制区域样式
  27846. areaStyle: {
  27847. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  27848. }
  27849. }
  27850. };
  27851. var axisDefault = {};
  27852. axisDefault.categoryAxis = merge({
  27853. // 类目起始和结束两端空白策略
  27854. boundaryGap: true,
  27855. // Set false to faster category collection.
  27856. // Only usefull in the case like: category is
  27857. // ['2012-01-01', '2012-01-02', ...], where the input
  27858. // data has been ensured not duplicate and is large data.
  27859. // null means "auto":
  27860. // if axis.data provided, do not deduplication,
  27861. // else do deduplication.
  27862. deduplication: null,
  27863. // splitArea: {
  27864. // show: false
  27865. // },
  27866. splitLine: {
  27867. show: false
  27868. },
  27869. // 坐标轴小标记
  27870. axisTick: {
  27871. // If tick is align with label when boundaryGap is true
  27872. alignWithLabel: false,
  27873. interval: 'auto'
  27874. },
  27875. // 坐标轴文本标签,详见axis.axisLabel
  27876. axisLabel: {
  27877. interval: 'auto'
  27878. }
  27879. }, defaultOption);
  27880. axisDefault.valueAxis = merge({
  27881. // 数值起始和结束两端空白策略
  27882. boundaryGap: [0, 0],
  27883. // TODO
  27884. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  27885. // 最小值, 设置成 'dataMin' 则从数据中计算最小值
  27886. // min: null,
  27887. // 最大值,设置成 'dataMax' 则从数据中计算最大值
  27888. // max: null,
  27889. // Readonly prop, specifies start value of the range when using data zoom.
  27890. // rangeStart: null
  27891. // Readonly prop, specifies end value of the range when using data zoom.
  27892. // rangeEnd: null
  27893. // 脱离0值比例,放大聚焦到最终_min,_max区间
  27894. // scale: false,
  27895. // 分割段数,默认为5
  27896. splitNumber: 5
  27897. // Minimum interval
  27898. // minInterval: null
  27899. // maxInterval: null
  27900. }, defaultOption);
  27901. // FIXME
  27902. axisDefault.timeAxis = defaults({
  27903. scale: true,
  27904. min: 'dataMin',
  27905. max: 'dataMax'
  27906. }, axisDefault.valueAxis);
  27907. axisDefault.logAxis = defaults({
  27908. scale: true,
  27909. logBase: 10
  27910. }, axisDefault.valueAxis);
  27911. // FIXME axisType is fixed ?
  27912. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  27913. /**
  27914. * Generate sub axis model class
  27915. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  27916. * @param {module:echarts/model/Component} BaseAxisModelClass
  27917. * @param {Function} axisTypeDefaulter
  27918. * @param {Object} [extraDefaultOption]
  27919. */
  27920. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  27921. each$1(AXIS_TYPES, function (axisType) {
  27922. BaseAxisModelClass.extend({
  27923. /**
  27924. * @readOnly
  27925. */
  27926. type: axisName + 'Axis.' + axisType,
  27927. mergeDefaultAndTheme: function (option, ecModel) {
  27928. var layoutMode = this.layoutMode;
  27929. var inputPositionParams = layoutMode
  27930. ? getLayoutParams(option) : {};
  27931. var themeModel = ecModel.getTheme();
  27932. merge(option, themeModel.get(axisType + 'Axis'));
  27933. merge(option, this.getDefaultOption());
  27934. option.type = axisTypeDefaulter(axisName, option);
  27935. if (layoutMode) {
  27936. mergeLayoutParam(option, inputPositionParams, layoutMode);
  27937. }
  27938. },
  27939. /**
  27940. * @override
  27941. */
  27942. optionUpdated: function () {
  27943. var thisOption = this.option;
  27944. if (thisOption.type === 'category') {
  27945. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  27946. }
  27947. },
  27948. /**
  27949. * Should not be called before all of 'getInitailData' finished.
  27950. * Because categories are collected during initializing data.
  27951. */
  27952. getCategories: function () {
  27953. // FIXME
  27954. // warning if called before all of 'getInitailData' finished.
  27955. if (this.option.type === 'category') {
  27956. return this.__ordinalMeta.categories;
  27957. }
  27958. },
  27959. getOrdinalMeta: function () {
  27960. return this.__ordinalMeta;
  27961. },
  27962. defaultOption: mergeAll(
  27963. [
  27964. {},
  27965. axisDefault[axisType + 'Axis'],
  27966. extraDefaultOption
  27967. ],
  27968. true
  27969. )
  27970. });
  27971. });
  27972. ComponentModel.registerSubTypeDefaulter(
  27973. axisName + 'Axis',
  27974. curry(axisTypeDefaulter, axisName)
  27975. );
  27976. };
  27977. var axisModelCommonMixin = {
  27978. /**
  27979. * Format labels
  27980. * @return {Array.<string>}
  27981. */
  27982. getFormattedLabels: function () {
  27983. return getFormattedLabels(
  27984. this.axis,
  27985. this.get('axisLabel.formatter')
  27986. );
  27987. },
  27988. /**
  27989. * @param {boolean} origin
  27990. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  27991. */
  27992. getMin: function (origin) {
  27993. var option = this.option;
  27994. var min = (!origin && option.rangeStart != null)
  27995. ? option.rangeStart : option.min;
  27996. if (this.axis
  27997. && min != null
  27998. && min !== 'dataMin'
  27999. && typeof min !== 'function'
  28000. && !eqNaN(min)
  28001. ) {
  28002. min = this.axis.scale.parse(min);
  28003. }
  28004. return min;
  28005. },
  28006. /**
  28007. * @param {boolean} origin
  28008. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  28009. */
  28010. getMax: function (origin) {
  28011. var option = this.option;
  28012. var max = (!origin && option.rangeEnd != null)
  28013. ? option.rangeEnd : option.max;
  28014. if (this.axis
  28015. && max != null
  28016. && max !== 'dataMax'
  28017. && typeof max !== 'function'
  28018. && !eqNaN(max)
  28019. ) {
  28020. max = this.axis.scale.parse(max);
  28021. }
  28022. return max;
  28023. },
  28024. /**
  28025. * @return {boolean}
  28026. */
  28027. getNeedCrossZero: function () {
  28028. var option = this.option;
  28029. return (option.rangeStart != null || option.rangeEnd != null)
  28030. ? false : !option.scale;
  28031. },
  28032. /**
  28033. * Should be implemented by each axis model if necessary.
  28034. * @return {module:echarts/model/Component} coordinate system model
  28035. */
  28036. getCoordSysModel: noop,
  28037. /**
  28038. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  28039. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  28040. */
  28041. setRange: function (rangeStart, rangeEnd) {
  28042. this.option.rangeStart = rangeStart;
  28043. this.option.rangeEnd = rangeEnd;
  28044. },
  28045. /**
  28046. * Reset range
  28047. */
  28048. resetRange: function () {
  28049. // rangeStart and rangeEnd is readonly.
  28050. this.option.rangeStart = this.option.rangeEnd = null;
  28051. }
  28052. };
  28053. var AxisModel = ComponentModel.extend({
  28054. type: 'cartesian2dAxis',
  28055. /**
  28056. * @type {module:echarts/coord/cartesian/Axis2D}
  28057. */
  28058. axis: null,
  28059. /**
  28060. * @override
  28061. */
  28062. init: function () {
  28063. AxisModel.superApply(this, 'init', arguments);
  28064. this.resetRange();
  28065. },
  28066. /**
  28067. * @override
  28068. */
  28069. mergeOption: function () {
  28070. AxisModel.superApply(this, 'mergeOption', arguments);
  28071. this.resetRange();
  28072. },
  28073. /**
  28074. * @override
  28075. */
  28076. restoreData: function () {
  28077. AxisModel.superApply(this, 'restoreData', arguments);
  28078. this.resetRange();
  28079. },
  28080. /**
  28081. * @override
  28082. * @return {module:echarts/model/Component}
  28083. */
  28084. getCoordSysModel: function () {
  28085. return this.ecModel.queryComponents({
  28086. mainType: 'grid',
  28087. index: this.option.gridIndex,
  28088. id: this.option.gridId
  28089. })[0];
  28090. }
  28091. });
  28092. function getAxisType(axisDim, option) {
  28093. // Default axis with data is category axis
  28094. return option.type || (option.data ? 'category' : 'value');
  28095. }
  28096. merge(AxisModel.prototype, axisModelCommonMixin);
  28097. var extraOption = {
  28098. // gridIndex: 0,
  28099. // gridId: '',
  28100. // Offset is for multiple axis on the same position
  28101. offset: 0
  28102. };
  28103. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  28104. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  28105. // Grid 是在有直角坐标系的时候必须要存在的
  28106. // 所以这里也要被 Cartesian2D 依赖
  28107. ComponentModel.extend({
  28108. type: 'grid',
  28109. dependencies: ['xAxis', 'yAxis'],
  28110. layoutMode: 'box',
  28111. /**
  28112. * @type {module:echarts/coord/cartesian/Grid}
  28113. */
  28114. coordinateSystem: null,
  28115. defaultOption: {
  28116. show: false,
  28117. zlevel: 0,
  28118. z: 0,
  28119. left: '10%',
  28120. top: 60,
  28121. right: '10%',
  28122. bottom: 60,
  28123. // If grid size contain label
  28124. containLabel: false,
  28125. // width: {totalWidth} - left - right,
  28126. // height: {totalHeight} - top - bottom,
  28127. backgroundColor: 'rgba(0,0,0,0)',
  28128. borderWidth: 1,
  28129. borderColor: '#ccc'
  28130. }
  28131. });
  28132. /**
  28133. * Grid is a region which contains at most 4 cartesian systems
  28134. *
  28135. * TODO Default cartesian
  28136. */
  28137. // Depends on GridModel, AxisModel, which performs preprocess.
  28138. var each$6 = each$1;
  28139. var ifAxisCrossZero = ifAxisCrossZero$1;
  28140. var niceScaleExtent = niceScaleExtent$1;
  28141. /**
  28142. * Check if the axis is used in the specified grid
  28143. * @inner
  28144. */
  28145. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  28146. return axisModel.getCoordSysModel() === gridModel;
  28147. }
  28148. function rotateTextRect(textRect, rotate) {
  28149. var rotateRadians = rotate * Math.PI / 180;
  28150. var boundingBox = textRect.plain();
  28151. var beforeWidth = boundingBox.width;
  28152. var beforeHeight = boundingBox.height;
  28153. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  28154. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  28155. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  28156. return rotatedRect;
  28157. }
  28158. function getLabelUnionRect(axis) {
  28159. var axisModel = axis.model;
  28160. var labels = axisModel.get('axisLabel.show') ? axisModel.getFormattedLabels() : [];
  28161. var axisLabelModel = axisModel.getModel('axisLabel');
  28162. var rect;
  28163. var step = 1;
  28164. var labelCount = labels.length;
  28165. if (labelCount > 40) {
  28166. // Simple optimization for large amount of labels
  28167. step = Math.ceil(labelCount / 40);
  28168. }
  28169. for (var i = 0; i < labelCount; i += step) {
  28170. if (!axis.isLabelIgnored(i)) {
  28171. var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]);
  28172. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  28173. rect ? rect.union(singleRect) : (rect = singleRect);
  28174. }
  28175. }
  28176. return rect;
  28177. }
  28178. function Grid(gridModel, ecModel, api) {
  28179. /**
  28180. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  28181. * @private
  28182. */
  28183. this._coordsMap = {};
  28184. /**
  28185. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  28186. * @private
  28187. */
  28188. this._coordsList = [];
  28189. /**
  28190. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  28191. * @private
  28192. */
  28193. this._axesMap = {};
  28194. /**
  28195. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  28196. * @private
  28197. */
  28198. this._axesList = [];
  28199. this._initCartesian(gridModel, ecModel, api);
  28200. this.model = gridModel;
  28201. }
  28202. var gridProto = Grid.prototype;
  28203. gridProto.type = 'grid';
  28204. gridProto.axisPointerEnabled = true;
  28205. gridProto.getRect = function () {
  28206. return this._rect;
  28207. };
  28208. gridProto.update = function (ecModel, api) {
  28209. var axesMap = this._axesMap;
  28210. this._updateScale(ecModel, this.model);
  28211. each$6(axesMap.x, function (xAxis) {
  28212. niceScaleExtent(xAxis.scale, xAxis.model);
  28213. });
  28214. each$6(axesMap.y, function (yAxis) {
  28215. niceScaleExtent(yAxis.scale, yAxis.model);
  28216. });
  28217. each$6(axesMap.x, function (xAxis) {
  28218. fixAxisOnZero(axesMap, 'y', xAxis);
  28219. });
  28220. each$6(axesMap.y, function (yAxis) {
  28221. fixAxisOnZero(axesMap, 'x', yAxis);
  28222. });
  28223. // Resize again if containLabel is enabled
  28224. // FIXME It may cause getting wrong grid size in data processing stage
  28225. this.resize(this.model, api);
  28226. };
  28227. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  28228. // onZero can not be enabled in these two situations:
  28229. // 1. When any other axis is a category axis.
  28230. // 2. When no axis is cross 0 point.
  28231. var axes = axesMap[otherAxisDim];
  28232. if (!axis.onZero) {
  28233. return;
  28234. }
  28235. var onZeroAxisIndex = axis.onZeroAxisIndex;
  28236. // If target axis is specified.
  28237. if (onZeroAxisIndex != null) {
  28238. var otherAxis = axes[onZeroAxisIndex];
  28239. if (otherAxis && canNotOnZeroToAxis(otherAxis)) {
  28240. axis.onZero = false;
  28241. }
  28242. return;
  28243. }
  28244. for (var idx in axes) {
  28245. if (axes.hasOwnProperty(idx)) {
  28246. var otherAxis = axes[idx];
  28247. if (otherAxis && !canNotOnZeroToAxis(otherAxis)) {
  28248. onZeroAxisIndex = +idx;
  28249. break;
  28250. }
  28251. }
  28252. }
  28253. if (onZeroAxisIndex == null) {
  28254. axis.onZero = false;
  28255. }
  28256. axis.onZeroAxisIndex = onZeroAxisIndex;
  28257. }
  28258. function canNotOnZeroToAxis(axis) {
  28259. return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero(axis);
  28260. }
  28261. /**
  28262. * Resize the grid
  28263. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  28264. * @param {module:echarts/ExtensionAPI} api
  28265. */
  28266. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  28267. var gridRect = getLayoutRect(
  28268. gridModel.getBoxLayoutParams(), {
  28269. width: api.getWidth(),
  28270. height: api.getHeight()
  28271. });
  28272. this._rect = gridRect;
  28273. var axesList = this._axesList;
  28274. adjustAxes();
  28275. // Minus label size
  28276. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  28277. each$6(axesList, function (axis) {
  28278. if (!axis.model.get('axisLabel.inside')) {
  28279. var labelUnionRect = getLabelUnionRect(axis);
  28280. if (labelUnionRect) {
  28281. var dim = axis.isHorizontal() ? 'height' : 'width';
  28282. var margin = axis.model.get('axisLabel.margin');
  28283. gridRect[dim] -= labelUnionRect[dim] + margin;
  28284. if (axis.position === 'top') {
  28285. gridRect.y += labelUnionRect.height + margin;
  28286. }
  28287. else if (axis.position === 'left') {
  28288. gridRect.x += labelUnionRect.width + margin;
  28289. }
  28290. }
  28291. }
  28292. });
  28293. adjustAxes();
  28294. }
  28295. function adjustAxes() {
  28296. each$6(axesList, function (axis) {
  28297. var isHorizontal = axis.isHorizontal();
  28298. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  28299. var idx = axis.inverse ? 1 : 0;
  28300. axis.setExtent(extent[idx], extent[1 - idx]);
  28301. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  28302. });
  28303. }
  28304. };
  28305. /**
  28306. * @param {string} axisType
  28307. * @param {number} [axisIndex]
  28308. */
  28309. gridProto.getAxis = function (axisType, axisIndex) {
  28310. var axesMapOnDim = this._axesMap[axisType];
  28311. if (axesMapOnDim != null) {
  28312. if (axisIndex == null) {
  28313. // Find first axis
  28314. for (var name in axesMapOnDim) {
  28315. if (axesMapOnDim.hasOwnProperty(name)) {
  28316. return axesMapOnDim[name];
  28317. }
  28318. }
  28319. }
  28320. return axesMapOnDim[axisIndex];
  28321. }
  28322. };
  28323. /**
  28324. * @return {Array.<module:echarts/coord/Axis>}
  28325. */
  28326. gridProto.getAxes = function () {
  28327. return this._axesList.slice();
  28328. };
  28329. /**
  28330. * Usage:
  28331. * grid.getCartesian(xAxisIndex, yAxisIndex);
  28332. * grid.getCartesian(xAxisIndex);
  28333. * grid.getCartesian(null, yAxisIndex);
  28334. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  28335. *
  28336. * @param {number|Object} [xAxisIndex]
  28337. * @param {number} [yAxisIndex]
  28338. */
  28339. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  28340. if (xAxisIndex != null && yAxisIndex != null) {
  28341. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  28342. return this._coordsMap[key];
  28343. }
  28344. if (isObject$1(xAxisIndex)) {
  28345. yAxisIndex = xAxisIndex.yAxisIndex;
  28346. xAxisIndex = xAxisIndex.xAxisIndex;
  28347. }
  28348. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  28349. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  28350. if (coordList[i].getAxis('x').index === xAxisIndex
  28351. || coordList[i].getAxis('y').index === yAxisIndex
  28352. ) {
  28353. return coordList[i];
  28354. }
  28355. }
  28356. };
  28357. gridProto.getCartesians = function () {
  28358. return this._coordsList.slice();
  28359. };
  28360. /**
  28361. * @implements
  28362. * see {module:echarts/CoodinateSystem}
  28363. */
  28364. gridProto.convertToPixel = function (ecModel, finder, value) {
  28365. var target = this._findConvertTarget(ecModel, finder);
  28366. return target.cartesian
  28367. ? target.cartesian.dataToPoint(value)
  28368. : target.axis
  28369. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  28370. : null;
  28371. };
  28372. /**
  28373. * @implements
  28374. * see {module:echarts/CoodinateSystem}
  28375. */
  28376. gridProto.convertFromPixel = function (ecModel, finder, value) {
  28377. var target = this._findConvertTarget(ecModel, finder);
  28378. return target.cartesian
  28379. ? target.cartesian.pointToData(value)
  28380. : target.axis
  28381. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  28382. : null;
  28383. };
  28384. /**
  28385. * @inner
  28386. */
  28387. gridProto._findConvertTarget = function (ecModel, finder) {
  28388. var seriesModel = finder.seriesModel;
  28389. var xAxisModel = finder.xAxisModel
  28390. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  28391. var yAxisModel = finder.yAxisModel
  28392. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  28393. var gridModel = finder.gridModel;
  28394. var coordsList = this._coordsList;
  28395. var cartesian;
  28396. var axis;
  28397. if (seriesModel) {
  28398. cartesian = seriesModel.coordinateSystem;
  28399. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  28400. }
  28401. else if (xAxisModel && yAxisModel) {
  28402. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  28403. }
  28404. else if (xAxisModel) {
  28405. axis = this.getAxis('x', xAxisModel.componentIndex);
  28406. }
  28407. else if (yAxisModel) {
  28408. axis = this.getAxis('y', yAxisModel.componentIndex);
  28409. }
  28410. // Lowest priority.
  28411. else if (gridModel) {
  28412. var grid = gridModel.coordinateSystem;
  28413. if (grid === this) {
  28414. cartesian = this._coordsList[0];
  28415. }
  28416. }
  28417. return {cartesian: cartesian, axis: axis};
  28418. };
  28419. /**
  28420. * @implements
  28421. * see {module:echarts/CoodinateSystem}
  28422. */
  28423. gridProto.containPoint = function (point) {
  28424. var coord = this._coordsList[0];
  28425. if (coord) {
  28426. return coord.containPoint(point);
  28427. }
  28428. };
  28429. /**
  28430. * Initialize cartesian coordinate systems
  28431. * @private
  28432. */
  28433. gridProto._initCartesian = function (gridModel, ecModel, api) {
  28434. var axisPositionUsed = {
  28435. left: false,
  28436. right: false,
  28437. top: false,
  28438. bottom: false
  28439. };
  28440. var axesMap = {
  28441. x: {},
  28442. y: {}
  28443. };
  28444. var axesCount = {
  28445. x: 0,
  28446. y: 0
  28447. };
  28448. /// Create axis
  28449. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  28450. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  28451. if (!axesCount.x || !axesCount.y) {
  28452. // Roll back when there no either x or y axis
  28453. this._axesMap = {};
  28454. this._axesList = [];
  28455. return;
  28456. }
  28457. this._axesMap = axesMap;
  28458. /// Create cartesian2d
  28459. each$6(axesMap.x, function (xAxis, xAxisIndex) {
  28460. each$6(axesMap.y, function (yAxis, yAxisIndex) {
  28461. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  28462. var cartesian = new Cartesian2D(key);
  28463. cartesian.grid = this;
  28464. cartesian.model = gridModel;
  28465. this._coordsMap[key] = cartesian;
  28466. this._coordsList.push(cartesian);
  28467. cartesian.addAxis(xAxis);
  28468. cartesian.addAxis(yAxis);
  28469. }, this);
  28470. }, this);
  28471. function createAxisCreator(axisType) {
  28472. return function (axisModel, idx) {
  28473. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  28474. return;
  28475. }
  28476. var axisPosition = axisModel.get('position');
  28477. if (axisType === 'x') {
  28478. // Fix position
  28479. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  28480. // Default bottom of X
  28481. axisPosition = 'bottom';
  28482. if (axisPositionUsed[axisPosition]) {
  28483. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  28484. }
  28485. }
  28486. }
  28487. else {
  28488. // Fix position
  28489. if (axisPosition !== 'left' && axisPosition !== 'right') {
  28490. // Default left of Y
  28491. axisPosition = 'left';
  28492. if (axisPositionUsed[axisPosition]) {
  28493. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  28494. }
  28495. }
  28496. }
  28497. axisPositionUsed[axisPosition] = true;
  28498. var axis = new Axis2D(
  28499. axisType, createScaleByModel(axisModel),
  28500. [0, 0],
  28501. axisModel.get('type'),
  28502. axisPosition
  28503. );
  28504. var isCategory = axis.type === 'category';
  28505. axis.onBand = isCategory && axisModel.get('boundaryGap');
  28506. axis.inverse = axisModel.get('inverse');
  28507. axis.onZero = axisModel.get('axisLine.onZero');
  28508. axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  28509. // Inject axis into axisModel
  28510. axisModel.axis = axis;
  28511. // Inject axisModel into axis
  28512. axis.model = axisModel;
  28513. // Inject grid info axis
  28514. axis.grid = this;
  28515. // Index of axis, can be used as key
  28516. axis.index = idx;
  28517. this._axesList.push(axis);
  28518. axesMap[axisType][idx] = axis;
  28519. axesCount[axisType]++;
  28520. };
  28521. }
  28522. };
  28523. /**
  28524. * Update cartesian properties from series
  28525. * @param {module:echarts/model/Option} option
  28526. * @private
  28527. */
  28528. gridProto._updateScale = function (ecModel, gridModel) {
  28529. // Reset scale
  28530. each$1(this._axesList, function (axis) {
  28531. axis.scale.setExtent(Infinity, -Infinity);
  28532. });
  28533. ecModel.eachSeries(function (seriesModel) {
  28534. if (isCartesian2D(seriesModel)) {
  28535. var axesModels = findAxesModels(seriesModel, ecModel);
  28536. var xAxisModel = axesModels[0];
  28537. var yAxisModel = axesModels[1];
  28538. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  28539. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  28540. ) {
  28541. return;
  28542. }
  28543. var cartesian = this.getCartesian(
  28544. xAxisModel.componentIndex, yAxisModel.componentIndex
  28545. );
  28546. var data = seriesModel.getData();
  28547. var xAxis = cartesian.getAxis('x');
  28548. var yAxis = cartesian.getAxis('y');
  28549. if (data.type === 'list') {
  28550. unionExtent(data, xAxis, seriesModel);
  28551. unionExtent(data, yAxis, seriesModel);
  28552. }
  28553. }
  28554. }, this);
  28555. function unionExtent(data, axis, seriesModel) {
  28556. each$6(data.mapDimension(axis.dim, true), function (dim) {
  28557. axis.scale.unionExtentFromData(data, dim);
  28558. });
  28559. }
  28560. };
  28561. /**
  28562. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  28563. * @return {Object} {baseAxes: [], otherAxes: []}
  28564. */
  28565. gridProto.getTooltipAxes = function (dim) {
  28566. var baseAxes = [];
  28567. var otherAxes = [];
  28568. each$6(this.getCartesians(), function (cartesian) {
  28569. var baseAxis = (dim != null && dim !== 'auto')
  28570. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  28571. var otherAxis = cartesian.getOtherAxis(baseAxis);
  28572. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  28573. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  28574. });
  28575. return {baseAxes: baseAxes, otherAxes: otherAxes};
  28576. };
  28577. /**
  28578. * @inner
  28579. */
  28580. function updateAxisTransform(axis, coordBase) {
  28581. var axisExtent = axis.getExtent();
  28582. var axisExtentSum = axisExtent[0] + axisExtent[1];
  28583. // Fast transform
  28584. axis.toGlobalCoord = axis.dim === 'x'
  28585. ? function (coord) {
  28586. return coord + coordBase;
  28587. }
  28588. : function (coord) {
  28589. return axisExtentSum - coord + coordBase;
  28590. };
  28591. axis.toLocalCoord = axis.dim === 'x'
  28592. ? function (coord) {
  28593. return coord - coordBase;
  28594. }
  28595. : function (coord) {
  28596. return axisExtentSum - coord + coordBase;
  28597. };
  28598. }
  28599. var axesTypes = ['xAxis', 'yAxis'];
  28600. /**
  28601. * @inner
  28602. */
  28603. function findAxesModels(seriesModel, ecModel) {
  28604. return map(axesTypes, function (axisType) {
  28605. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  28606. if (__DEV__) {
  28607. if (!axisModel) {
  28608. throw new Error(axisType + ' "' + retrieve(
  28609. seriesModel.get(axisType + 'Index'),
  28610. seriesModel.get(axisType + 'Id'),
  28611. 0
  28612. ) + '" not found');
  28613. }
  28614. }
  28615. return axisModel;
  28616. });
  28617. }
  28618. /**
  28619. * @inner
  28620. */
  28621. function isCartesian2D(seriesModel) {
  28622. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  28623. }
  28624. Grid.create = function (ecModel, api) {
  28625. var grids = [];
  28626. ecModel.eachComponent('grid', function (gridModel, idx) {
  28627. var grid = new Grid(gridModel, ecModel, api);
  28628. grid.name = 'grid_' + idx;
  28629. // dataSampling requires axis extent, so resize
  28630. // should be performed in create stage.
  28631. grid.resize(gridModel, api, true);
  28632. gridModel.coordinateSystem = grid;
  28633. grids.push(grid);
  28634. });
  28635. // Inject the coordinateSystems into seriesModel
  28636. ecModel.eachSeries(function (seriesModel) {
  28637. if (!isCartesian2D(seriesModel)) {
  28638. return;
  28639. }
  28640. var axesModels = findAxesModels(seriesModel, ecModel);
  28641. var xAxisModel = axesModels[0];
  28642. var yAxisModel = axesModels[1];
  28643. var gridModel = xAxisModel.getCoordSysModel();
  28644. if (__DEV__) {
  28645. if (!gridModel) {
  28646. throw new Error(
  28647. 'Grid "' + retrieve(
  28648. xAxisModel.get('gridIndex'),
  28649. xAxisModel.get('gridId'),
  28650. 0
  28651. ) + '" not found'
  28652. );
  28653. }
  28654. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  28655. throw new Error('xAxis and yAxis must use the same grid');
  28656. }
  28657. }
  28658. var grid = gridModel.coordinateSystem;
  28659. seriesModel.coordinateSystem = grid.getCartesian(
  28660. xAxisModel.componentIndex, yAxisModel.componentIndex
  28661. );
  28662. });
  28663. return grids;
  28664. };
  28665. // For deciding which dimensions to use when creating list data
  28666. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  28667. CoordinateSystemManager.register('cartesian2d', Grid);
  28668. var PI$2 = Math.PI;
  28669. function makeAxisEventDataBase(axisModel) {
  28670. var eventData = {
  28671. componentType: axisModel.mainType
  28672. };
  28673. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  28674. return eventData;
  28675. }
  28676. /**
  28677. * A final axis is translated and rotated from a "standard axis".
  28678. * So opt.position and opt.rotation is required.
  28679. *
  28680. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  28681. * for example: (0, 0) ------------> (0, 50)
  28682. *
  28683. * nameDirection or tickDirection or labelDirection is 1 means tick
  28684. * or label is below the standard axis, whereas is -1 means above
  28685. * the standard axis. labelOffset means offset between label and axis,
  28686. * which is useful when 'onZero', where axisLabel is in the grid and
  28687. * label in outside grid.
  28688. *
  28689. * Tips: like always,
  28690. * positive rotation represents anticlockwise, and negative rotation
  28691. * represents clockwise.
  28692. * The direction of position coordinate is the same as the direction
  28693. * of screen coordinate.
  28694. *
  28695. * Do not need to consider axis 'inverse', which is auto processed by
  28696. * axis extent.
  28697. *
  28698. * @param {module:zrender/container/Group} group
  28699. * @param {Object} axisModel
  28700. * @param {Object} opt Standard axis parameters.
  28701. * @param {Array.<number>} opt.position [x, y]
  28702. * @param {number} opt.rotation by radian
  28703. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  28704. * @param {number} [opt.tickDirection=1] 1 or -1
  28705. * @param {number} [opt.labelDirection=1] 1 or -1
  28706. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  28707. * @param {string} [opt.axisLabelShow] default get from axisModel.
  28708. * @param {string} [opt.axisName] default get from axisModel.
  28709. * @param {number} [opt.axisNameAvailableWidth]
  28710. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  28711. * @param {number} [opt.labelInterval] Default label interval when label
  28712. * interval from model is null or 'auto'.
  28713. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  28714. * @param {number} [opt.nameTruncateMaxWidth]
  28715. */
  28716. var AxisBuilder = function (axisModel, opt) {
  28717. /**
  28718. * @readOnly
  28719. */
  28720. this.opt = opt;
  28721. /**
  28722. * @readOnly
  28723. */
  28724. this.axisModel = axisModel;
  28725. // Default value
  28726. defaults(
  28727. opt,
  28728. {
  28729. labelOffset: 0,
  28730. nameDirection: 1,
  28731. tickDirection: 1,
  28732. labelDirection: 1,
  28733. silent: true
  28734. }
  28735. );
  28736. /**
  28737. * @readOnly
  28738. */
  28739. this.group = new Group();
  28740. // FIXME Not use a seperate text group?
  28741. var dumbGroup = new Group({
  28742. position: opt.position.slice(),
  28743. rotation: opt.rotation
  28744. });
  28745. // this.group.add(dumbGroup);
  28746. // this._dumbGroup = dumbGroup;
  28747. dumbGroup.updateTransform();
  28748. this._transform = dumbGroup.transform;
  28749. this._dumbGroup = dumbGroup;
  28750. };
  28751. AxisBuilder.prototype = {
  28752. constructor: AxisBuilder,
  28753. hasBuilder: function (name) {
  28754. return !!builders[name];
  28755. },
  28756. add: function (name) {
  28757. builders[name].call(this);
  28758. },
  28759. getGroup: function () {
  28760. return this.group;
  28761. }
  28762. };
  28763. var builders = {
  28764. /**
  28765. * @private
  28766. */
  28767. axisLine: function () {
  28768. var opt = this.opt;
  28769. var axisModel = this.axisModel;
  28770. if (!axisModel.get('axisLine.show')) {
  28771. return;
  28772. }
  28773. var extent = this.axisModel.axis.getExtent();
  28774. var matrix = this._transform;
  28775. var pt1 = [extent[0], 0];
  28776. var pt2 = [extent[1], 0];
  28777. if (matrix) {
  28778. applyTransform(pt1, pt1, matrix);
  28779. applyTransform(pt2, pt2, matrix);
  28780. }
  28781. var lineStyle = extend(
  28782. {
  28783. lineCap: 'round'
  28784. },
  28785. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  28786. );
  28787. this.group.add(new Line(subPixelOptimizeLine({
  28788. // Id for animation
  28789. anid: 'line',
  28790. shape: {
  28791. x1: pt1[0],
  28792. y1: pt1[1],
  28793. x2: pt2[0],
  28794. y2: pt2[1]
  28795. },
  28796. style: lineStyle,
  28797. strokeContainThreshold: opt.strokeContainThreshold || 5,
  28798. silent: true,
  28799. z2: 1
  28800. })));
  28801. var arrows = axisModel.get('axisLine.symbol');
  28802. var arrowSize = axisModel.get('axisLine.symbolSize');
  28803. if (arrows != null) {
  28804. if (typeof arrows === 'string') {
  28805. // Use the same arrow for start and end point
  28806. arrows = [arrows, arrows];
  28807. }
  28808. if (typeof arrowSize === 'string'
  28809. || typeof arrowSize === 'number'
  28810. ) {
  28811. // Use the same size for width and height
  28812. arrowSize = [arrowSize, arrowSize];
  28813. }
  28814. var symbolWidth = arrowSize[0];
  28815. var symbolHeight = arrowSize[1];
  28816. each$1([
  28817. [opt.rotation + Math.PI / 2, pt1],
  28818. [opt.rotation - Math.PI / 2, pt2]
  28819. ], function (item, index) {
  28820. if (arrows[index] !== 'none' && arrows[index] != null) {
  28821. var symbol = createSymbol(
  28822. arrows[index],
  28823. -symbolWidth / 2,
  28824. -symbolHeight / 2,
  28825. symbolWidth,
  28826. symbolHeight,
  28827. lineStyle.stroke,
  28828. true
  28829. );
  28830. symbol.attr({
  28831. rotation: item[0],
  28832. position: item[1],
  28833. silent: true
  28834. });
  28835. this.group.add(symbol);
  28836. }
  28837. }, this);
  28838. }
  28839. },
  28840. /**
  28841. * @private
  28842. */
  28843. axisTickLabel: function () {
  28844. var axisModel = this.axisModel;
  28845. var opt = this.opt;
  28846. var tickEls = buildAxisTick(this, axisModel, opt);
  28847. var labelEls = buildAxisLabel(this, axisModel, opt);
  28848. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  28849. },
  28850. /**
  28851. * @private
  28852. */
  28853. axisName: function () {
  28854. var opt = this.opt;
  28855. var axisModel = this.axisModel;
  28856. var name = retrieve(opt.axisName, axisModel.get('name'));
  28857. if (!name) {
  28858. return;
  28859. }
  28860. var nameLocation = axisModel.get('nameLocation');
  28861. var nameDirection = opt.nameDirection;
  28862. var textStyleModel = axisModel.getModel('nameTextStyle');
  28863. var gap = axisModel.get('nameGap') || 0;
  28864. var extent = this.axisModel.axis.getExtent();
  28865. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  28866. var pos = [
  28867. nameLocation === 'start'
  28868. ? extent[0] - gapSignal * gap
  28869. : nameLocation === 'end'
  28870. ? extent[1] + gapSignal * gap
  28871. : (extent[0] + extent[1]) / 2, // 'middle'
  28872. // Reuse labelOffset.
  28873. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  28874. ];
  28875. var labelLayout;
  28876. var nameRotation = axisModel.get('nameRotate');
  28877. if (nameRotation != null) {
  28878. nameRotation = nameRotation * PI$2 / 180; // To radian.
  28879. }
  28880. var axisNameAvailableWidth;
  28881. if (isNameLocationCenter(nameLocation)) {
  28882. labelLayout = innerTextLayout(
  28883. opt.rotation,
  28884. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  28885. nameDirection
  28886. );
  28887. }
  28888. else {
  28889. labelLayout = endTextLayout(
  28890. opt, nameLocation, nameRotation || 0, extent
  28891. );
  28892. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  28893. if (axisNameAvailableWidth != null) {
  28894. axisNameAvailableWidth = Math.abs(
  28895. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  28896. );
  28897. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  28898. }
  28899. }
  28900. var textFont = textStyleModel.getFont();
  28901. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  28902. var ellipsis = truncateOpt.ellipsis;
  28903. var maxWidth = retrieve(
  28904. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  28905. );
  28906. // FIXME
  28907. // truncate rich text? (consider performance)
  28908. var truncatedText = (ellipsis != null && maxWidth != null)
  28909. ? truncateText$1(
  28910. name, maxWidth, textFont, ellipsis,
  28911. {minChar: 2, placeholder: truncateOpt.placeholder}
  28912. )
  28913. : name;
  28914. var tooltipOpt = axisModel.get('tooltip', true);
  28915. var mainType = axisModel.mainType;
  28916. var formatterParams = {
  28917. componentType: mainType,
  28918. name: name,
  28919. $vars: ['name']
  28920. };
  28921. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  28922. var textEl = new Text({
  28923. // Id for animation
  28924. anid: 'name',
  28925. __fullText: name,
  28926. __truncatedText: truncatedText,
  28927. position: pos,
  28928. rotation: labelLayout.rotation,
  28929. silent: isSilent(axisModel),
  28930. z2: 1,
  28931. tooltip: (tooltipOpt && tooltipOpt.show)
  28932. ? extend({
  28933. content: name,
  28934. formatter: function () {
  28935. return name;
  28936. },
  28937. formatterParams: formatterParams
  28938. }, tooltipOpt)
  28939. : null
  28940. });
  28941. setTextStyle(textEl.style, textStyleModel, {
  28942. text: truncatedText,
  28943. textFont: textFont,
  28944. textFill: textStyleModel.getTextColor()
  28945. || axisModel.get('axisLine.lineStyle.color'),
  28946. textAlign: labelLayout.textAlign,
  28947. textVerticalAlign: labelLayout.textVerticalAlign
  28948. });
  28949. if (axisModel.get('triggerEvent')) {
  28950. textEl.eventData = makeAxisEventDataBase(axisModel);
  28951. textEl.eventData.targetType = 'axisName';
  28952. textEl.eventData.name = name;
  28953. }
  28954. // FIXME
  28955. this._dumbGroup.add(textEl);
  28956. textEl.updateTransform();
  28957. this.group.add(textEl);
  28958. textEl.decomposeTransform();
  28959. }
  28960. };
  28961. /**
  28962. * @public
  28963. * @static
  28964. * @param {Object} opt
  28965. * @param {number} axisRotation in radian
  28966. * @param {number} textRotation in radian
  28967. * @param {number} direction
  28968. * @return {Object} {
  28969. * rotation, // according to axis
  28970. * textAlign,
  28971. * textVerticalAlign
  28972. * }
  28973. */
  28974. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  28975. var rotationDiff = remRadian(textRotation - axisRotation);
  28976. var textAlign;
  28977. var textVerticalAlign;
  28978. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  28979. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  28980. textAlign = 'center';
  28981. }
  28982. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  28983. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  28984. textAlign = 'center';
  28985. }
  28986. else {
  28987. textVerticalAlign = 'middle';
  28988. if (rotationDiff > 0 && rotationDiff < PI$2) {
  28989. textAlign = direction > 0 ? 'right' : 'left';
  28990. }
  28991. else {
  28992. textAlign = direction > 0 ? 'left' : 'right';
  28993. }
  28994. }
  28995. return {
  28996. rotation: rotationDiff,
  28997. textAlign: textAlign,
  28998. textVerticalAlign: textVerticalAlign
  28999. };
  29000. };
  29001. function endTextLayout(opt, textPosition, textRotate, extent) {
  29002. var rotationDiff = remRadian(textRotate - opt.rotation);
  29003. var textAlign;
  29004. var textVerticalAlign;
  29005. var inverse = extent[0] > extent[1];
  29006. var onLeft = (textPosition === 'start' && !inverse)
  29007. || (textPosition !== 'start' && inverse);
  29008. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  29009. textVerticalAlign = onLeft ? 'bottom' : 'top';
  29010. textAlign = 'center';
  29011. }
  29012. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  29013. textVerticalAlign = onLeft ? 'top' : 'bottom';
  29014. textAlign = 'center';
  29015. }
  29016. else {
  29017. textVerticalAlign = 'middle';
  29018. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  29019. textAlign = onLeft ? 'left' : 'right';
  29020. }
  29021. else {
  29022. textAlign = onLeft ? 'right' : 'left';
  29023. }
  29024. }
  29025. return {
  29026. rotation: rotationDiff,
  29027. textAlign: textAlign,
  29028. textVerticalAlign: textVerticalAlign
  29029. };
  29030. }
  29031. function isSilent(axisModel) {
  29032. var tooltipOpt = axisModel.get('tooltip');
  29033. return axisModel.get('silent')
  29034. // Consider mouse cursor, add these restrictions.
  29035. || !(
  29036. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  29037. );
  29038. }
  29039. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  29040. // If min or max are user set, we need to check
  29041. // If the tick on min(max) are overlap on their neighbour tick
  29042. // If they are overlapped, we need to hide the min(max) tick label
  29043. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29044. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29045. // FIXME
  29046. // Have not consider onBand yet, where tick els is more than label els.
  29047. labelEls = labelEls || [];
  29048. tickEls = tickEls || [];
  29049. var firstLabel = labelEls[0];
  29050. var nextLabel = labelEls[1];
  29051. var lastLabel = labelEls[labelEls.length - 1];
  29052. var prevLabel = labelEls[labelEls.length - 2];
  29053. var firstTick = tickEls[0];
  29054. var nextTick = tickEls[1];
  29055. var lastTick = tickEls[tickEls.length - 1];
  29056. var prevTick = tickEls[tickEls.length - 2];
  29057. if (showMinLabel === false) {
  29058. ignoreEl(firstLabel);
  29059. ignoreEl(firstTick);
  29060. }
  29061. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  29062. if (showMinLabel) {
  29063. ignoreEl(nextLabel);
  29064. ignoreEl(nextTick);
  29065. }
  29066. else {
  29067. ignoreEl(firstLabel);
  29068. ignoreEl(firstTick);
  29069. }
  29070. }
  29071. if (showMaxLabel === false) {
  29072. ignoreEl(lastLabel);
  29073. ignoreEl(lastTick);
  29074. }
  29075. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  29076. if (showMaxLabel) {
  29077. ignoreEl(prevLabel);
  29078. ignoreEl(prevTick);
  29079. }
  29080. else {
  29081. ignoreEl(lastLabel);
  29082. ignoreEl(lastTick);
  29083. }
  29084. }
  29085. }
  29086. function ignoreEl(el) {
  29087. el && (el.ignore = true);
  29088. }
  29089. function isTwoLabelOverlapped(current, next, labelLayout) {
  29090. // current and next has the same rotation.
  29091. var firstRect = current && current.getBoundingRect().clone();
  29092. var nextRect = next && next.getBoundingRect().clone();
  29093. if (!firstRect || !nextRect) {
  29094. return;
  29095. }
  29096. // When checking intersect of two rotated labels, we use mRotationBack
  29097. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  29098. var mRotationBack = identity([]);
  29099. rotate(mRotationBack, mRotationBack, -current.rotation);
  29100. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  29101. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  29102. return firstRect.intersect(nextRect);
  29103. }
  29104. function isNameLocationCenter(nameLocation) {
  29105. return nameLocation === 'middle' || nameLocation === 'center';
  29106. }
  29107. /**
  29108. * @static
  29109. */
  29110. var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function (
  29111. axis,
  29112. i,
  29113. interval,
  29114. ticksCnt,
  29115. showMinLabel,
  29116. showMaxLabel
  29117. ) {
  29118. if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) {
  29119. return false;
  29120. }
  29121. // FIXME
  29122. // Have not consider label overlap (if label is too long) yet.
  29123. var rawTick;
  29124. var scale$$1 = axis.scale;
  29125. return scale$$1.type === 'ordinal'
  29126. && (
  29127. typeof interval === 'function'
  29128. ? (
  29129. rawTick = scale$$1.getTicks()[i],
  29130. !interval(rawTick, scale$$1.getLabel(rawTick))
  29131. )
  29132. : i % (interval + 1)
  29133. );
  29134. };
  29135. /**
  29136. * @static
  29137. */
  29138. var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) {
  29139. var interval = model.get('interval');
  29140. if (interval == null || interval == 'auto') {
  29141. interval = labelInterval;
  29142. }
  29143. return interval;
  29144. };
  29145. function buildAxisTick(axisBuilder, axisModel, opt) {
  29146. var axis = axisModel.axis;
  29147. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  29148. return;
  29149. }
  29150. var tickModel = axisModel.getModel('axisTick');
  29151. var lineStyleModel = tickModel.getModel('lineStyle');
  29152. var tickLen = tickModel.get('length');
  29153. var tickInterval = getInterval$1(tickModel, opt.labelInterval);
  29154. var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel'));
  29155. // FIXME
  29156. // Corresponds to ticksCoords ?
  29157. var ticks = axis.scale.getTicks();
  29158. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29159. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29160. var pt1 = [];
  29161. var pt2 = [];
  29162. var matrix = axisBuilder._transform;
  29163. var tickEls = [];
  29164. var ticksCnt = ticksCoords.length;
  29165. for (var i = 0; i < ticksCnt; i++) {
  29166. // Only ordinal scale support tick interval
  29167. if (ifIgnoreOnTick$1(
  29168. axis, i, tickInterval, ticksCnt,
  29169. showMinLabel, showMaxLabel
  29170. )) {
  29171. continue;
  29172. }
  29173. var tickCoord = ticksCoords[i];
  29174. pt1[0] = tickCoord;
  29175. pt1[1] = 0;
  29176. pt2[0] = tickCoord;
  29177. pt2[1] = opt.tickDirection * tickLen;
  29178. if (matrix) {
  29179. applyTransform(pt1, pt1, matrix);
  29180. applyTransform(pt2, pt2, matrix);
  29181. }
  29182. // Tick line, Not use group transform to have better line draw
  29183. var tickEl = new Line(subPixelOptimizeLine({
  29184. // Id for animation
  29185. anid: 'tick_' + ticks[i],
  29186. shape: {
  29187. x1: pt1[0],
  29188. y1: pt1[1],
  29189. x2: pt2[0],
  29190. y2: pt2[1]
  29191. },
  29192. style: defaults(
  29193. lineStyleModel.getLineStyle(),
  29194. {
  29195. stroke: axisModel.get('axisLine.lineStyle.color')
  29196. }
  29197. ),
  29198. z2: 2,
  29199. silent: true
  29200. }));
  29201. axisBuilder.group.add(tickEl);
  29202. tickEls.push(tickEl);
  29203. }
  29204. return tickEls;
  29205. }
  29206. function buildAxisLabel(axisBuilder, axisModel, opt) {
  29207. var axis = axisModel.axis;
  29208. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  29209. if (!show || axis.scale.isBlank()) {
  29210. return;
  29211. }
  29212. var labelModel = axisModel.getModel('axisLabel');
  29213. var labelMargin = labelModel.get('margin');
  29214. var ticks = axis.scale.getTicks();
  29215. var labels = axisModel.getFormattedLabels();
  29216. // Special label rotate.
  29217. var labelRotation = (
  29218. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  29219. ) * PI$2 / 180;
  29220. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  29221. var categoryData = axisModel.getCategories();
  29222. var labelEls = [];
  29223. var silent = isSilent(axisModel);
  29224. var triggerEvent = axisModel.get('triggerEvent');
  29225. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29226. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29227. each$1(ticks, function (tickVal, index) {
  29228. if (ifIgnoreOnTick$1(
  29229. axis, index, opt.labelInterval, ticks.length,
  29230. showMinLabel, showMaxLabel
  29231. )) {
  29232. return;
  29233. }
  29234. var itemLabelModel = labelModel;
  29235. if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) {
  29236. itemLabelModel = new Model(
  29237. categoryData[tickVal].textStyle, labelModel, axisModel.ecModel
  29238. );
  29239. }
  29240. var textColor = itemLabelModel.getTextColor()
  29241. || axisModel.get('axisLine.lineStyle.color');
  29242. var tickCoord = axis.dataToCoord(tickVal);
  29243. var pos = [
  29244. tickCoord,
  29245. opt.labelOffset + opt.labelDirection * labelMargin
  29246. ];
  29247. var labelStr = axis.scale.getLabel(tickVal);
  29248. var textEl = new Text({
  29249. // Id for animation
  29250. anid: 'label_' + tickVal,
  29251. position: pos,
  29252. rotation: labelLayout.rotation,
  29253. silent: silent,
  29254. z2: 10
  29255. });
  29256. setTextStyle(textEl.style, itemLabelModel, {
  29257. text: labels[index],
  29258. textAlign: itemLabelModel.getShallow('align', true)
  29259. || labelLayout.textAlign,
  29260. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  29261. || itemLabelModel.getShallow('baseline', true)
  29262. || labelLayout.textVerticalAlign,
  29263. textFill: typeof textColor === 'function'
  29264. ? textColor(
  29265. // (1) In category axis with data zoom, tick is not the original
  29266. // index of axis.data. So tick should not be exposed to user
  29267. // in category axis.
  29268. // (2) Compatible with previous version, which always returns labelStr.
  29269. // But in interval scale labelStr is like '223,445', which maked
  29270. // user repalce ','. So we modify it to return original val but remain
  29271. // it as 'string' to avoid error in replacing.
  29272. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal,
  29273. index
  29274. )
  29275. : textColor
  29276. });
  29277. // Pack data for mouse event
  29278. if (triggerEvent) {
  29279. textEl.eventData = makeAxisEventDataBase(axisModel);
  29280. textEl.eventData.targetType = 'axisLabel';
  29281. textEl.eventData.value = labelStr;
  29282. }
  29283. // FIXME
  29284. axisBuilder._dumbGroup.add(textEl);
  29285. textEl.updateTransform();
  29286. labelEls.push(textEl);
  29287. axisBuilder.group.add(textEl);
  29288. textEl.decomposeTransform();
  29289. });
  29290. return labelEls;
  29291. }
  29292. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  29293. // allAxesInfo should be updated when setOption performed.
  29294. function fixValue(axisModel) {
  29295. var axisInfo = getAxisInfo(axisModel);
  29296. if (!axisInfo) {
  29297. return;
  29298. }
  29299. var axisPointerModel = axisInfo.axisPointerModel;
  29300. var scale = axisInfo.axis.scale;
  29301. var option = axisPointerModel.option;
  29302. var status = axisPointerModel.get('status');
  29303. var value = axisPointerModel.get('value');
  29304. // Parse init value for category and time axis.
  29305. if (value != null) {
  29306. value = scale.parse(value);
  29307. }
  29308. var useHandle = isHandleTrigger(axisPointerModel);
  29309. // If `handle` used, `axisPointer` will always be displayed, so value
  29310. // and status should be initialized.
  29311. if (status == null) {
  29312. option.status = useHandle ? 'show' : 'hide';
  29313. }
  29314. var extent = scale.getExtent().slice();
  29315. extent[0] > extent[1] && extent.reverse();
  29316. if (// Pick a value on axis when initializing.
  29317. value == null
  29318. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  29319. // where we should re-pick a value to keep `handle` displaying normally.
  29320. || value > extent[1]
  29321. ) {
  29322. // Make handle displayed on the end of the axis when init, which looks better.
  29323. value = extent[1];
  29324. }
  29325. if (value < extent[0]) {
  29326. value = extent[0];
  29327. }
  29328. option.value = value;
  29329. if (useHandle) {
  29330. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  29331. }
  29332. }
  29333. function getAxisInfo(axisModel) {
  29334. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  29335. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  29336. }
  29337. function getAxisPointerModel(axisModel) {
  29338. var axisInfo = getAxisInfo(axisModel);
  29339. return axisInfo && axisInfo.axisPointerModel;
  29340. }
  29341. function isHandleTrigger(axisPointerModel) {
  29342. return !!axisPointerModel.get('handle.show');
  29343. }
  29344. /**
  29345. * @param {module:echarts/model/Model} model
  29346. * @return {string} unique key
  29347. */
  29348. function makeKey(model) {
  29349. return model.type + '||' + model.id;
  29350. }
  29351. /**
  29352. * Base class of AxisView.
  29353. */
  29354. var AxisView = extendComponentView({
  29355. type: 'axis',
  29356. /**
  29357. * @private
  29358. */
  29359. _axisPointer: null,
  29360. /**
  29361. * @protected
  29362. * @type {string}
  29363. */
  29364. axisPointerClass: null,
  29365. /**
  29366. * @override
  29367. */
  29368. render: function (axisModel, ecModel, api, payload) {
  29369. // FIXME
  29370. // This process should proformed after coordinate systems updated
  29371. // (axis scale updated), and should be performed each time update.
  29372. // So put it here temporarily, although it is not appropriate to
  29373. // put a model-writing procedure in `view`.
  29374. this.axisPointerClass && fixValue(axisModel);
  29375. AxisView.superApply(this, 'render', arguments);
  29376. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  29377. },
  29378. /**
  29379. * Action handler.
  29380. * @public
  29381. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  29382. * @param {module:echarts/model/Global} ecModel
  29383. * @param {module:echarts/ExtensionAPI} api
  29384. * @param {Object} payload
  29385. */
  29386. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  29387. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  29388. },
  29389. /**
  29390. * @override
  29391. */
  29392. remove: function (ecModel, api) {
  29393. var axisPointer = this._axisPointer;
  29394. axisPointer && axisPointer.remove(api);
  29395. AxisView.superApply(this, 'remove', arguments);
  29396. },
  29397. /**
  29398. * @override
  29399. */
  29400. dispose: function (ecModel, api) {
  29401. disposeAxisPointer(this, api);
  29402. AxisView.superApply(this, 'dispose', arguments);
  29403. }
  29404. });
  29405. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  29406. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  29407. if (!Clazz) {
  29408. return;
  29409. }
  29410. var axisPointerModel = getAxisPointerModel(axisModel);
  29411. axisPointerModel
  29412. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  29413. .render(axisModel, axisPointerModel, api, forceRender)
  29414. : disposeAxisPointer(axisView, api);
  29415. }
  29416. function disposeAxisPointer(axisView, ecModel, api) {
  29417. var axisPointer = axisView._axisPointer;
  29418. axisPointer && axisPointer.dispose(ecModel, api);
  29419. axisView._axisPointer = null;
  29420. }
  29421. var axisPointerClazz = [];
  29422. AxisView.registerAxisPointerClass = function (type, clazz) {
  29423. if (__DEV__) {
  29424. if (axisPointerClazz[type]) {
  29425. throw new Error('axisPointer ' + type + ' exists');
  29426. }
  29427. }
  29428. axisPointerClazz[type] = clazz;
  29429. };
  29430. AxisView.getAxisPointerClass = function (type) {
  29431. return type && axisPointerClazz[type];
  29432. };
  29433. /**
  29434. * @param {Object} opt {labelInside}
  29435. * @return {Object} {
  29436. * position, rotation, labelDirection, labelOffset,
  29437. * tickDirection, labelRotate, labelInterval, z2
  29438. * }
  29439. */
  29440. function layout$1(gridModel, axisModel, opt) {
  29441. opt = opt || {};
  29442. var grid = gridModel.coordinateSystem;
  29443. var axis = axisModel.axis;
  29444. var layout = {};
  29445. var rawAxisPosition = axis.position;
  29446. var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition;
  29447. var axisDim = axis.dim;
  29448. var rect = grid.getRect();
  29449. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  29450. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  29451. var axisOffset = axisModel.get('offset') || 0;
  29452. var posBound = axisDim === 'x'
  29453. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  29454. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  29455. if (axis.onZero) {
  29456. var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex);
  29457. var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0));
  29458. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  29459. }
  29460. // Axis position
  29461. layout.position = [
  29462. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  29463. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  29464. ];
  29465. // Axis rotation
  29466. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  29467. // Tick and label direction, x y is axisDim
  29468. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  29469. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  29470. layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  29471. if (axisModel.get('axisTick.inside')) {
  29472. layout.tickDirection = -layout.tickDirection;
  29473. }
  29474. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  29475. layout.labelDirection = -layout.labelDirection;
  29476. }
  29477. // Special label rotation
  29478. var labelRotate = axisModel.get('axisLabel.rotate');
  29479. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  29480. // label interval when auto mode.
  29481. layout.labelInterval = axis.getLabelInterval();
  29482. // Over splitLine and splitArea
  29483. layout.z2 = 1;
  29484. return layout;
  29485. }
  29486. var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick;
  29487. var getInterval = AxisBuilder.getInterval;
  29488. var axisBuilderAttrs = [
  29489. 'axisLine', 'axisTickLabel', 'axisName'
  29490. ];
  29491. var selfBuilderAttrs = [
  29492. 'splitArea', 'splitLine'
  29493. ];
  29494. // function getAlignWithLabel(model, axisModel) {
  29495. // var alignWithLabel = model.get('alignWithLabel');
  29496. // if (alignWithLabel === 'auto') {
  29497. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  29498. // }
  29499. // return alignWithLabel;
  29500. // }
  29501. var CartesianAxisView = AxisView.extend({
  29502. type: 'cartesianAxis',
  29503. axisPointerClass: 'CartesianAxisPointer',
  29504. /**
  29505. * @override
  29506. */
  29507. render: function (axisModel, ecModel, api, payload) {
  29508. this.group.removeAll();
  29509. var oldAxisGroup = this._axisGroup;
  29510. this._axisGroup = new Group();
  29511. this.group.add(this._axisGroup);
  29512. if (!axisModel.get('show')) {
  29513. return;
  29514. }
  29515. var gridModel = axisModel.getCoordSysModel();
  29516. var layout = layout$1(gridModel, axisModel);
  29517. var axisBuilder = new AxisBuilder(axisModel, layout);
  29518. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  29519. this._axisGroup.add(axisBuilder.getGroup());
  29520. each$1(selfBuilderAttrs, function (name) {
  29521. if (axisModel.get(name + '.show')) {
  29522. this['_' + name](axisModel, gridModel, layout.labelInterval);
  29523. }
  29524. }, this);
  29525. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  29526. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  29527. },
  29528. /**
  29529. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  29530. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29531. * @param {number|Function} labelInterval
  29532. * @private
  29533. */
  29534. _splitLine: function (axisModel, gridModel, labelInterval) {
  29535. var axis = axisModel.axis;
  29536. if (axis.scale.isBlank()) {
  29537. return;
  29538. }
  29539. var splitLineModel = axisModel.getModel('splitLine');
  29540. var lineStyleModel = splitLineModel.getModel('lineStyle');
  29541. var lineColors = lineStyleModel.get('color');
  29542. var lineInterval = getInterval(splitLineModel, labelInterval);
  29543. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  29544. var gridRect = gridModel.coordinateSystem.getRect();
  29545. var isHorizontal = axis.isHorizontal();
  29546. var lineCount = 0;
  29547. var ticksCoords = axis.getTicksCoords(
  29548. // splitLineModel.get('alignWithLabel')
  29549. );
  29550. var ticks = axis.scale.getTicks();
  29551. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29552. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29553. var p1 = [];
  29554. var p2 = [];
  29555. // Simple optimization
  29556. // Batching the lines if color are the same
  29557. var lineStyle = lineStyleModel.getLineStyle();
  29558. for (var i = 0; i < ticksCoords.length; i++) {
  29559. if (ifIgnoreOnTick(
  29560. axis, i, lineInterval, ticksCoords.length,
  29561. showMinLabel, showMaxLabel
  29562. )) {
  29563. continue;
  29564. }
  29565. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  29566. if (isHorizontal) {
  29567. p1[0] = tickCoord;
  29568. p1[1] = gridRect.y;
  29569. p2[0] = tickCoord;
  29570. p2[1] = gridRect.y + gridRect.height;
  29571. }
  29572. else {
  29573. p1[0] = gridRect.x;
  29574. p1[1] = tickCoord;
  29575. p2[0] = gridRect.x + gridRect.width;
  29576. p2[1] = tickCoord;
  29577. }
  29578. var colorIndex = (lineCount++) % lineColors.length;
  29579. this._axisGroup.add(new Line(subPixelOptimizeLine({
  29580. anid: 'line_' + ticks[i],
  29581. shape: {
  29582. x1: p1[0],
  29583. y1: p1[1],
  29584. x2: p2[0],
  29585. y2: p2[1]
  29586. },
  29587. style: defaults({
  29588. stroke: lineColors[colorIndex]
  29589. }, lineStyle),
  29590. silent: true
  29591. })));
  29592. }
  29593. },
  29594. /**
  29595. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  29596. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  29597. * @param {number|Function} labelInterval
  29598. * @private
  29599. */
  29600. _splitArea: function (axisModel, gridModel, labelInterval) {
  29601. var axis = axisModel.axis;
  29602. if (axis.scale.isBlank()) {
  29603. return;
  29604. }
  29605. var splitAreaModel = axisModel.getModel('splitArea');
  29606. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  29607. var areaColors = areaStyleModel.get('color');
  29608. var gridRect = gridModel.coordinateSystem.getRect();
  29609. var ticksCoords = axis.getTicksCoords(
  29610. // splitAreaModel.get('alignWithLabel')
  29611. );
  29612. var ticks = axis.scale.getTicks();
  29613. var prevX = axis.toGlobalCoord(ticksCoords[0]);
  29614. var prevY = axis.toGlobalCoord(ticksCoords[0]);
  29615. var count = 0;
  29616. var areaInterval = getInterval(splitAreaModel, labelInterval);
  29617. var areaStyle = areaStyleModel.getAreaStyle();
  29618. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  29619. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  29620. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  29621. for (var i = 1; i < ticksCoords.length; i++) {
  29622. if (ifIgnoreOnTick(
  29623. axis, i, areaInterval, ticksCoords.length,
  29624. showMinLabel, showMaxLabel
  29625. )) {
  29626. continue;
  29627. }
  29628. var tickCoord = axis.toGlobalCoord(ticksCoords[i]);
  29629. var x;
  29630. var y;
  29631. var width;
  29632. var height;
  29633. if (axis.isHorizontal()) {
  29634. x = prevX;
  29635. y = gridRect.y;
  29636. width = tickCoord - x;
  29637. height = gridRect.height;
  29638. }
  29639. else {
  29640. x = gridRect.x;
  29641. y = prevY;
  29642. width = gridRect.width;
  29643. height = tickCoord - y;
  29644. }
  29645. var colorIndex = (count++) % areaColors.length;
  29646. this._axisGroup.add(new Rect({
  29647. anid: 'area_' + ticks[i],
  29648. shape: {
  29649. x: x,
  29650. y: y,
  29651. width: width,
  29652. height: height
  29653. },
  29654. style: defaults({
  29655. fill: areaColors[colorIndex]
  29656. }, areaStyle),
  29657. silent: true
  29658. }));
  29659. prevX = x + width;
  29660. prevY = y + height;
  29661. }
  29662. }
  29663. });
  29664. CartesianAxisView.extend({
  29665. type: 'xAxis'
  29666. });
  29667. CartesianAxisView.extend({
  29668. type: 'yAxis'
  29669. });
  29670. // Grid view
  29671. extendComponentView({
  29672. type: 'grid',
  29673. render: function (gridModel, ecModel) {
  29674. this.group.removeAll();
  29675. if (gridModel.get('show')) {
  29676. this.group.add(new Rect({
  29677. shape: gridModel.coordinateSystem.getRect(),
  29678. style: defaults({
  29679. fill: gridModel.get('backgroundColor')
  29680. }, gridModel.getItemStyle()),
  29681. silent: true,
  29682. z2: -1
  29683. }));
  29684. }
  29685. }
  29686. });
  29687. registerPreprocessor(function (option) {
  29688. // Only create grid when need
  29689. if (option.xAxis && option.yAxis && !option.grid) {
  29690. option.grid = {};
  29691. }
  29692. });
  29693. // In case developer forget to include grid component
  29694. registerVisual(visualSymbol('line', 'circle', 'line'));
  29695. registerLayout(layoutPoints('line'));
  29696. // Down sample after filter
  29697. registerProcessor(
  29698. PRIORITY.PROCESSOR.STATISTIC,
  29699. dataSample('line')
  29700. );
  29701. var BaseBarSeries = SeriesModel.extend({
  29702. type: 'series.__base_bar__',
  29703. getInitialData: function (option, ecModel) {
  29704. return createListFromArray(this.getSource(), this);
  29705. },
  29706. getMarkerPosition: function (value) {
  29707. var coordSys = this.coordinateSystem;
  29708. if (coordSys) {
  29709. // PENDING if clamp ?
  29710. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  29711. var data = this.getData();
  29712. var offset = data.getLayout('offset');
  29713. var size = data.getLayout('size');
  29714. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  29715. pt[offsetIndex] += offset + size / 2;
  29716. return pt;
  29717. }
  29718. return [NaN, NaN];
  29719. },
  29720. defaultOption: {
  29721. zlevel: 0, // 一级层叠
  29722. z: 2, // 二级层叠
  29723. coordinateSystem: 'cartesian2d',
  29724. legendHoverLink: true,
  29725. // stack: null
  29726. // Cartesian coordinate system
  29727. // xAxisIndex: 0,
  29728. // yAxisIndex: 0,
  29729. // 最小高度改为0
  29730. barMinHeight: 0,
  29731. // 最小角度为0,仅对极坐标系下的柱状图有效
  29732. barMinAngle: 0,
  29733. // cursor: null,
  29734. // barMaxWidth: null,
  29735. // 默认自适应
  29736. // barWidth: null,
  29737. // 柱间距离,默认为柱形宽度的30%,可设固定值
  29738. // barGap: '30%',
  29739. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  29740. // barCategoryGap: '20%',
  29741. // label: {
  29742. // show: false
  29743. // },
  29744. itemStyle: {},
  29745. emphasis: {}
  29746. }
  29747. });
  29748. BaseBarSeries.extend({
  29749. type: 'series.bar',
  29750. dependencies: ['grid', 'polar'],
  29751. brushSelector: 'rect'
  29752. });
  29753. function setLabel(
  29754. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  29755. ) {
  29756. var labelModel = itemModel.getModel('label');
  29757. var hoverLabelModel = itemModel.getModel('emphasis.label');
  29758. setLabelStyle(
  29759. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  29760. {
  29761. labelFetcher: seriesModel,
  29762. labelDataIndex: dataIndex,
  29763. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  29764. isRectText: true,
  29765. autoColor: color
  29766. }
  29767. );
  29768. fixPosition(normalStyle);
  29769. fixPosition(hoverStyle);
  29770. }
  29771. function fixPosition(style, labelPositionOutside) {
  29772. if (style.textPosition === 'outside') {
  29773. style.textPosition = labelPositionOutside;
  29774. }
  29775. }
  29776. var getBarItemStyle = makeStyleMapper(
  29777. [
  29778. ['fill', 'color'],
  29779. ['stroke', 'borderColor'],
  29780. ['lineWidth', 'borderWidth'],
  29781. // Compatitable with 2
  29782. ['stroke', 'barBorderColor'],
  29783. ['lineWidth', 'barBorderWidth'],
  29784. ['opacity'],
  29785. ['shadowBlur'],
  29786. ['shadowOffsetX'],
  29787. ['shadowOffsetY'],
  29788. ['shadowColor']
  29789. ]
  29790. );
  29791. var barItemStyle = {
  29792. getBarItemStyle: function (excludes) {
  29793. var style = getBarItemStyle(this, excludes);
  29794. if (this.getBorderLineDash) {
  29795. var lineDash = this.getBorderLineDash();
  29796. lineDash && (style.lineDash = lineDash);
  29797. }
  29798. return style;
  29799. }
  29800. };
  29801. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  29802. // FIXME
  29803. // Just for compatible with ec2.
  29804. extend(Model.prototype, barItemStyle);
  29805. extendChartView({
  29806. type: 'bar',
  29807. render: function (seriesModel, ecModel, api) {
  29808. var coordinateSystemType = seriesModel.get('coordinateSystem');
  29809. if (coordinateSystemType === 'cartesian2d'
  29810. || coordinateSystemType === 'polar'
  29811. ) {
  29812. this._render(seriesModel, ecModel, api);
  29813. }
  29814. else if (__DEV__) {
  29815. console.warn('Only cartesian2d and polar supported for bar.');
  29816. }
  29817. return this.group;
  29818. },
  29819. dispose: noop,
  29820. _render: function (seriesModel, ecModel, api) {
  29821. var group = this.group;
  29822. var data = seriesModel.getData();
  29823. var oldData = this._data;
  29824. var coord = seriesModel.coordinateSystem;
  29825. var baseAxis = coord.getBaseAxis();
  29826. var isHorizontalOrRadial;
  29827. if (coord.type === 'cartesian2d') {
  29828. isHorizontalOrRadial = baseAxis.isHorizontal();
  29829. }
  29830. else if (coord.type === 'polar') {
  29831. isHorizontalOrRadial = baseAxis.dim === 'angle';
  29832. }
  29833. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  29834. data.diff(oldData)
  29835. .add(function (dataIndex) {
  29836. if (!data.hasValue(dataIndex)) {
  29837. return;
  29838. }
  29839. var itemModel = data.getItemModel(dataIndex);
  29840. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  29841. var el = elementCreator[coord.type](
  29842. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  29843. );
  29844. data.setItemGraphicEl(dataIndex, el);
  29845. group.add(el);
  29846. updateStyle(
  29847. el, data, dataIndex, itemModel, layout,
  29848. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  29849. );
  29850. })
  29851. .update(function (newIndex, oldIndex) {
  29852. var el = oldData.getItemGraphicEl(oldIndex);
  29853. if (!data.hasValue(newIndex)) {
  29854. group.remove(el);
  29855. return;
  29856. }
  29857. var itemModel = data.getItemModel(newIndex);
  29858. var layout = getLayout[coord.type](data, newIndex, itemModel);
  29859. if (el) {
  29860. updateProps(el, {shape: layout}, animationModel, newIndex);
  29861. }
  29862. else {
  29863. el = elementCreator[coord.type](
  29864. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  29865. );
  29866. }
  29867. data.setItemGraphicEl(newIndex, el);
  29868. // Add back
  29869. group.add(el);
  29870. updateStyle(
  29871. el, data, newIndex, itemModel, layout,
  29872. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  29873. );
  29874. })
  29875. .remove(function (dataIndex) {
  29876. var el = oldData.getItemGraphicEl(dataIndex);
  29877. if (coord.type === 'cartesian2d') {
  29878. el && removeRect(dataIndex, animationModel, el);
  29879. }
  29880. else {
  29881. el && removeSector(dataIndex, animationModel, el);
  29882. }
  29883. })
  29884. .execute();
  29885. this._data = data;
  29886. },
  29887. remove: function (ecModel, api) {
  29888. var group = this.group;
  29889. var data = this._data;
  29890. if (ecModel.get('animation')) {
  29891. if (data) {
  29892. data.eachItemGraphicEl(function (el) {
  29893. if (el.type === 'sector') {
  29894. removeSector(el.dataIndex, ecModel, el);
  29895. }
  29896. else {
  29897. removeRect(el.dataIndex, ecModel, el);
  29898. }
  29899. });
  29900. }
  29901. }
  29902. else {
  29903. group.removeAll();
  29904. }
  29905. }
  29906. });
  29907. var elementCreator = {
  29908. cartesian2d: function (
  29909. data, dataIndex, itemModel, layout, isHorizontal,
  29910. animationModel, isUpdate
  29911. ) {
  29912. var rect = new Rect({shape: extend({}, layout)});
  29913. // Animation
  29914. if (animationModel) {
  29915. var rectShape = rect.shape;
  29916. var animateProperty = isHorizontal ? 'height' : 'width';
  29917. var animateTarget = {};
  29918. rectShape[animateProperty] = 0;
  29919. animateTarget[animateProperty] = layout[animateProperty];
  29920. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  29921. shape: animateTarget
  29922. }, animationModel, dataIndex);
  29923. }
  29924. return rect;
  29925. },
  29926. polar: function (
  29927. data, dataIndex, itemModel, layout, isRadial,
  29928. animationModel, isUpdate
  29929. ) {
  29930. var sector = new Sector({shape: extend({}, layout)});
  29931. // Animation
  29932. if (animationModel) {
  29933. var sectorShape = sector.shape;
  29934. var animateProperty = isRadial ? 'r' : 'endAngle';
  29935. var animateTarget = {};
  29936. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  29937. animateTarget[animateProperty] = layout[animateProperty];
  29938. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  29939. shape: animateTarget
  29940. }, animationModel, dataIndex);
  29941. }
  29942. return sector;
  29943. }
  29944. };
  29945. function removeRect(dataIndex, animationModel, el) {
  29946. // Not show text when animating
  29947. el.style.text = null;
  29948. updateProps(el, {
  29949. shape: {
  29950. width: 0
  29951. }
  29952. }, animationModel, dataIndex, function () {
  29953. el.parent && el.parent.remove(el);
  29954. });
  29955. }
  29956. function removeSector(dataIndex, animationModel, el) {
  29957. // Not show text when animating
  29958. el.style.text = null;
  29959. updateProps(el, {
  29960. shape: {
  29961. r: el.shape.r0
  29962. }
  29963. }, animationModel, dataIndex, function () {
  29964. el.parent && el.parent.remove(el);
  29965. });
  29966. }
  29967. var getLayout = {
  29968. cartesian2d: function (data, dataIndex, itemModel) {
  29969. var layout = data.getItemLayout(dataIndex);
  29970. var fixedLineWidth = getLineWidth(itemModel, layout);
  29971. // fix layout with lineWidth
  29972. var signX = layout.width > 0 ? 1 : -1;
  29973. var signY = layout.height > 0 ? 1 : -1;
  29974. return {
  29975. x: layout.x + signX * fixedLineWidth / 2,
  29976. y: layout.y + signY * fixedLineWidth / 2,
  29977. width: layout.width - signX * fixedLineWidth,
  29978. height: layout.height - signY * fixedLineWidth
  29979. };
  29980. },
  29981. polar: function (data, dataIndex, itemModel) {
  29982. var layout = data.getItemLayout(dataIndex);
  29983. return {
  29984. cx: layout.cx,
  29985. cy: layout.cy,
  29986. r0: layout.r0,
  29987. r: layout.r,
  29988. startAngle: layout.startAngle,
  29989. endAngle: layout.endAngle
  29990. };
  29991. }
  29992. };
  29993. function updateStyle(
  29994. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  29995. ) {
  29996. var color = data.getItemVisual(dataIndex, 'color');
  29997. var opacity = data.getItemVisual(dataIndex, 'opacity');
  29998. var itemStyleModel = itemModel.getModel('itemStyle');
  29999. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  30000. if (!isPolar) {
  30001. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  30002. }
  30003. el.useStyle(defaults(
  30004. {
  30005. fill: color,
  30006. opacity: opacity
  30007. },
  30008. itemStyleModel.getBarItemStyle()
  30009. ));
  30010. var cursorStyle = itemModel.getShallow('cursor');
  30011. cursorStyle && el.attr('cursor', cursorStyle);
  30012. var labelPositionOutside = isHorizontal
  30013. ? (layout.height > 0 ? 'bottom' : 'top')
  30014. : (layout.width > 0 ? 'left' : 'right');
  30015. if (!isPolar) {
  30016. setLabel(
  30017. el.style, hoverStyle, itemModel, color,
  30018. seriesModel, dataIndex, labelPositionOutside
  30019. );
  30020. }
  30021. setHoverStyle(el, hoverStyle);
  30022. }
  30023. // In case width or height are too small.
  30024. function getLineWidth(itemModel, rawLayout) {
  30025. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  30026. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  30027. }
  30028. // In case developer forget to include grid component
  30029. registerLayout(curry(layout, 'bar'));
  30030. // Visual coding for legend
  30031. registerVisual(function (ecModel) {
  30032. ecModel.eachSeriesByType('bar', function (seriesModel) {
  30033. var data = seriesModel.getData();
  30034. data.setVisual('legendSymbol', 'roundRect');
  30035. });
  30036. });
  30037. /**
  30038. * [Usage]:
  30039. * (1)
  30040. * createListSimply(seriesModel, ['value']);
  30041. * (2)
  30042. * createListSimply(seriesModel, {
  30043. * coordDimensions: ['value'],
  30044. * dimensionsCount: 5
  30045. * });
  30046. *
  30047. * @param {module:echarts/model/Series} seriesModel
  30048. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  30049. * The options in opt, see `echarts/data/helper/createDimensions`
  30050. * @param {Array.<string>} [nameList]
  30051. * @return {module:echarts/data/List}
  30052. */
  30053. var createListSimply = function (seriesModel, opt, nameList) {
  30054. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  30055. var source = seriesModel.getSource();
  30056. var dimensionsInfo = createDimensions(source, opt);
  30057. var list = new List(dimensionsInfo, seriesModel);
  30058. list.initData(source, nameList);
  30059. return list;
  30060. };
  30061. /**
  30062. * Data selectable mixin for chart series.
  30063. * To eanble data select, option of series must have `selectedMode`.
  30064. * And each data item will use `selected` to toggle itself selected status
  30065. */
  30066. var dataSelectableMixin = {
  30067. /**
  30068. * @param {Array.<Object>|module:echars/data/List} targetList
  30069. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  30070. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  30071. */
  30072. updateSelectedMap: function (targetList) {
  30073. if (isArray(targetList)) {
  30074. this._targetList = targetList.slice();
  30075. }
  30076. else {
  30077. var ecList = targetList;
  30078. var valueDim = ecList.mapDimension('value');
  30079. var targetList = this._targetList = [];
  30080. for (var i = 0, len = ecList.count(); i < len; i++) {
  30081. targetList.push({
  30082. name: ecList.getName(i),
  30083. value: ecList.get(valueDim, i),
  30084. selected: retrieveRawAttr(ecList, i, 'selected')
  30085. });
  30086. }
  30087. }
  30088. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  30089. targetMap.set(target.name, target);
  30090. return targetMap;
  30091. }, createHashMap());
  30092. },
  30093. /**
  30094. * Either name or id should be passed as input here.
  30095. * If both of them are defined, id is used.
  30096. *
  30097. * @param {string|undefined} name name of data
  30098. * @param {number|undefined} id dataIndex of data
  30099. */
  30100. // PENGING If selectedMode is null ?
  30101. select: function (name, id) {
  30102. var target = id != null
  30103. ? this._targetList[id]
  30104. : this._selectTargetMap.get(name);
  30105. var selectedMode = this.get('selectedMode');
  30106. if (selectedMode === 'single') {
  30107. this._selectTargetMap.each(function (target) {
  30108. target.selected = false;
  30109. });
  30110. }
  30111. target && (target.selected = true);
  30112. },
  30113. /**
  30114. * Either name or id should be passed as input here.
  30115. * If both of them are defined, id is used.
  30116. *
  30117. * @param {string|undefined} name name of data
  30118. * @param {number|undefined} id dataIndex of data
  30119. */
  30120. unSelect: function (name, id) {
  30121. var target = id != null
  30122. ? this._targetList[id]
  30123. : this._selectTargetMap.get(name);
  30124. // var selectedMode = this.get('selectedMode');
  30125. // selectedMode !== 'single' && target && (target.selected = false);
  30126. target && (target.selected = false);
  30127. },
  30128. /**
  30129. * Either name or id should be passed as input here.
  30130. * If both of them are defined, id is used.
  30131. *
  30132. * @param {string|undefined} name name of data
  30133. * @param {number|undefined} id dataIndex of data
  30134. */
  30135. toggleSelected: function (name, id) {
  30136. var target = id != null
  30137. ? this._targetList[id]
  30138. : this._selectTargetMap.get(name);
  30139. if (target != null) {
  30140. this[target.selected ? 'unSelect' : 'select'](name, id);
  30141. return target.selected;
  30142. }
  30143. },
  30144. /**
  30145. * Either name or id should be passed as input here.
  30146. * If both of them are defined, id is used.
  30147. *
  30148. * @param {string|undefined} name name of data
  30149. * @param {number|undefined} id dataIndex of data
  30150. */
  30151. isSelected: function (name, id) {
  30152. var target = id != null
  30153. ? this._targetList[id]
  30154. : this._selectTargetMap.get(name);
  30155. return target && target.selected;
  30156. }
  30157. };
  30158. var PieSeries = extendSeriesModel({
  30159. type: 'series.pie',
  30160. // Overwrite
  30161. init: function (option) {
  30162. PieSeries.superApply(this, 'init', arguments);
  30163. // Enable legend selection for each data item
  30164. // Use a function instead of direct access because data reference may changed
  30165. this.legendDataProvider = function () {
  30166. return this.getRawData();
  30167. };
  30168. this.updateSelectedMap(this.getRawData());
  30169. this._defaultLabelLine(option);
  30170. },
  30171. // Overwrite
  30172. mergeOption: function (newOption) {
  30173. PieSeries.superCall(this, 'mergeOption', newOption);
  30174. this.updateSelectedMap(this.getRawData());
  30175. },
  30176. getInitialData: function (option, ecModel) {
  30177. return createListSimply(this, ['value']);
  30178. },
  30179. // Overwrite
  30180. getDataParams: function (dataIndex) {
  30181. var data = this.getData();
  30182. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  30183. // FIXME toFixed?
  30184. var valueList = [];
  30185. data.each(data.mapDimension('value'), function (value) {
  30186. valueList.push(value);
  30187. });
  30188. params.percent = getPercentWithPrecision(
  30189. valueList,
  30190. dataIndex,
  30191. data.hostModel.get('percentPrecision')
  30192. );
  30193. params.$vars.push('percent');
  30194. return params;
  30195. },
  30196. _defaultLabelLine: function (option) {
  30197. // Extend labelLine emphasis
  30198. defaultEmphasis(option, 'labelLine', ['show']);
  30199. var labelLineNormalOpt = option.labelLine;
  30200. var labelLineEmphasisOpt = option.emphasis.labelLine;
  30201. // Not show label line if `label.normal.show = false`
  30202. labelLineNormalOpt.show = labelLineNormalOpt.show
  30203. && option.label.show;
  30204. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  30205. && option.emphasis.label.show;
  30206. },
  30207. defaultOption: {
  30208. zlevel: 0,
  30209. z: 2,
  30210. legendHoverLink: true,
  30211. hoverAnimation: true,
  30212. // 默认全局居中
  30213. center: ['50%', '50%'],
  30214. radius: [0, '75%'],
  30215. // 默认顺时针
  30216. clockwise: true,
  30217. startAngle: 90,
  30218. // 最小角度改为0
  30219. minAngle: 0,
  30220. // 选中时扇区偏移量
  30221. selectedOffset: 10,
  30222. // 高亮扇区偏移量
  30223. hoverOffset: 10,
  30224. // If use strategy to avoid label overlapping
  30225. avoidLabelOverlap: true,
  30226. // 选择模式,默认关闭,可选single,multiple
  30227. // selectedMode: false,
  30228. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  30229. // roseType: null,
  30230. percentPrecision: 2,
  30231. // If still show when all data zero.
  30232. stillShowZeroSum: true,
  30233. // cursor: null,
  30234. label: {
  30235. // If rotate around circle
  30236. rotate: false,
  30237. show: true,
  30238. // 'outer', 'inside', 'center'
  30239. position: 'outer'
  30240. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  30241. // 默认使用全局文本样式,详见TEXTSTYLE
  30242. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  30243. },
  30244. // Enabled when label.normal.position is 'outer'
  30245. labelLine: {
  30246. show: true,
  30247. // 引导线两段中的第一段长度
  30248. length: 15,
  30249. // 引导线两段中的第二段长度
  30250. length2: 15,
  30251. smooth: false,
  30252. lineStyle: {
  30253. // color: 各异,
  30254. width: 1,
  30255. type: 'solid'
  30256. }
  30257. },
  30258. itemStyle: {
  30259. borderWidth: 1
  30260. },
  30261. // Animation type canbe expansion, scale
  30262. animationType: 'expansion',
  30263. animationEasing: 'cubicOut'
  30264. }
  30265. });
  30266. mixin(PieSeries, dataSelectableMixin);
  30267. /**
  30268. * @param {module:echarts/model/Series} seriesModel
  30269. * @param {boolean} hasAnimation
  30270. * @inner
  30271. */
  30272. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  30273. var data = seriesModel.getData();
  30274. var dataIndex = this.dataIndex;
  30275. var name = data.getName(dataIndex);
  30276. var selectedOffset = seriesModel.get('selectedOffset');
  30277. api.dispatchAction({
  30278. type: 'pieToggleSelect',
  30279. from: uid,
  30280. name: name,
  30281. seriesId: seriesModel.id
  30282. });
  30283. data.each(function (idx) {
  30284. toggleItemSelected(
  30285. data.getItemGraphicEl(idx),
  30286. data.getItemLayout(idx),
  30287. seriesModel.isSelected(data.getName(idx)),
  30288. selectedOffset,
  30289. hasAnimation
  30290. );
  30291. });
  30292. }
  30293. /**
  30294. * @param {module:zrender/graphic/Sector} el
  30295. * @param {Object} layout
  30296. * @param {boolean} isSelected
  30297. * @param {number} selectedOffset
  30298. * @param {boolean} hasAnimation
  30299. * @inner
  30300. */
  30301. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  30302. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  30303. var dx = Math.cos(midAngle);
  30304. var dy = Math.sin(midAngle);
  30305. var offset = isSelected ? selectedOffset : 0;
  30306. var position = [dx * offset, dy * offset];
  30307. hasAnimation
  30308. // animateTo will stop revious animation like update transition
  30309. ? el.animate()
  30310. .when(200, {
  30311. position: position
  30312. })
  30313. .start('bounceOut')
  30314. : el.attr('position', position);
  30315. }
  30316. /**
  30317. * Piece of pie including Sector, Label, LabelLine
  30318. * @constructor
  30319. * @extends {module:zrender/graphic/Group}
  30320. */
  30321. function PiePiece(data, idx) {
  30322. Group.call(this);
  30323. var sector = new Sector({
  30324. z2: 2
  30325. });
  30326. var polyline = new Polyline();
  30327. var text = new Text();
  30328. this.add(sector);
  30329. this.add(polyline);
  30330. this.add(text);
  30331. this.updateData(data, idx, true);
  30332. // Hover to change label and labelLine
  30333. function onEmphasis() {
  30334. polyline.ignore = polyline.hoverIgnore;
  30335. text.ignore = text.hoverIgnore;
  30336. }
  30337. function onNormal() {
  30338. polyline.ignore = polyline.normalIgnore;
  30339. text.ignore = text.normalIgnore;
  30340. }
  30341. this.on('emphasis', onEmphasis)
  30342. .on('normal', onNormal)
  30343. .on('mouseover', onEmphasis)
  30344. .on('mouseout', onNormal);
  30345. }
  30346. var piePieceProto = PiePiece.prototype;
  30347. piePieceProto.updateData = function (data, idx, firstCreate) {
  30348. var sector = this.childAt(0);
  30349. var seriesModel = data.hostModel;
  30350. var itemModel = data.getItemModel(idx);
  30351. var layout = data.getItemLayout(idx);
  30352. var sectorShape = extend({}, layout);
  30353. sectorShape.label = null;
  30354. if (firstCreate) {
  30355. sector.setShape(sectorShape);
  30356. var animationType = seriesModel.getShallow('animationType');
  30357. if (animationType === 'scale') {
  30358. sector.shape.r = layout.r0;
  30359. initProps(sector, {
  30360. shape: {
  30361. r: layout.r
  30362. }
  30363. }, seriesModel, idx);
  30364. }
  30365. // Expansion
  30366. else {
  30367. sector.shape.endAngle = layout.startAngle;
  30368. updateProps(sector, {
  30369. shape: {
  30370. endAngle: layout.endAngle
  30371. }
  30372. }, seriesModel, idx);
  30373. }
  30374. }
  30375. else {
  30376. updateProps(sector, {
  30377. shape: sectorShape
  30378. }, seriesModel, idx);
  30379. }
  30380. // Update common style
  30381. var visualColor = data.getItemVisual(idx, 'color');
  30382. sector.useStyle(
  30383. defaults(
  30384. {
  30385. lineJoin: 'bevel',
  30386. fill: visualColor
  30387. },
  30388. itemModel.getModel('itemStyle').getItemStyle()
  30389. )
  30390. );
  30391. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  30392. var cursorStyle = itemModel.getShallow('cursor');
  30393. cursorStyle && sector.attr('cursor', cursorStyle);
  30394. // Toggle selected
  30395. toggleItemSelected(
  30396. this,
  30397. data.getItemLayout(idx),
  30398. seriesModel.isSelected(null, idx),
  30399. seriesModel.get('selectedOffset'),
  30400. seriesModel.get('animation')
  30401. );
  30402. function onEmphasis() {
  30403. // Sector may has animation of updating data. Force to move to the last frame
  30404. // Or it may stopped on the wrong shape
  30405. sector.stopAnimation(true);
  30406. sector.animateTo({
  30407. shape: {
  30408. r: layout.r + seriesModel.get('hoverOffset')
  30409. }
  30410. }, 300, 'elasticOut');
  30411. }
  30412. function onNormal() {
  30413. sector.stopAnimation(true);
  30414. sector.animateTo({
  30415. shape: {
  30416. r: layout.r
  30417. }
  30418. }, 300, 'elasticOut');
  30419. }
  30420. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  30421. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  30422. sector
  30423. .on('mouseover', onEmphasis)
  30424. .on('mouseout', onNormal)
  30425. .on('emphasis', onEmphasis)
  30426. .on('normal', onNormal);
  30427. }
  30428. this._updateLabel(data, idx);
  30429. setHoverStyle(this);
  30430. };
  30431. piePieceProto._updateLabel = function (data, idx) {
  30432. var labelLine = this.childAt(1);
  30433. var labelText = this.childAt(2);
  30434. var seriesModel = data.hostModel;
  30435. var itemModel = data.getItemModel(idx);
  30436. var layout = data.getItemLayout(idx);
  30437. var labelLayout = layout.label;
  30438. var visualColor = data.getItemVisual(idx, 'color');
  30439. updateProps(labelLine, {
  30440. shape: {
  30441. points: labelLayout.linePoints || [
  30442. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  30443. ]
  30444. }
  30445. }, seriesModel, idx);
  30446. updateProps(labelText, {
  30447. style: {
  30448. x: labelLayout.x,
  30449. y: labelLayout.y
  30450. }
  30451. }, seriesModel, idx);
  30452. labelText.attr({
  30453. rotation: labelLayout.rotation,
  30454. origin: [labelLayout.x, labelLayout.y],
  30455. z2: 10
  30456. });
  30457. var labelModel = itemModel.getModel('label');
  30458. var labelHoverModel = itemModel.getModel('emphasis.label');
  30459. var labelLineModel = itemModel.getModel('labelLine');
  30460. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  30461. var visualColor = data.getItemVisual(idx, 'color');
  30462. setLabelStyle(
  30463. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  30464. {
  30465. labelFetcher: data.hostModel,
  30466. labelDataIndex: idx,
  30467. defaultText: data.getName(idx),
  30468. autoColor: visualColor,
  30469. useInsideStyle: !!labelLayout.inside
  30470. },
  30471. {
  30472. textAlign: labelLayout.textAlign,
  30473. textVerticalAlign: labelLayout.verticalAlign,
  30474. opacity: data.getItemVisual(idx, 'opacity')
  30475. }
  30476. );
  30477. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  30478. labelText.hoverIgnore = !labelHoverModel.get('show');
  30479. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  30480. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  30481. // Default use item visual color
  30482. labelLine.setStyle({
  30483. stroke: visualColor,
  30484. opacity: data.getItemVisual(idx, 'opacity')
  30485. });
  30486. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  30487. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  30488. var smooth = labelLineModel.get('smooth');
  30489. if (smooth && smooth === true) {
  30490. smooth = 0.4;
  30491. }
  30492. labelLine.setShape({
  30493. smooth: smooth
  30494. });
  30495. };
  30496. inherits(PiePiece, Group);
  30497. // Pie view
  30498. var PieView = Chart.extend({
  30499. type: 'pie',
  30500. init: function () {
  30501. var sectorGroup = new Group();
  30502. this._sectorGroup = sectorGroup;
  30503. },
  30504. render: function (seriesModel, ecModel, api, payload) {
  30505. if (payload && (payload.from === this.uid)) {
  30506. return;
  30507. }
  30508. var data = seriesModel.getData();
  30509. var oldData = this._data;
  30510. var group = this.group;
  30511. var hasAnimation = ecModel.get('animation');
  30512. var isFirstRender = !oldData;
  30513. var animationType = seriesModel.get('animationType');
  30514. var onSectorClick = curry(
  30515. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  30516. );
  30517. var selectedMode = seriesModel.get('selectedMode');
  30518. data.diff(oldData)
  30519. .add(function (idx) {
  30520. var piePiece = new PiePiece(data, idx);
  30521. // Default expansion animation
  30522. if (isFirstRender && animationType !== 'scale') {
  30523. piePiece.eachChild(function (child) {
  30524. child.stopAnimation(true);
  30525. });
  30526. }
  30527. selectedMode && piePiece.on('click', onSectorClick);
  30528. data.setItemGraphicEl(idx, piePiece);
  30529. group.add(piePiece);
  30530. })
  30531. .update(function (newIdx, oldIdx) {
  30532. var piePiece = oldData.getItemGraphicEl(oldIdx);
  30533. piePiece.updateData(data, newIdx);
  30534. piePiece.off('click');
  30535. selectedMode && piePiece.on('click', onSectorClick);
  30536. group.add(piePiece);
  30537. data.setItemGraphicEl(newIdx, piePiece);
  30538. })
  30539. .remove(function (idx) {
  30540. var piePiece = oldData.getItemGraphicEl(idx);
  30541. group.remove(piePiece);
  30542. })
  30543. .execute();
  30544. if (
  30545. hasAnimation && isFirstRender && data.count() > 0
  30546. // Default expansion animation
  30547. && animationType !== 'scale'
  30548. ) {
  30549. var shape = data.getItemLayout(0);
  30550. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  30551. var removeClipPath = bind(group.removeClipPath, group);
  30552. group.setClipPath(this._createClipPath(
  30553. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  30554. ));
  30555. }
  30556. this._data = data;
  30557. },
  30558. dispose: function () {},
  30559. _createClipPath: function (
  30560. cx, cy, r, startAngle, clockwise, cb, seriesModel
  30561. ) {
  30562. var clipPath = new Sector({
  30563. shape: {
  30564. cx: cx,
  30565. cy: cy,
  30566. r0: 0,
  30567. r: r,
  30568. startAngle: startAngle,
  30569. endAngle: startAngle,
  30570. clockwise: clockwise
  30571. }
  30572. });
  30573. initProps(clipPath, {
  30574. shape: {
  30575. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  30576. }
  30577. }, seriesModel, cb);
  30578. return clipPath;
  30579. },
  30580. /**
  30581. * @implement
  30582. */
  30583. containPoint: function (point, seriesModel) {
  30584. var data = seriesModel.getData();
  30585. var itemLayout = data.getItemLayout(0);
  30586. if (itemLayout) {
  30587. var dx = point[0] - itemLayout.cx;
  30588. var dy = point[1] - itemLayout.cy;
  30589. var radius = Math.sqrt(dx * dx + dy * dy);
  30590. return radius <= itemLayout.r && radius >= itemLayout.r0;
  30591. }
  30592. }
  30593. });
  30594. var createDataSelectAction = function (seriesType, actionInfos) {
  30595. each$1(actionInfos, function (actionInfo) {
  30596. actionInfo.update = 'updateView';
  30597. /**
  30598. * @payload
  30599. * @property {string} seriesName
  30600. * @property {string} name
  30601. */
  30602. registerAction(actionInfo, function (payload, ecModel) {
  30603. var selected = {};
  30604. ecModel.eachComponent(
  30605. {mainType: 'series', subType: seriesType, query: payload},
  30606. function (seriesModel) {
  30607. if (seriesModel[actionInfo.method]) {
  30608. seriesModel[actionInfo.method](
  30609. payload.name,
  30610. payload.dataIndex
  30611. );
  30612. }
  30613. var data = seriesModel.getData();
  30614. // Create selected map
  30615. data.each(function (idx) {
  30616. var name = data.getName(idx);
  30617. selected[name] = seriesModel.isSelected(name)
  30618. || false;
  30619. });
  30620. }
  30621. );
  30622. return {
  30623. name: payload.name,
  30624. selected: selected
  30625. };
  30626. });
  30627. });
  30628. };
  30629. // Pick color from palette for each data item.
  30630. // Applicable for charts that require applying color palette
  30631. // in data level (like pie, funnel, chord).
  30632. var dataColor = function (seriesType) {
  30633. return {
  30634. getTargetSeries: function (ecModel) {
  30635. // Pie and funnel may use diferrent scope
  30636. var paletteScope = {};
  30637. var seiresModelMap = createHashMap();
  30638. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30639. seriesModel.__paletteScope = paletteScope;
  30640. seiresModelMap.set(seriesModel.uid, seriesModel);
  30641. });
  30642. return seiresModelMap;
  30643. },
  30644. reset: function (seriesModel, ecModel) {
  30645. var dataAll = seriesModel.getRawData();
  30646. var idxMap = {};
  30647. var data = seriesModel.getData();
  30648. data.each(function (idx) {
  30649. var rawIdx = data.getRawIndex(idx);
  30650. idxMap[rawIdx] = idx;
  30651. });
  30652. dataAll.each(function (rawIdx) {
  30653. var filteredIdx = idxMap[rawIdx];
  30654. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  30655. var singleDataColor = filteredIdx != null
  30656. && data.getItemVisual(filteredIdx, 'color', true);
  30657. if (!singleDataColor) {
  30658. // FIXME Performance
  30659. var itemModel = dataAll.getItemModel(rawIdx);
  30660. var color = itemModel.get('itemStyle.color')
  30661. || seriesModel.getColorFromPalette(
  30662. dataAll.getName(rawIdx), seriesModel.__paletteScope,
  30663. dataAll.count()
  30664. );
  30665. // Legend may use the visual info in data before processed
  30666. dataAll.setItemVisual(rawIdx, 'color', color);
  30667. // Data is not filtered
  30668. if (filteredIdx != null) {
  30669. data.setItemVisual(filteredIdx, 'color', color);
  30670. }
  30671. }
  30672. else {
  30673. // Set data all color for legend
  30674. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  30675. }
  30676. });
  30677. }
  30678. };
  30679. };
  30680. // FIXME emphasis label position is not same with normal label position
  30681. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  30682. list.sort(function (a, b) {
  30683. return a.y - b.y;
  30684. });
  30685. // 压
  30686. function shiftDown(start, end, delta, dir) {
  30687. for (var j = start; j < end; j++) {
  30688. list[j].y += delta;
  30689. if (j > start
  30690. && j + 1 < end
  30691. && list[j + 1].y > list[j].y + list[j].height
  30692. ) {
  30693. shiftUp(j, delta / 2);
  30694. return;
  30695. }
  30696. }
  30697. shiftUp(end - 1, delta / 2);
  30698. }
  30699. // 弹
  30700. function shiftUp(end, delta) {
  30701. for (var j = end; j >= 0; j--) {
  30702. list[j].y -= delta;
  30703. if (j > 0
  30704. && list[j].y > list[j - 1].y + list[j - 1].height
  30705. ) {
  30706. break;
  30707. }
  30708. }
  30709. }
  30710. function changeX(list, isDownList, cx, cy, r, dir) {
  30711. var lastDeltaX = dir > 0
  30712. ? isDownList // 右侧
  30713. ? Number.MAX_VALUE // 下
  30714. : 0 // 上
  30715. : isDownList // 左侧
  30716. ? Number.MAX_VALUE // 下
  30717. : 0; // 上
  30718. for (var i = 0, l = list.length; i < l; i++) {
  30719. // Not change x for center label
  30720. if (list[i].position === 'center') {
  30721. continue;
  30722. }
  30723. var deltaY = Math.abs(list[i].y - cy);
  30724. var length = list[i].len;
  30725. var length2 = list[i].len2;
  30726. var deltaX = (deltaY < r + length)
  30727. ? Math.sqrt(
  30728. (r + length + length2) * (r + length + length2)
  30729. - deltaY * deltaY
  30730. )
  30731. : Math.abs(list[i].x - cx);
  30732. if (isDownList && deltaX >= lastDeltaX) {
  30733. // 右下,左下
  30734. deltaX = lastDeltaX - 10;
  30735. }
  30736. if (!isDownList && deltaX <= lastDeltaX) {
  30737. // 右上,左上
  30738. deltaX = lastDeltaX + 10;
  30739. }
  30740. list[i].x = cx + deltaX * dir;
  30741. lastDeltaX = deltaX;
  30742. }
  30743. }
  30744. var lastY = 0;
  30745. var delta;
  30746. var len = list.length;
  30747. var upList = [];
  30748. var downList = [];
  30749. for (var i = 0; i < len; i++) {
  30750. delta = list[i].y - lastY;
  30751. if (delta < 0) {
  30752. shiftDown(i, len, -delta, dir);
  30753. }
  30754. lastY = list[i].y + list[i].height;
  30755. }
  30756. if (viewHeight - lastY < 0) {
  30757. shiftUp(len - 1, lastY - viewHeight);
  30758. }
  30759. for (var i = 0; i < len; i++) {
  30760. if (list[i].y >= cy) {
  30761. downList.push(list[i]);
  30762. }
  30763. else {
  30764. upList.push(list[i]);
  30765. }
  30766. }
  30767. changeX(upList, false, cx, cy, r, dir);
  30768. changeX(downList, true, cx, cy, r, dir);
  30769. }
  30770. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  30771. var leftList = [];
  30772. var rightList = [];
  30773. for (var i = 0; i < labelLayoutList.length; i++) {
  30774. if (labelLayoutList[i].x < cx) {
  30775. leftList.push(labelLayoutList[i]);
  30776. }
  30777. else {
  30778. rightList.push(labelLayoutList[i]);
  30779. }
  30780. }
  30781. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  30782. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  30783. for (var i = 0; i < labelLayoutList.length; i++) {
  30784. var linePoints = labelLayoutList[i].linePoints;
  30785. if (linePoints) {
  30786. var dist = linePoints[1][0] - linePoints[2][0];
  30787. if (labelLayoutList[i].x < cx) {
  30788. linePoints[2][0] = labelLayoutList[i].x + 3;
  30789. }
  30790. else {
  30791. linePoints[2][0] = labelLayoutList[i].x - 3;
  30792. }
  30793. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  30794. linePoints[1][0] = linePoints[2][0] + dist;
  30795. }
  30796. }
  30797. }
  30798. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  30799. var data = seriesModel.getData();
  30800. var labelLayoutList = [];
  30801. var cx;
  30802. var cy;
  30803. var hasLabelRotate = false;
  30804. data.each(function (idx) {
  30805. var layout = data.getItemLayout(idx);
  30806. var itemModel = data.getItemModel(idx);
  30807. var labelModel = itemModel.getModel('label');
  30808. // Use position in normal or emphasis
  30809. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  30810. var labelLineModel = itemModel.getModel('labelLine');
  30811. var labelLineLen = labelLineModel.get('length');
  30812. var labelLineLen2 = labelLineModel.get('length2');
  30813. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  30814. var dx = Math.cos(midAngle);
  30815. var dy = Math.sin(midAngle);
  30816. var textX;
  30817. var textY;
  30818. var linePoints;
  30819. var textAlign;
  30820. cx = layout.cx;
  30821. cy = layout.cy;
  30822. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  30823. if (labelPosition === 'center') {
  30824. textX = layout.cx;
  30825. textY = layout.cy;
  30826. textAlign = 'center';
  30827. }
  30828. else {
  30829. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  30830. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  30831. textX = x1 + dx * 3;
  30832. textY = y1 + dy * 3;
  30833. if (!isLabelInside) {
  30834. // For roseType
  30835. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  30836. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  30837. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  30838. var y3 = y2;
  30839. textX = x3 + (dx < 0 ? -5 : 5);
  30840. textY = y3;
  30841. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  30842. }
  30843. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  30844. }
  30845. var font = labelModel.getFont();
  30846. var labelRotate = labelModel.get('rotate')
  30847. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  30848. var text = seriesModel.getFormattedLabel(idx, 'normal')
  30849. || data.getName(idx);
  30850. var textRect = getBoundingRect(
  30851. text, font, textAlign, 'top'
  30852. );
  30853. hasLabelRotate = !!labelRotate;
  30854. layout.label = {
  30855. x: textX,
  30856. y: textY,
  30857. position: labelPosition,
  30858. height: textRect.height,
  30859. len: labelLineLen,
  30860. len2: labelLineLen2,
  30861. linePoints: linePoints,
  30862. textAlign: textAlign,
  30863. verticalAlign: 'middle',
  30864. rotation: labelRotate,
  30865. inside: isLabelInside
  30866. };
  30867. // Not layout the inside label
  30868. if (!isLabelInside) {
  30869. labelLayoutList.push(layout.label);
  30870. }
  30871. });
  30872. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  30873. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  30874. }
  30875. };
  30876. var PI2$4 = Math.PI * 2;
  30877. var RADIAN = Math.PI / 180;
  30878. var pieLayout = function (seriesType, ecModel, api, payload) {
  30879. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30880. var data = seriesModel.getData();
  30881. var valueDim = data.mapDimension('value');
  30882. var center = seriesModel.get('center');
  30883. var radius = seriesModel.get('radius');
  30884. if (!isArray(radius)) {
  30885. radius = [0, radius];
  30886. }
  30887. if (!isArray(center)) {
  30888. center = [center, center];
  30889. }
  30890. var width = api.getWidth();
  30891. var height = api.getHeight();
  30892. var size = Math.min(width, height);
  30893. var cx = parsePercent$1(center[0], width);
  30894. var cy = parsePercent$1(center[1], height);
  30895. var r0 = parsePercent$1(radius[0], size / 2);
  30896. var r = parsePercent$1(radius[1], size / 2);
  30897. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  30898. var minAngle = seriesModel.get('minAngle') * RADIAN;
  30899. var validDataCount = 0;
  30900. data.each(valueDim, function (value) {
  30901. !isNaN(value) && validDataCount++;
  30902. });
  30903. var sum = data.getSum(valueDim);
  30904. // Sum may be 0
  30905. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  30906. var clockwise = seriesModel.get('clockwise');
  30907. var roseType = seriesModel.get('roseType');
  30908. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  30909. // [0...max]
  30910. var extent = data.getDataExtent(valueDim);
  30911. extent[0] = 0;
  30912. // In the case some sector angle is smaller than minAngle
  30913. var restAngle = PI2$4;
  30914. var valueSumLargerThanMinAngle = 0;
  30915. var currentAngle = startAngle;
  30916. var dir = clockwise ? 1 : -1;
  30917. data.each(valueDim, function (value, idx) {
  30918. var angle;
  30919. if (isNaN(value)) {
  30920. data.setItemLayout(idx, {
  30921. angle: NaN,
  30922. startAngle: NaN,
  30923. endAngle: NaN,
  30924. clockwise: clockwise,
  30925. cx: cx,
  30926. cy: cy,
  30927. r0: r0,
  30928. r: roseType
  30929. ? NaN
  30930. : r
  30931. });
  30932. return;
  30933. }
  30934. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  30935. if (roseType !== 'area') {
  30936. angle = (sum === 0 && stillShowZeroSum)
  30937. ? unitRadian : (value * unitRadian);
  30938. }
  30939. else {
  30940. angle = PI2$4 / validDataCount;
  30941. }
  30942. if (angle < minAngle) {
  30943. angle = minAngle;
  30944. restAngle -= minAngle;
  30945. }
  30946. else {
  30947. valueSumLargerThanMinAngle += value;
  30948. }
  30949. var endAngle = currentAngle + dir * angle;
  30950. data.setItemLayout(idx, {
  30951. angle: angle,
  30952. startAngle: currentAngle,
  30953. endAngle: endAngle,
  30954. clockwise: clockwise,
  30955. cx: cx,
  30956. cy: cy,
  30957. r0: r0,
  30958. r: roseType
  30959. ? linearMap(value, extent, [r0, r])
  30960. : r
  30961. });
  30962. currentAngle = endAngle;
  30963. }, true);
  30964. // Some sector is constrained by minAngle
  30965. // Rest sectors needs recalculate angle
  30966. if (restAngle < PI2$4 && validDataCount) {
  30967. // Average the angle if rest angle is not enough after all angles is
  30968. // Constrained by minAngle
  30969. if (restAngle <= 1e-3) {
  30970. var angle = PI2$4 / validDataCount;
  30971. data.each(valueDim, function (value, idx) {
  30972. if (!isNaN(value)) {
  30973. var layout = data.getItemLayout(idx);
  30974. layout.angle = angle;
  30975. layout.startAngle = startAngle + dir * idx * angle;
  30976. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  30977. }
  30978. });
  30979. }
  30980. else {
  30981. unitRadian = restAngle / valueSumLargerThanMinAngle;
  30982. currentAngle = startAngle;
  30983. data.each(valueDim, function (value, idx) {
  30984. if (!isNaN(value)) {
  30985. var layout = data.getItemLayout(idx);
  30986. var angle = layout.angle === minAngle
  30987. ? minAngle : value * unitRadian;
  30988. layout.startAngle = currentAngle;
  30989. layout.endAngle = currentAngle + dir * angle;
  30990. currentAngle += dir * angle;
  30991. }
  30992. });
  30993. }
  30994. }
  30995. labelLayout(seriesModel, r, width, height);
  30996. });
  30997. };
  30998. var dataFilter = function (seriesType) {
  30999. return {
  31000. seriesType: seriesType,
  31001. reset: function (seriesModel, ecModel) {
  31002. var legendModels = ecModel.findComponents({
  31003. mainType: 'legend'
  31004. });
  31005. if (!legendModels || !legendModels.length) {
  31006. return;
  31007. }
  31008. var data = seriesModel.getData();
  31009. data.filterSelf(function (idx) {
  31010. var name = data.getName(idx);
  31011. // If in any legend component the status is not selected.
  31012. for (var i = 0; i < legendModels.length; i++) {
  31013. if (!legendModels[i].isSelected(name)) {
  31014. return false;
  31015. }
  31016. }
  31017. return true;
  31018. }, this);
  31019. }
  31020. };
  31021. };
  31022. createDataSelectAction('pie', [{
  31023. type: 'pieToggleSelect',
  31024. event: 'pieselectchanged',
  31025. method: 'toggleSelected'
  31026. }, {
  31027. type: 'pieSelect',
  31028. event: 'pieselected',
  31029. method: 'select'
  31030. }, {
  31031. type: 'pieUnSelect',
  31032. event: 'pieunselected',
  31033. method: 'unSelect'
  31034. }]);
  31035. registerVisual(dataColor('pie'));
  31036. registerLayout(curry(pieLayout, 'pie'));
  31037. registerProcessor(dataFilter('pie'));
  31038. exports.version = version;
  31039. exports.dependencies = dependencies;
  31040. exports.PRIORITY = PRIORITY;
  31041. exports.init = init;
  31042. exports.connect = connect;
  31043. exports.disConnect = disConnect;
  31044. exports.disconnect = disconnect;
  31045. exports.dispose = dispose;
  31046. exports.getInstanceByDom = getInstanceByDom;
  31047. exports.getInstanceById = getInstanceById;
  31048. exports.registerTheme = registerTheme;
  31049. exports.registerPreprocessor = registerPreprocessor;
  31050. exports.registerProcessor = registerProcessor;
  31051. exports.registerPostUpdate = registerPostUpdate;
  31052. exports.registerAction = registerAction;
  31053. exports.registerCoordinateSystem = registerCoordinateSystem;
  31054. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  31055. exports.registerLayout = registerLayout;
  31056. exports.registerVisual = registerVisual;
  31057. exports.registerLoading = registerLoading;
  31058. exports.extendComponentModel = extendComponentModel;
  31059. exports.extendComponentView = extendComponentView;
  31060. exports.extendSeriesModel = extendSeriesModel;
  31061. exports.extendChartView = extendChartView;
  31062. exports.setCanvasCreator = setCanvasCreator;
  31063. exports.registerMap = registerMap;
  31064. exports.getMap = getMap;
  31065. exports.dataTool = dataTool;
  31066. })));