echarts.simple.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. /**
  575. * @memberOf module:zrender/core/util
  576. * @param {Function} func
  577. * @param {*} context
  578. * @return {Function}
  579. */
  580. function bind(func, context) {
  581. var args = nativeSlice.call(arguments, 2);
  582. return function () {
  583. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  584. };
  585. }
  586. /**
  587. * @memberOf module:zrender/core/util
  588. * @param {Function} func
  589. * @return {Function}
  590. */
  591. function curry(func) {
  592. var args = nativeSlice.call(arguments, 1);
  593. return function () {
  594. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  595. };
  596. }
  597. /**
  598. * @memberOf module:zrender/core/util
  599. * @param {*} value
  600. * @return {boolean}
  601. */
  602. function isArray(value) {
  603. return objToString.call(value) === '[object Array]';
  604. }
  605. /**
  606. * @memberOf module:zrender/core/util
  607. * @param {*} value
  608. * @return {boolean}
  609. */
  610. function isFunction$1(value) {
  611. return typeof value === 'function';
  612. }
  613. /**
  614. * @memberOf module:zrender/core/util
  615. * @param {*} value
  616. * @return {boolean}
  617. */
  618. function isString(value) {
  619. return objToString.call(value) === '[object String]';
  620. }
  621. /**
  622. * @memberOf module:zrender/core/util
  623. * @param {*} value
  624. * @return {boolean}
  625. */
  626. function isObject$1(value) {
  627. // Avoid a V8 JIT bug in Chrome 19-20.
  628. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  629. var type = typeof value;
  630. return type === 'function' || (!!value && type === 'object');
  631. }
  632. /**
  633. * @memberOf module:zrender/core/util
  634. * @param {*} value
  635. * @return {boolean}
  636. */
  637. function isBuiltInObject(value) {
  638. return !!BUILTIN_OBJECT[objToString.call(value)];
  639. }
  640. /**
  641. * @memberOf module:zrender/core/util
  642. * @param {*} value
  643. * @return {boolean}
  644. */
  645. function isTypedArray(value) {
  646. return !!TYPED_ARRAY[objToString.call(value)];
  647. }
  648. /**
  649. * @memberOf module:zrender/core/util
  650. * @param {*} value
  651. * @return {boolean}
  652. */
  653. function isDom(value) {
  654. return typeof value === 'object'
  655. && typeof value.nodeType === 'number'
  656. && typeof value.ownerDocument === 'object';
  657. }
  658. /**
  659. * Whether is exactly NaN. Notice isNaN('a') returns true.
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function eqNaN(value) {
  664. /* eslint-disable-next-line no-self-compare */
  665. return value !== value;
  666. }
  667. /**
  668. * If value1 is not null, then return value1, otherwise judget rest of values.
  669. * Low performance.
  670. * @memberOf module:zrender/core/util
  671. * @return {*} Final value
  672. */
  673. function retrieve(values) {
  674. for (var i = 0, len = arguments.length; i < len; i++) {
  675. if (arguments[i] != null) {
  676. return arguments[i];
  677. }
  678. }
  679. }
  680. function retrieve2(value0, value1) {
  681. return value0 != null
  682. ? value0
  683. : value1;
  684. }
  685. function retrieve3(value0, value1, value2) {
  686. return value0 != null
  687. ? value0
  688. : value1 != null
  689. ? value1
  690. : value2;
  691. }
  692. /**
  693. * @memberOf module:zrender/core/util
  694. * @param {Array} arr
  695. * @param {number} startIndex
  696. * @param {number} endIndex
  697. * @return {Array}
  698. */
  699. function slice() {
  700. return Function.call.apply(nativeSlice, arguments);
  701. }
  702. /**
  703. * Normalize css liked array configuration
  704. * e.g.
  705. * 3 => [3, 3, 3, 3]
  706. * [4, 2] => [4, 2, 4, 2]
  707. * [4, 3, 2] => [4, 3, 2, 3]
  708. * @param {number|Array.<number>} val
  709. * @return {Array.<number>}
  710. */
  711. function normalizeCssArray(val) {
  712. if (typeof (val) === 'number') {
  713. return [val, val, val, val];
  714. }
  715. var len = val.length;
  716. if (len === 2) {
  717. // vertical | horizontal
  718. return [val[0], val[1], val[0], val[1]];
  719. }
  720. else if (len === 3) {
  721. // top | horizontal | bottom
  722. return [val[0], val[1], val[2], val[1]];
  723. }
  724. return val;
  725. }
  726. /**
  727. * @memberOf module:zrender/core/util
  728. * @param {boolean} condition
  729. * @param {string} message
  730. */
  731. function assert$1(condition, message) {
  732. if (!condition) {
  733. throw new Error(message);
  734. }
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {string} str string to be trimed
  739. * @return {string} trimed string
  740. */
  741. function trim(str) {
  742. if (str == null) {
  743. return null;
  744. }
  745. else if (typeof str.trim === 'function') {
  746. return str.trim();
  747. }
  748. else {
  749. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  750. }
  751. }
  752. var primitiveKey = '__ec_primitive__';
  753. /**
  754. * Set an object as primitive to be ignored traversing children in clone or merge
  755. */
  756. function setAsPrimitive(obj) {
  757. obj[primitiveKey] = true;
  758. }
  759. function isPrimitive(obj) {
  760. return obj[primitiveKey];
  761. }
  762. /**
  763. * @constructor
  764. * @param {Object} obj Only apply `ownProperty`.
  765. */
  766. function HashMap(obj) {
  767. var isArr = isArray(obj);
  768. // Key should not be set on this, otherwise
  769. // methods get/set/... may be overrided.
  770. this.data = {};
  771. var thisMap = this;
  772. (obj instanceof HashMap)
  773. ? obj.each(visit)
  774. : (obj && each$1(obj, visit));
  775. function visit(value, key) {
  776. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  777. }
  778. }
  779. HashMap.prototype = {
  780. constructor: HashMap,
  781. // Do not provide `has` method to avoid defining what is `has`.
  782. // (We usually treat `null` and `undefined` as the same, different
  783. // from ES6 Map).
  784. get: function (key) {
  785. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  786. },
  787. set: function (key, value) {
  788. // Comparing with invocation chaining, `return value` is more commonly
  789. // used in this case: `var someVal = map.set('a', genVal());`
  790. return (this.data[key] = value);
  791. },
  792. // Although util.each can be performed on this hashMap directly, user
  793. // should not use the exposed keys, who are prefixed.
  794. each: function (cb, context) {
  795. context !== void 0 && (cb = bind(cb, context));
  796. /* eslint-disable guard-for-in */
  797. for (var key in this.data) {
  798. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  799. }
  800. /* eslint-enable guard-for-in */
  801. },
  802. // Do not use this method if performance sensitive.
  803. removeKey: function (key) {
  804. delete this.data[key];
  805. }
  806. };
  807. function createHashMap(obj) {
  808. return new HashMap(obj);
  809. }
  810. function noop() {}
  811. /* global Float32Array */
  812. var ArrayCtor = typeof Float32Array === 'undefined'
  813. ? Array
  814. : Float32Array;
  815. /**
  816. * 创建一个向量
  817. * @param {number} [x=0]
  818. * @param {number} [y=0]
  819. * @return {Vector2}
  820. */
  821. function create(x, y) {
  822. var out = new ArrayCtor(2);
  823. if (x == null) {
  824. x = 0;
  825. }
  826. if (y == null) {
  827. y = 0;
  828. }
  829. out[0] = x;
  830. out[1] = y;
  831. return out;
  832. }
  833. /**
  834. * 复制向量数据
  835. * @param {Vector2} out
  836. * @param {Vector2} v
  837. * @return {Vector2}
  838. */
  839. function copy(out, v) {
  840. out[0] = v[0];
  841. out[1] = v[1];
  842. return out;
  843. }
  844. /**
  845. * 克隆一个向量
  846. * @param {Vector2} v
  847. * @return {Vector2}
  848. */
  849. function clone$1(v) {
  850. var out = new ArrayCtor(2);
  851. out[0] = v[0];
  852. out[1] = v[1];
  853. return out;
  854. }
  855. /**
  856. * 设置向量的两个项
  857. * @param {Vector2} out
  858. * @param {number} a
  859. * @param {number} b
  860. * @return {Vector2} 结果
  861. */
  862. /**
  863. * 向量相加
  864. * @param {Vector2} out
  865. * @param {Vector2} v1
  866. * @param {Vector2} v2
  867. */
  868. function add(out, v1, v2) {
  869. out[0] = v1[0] + v2[0];
  870. out[1] = v1[1] + v2[1];
  871. return out;
  872. }
  873. /**
  874. * 向量缩放后相加
  875. * @param {Vector2} out
  876. * @param {Vector2} v1
  877. * @param {Vector2} v2
  878. * @param {number} a
  879. */
  880. function scaleAndAdd(out, v1, v2, a) {
  881. out[0] = v1[0] + v2[0] * a;
  882. out[1] = v1[1] + v2[1] * a;
  883. return out;
  884. }
  885. /**
  886. * 向量相减
  887. * @param {Vector2} out
  888. * @param {Vector2} v1
  889. * @param {Vector2} v2
  890. */
  891. function sub(out, v1, v2) {
  892. out[0] = v1[0] - v2[0];
  893. out[1] = v1[1] - v2[1];
  894. return out;
  895. }
  896. /**
  897. * 向量长度
  898. * @param {Vector2} v
  899. * @return {number}
  900. */
  901. function len(v) {
  902. return Math.sqrt(lenSquare(v));
  903. }
  904. // jshint ignore:line
  905. /**
  906. * 向量长度平方
  907. * @param {Vector2} v
  908. * @return {number}
  909. */
  910. function lenSquare(v) {
  911. return v[0] * v[0] + v[1] * v[1];
  912. }
  913. /**
  914. * 向量乘法
  915. * @param {Vector2} out
  916. * @param {Vector2} v1
  917. * @param {Vector2} v2
  918. */
  919. /**
  920. * 向量除法
  921. * @param {Vector2} out
  922. * @param {Vector2} v1
  923. * @param {Vector2} v2
  924. */
  925. /**
  926. * 向量点乘
  927. * @param {Vector2} v1
  928. * @param {Vector2} v2
  929. * @return {number}
  930. */
  931. /**
  932. * 向量缩放
  933. * @param {Vector2} out
  934. * @param {Vector2} v
  935. * @param {number} s
  936. */
  937. function scale(out, v, s) {
  938. out[0] = v[0] * s;
  939. out[1] = v[1] * s;
  940. return out;
  941. }
  942. /**
  943. * 向量归一化
  944. * @param {Vector2} out
  945. * @param {Vector2} v
  946. */
  947. function normalize(out, v) {
  948. var d = len(v);
  949. if (d === 0) {
  950. out[0] = 0;
  951. out[1] = 0;
  952. }
  953. else {
  954. out[0] = v[0] / d;
  955. out[1] = v[1] / d;
  956. }
  957. return out;
  958. }
  959. /**
  960. * 计算向量间距离
  961. * @param {Vector2} v1
  962. * @param {Vector2} v2
  963. * @return {number}
  964. */
  965. function distance(v1, v2) {
  966. return Math.sqrt(
  967. (v1[0] - v2[0]) * (v1[0] - v2[0])
  968. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  969. );
  970. }
  971. var dist = distance;
  972. /**
  973. * 向量距离平方
  974. * @param {Vector2} v1
  975. * @param {Vector2} v2
  976. * @return {number}
  977. */
  978. function distanceSquare(v1, v2) {
  979. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  980. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  981. }
  982. var distSquare = distanceSquare;
  983. /**
  984. * 求负向量
  985. * @param {Vector2} out
  986. * @param {Vector2} v
  987. */
  988. /**
  989. * 插值两个点
  990. * @param {Vector2} out
  991. * @param {Vector2} v1
  992. * @param {Vector2} v2
  993. * @param {number} t
  994. */
  995. /**
  996. * 矩阵左乘向量
  997. * @param {Vector2} out
  998. * @param {Vector2} v
  999. * @param {Vector2} m
  1000. */
  1001. function applyTransform(out, v, m) {
  1002. var x = v[0];
  1003. var y = v[1];
  1004. out[0] = m[0] * x + m[2] * y + m[4];
  1005. out[1] = m[1] * x + m[3] * y + m[5];
  1006. return out;
  1007. }
  1008. /**
  1009. * 求两个向量最小值
  1010. * @param {Vector2} out
  1011. * @param {Vector2} v1
  1012. * @param {Vector2} v2
  1013. */
  1014. function min(out, v1, v2) {
  1015. out[0] = Math.min(v1[0], v2[0]);
  1016. out[1] = Math.min(v1[1], v2[1]);
  1017. return out;
  1018. }
  1019. /**
  1020. * 求两个向量最大值
  1021. * @param {Vector2} out
  1022. * @param {Vector2} v1
  1023. * @param {Vector2} v2
  1024. */
  1025. function max(out, v1, v2) {
  1026. out[0] = Math.max(v1[0], v2[0]);
  1027. out[1] = Math.max(v1[1], v2[1]);
  1028. return out;
  1029. }
  1030. // TODO Draggable for group
  1031. // FIXME Draggable on element which has parent rotation or scale
  1032. function Draggable() {
  1033. this.on('mousedown', this._dragStart, this);
  1034. this.on('mousemove', this._drag, this);
  1035. this.on('mouseup', this._dragEnd, this);
  1036. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1037. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1038. // `_dragEnd` when globalout. That would brings better user experience.
  1039. // this.on('globalout', this._dragEnd, this);
  1040. // this._dropTarget = null;
  1041. // this._draggingTarget = null;
  1042. // this._x = 0;
  1043. // this._y = 0;
  1044. }
  1045. Draggable.prototype = {
  1046. constructor: Draggable,
  1047. _dragStart: function (e) {
  1048. var draggingTarget = e.target;
  1049. if (draggingTarget && draggingTarget.draggable) {
  1050. this._draggingTarget = draggingTarget;
  1051. draggingTarget.dragging = true;
  1052. this._x = e.offsetX;
  1053. this._y = e.offsetY;
  1054. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1055. }
  1056. },
  1057. _drag: function (e) {
  1058. var draggingTarget = this._draggingTarget;
  1059. if (draggingTarget) {
  1060. var x = e.offsetX;
  1061. var y = e.offsetY;
  1062. var dx = x - this._x;
  1063. var dy = y - this._y;
  1064. this._x = x;
  1065. this._y = y;
  1066. draggingTarget.drift(dx, dy, e);
  1067. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1068. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1069. var lastDropTarget = this._dropTarget;
  1070. this._dropTarget = dropTarget;
  1071. if (draggingTarget !== dropTarget) {
  1072. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1073. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1074. }
  1075. if (dropTarget && dropTarget !== lastDropTarget) {
  1076. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1077. }
  1078. }
  1079. }
  1080. },
  1081. _dragEnd: function (e) {
  1082. var draggingTarget = this._draggingTarget;
  1083. if (draggingTarget) {
  1084. draggingTarget.dragging = false;
  1085. }
  1086. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1087. if (this._dropTarget) {
  1088. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1089. }
  1090. this._draggingTarget = null;
  1091. this._dropTarget = null;
  1092. }
  1093. };
  1094. function param(target, e) {
  1095. return {target: target, topTarget: e && e.topTarget};
  1096. }
  1097. /**
  1098. * Event Mixin
  1099. * @module zrender/mixin/Eventful
  1100. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1101. * pissang (https://www.github.com/pissang)
  1102. */
  1103. var arrySlice = Array.prototype.slice;
  1104. /**
  1105. * Event dispatcher.
  1106. *
  1107. * @alias module:zrender/mixin/Eventful
  1108. * @constructor
  1109. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1110. * `eventProcessor.xxx` called.
  1111. * @param {Function} [eventProcessor.normalizeQuery]
  1112. * param: {string|Object} Raw query.
  1113. * return: {string|Object} Normalized query.
  1114. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1115. * if it returns `true`.
  1116. * param: {string} eventType
  1117. * param: {string|Object} query
  1118. * return: {boolean}
  1119. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1120. * param: {string} eventType
  1121. */
  1122. var Eventful = function (eventProcessor) {
  1123. this._$handlers = {};
  1124. this._$eventProcessor = eventProcessor;
  1125. };
  1126. Eventful.prototype = {
  1127. constructor: Eventful,
  1128. /**
  1129. * The handler can only be triggered once, then removed.
  1130. *
  1131. * @param {string} event The event name.
  1132. * @param {string|Object} [query] Condition used on event filter.
  1133. * @param {Function} handler The event handler.
  1134. * @param {Object} context
  1135. */
  1136. one: function (event, query, handler, context) {
  1137. return on(this, event, query, handler, context, true);
  1138. },
  1139. /**
  1140. * Bind a handler.
  1141. *
  1142. * @param {string} event The event name.
  1143. * @param {string|Object} [query] Condition used on event filter.
  1144. * @param {Function} handler The event handler.
  1145. * @param {Object} [context]
  1146. */
  1147. on: function (event, query, handler, context) {
  1148. return on(this, event, query, handler, context, false);
  1149. },
  1150. /**
  1151. * Whether any handler has bound.
  1152. *
  1153. * @param {string} event
  1154. * @return {boolean}
  1155. */
  1156. isSilent: function (event) {
  1157. var _h = this._$handlers;
  1158. return !_h[event] || !_h[event].length;
  1159. },
  1160. /**
  1161. * Unbind a event.
  1162. *
  1163. * @param {string} [event] The event name.
  1164. * If no `event` input, "off" all listeners.
  1165. * @param {Function} [handler] The event handler.
  1166. * If no `handler` input, "off" all listeners of the `event`.
  1167. */
  1168. off: function (event, handler) {
  1169. var _h = this._$handlers;
  1170. if (!event) {
  1171. this._$handlers = {};
  1172. return this;
  1173. }
  1174. if (handler) {
  1175. if (_h[event]) {
  1176. var newList = [];
  1177. for (var i = 0, l = _h[event].length; i < l; i++) {
  1178. if (_h[event][i].h !== handler) {
  1179. newList.push(_h[event][i]);
  1180. }
  1181. }
  1182. _h[event] = newList;
  1183. }
  1184. if (_h[event] && _h[event].length === 0) {
  1185. delete _h[event];
  1186. }
  1187. }
  1188. else {
  1189. delete _h[event];
  1190. }
  1191. return this;
  1192. },
  1193. /**
  1194. * Dispatch a event.
  1195. *
  1196. * @param {string} type The event name.
  1197. */
  1198. trigger: function (type) {
  1199. var _h = this._$handlers[type];
  1200. var eventProcessor = this._$eventProcessor;
  1201. if (_h) {
  1202. var args = arguments;
  1203. var argLen = args.length;
  1204. if (argLen > 3) {
  1205. args = arrySlice.call(args, 1);
  1206. }
  1207. var len = _h.length;
  1208. for (var i = 0; i < len;) {
  1209. var hItem = _h[i];
  1210. if (eventProcessor
  1211. && eventProcessor.filter
  1212. && hItem.query != null
  1213. && !eventProcessor.filter(type, hItem.query)
  1214. ) {
  1215. i++;
  1216. continue;
  1217. }
  1218. // Optimize advise from backbone
  1219. switch (argLen) {
  1220. case 1:
  1221. hItem.h.call(hItem.ctx);
  1222. break;
  1223. case 2:
  1224. hItem.h.call(hItem.ctx, args[1]);
  1225. break;
  1226. case 3:
  1227. hItem.h.call(hItem.ctx, args[1], args[2]);
  1228. break;
  1229. default:
  1230. // have more than 2 given arguments
  1231. hItem.h.apply(hItem.ctx, args);
  1232. break;
  1233. }
  1234. if (hItem.one) {
  1235. _h.splice(i, 1);
  1236. len--;
  1237. }
  1238. else {
  1239. i++;
  1240. }
  1241. }
  1242. }
  1243. eventProcessor && eventProcessor.afterTrigger
  1244. && eventProcessor.afterTrigger(type);
  1245. return this;
  1246. },
  1247. /**
  1248. * Dispatch a event with context, which is specified at the last parameter.
  1249. *
  1250. * @param {string} type The event name.
  1251. */
  1252. triggerWithContext: function (type) {
  1253. var _h = this._$handlers[type];
  1254. var eventProcessor = this._$eventProcessor;
  1255. if (_h) {
  1256. var args = arguments;
  1257. var argLen = args.length;
  1258. if (argLen > 4) {
  1259. args = arrySlice.call(args, 1, args.length - 1);
  1260. }
  1261. var ctx = args[args.length - 1];
  1262. var len = _h.length;
  1263. for (var i = 0; i < len;) {
  1264. var hItem = _h[i];
  1265. if (eventProcessor
  1266. && eventProcessor.filter
  1267. && hItem.query != null
  1268. && !eventProcessor.filter(type, hItem.query)
  1269. ) {
  1270. i++;
  1271. continue;
  1272. }
  1273. // Optimize advise from backbone
  1274. switch (argLen) {
  1275. case 1:
  1276. hItem.h.call(ctx);
  1277. break;
  1278. case 2:
  1279. hItem.h.call(ctx, args[1]);
  1280. break;
  1281. case 3:
  1282. hItem.h.call(ctx, args[1], args[2]);
  1283. break;
  1284. default:
  1285. // have more than 2 given arguments
  1286. hItem.h.apply(ctx, args);
  1287. break;
  1288. }
  1289. if (hItem.one) {
  1290. _h.splice(i, 1);
  1291. len--;
  1292. }
  1293. else {
  1294. i++;
  1295. }
  1296. }
  1297. }
  1298. eventProcessor && eventProcessor.afterTrigger
  1299. && eventProcessor.afterTrigger(type);
  1300. return this;
  1301. }
  1302. };
  1303. function normalizeQuery(host, query) {
  1304. var eventProcessor = host._$eventProcessor;
  1305. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1306. query = eventProcessor.normalizeQuery(query);
  1307. }
  1308. return query;
  1309. }
  1310. function on(eventful, event, query, handler, context, isOnce) {
  1311. var _h = eventful._$handlers;
  1312. if (typeof query === 'function') {
  1313. context = handler;
  1314. handler = query;
  1315. query = null;
  1316. }
  1317. if (!handler || !event) {
  1318. return eventful;
  1319. }
  1320. query = normalizeQuery(eventful, query);
  1321. if (!_h[event]) {
  1322. _h[event] = [];
  1323. }
  1324. for (var i = 0; i < _h[event].length; i++) {
  1325. if (_h[event][i].h === handler) {
  1326. return eventful;
  1327. }
  1328. }
  1329. var wrap = {
  1330. h: handler,
  1331. one: isOnce,
  1332. query: query,
  1333. ctx: context || eventful,
  1334. // FIXME
  1335. // Do not publish this feature util it is proved that it makes sense.
  1336. callAtLast: handler.zrEventfulCallAtLast
  1337. };
  1338. var lastIndex = _h[event].length - 1;
  1339. var lastWrap = _h[event][lastIndex];
  1340. (lastWrap && lastWrap.callAtLast)
  1341. ? _h[event].splice(lastIndex, 0, wrap)
  1342. : _h[event].push(wrap);
  1343. return eventful;
  1344. }
  1345. /**
  1346. * The algoritm is learnt from
  1347. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1348. * And we made some optimization for matrix inversion.
  1349. * Other similar approaches:
  1350. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1351. */
  1352. var LN2 = Math.log(2);
  1353. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1354. var cacheKey = rowMask + '-' + colMask;
  1355. var fullRank = rows.length;
  1356. if (detCache.hasOwnProperty(cacheKey)) {
  1357. return detCache[cacheKey];
  1358. }
  1359. if (rank === 1) {
  1360. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1361. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1362. return rows[rowStart][colStart];
  1363. }
  1364. var subRowMask = rowMask | (1 << rowStart);
  1365. var subRowStart = rowStart + 1;
  1366. while (rowMask & (1 << subRowStart)) {
  1367. subRowStart++;
  1368. }
  1369. var sum = 0;
  1370. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1371. var colTag = 1 << j;
  1372. if (!(colTag & colMask)) {
  1373. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1374. // det(subMatrix(0, j))
  1375. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1376. colLocalIdx++;
  1377. }
  1378. }
  1379. detCache[cacheKey] = sum;
  1380. return sum;
  1381. }
  1382. /**
  1383. * Usage:
  1384. * ```js
  1385. * var transformer = buildTransformer(
  1386. * [10, 44, 100, 44, 100, 300, 10, 300],
  1387. * [50, 54, 130, 14, 140, 330, 14, 220]
  1388. * );
  1389. * var out = [];
  1390. * transformer && transformer([11, 33], out);
  1391. * ```
  1392. *
  1393. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1394. *
  1395. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1396. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1397. * @return {Function} transformer If fail, return null/undefined.
  1398. */
  1399. function buildTransformer(src, dest) {
  1400. var mA = [
  1401. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1402. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1403. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1404. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1405. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1406. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1407. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1408. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1409. ];
  1410. var detCache = {};
  1411. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1412. if (det === 0) {
  1413. return;
  1414. }
  1415. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1416. var vh = [];
  1417. for (var i = 0; i < 8; i++) {
  1418. for (var j = 0; j < 8; j++) {
  1419. vh[j] == null && (vh[j] = 0);
  1420. vh[j] += ((i + j) % 2 ? -1 : 1)
  1421. // det(subMatrix(i, j))
  1422. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1423. / det * dest[i];
  1424. }
  1425. }
  1426. return function (out, srcPointX, srcPointY) {
  1427. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1428. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1429. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1430. };
  1431. }
  1432. /**
  1433. * Utilities for mouse or touch events.
  1434. */
  1435. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1436. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1437. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1438. var _calcOut = [];
  1439. /**
  1440. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1441. * the input `el`.
  1442. * CSS transform (2D & 3D) is supported.
  1443. *
  1444. * The strategy to fetch the coords:
  1445. * + If `calculate` is not set as `true`, users of this method should
  1446. * ensure that `el` is the same or the same size & location as `e.target`.
  1447. * Otherwise the result coords are probably not expected. Because we
  1448. * firstly try to get coords from e.offsetX/e.offsetY.
  1449. * + If `calculate` is set as `true`, the input `el` can be any element
  1450. * and we force to calculate the coords based on `el`.
  1451. * + The input `el` should be positionable (not position:static).
  1452. *
  1453. * The force `calculate` can be used in case like:
  1454. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1455. *
  1456. * @param {HTMLElement} el DOM element.
  1457. * @param {Event} e Mouse event or touch event.
  1458. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1459. * @param {boolean} [calculate=false] Whether to force calculate
  1460. * the coordinates but not use ones provided by browser.
  1461. */
  1462. function clientToLocal(el, e, out, calculate) {
  1463. out = out || {};
  1464. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1465. // to the padding edge of the target element. The only browser using this convention
  1466. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1467. // not support the properties.
  1468. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1469. // In zr painter.dom, padding edge equals to border edge.
  1470. if (calculate || !env$1.canvasSupported) {
  1471. calculateZrXY(el, e, out);
  1472. }
  1473. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1474. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1475. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1476. // zoom-factor, overflow / opacity layers, transforms ...)
  1477. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1478. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1479. // BTW3, In ff, offsetX/offsetY is always 0.
  1480. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1481. out.zrX = e.layerX;
  1482. out.zrY = e.layerY;
  1483. }
  1484. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1485. else if (e.offsetX != null) {
  1486. out.zrX = e.offsetX;
  1487. out.zrY = e.offsetY;
  1488. }
  1489. // For some other device, e.g., IOS safari.
  1490. else {
  1491. calculateZrXY(el, e, out);
  1492. }
  1493. return out;
  1494. }
  1495. function calculateZrXY(el, e, out) {
  1496. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1497. if (el.getBoundingClientRect && env$1.domSupported) {
  1498. var ex = e.clientX;
  1499. var ey = e.clientY;
  1500. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1501. // Original approach, which do not support CSS transform.
  1502. // marker can not be locationed in a canvas container
  1503. // (getBoundingClientRect is always 0). We do not support
  1504. // that input a pre-created canvas to zr while using css
  1505. // transform in iOS.
  1506. var box = el.getBoundingClientRect();
  1507. out.zrX = ex - box.left;
  1508. out.zrY = ey - box.top;
  1509. return;
  1510. }
  1511. else {
  1512. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1513. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1514. if (transformer) {
  1515. transformer(_calcOut, ex, ey);
  1516. out.zrX = _calcOut[0];
  1517. out.zrY = _calcOut[1];
  1518. return;
  1519. }
  1520. }
  1521. }
  1522. out.zrX = out.zrY = 0;
  1523. }
  1524. function prepareCoordMarkers(el, saved) {
  1525. var markers = saved.markers;
  1526. if (markers) {
  1527. return markers;
  1528. }
  1529. markers = saved.markers = [];
  1530. var propLR = ['left', 'right'];
  1531. var propTB = ['top', 'bottom'];
  1532. for (var i = 0; i < 4; i++) {
  1533. var marker = document.createElement('div');
  1534. var stl = marker.style;
  1535. var idxLR = i % 2;
  1536. var idxTB = (i >> 1) % 2;
  1537. stl.cssText = [
  1538. 'position:absolute',
  1539. 'visibility: hidden',
  1540. 'padding: 0',
  1541. 'margin: 0',
  1542. 'border-width: 0',
  1543. 'width:0',
  1544. 'height:0',
  1545. // 'width: 5px',
  1546. // 'height: 5px',
  1547. propLR[idxLR] + ':0',
  1548. propTB[idxTB] + ':0',
  1549. propLR[1 - idxLR] + ':auto',
  1550. propTB[1 - idxTB] + ':auto',
  1551. ''
  1552. ].join('!important;');
  1553. el.appendChild(marker);
  1554. markers.push(marker);
  1555. }
  1556. return markers;
  1557. }
  1558. function preparePointerTransformer(markers, saved) {
  1559. var transformer = saved.transformer;
  1560. var oldSrcCoords = saved.srcCoords;
  1561. var useOld = true;
  1562. var srcCoords = [];
  1563. var destCoords = [];
  1564. for (var i = 0; i < 4; i++) {
  1565. var rect = markers[i].getBoundingClientRect();
  1566. var ii = 2 * i;
  1567. var x = rect.left;
  1568. var y = rect.top;
  1569. srcCoords.push(x, y);
  1570. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1571. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1572. }
  1573. // Cache to avoid time consuming of `buildTransformer`.
  1574. return useOld
  1575. ? transformer
  1576. : (
  1577. saved.srcCoords = srcCoords,
  1578. saved.transformer = buildTransformer(srcCoords, destCoords)
  1579. );
  1580. }
  1581. /**
  1582. * Find native event compat for legency IE.
  1583. * Should be called at the begining of a native event listener.
  1584. *
  1585. * @param {Event} [e] Mouse event or touch event or pointer event.
  1586. * For lagency IE, we use `window.event` is used.
  1587. * @return {Event} The native event.
  1588. */
  1589. function getNativeEvent(e) {
  1590. return e || window.event;
  1591. }
  1592. /**
  1593. * Normalize the coordinates of the input event.
  1594. *
  1595. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1596. * the input `el`.
  1597. * Get `e.zrDelta` if using mouse wheel.
  1598. * Get `e.which`, see the comment inside this function.
  1599. *
  1600. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1601. *
  1602. * Notice: see comments in `clientToLocal`. check the relationship
  1603. * between the result coords and the parameters `el` and `calculate`.
  1604. *
  1605. * @param {HTMLElement} el DOM element.
  1606. * @param {Event} [e] See `getNativeEvent`.
  1607. * @param {boolean} [calculate=false] Whether to force calculate
  1608. * the coordinates but not use ones provided by browser.
  1609. * @return {UIEvent} The normalized native UIEvent.
  1610. */
  1611. function normalizeEvent(el, e, calculate) {
  1612. e = getNativeEvent(e);
  1613. if (e.zrX != null) {
  1614. return e;
  1615. }
  1616. var eventType = e.type;
  1617. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1618. if (!isTouch) {
  1619. clientToLocal(el, e, e, calculate);
  1620. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1621. }
  1622. else {
  1623. var touch = eventType !== 'touchend'
  1624. ? e.targetTouches[0]
  1625. : e.changedTouches[0];
  1626. touch && clientToLocal(el, touch, e, calculate);
  1627. }
  1628. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1629. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1630. // If e.which has been defined, it may be readonly,
  1631. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1632. var button = e.button;
  1633. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1634. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1635. }
  1636. // [Caution]: `e.which` from browser is not always reliable. For example,
  1637. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1638. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1639. // `mousedown (pointerdown)` is the same as Chrome does.
  1640. return e;
  1641. }
  1642. /**
  1643. * @param {HTMLElement} el
  1644. * @param {string} name
  1645. * @param {Function} handler
  1646. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1647. * @param {boolean} [opt.capture=false]
  1648. * @param {boolean} [opt.passive=false]
  1649. */
  1650. function addEventListener(el, name, handler, opt) {
  1651. if (isDomLevel2) {
  1652. // Reproduct the console warning:
  1653. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1654. // Consider marking event handler as 'passive' to make the page more responsive.
  1655. // Just set console log level: verbose in chrome dev tool.
  1656. // then the warning log will be printed when addEventListener called.
  1657. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1658. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1659. // listener delegate all of the upper events of element. Some of those events need
  1660. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1661. // Before passive can be adopted, these issues should be considered:
  1662. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1663. // passive or not.
  1664. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1665. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1666. // compatibility should be handled.
  1667. // var opts = (env.passiveSupported && name === 'mousewheel')
  1668. // ? {passive: true}
  1669. // // By default, the third param of el.addEventListener is `capture: false`.
  1670. // : void 0;
  1671. // el.addEventListener(name, handler /* , opts */);
  1672. el.addEventListener(name, handler, opt);
  1673. }
  1674. else {
  1675. // For simplicity, do not implement `setCapture` for IE9-.
  1676. el.attachEvent('on' + name, handler);
  1677. }
  1678. }
  1679. /**
  1680. * Parameter are the same as `addEventListener`.
  1681. *
  1682. * Notice that if a listener is registered twice, one with capture and one without,
  1683. * remove each one separately. Removal of a capturing listener does not affect a
  1684. * non-capturing version of the same listener, and vice versa.
  1685. */
  1686. function removeEventListener(el, name, handler, opt) {
  1687. if (isDomLevel2) {
  1688. el.removeEventListener(name, handler, opt);
  1689. }
  1690. else {
  1691. el.detachEvent('on' + name, handler);
  1692. }
  1693. }
  1694. /**
  1695. * preventDefault and stopPropagation.
  1696. * Notice: do not use this method in zrender. It can only be
  1697. * used by upper applications if necessary.
  1698. *
  1699. * @param {Event} e A mouse or touch event.
  1700. */
  1701. var stop = isDomLevel2
  1702. ? function (e) {
  1703. e.preventDefault();
  1704. e.stopPropagation();
  1705. e.cancelBubble = true;
  1706. }
  1707. : function (e) {
  1708. e.returnValue = false;
  1709. e.cancelBubble = true;
  1710. };
  1711. /**
  1712. * This method only works for mouseup and mousedown. The functionality is restricted
  1713. * for fault tolerance, See the `e.which` compatibility above.
  1714. *
  1715. * @param {MouseEvent} e
  1716. * @return {boolean}
  1717. */
  1718. /**
  1719. * To be removed.
  1720. * @deprecated
  1721. */
  1722. /**
  1723. * Only implements needed gestures for mobile.
  1724. */
  1725. var GestureMgr = function () {
  1726. /**
  1727. * @private
  1728. * @type {Array.<Object>}
  1729. */
  1730. this._track = [];
  1731. };
  1732. GestureMgr.prototype = {
  1733. constructor: GestureMgr,
  1734. recognize: function (event, target, root) {
  1735. this._doTrack(event, target, root);
  1736. return this._recognize(event);
  1737. },
  1738. clear: function () {
  1739. this._track.length = 0;
  1740. return this;
  1741. },
  1742. _doTrack: function (event, target, root) {
  1743. var touches = event.touches;
  1744. if (!touches) {
  1745. return;
  1746. }
  1747. var trackItem = {
  1748. points: [],
  1749. touches: [],
  1750. target: target,
  1751. event: event
  1752. };
  1753. for (var i = 0, len = touches.length; i < len; i++) {
  1754. var touch = touches[i];
  1755. var pos = clientToLocal(root, touch, {});
  1756. trackItem.points.push([pos.zrX, pos.zrY]);
  1757. trackItem.touches.push(touch);
  1758. }
  1759. this._track.push(trackItem);
  1760. },
  1761. _recognize: function (event) {
  1762. for (var eventName in recognizers) {
  1763. if (recognizers.hasOwnProperty(eventName)) {
  1764. var gestureInfo = recognizers[eventName](this._track, event);
  1765. if (gestureInfo) {
  1766. return gestureInfo;
  1767. }
  1768. }
  1769. }
  1770. }
  1771. };
  1772. function dist$1(pointPair) {
  1773. var dx = pointPair[1][0] - pointPair[0][0];
  1774. var dy = pointPair[1][1] - pointPair[0][1];
  1775. return Math.sqrt(dx * dx + dy * dy);
  1776. }
  1777. function center(pointPair) {
  1778. return [
  1779. (pointPair[0][0] + pointPair[1][0]) / 2,
  1780. (pointPair[0][1] + pointPair[1][1]) / 2
  1781. ];
  1782. }
  1783. var recognizers = {
  1784. pinch: function (track, event) {
  1785. var trackLen = track.length;
  1786. if (!trackLen) {
  1787. return;
  1788. }
  1789. var pinchEnd = (track[trackLen - 1] || {}).points;
  1790. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1791. if (pinchPre
  1792. && pinchPre.length > 1
  1793. && pinchEnd
  1794. && pinchEnd.length > 1
  1795. ) {
  1796. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1797. !isFinite(pinchScale) && (pinchScale = 1);
  1798. event.pinchScale = pinchScale;
  1799. var pinchCenter = center(pinchEnd);
  1800. event.pinchX = pinchCenter[0];
  1801. event.pinchY = pinchCenter[1];
  1802. return {
  1803. type: 'pinch',
  1804. target: track[0].target,
  1805. event: event
  1806. };
  1807. }
  1808. }
  1809. // Only pinch currently.
  1810. };
  1811. /**
  1812. * [The interface between `Handler` and `HandlerProxy`]:
  1813. *
  1814. * The default `HandlerProxy` only support the common standard web environment
  1815. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1816. * But `HandlerProxy` can be replaced to support more non-standard environment
  1817. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1818. * not provided (like echarts-gl did).
  1819. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1820. * make break changes util inevitable. The interface include the public methods
  1821. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1822. * drives `Handler`.
  1823. */
  1824. /**
  1825. * [Drag outside]:
  1826. *
  1827. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1828. * zrender area when dragging. That is important for the improvement of the user experience
  1829. * when dragging something near the boundary without being terminated unexpectedly.
  1830. *
  1831. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1832. * to resolve this issue. But some drawbacks of it is described in
  1833. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1834. *
  1835. * Instead, we referenced the specifications:
  1836. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1837. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1838. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1839. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1840. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1841. *
  1842. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1843. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1844. * to fire until release the pointer. That is implemented by listen to those event on
  1845. * `document`.
  1846. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1847. * The touch event support this feature by default.
  1848. *
  1849. * Note:
  1850. * There might be some cases that the mouse event can not be
  1851. * received on `document`. For example,
  1852. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1853. * of zr dom throw Error .
  1854. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1855. * zr dom call `stopPropagation`.
  1856. * In these cases, the `mousemove` event might be keep triggered event
  1857. * if the mouse is released. We try to reduce the side-effect in those cases.
  1858. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1859. *
  1860. * Note:
  1861. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1862. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1863. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1864. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1865. * But they are needed to work when the pointer inside the zrender dom.
  1866. */
  1867. var SILENT = 'silent';
  1868. function makeEventPacket(eveType, targetInfo, event) {
  1869. return {
  1870. type: eveType,
  1871. event: event,
  1872. // target can only be an element that is not silent.
  1873. target: targetInfo.target,
  1874. // topTarget can be a silent element.
  1875. topTarget: targetInfo.topTarget,
  1876. cancelBubble: false,
  1877. offsetX: event.zrX,
  1878. offsetY: event.zrY,
  1879. gestureEvent: event.gestureEvent,
  1880. pinchX: event.pinchX,
  1881. pinchY: event.pinchY,
  1882. pinchScale: event.pinchScale,
  1883. wheelDelta: event.zrDelta,
  1884. zrByTouch: event.zrByTouch,
  1885. which: event.which,
  1886. stop: stopEvent
  1887. };
  1888. }
  1889. function stopEvent() {
  1890. stop(this.event);
  1891. }
  1892. function EmptyProxy() {}
  1893. EmptyProxy.prototype.dispose = function () {};
  1894. var handlerNames = [
  1895. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1896. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1897. ];
  1898. /**
  1899. * @alias module:zrender/Handler
  1900. * @constructor
  1901. * @extends module:zrender/mixin/Eventful
  1902. * @param {module:zrender/Storage} storage Storage instance.
  1903. * @param {module:zrender/Painter} painter Painter instance.
  1904. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1905. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1906. */
  1907. var Handler = function (storage, painter, proxy, painterRoot) {
  1908. Eventful.call(this);
  1909. this.storage = storage;
  1910. this.painter = painter;
  1911. this.painterRoot = painterRoot;
  1912. proxy = proxy || new EmptyProxy();
  1913. /**
  1914. * Proxy of event. can be Dom, WebGLSurface, etc.
  1915. */
  1916. this.proxy = null;
  1917. /**
  1918. * {target, topTarget, x, y}
  1919. * @private
  1920. * @type {Object}
  1921. */
  1922. this._hovered = {};
  1923. /**
  1924. * @private
  1925. * @type {Date}
  1926. */
  1927. this._lastTouchMoment;
  1928. /**
  1929. * @private
  1930. * @type {number}
  1931. */
  1932. this._lastX;
  1933. /**
  1934. * @private
  1935. * @type {number}
  1936. */
  1937. this._lastY;
  1938. /**
  1939. * @private
  1940. * @type {module:zrender/core/GestureMgr}
  1941. */
  1942. this._gestureMgr;
  1943. Draggable.call(this);
  1944. this.setHandlerProxy(proxy);
  1945. };
  1946. Handler.prototype = {
  1947. constructor: Handler,
  1948. setHandlerProxy: function (proxy) {
  1949. if (this.proxy) {
  1950. this.proxy.dispose();
  1951. }
  1952. if (proxy) {
  1953. each$1(handlerNames, function (name) {
  1954. proxy.on && proxy.on(name, this[name], this);
  1955. }, this);
  1956. // Attach handler
  1957. proxy.handler = this;
  1958. }
  1959. this.proxy = proxy;
  1960. },
  1961. mousemove: function (event) {
  1962. var x = event.zrX;
  1963. var y = event.zrY;
  1964. var isOutside = isOutsideBoundary(this, x, y);
  1965. var lastHovered = this._hovered;
  1966. var lastHoveredTarget = lastHovered.target;
  1967. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1968. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1969. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1970. // See #6198.
  1971. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1972. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1973. lastHoveredTarget = lastHovered.target;
  1974. }
  1975. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  1976. var hoveredTarget = hovered.target;
  1977. var proxy = this.proxy;
  1978. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1979. // Mouse out on previous hovered element
  1980. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1981. this.dispatchToElement(lastHovered, 'mouseout', event);
  1982. }
  1983. // Mouse moving on one element
  1984. this.dispatchToElement(hovered, 'mousemove', event);
  1985. // Mouse over on a new element
  1986. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1987. this.dispatchToElement(hovered, 'mouseover', event);
  1988. }
  1989. },
  1990. mouseout: function (event) {
  1991. var eventControl = event.zrEventControl;
  1992. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  1993. if (eventControl !== 'only_globalout') {
  1994. this.dispatchToElement(this._hovered, 'mouseout', event);
  1995. }
  1996. if (eventControl !== 'no_globalout') {
  1997. // FIXME: if the pointer moving from the extra doms to realy "outside",
  1998. // the `globalout` should have been triggered. But currently not.
  1999. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2000. }
  2001. },
  2002. /**
  2003. * Resize
  2004. */
  2005. resize: function (event) {
  2006. this._hovered = {};
  2007. },
  2008. /**
  2009. * Dispatch event
  2010. * @param {string} eventName
  2011. * @param {event=} eventArgs
  2012. */
  2013. dispatch: function (eventName, eventArgs) {
  2014. var handler = this[eventName];
  2015. handler && handler.call(this, eventArgs);
  2016. },
  2017. /**
  2018. * Dispose
  2019. */
  2020. dispose: function () {
  2021. this.proxy.dispose();
  2022. this.storage =
  2023. this.proxy =
  2024. this.painter = null;
  2025. },
  2026. /**
  2027. * 设置默认的cursor style
  2028. * @param {string} [cursorStyle='default'] 例如 crosshair
  2029. */
  2030. setCursorStyle: function (cursorStyle) {
  2031. var proxy = this.proxy;
  2032. proxy.setCursor && proxy.setCursor(cursorStyle);
  2033. },
  2034. /**
  2035. * 事件分发代理
  2036. *
  2037. * @private
  2038. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2039. * @param {string} eventName 事件名称
  2040. * @param {Object} event 事件对象
  2041. */
  2042. dispatchToElement: function (targetInfo, eventName, event) {
  2043. targetInfo = targetInfo || {};
  2044. var el = targetInfo.target;
  2045. if (el && el.silent) {
  2046. return;
  2047. }
  2048. var eventHandler = 'on' + eventName;
  2049. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2050. while (el) {
  2051. el[eventHandler]
  2052. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2053. el.trigger(eventName, eventPacket);
  2054. el = el.parent;
  2055. if (eventPacket.cancelBubble) {
  2056. break;
  2057. }
  2058. }
  2059. if (!eventPacket.cancelBubble) {
  2060. // 冒泡到顶级 zrender 对象
  2061. this.trigger(eventName, eventPacket);
  2062. // 分发事件到用户自定义层
  2063. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2064. this.painter && this.painter.eachOtherLayer(function (layer) {
  2065. if (typeof (layer[eventHandler]) === 'function') {
  2066. layer[eventHandler].call(layer, eventPacket);
  2067. }
  2068. if (layer.trigger) {
  2069. layer.trigger(eventName, eventPacket);
  2070. }
  2071. });
  2072. }
  2073. },
  2074. /**
  2075. * @private
  2076. * @param {number} x
  2077. * @param {number} y
  2078. * @param {module:zrender/graphic/Displayable} exclude
  2079. * @return {model:zrender/Element}
  2080. * @method
  2081. */
  2082. findHover: function (x, y, exclude) {
  2083. var list = this.storage.getDisplayList();
  2084. var out = {x: x, y: y};
  2085. for (var i = list.length - 1; i >= 0; i--) {
  2086. var hoverCheckResult;
  2087. if (list[i] !== exclude
  2088. // getDisplayList may include ignored item in VML mode
  2089. && !list[i].ignore
  2090. && (hoverCheckResult = isHover(list[i], x, y))
  2091. ) {
  2092. !out.topTarget && (out.topTarget = list[i]);
  2093. if (hoverCheckResult !== SILENT) {
  2094. out.target = list[i];
  2095. break;
  2096. }
  2097. }
  2098. }
  2099. return out;
  2100. },
  2101. processGesture: function (event, stage) {
  2102. if (!this._gestureMgr) {
  2103. this._gestureMgr = new GestureMgr();
  2104. }
  2105. var gestureMgr = this._gestureMgr;
  2106. stage === 'start' && gestureMgr.clear();
  2107. var gestureInfo = gestureMgr.recognize(
  2108. event,
  2109. this.findHover(event.zrX, event.zrY, null).target,
  2110. this.proxy.dom
  2111. );
  2112. stage === 'end' && gestureMgr.clear();
  2113. // Do not do any preventDefault here. Upper application do that if necessary.
  2114. if (gestureInfo) {
  2115. var type = gestureInfo.type;
  2116. event.gestureEvent = type;
  2117. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2118. }
  2119. }
  2120. };
  2121. // Common handlers
  2122. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2123. Handler.prototype[name] = function (event) {
  2124. var x = event.zrX;
  2125. var y = event.zrY;
  2126. var isOutside = isOutsideBoundary(this, x, y);
  2127. var hovered;
  2128. var hoveredTarget;
  2129. if (name !== 'mouseup' || !isOutside) {
  2130. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2131. hovered = this.findHover(x, y);
  2132. hoveredTarget = hovered.target;
  2133. }
  2134. if (name === 'mousedown') {
  2135. this._downEl = hoveredTarget;
  2136. this._downPoint = [event.zrX, event.zrY];
  2137. // In case click triggered before mouseup
  2138. this._upEl = hoveredTarget;
  2139. }
  2140. else if (name === 'mouseup') {
  2141. this._upEl = hoveredTarget;
  2142. }
  2143. else if (name === 'click') {
  2144. if (this._downEl !== this._upEl
  2145. // Original click event is triggered on the whole canvas element,
  2146. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2147. // which should be filtered, otherwise it will bring trouble to
  2148. // pan and zoom.
  2149. || !this._downPoint
  2150. // Arbitrary value
  2151. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2152. ) {
  2153. return;
  2154. }
  2155. this._downPoint = null;
  2156. }
  2157. this.dispatchToElement(hovered, name, event);
  2158. };
  2159. });
  2160. function isHover(displayable, x, y) {
  2161. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2162. var el = displayable;
  2163. var isSilent;
  2164. while (el) {
  2165. // If clipped by ancestor.
  2166. // FIXME: If clipPath has neither stroke nor fill,
  2167. // el.clipPath.contain(x, y) will always return false.
  2168. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2169. return false;
  2170. }
  2171. if (el.silent) {
  2172. isSilent = true;
  2173. }
  2174. el = el.parent;
  2175. }
  2176. return isSilent ? SILENT : true;
  2177. }
  2178. return false;
  2179. }
  2180. /**
  2181. * See [Drag outside].
  2182. */
  2183. function isOutsideBoundary(handlerInstance, x, y) {
  2184. var painter = handlerInstance.painter;
  2185. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2186. }
  2187. mixin(Handler, Eventful);
  2188. mixin(Handler, Draggable);
  2189. /**
  2190. * 3x2矩阵操作类
  2191. * @exports zrender/tool/matrix
  2192. */
  2193. /* global Float32Array */
  2194. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2195. ? Array
  2196. : Float32Array;
  2197. /**
  2198. * Create a identity matrix.
  2199. * @return {Float32Array|Array.<number>}
  2200. */
  2201. function create$1() {
  2202. var out = new ArrayCtor$1(6);
  2203. identity(out);
  2204. return out;
  2205. }
  2206. /**
  2207. * 设置矩阵为单位矩阵
  2208. * @param {Float32Array|Array.<number>} out
  2209. */
  2210. function identity(out) {
  2211. out[0] = 1;
  2212. out[1] = 0;
  2213. out[2] = 0;
  2214. out[3] = 1;
  2215. out[4] = 0;
  2216. out[5] = 0;
  2217. return out;
  2218. }
  2219. /**
  2220. * 复制矩阵
  2221. * @param {Float32Array|Array.<number>} out
  2222. * @param {Float32Array|Array.<number>} m
  2223. */
  2224. function copy$1(out, m) {
  2225. out[0] = m[0];
  2226. out[1] = m[1];
  2227. out[2] = m[2];
  2228. out[3] = m[3];
  2229. out[4] = m[4];
  2230. out[5] = m[5];
  2231. return out;
  2232. }
  2233. /**
  2234. * 矩阵相乘
  2235. * @param {Float32Array|Array.<number>} out
  2236. * @param {Float32Array|Array.<number>} m1
  2237. * @param {Float32Array|Array.<number>} m2
  2238. */
  2239. function mul$1(out, m1, m2) {
  2240. // Consider matrix.mul(m, m2, m);
  2241. // where out is the same as m2.
  2242. // So use temp variable to escape error.
  2243. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2244. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2245. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2246. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2247. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2248. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2249. out[0] = out0;
  2250. out[1] = out1;
  2251. out[2] = out2;
  2252. out[3] = out3;
  2253. out[4] = out4;
  2254. out[5] = out5;
  2255. return out;
  2256. }
  2257. /**
  2258. * 平移变换
  2259. * @param {Float32Array|Array.<number>} out
  2260. * @param {Float32Array|Array.<number>} a
  2261. * @param {Float32Array|Array.<number>} v
  2262. */
  2263. function translate(out, a, v) {
  2264. out[0] = a[0];
  2265. out[1] = a[1];
  2266. out[2] = a[2];
  2267. out[3] = a[3];
  2268. out[4] = a[4] + v[0];
  2269. out[5] = a[5] + v[1];
  2270. return out;
  2271. }
  2272. /**
  2273. * 旋转变换
  2274. * @param {Float32Array|Array.<number>} out
  2275. * @param {Float32Array|Array.<number>} a
  2276. * @param {number} rad
  2277. */
  2278. function rotate(out, a, rad) {
  2279. var aa = a[0];
  2280. var ac = a[2];
  2281. var atx = a[4];
  2282. var ab = a[1];
  2283. var ad = a[3];
  2284. var aty = a[5];
  2285. var st = Math.sin(rad);
  2286. var ct = Math.cos(rad);
  2287. out[0] = aa * ct + ab * st;
  2288. out[1] = -aa * st + ab * ct;
  2289. out[2] = ac * ct + ad * st;
  2290. out[3] = -ac * st + ct * ad;
  2291. out[4] = ct * atx + st * aty;
  2292. out[5] = ct * aty - st * atx;
  2293. return out;
  2294. }
  2295. /**
  2296. * 缩放变换
  2297. * @param {Float32Array|Array.<number>} out
  2298. * @param {Float32Array|Array.<number>} a
  2299. * @param {Float32Array|Array.<number>} v
  2300. */
  2301. function scale$1(out, a, v) {
  2302. var vx = v[0];
  2303. var vy = v[1];
  2304. out[0] = a[0] * vx;
  2305. out[1] = a[1] * vy;
  2306. out[2] = a[2] * vx;
  2307. out[3] = a[3] * vy;
  2308. out[4] = a[4] * vx;
  2309. out[5] = a[5] * vy;
  2310. return out;
  2311. }
  2312. /**
  2313. * 求逆矩阵
  2314. * @param {Float32Array|Array.<number>} out
  2315. * @param {Float32Array|Array.<number>} a
  2316. */
  2317. function invert(out, a) {
  2318. var aa = a[0];
  2319. var ac = a[2];
  2320. var atx = a[4];
  2321. var ab = a[1];
  2322. var ad = a[3];
  2323. var aty = a[5];
  2324. var det = aa * ad - ab * ac;
  2325. if (!det) {
  2326. return null;
  2327. }
  2328. det = 1.0 / det;
  2329. out[0] = ad * det;
  2330. out[1] = -ab * det;
  2331. out[2] = -ac * det;
  2332. out[3] = aa * det;
  2333. out[4] = (ac * aty - ad * atx) * det;
  2334. out[5] = (ab * atx - aa * aty) * det;
  2335. return out;
  2336. }
  2337. /**
  2338. * Clone a new matrix.
  2339. * @param {Float32Array|Array.<number>} a
  2340. */
  2341. /**
  2342. * 提供变换扩展
  2343. * @module zrender/mixin/Transformable
  2344. * @author pissang (https://www.github.com/pissang)
  2345. */
  2346. var mIdentity = identity;
  2347. var EPSILON = 5e-5;
  2348. function isNotAroundZero(val) {
  2349. return val > EPSILON || val < -EPSILON;
  2350. }
  2351. /**
  2352. * @alias module:zrender/mixin/Transformable
  2353. * @constructor
  2354. */
  2355. var Transformable = function (opts) {
  2356. opts = opts || {};
  2357. // If there are no given position, rotation, scale
  2358. if (!opts.position) {
  2359. /**
  2360. * 平移
  2361. * @type {Array.<number>}
  2362. * @default [0, 0]
  2363. */
  2364. this.position = [0, 0];
  2365. }
  2366. if (opts.rotation == null) {
  2367. /**
  2368. * 旋转
  2369. * @type {Array.<number>}
  2370. * @default 0
  2371. */
  2372. this.rotation = 0;
  2373. }
  2374. if (!opts.scale) {
  2375. /**
  2376. * 缩放
  2377. * @type {Array.<number>}
  2378. * @default [1, 1]
  2379. */
  2380. this.scale = [1, 1];
  2381. }
  2382. /**
  2383. * 旋转和缩放的原点
  2384. * @type {Array.<number>}
  2385. * @default null
  2386. */
  2387. this.origin = this.origin || null;
  2388. };
  2389. var transformableProto = Transformable.prototype;
  2390. transformableProto.transform = null;
  2391. /**
  2392. * 判断是否需要有坐标变换
  2393. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2394. */
  2395. transformableProto.needLocalTransform = function () {
  2396. return isNotAroundZero(this.rotation)
  2397. || isNotAroundZero(this.position[0])
  2398. || isNotAroundZero(this.position[1])
  2399. || isNotAroundZero(this.scale[0] - 1)
  2400. || isNotAroundZero(this.scale[1] - 1);
  2401. };
  2402. var scaleTmp = [];
  2403. transformableProto.updateTransform = function () {
  2404. var parent = this.parent;
  2405. var parentHasTransform = parent && parent.transform;
  2406. var needLocalTransform = this.needLocalTransform();
  2407. var m = this.transform;
  2408. if (!(needLocalTransform || parentHasTransform)) {
  2409. m && mIdentity(m);
  2410. return;
  2411. }
  2412. m = m || create$1();
  2413. if (needLocalTransform) {
  2414. this.getLocalTransform(m);
  2415. }
  2416. else {
  2417. mIdentity(m);
  2418. }
  2419. // 应用父节点变换
  2420. if (parentHasTransform) {
  2421. if (needLocalTransform) {
  2422. mul$1(m, parent.transform, m);
  2423. }
  2424. else {
  2425. copy$1(m, parent.transform);
  2426. }
  2427. }
  2428. // 保存这个变换矩阵
  2429. this.transform = m;
  2430. var globalScaleRatio = this.globalScaleRatio;
  2431. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2432. this.getGlobalScale(scaleTmp);
  2433. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2434. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2435. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2436. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2437. m[0] *= sx;
  2438. m[1] *= sx;
  2439. m[2] *= sy;
  2440. m[3] *= sy;
  2441. }
  2442. this.invTransform = this.invTransform || create$1();
  2443. invert(this.invTransform, m);
  2444. };
  2445. transformableProto.getLocalTransform = function (m) {
  2446. return Transformable.getLocalTransform(this, m);
  2447. };
  2448. /**
  2449. * 将自己的transform应用到context上
  2450. * @param {CanvasRenderingContext2D} ctx
  2451. */
  2452. transformableProto.setTransform = function (ctx) {
  2453. var m = this.transform;
  2454. var dpr = ctx.dpr || 1;
  2455. if (m) {
  2456. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2457. }
  2458. else {
  2459. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2460. }
  2461. };
  2462. transformableProto.restoreTransform = function (ctx) {
  2463. var dpr = ctx.dpr || 1;
  2464. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2465. };
  2466. var tmpTransform = [];
  2467. var originTransform = create$1();
  2468. transformableProto.setLocalTransform = function (m) {
  2469. if (!m) {
  2470. // TODO return or set identity?
  2471. return;
  2472. }
  2473. var sx = m[0] * m[0] + m[1] * m[1];
  2474. var sy = m[2] * m[2] + m[3] * m[3];
  2475. var position = this.position;
  2476. var scale$$1 = this.scale;
  2477. if (isNotAroundZero(sx - 1)) {
  2478. sx = Math.sqrt(sx);
  2479. }
  2480. if (isNotAroundZero(sy - 1)) {
  2481. sy = Math.sqrt(sy);
  2482. }
  2483. if (m[0] < 0) {
  2484. sx = -sx;
  2485. }
  2486. if (m[3] < 0) {
  2487. sy = -sy;
  2488. }
  2489. position[0] = m[4];
  2490. position[1] = m[5];
  2491. scale$$1[0] = sx;
  2492. scale$$1[1] = sy;
  2493. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2494. };
  2495. /**
  2496. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2497. */
  2498. transformableProto.decomposeTransform = function () {
  2499. if (!this.transform) {
  2500. return;
  2501. }
  2502. var parent = this.parent;
  2503. var m = this.transform;
  2504. if (parent && parent.transform) {
  2505. // Get local transform and decompose them to position, scale, rotation
  2506. mul$1(tmpTransform, parent.invTransform, m);
  2507. m = tmpTransform;
  2508. }
  2509. var origin = this.origin;
  2510. if (origin && (origin[0] || origin[1])) {
  2511. originTransform[4] = origin[0];
  2512. originTransform[5] = origin[1];
  2513. mul$1(tmpTransform, m, originTransform);
  2514. tmpTransform[4] -= origin[0];
  2515. tmpTransform[5] -= origin[1];
  2516. m = tmpTransform;
  2517. }
  2518. this.setLocalTransform(m);
  2519. };
  2520. /**
  2521. * Get global scale
  2522. * @return {Array.<number>}
  2523. */
  2524. transformableProto.getGlobalScale = function (out) {
  2525. var m = this.transform;
  2526. out = out || [];
  2527. if (!m) {
  2528. out[0] = 1;
  2529. out[1] = 1;
  2530. return out;
  2531. }
  2532. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2533. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2534. if (m[0] < 0) {
  2535. out[0] = -out[0];
  2536. }
  2537. if (m[3] < 0) {
  2538. out[1] = -out[1];
  2539. }
  2540. return out;
  2541. };
  2542. /**
  2543. * 变换坐标位置到 shape 的局部坐标空间
  2544. * @method
  2545. * @param {number} x
  2546. * @param {number} y
  2547. * @return {Array.<number>}
  2548. */
  2549. transformableProto.transformCoordToLocal = function (x, y) {
  2550. var v2 = [x, y];
  2551. var invTransform = this.invTransform;
  2552. if (invTransform) {
  2553. applyTransform(v2, v2, invTransform);
  2554. }
  2555. return v2;
  2556. };
  2557. /**
  2558. * 变换局部坐标位置到全局坐标空间
  2559. * @method
  2560. * @param {number} x
  2561. * @param {number} y
  2562. * @return {Array.<number>}
  2563. */
  2564. transformableProto.transformCoordToGlobal = function (x, y) {
  2565. var v2 = [x, y];
  2566. var transform = this.transform;
  2567. if (transform) {
  2568. applyTransform(v2, v2, transform);
  2569. }
  2570. return v2;
  2571. };
  2572. /**
  2573. * @static
  2574. * @param {Object} target
  2575. * @param {Array.<number>} target.origin
  2576. * @param {number} target.rotation
  2577. * @param {Array.<number>} target.position
  2578. * @param {Array.<number>} [m]
  2579. */
  2580. Transformable.getLocalTransform = function (target, m) {
  2581. m = m || [];
  2582. mIdentity(m);
  2583. var origin = target.origin;
  2584. var scale$$1 = target.scale || [1, 1];
  2585. var rotation = target.rotation || 0;
  2586. var position = target.position || [0, 0];
  2587. if (origin) {
  2588. // Translate to origin
  2589. m[4] -= origin[0];
  2590. m[5] -= origin[1];
  2591. }
  2592. scale$1(m, m, scale$$1);
  2593. if (rotation) {
  2594. rotate(m, m, rotation);
  2595. }
  2596. if (origin) {
  2597. // Translate back from origin
  2598. m[4] += origin[0];
  2599. m[5] += origin[1];
  2600. }
  2601. m[4] += position[0];
  2602. m[5] += position[1];
  2603. return m;
  2604. };
  2605. /**
  2606. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2607. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2608. * @exports zrender/animation/easing
  2609. */
  2610. var easing = {
  2611. /**
  2612. * @param {number} k
  2613. * @return {number}
  2614. */
  2615. linear: function (k) {
  2616. return k;
  2617. },
  2618. /**
  2619. * @param {number} k
  2620. * @return {number}
  2621. */
  2622. quadraticIn: function (k) {
  2623. return k * k;
  2624. },
  2625. /**
  2626. * @param {number} k
  2627. * @return {number}
  2628. */
  2629. quadraticOut: function (k) {
  2630. return k * (2 - k);
  2631. },
  2632. /**
  2633. * @param {number} k
  2634. * @return {number}
  2635. */
  2636. quadraticInOut: function (k) {
  2637. if ((k *= 2) < 1) {
  2638. return 0.5 * k * k;
  2639. }
  2640. return -0.5 * (--k * (k - 2) - 1);
  2641. },
  2642. // 三次方的缓动(t^3)
  2643. /**
  2644. * @param {number} k
  2645. * @return {number}
  2646. */
  2647. cubicIn: function (k) {
  2648. return k * k * k;
  2649. },
  2650. /**
  2651. * @param {number} k
  2652. * @return {number}
  2653. */
  2654. cubicOut: function (k) {
  2655. return --k * k * k + 1;
  2656. },
  2657. /**
  2658. * @param {number} k
  2659. * @return {number}
  2660. */
  2661. cubicInOut: function (k) {
  2662. if ((k *= 2) < 1) {
  2663. return 0.5 * k * k * k;
  2664. }
  2665. return 0.5 * ((k -= 2) * k * k + 2);
  2666. },
  2667. // 四次方的缓动(t^4)
  2668. /**
  2669. * @param {number} k
  2670. * @return {number}
  2671. */
  2672. quarticIn: function (k) {
  2673. return k * k * k * k;
  2674. },
  2675. /**
  2676. * @param {number} k
  2677. * @return {number}
  2678. */
  2679. quarticOut: function (k) {
  2680. return 1 - (--k * k * k * k);
  2681. },
  2682. /**
  2683. * @param {number} k
  2684. * @return {number}
  2685. */
  2686. quarticInOut: function (k) {
  2687. if ((k *= 2) < 1) {
  2688. return 0.5 * k * k * k * k;
  2689. }
  2690. return -0.5 * ((k -= 2) * k * k * k - 2);
  2691. },
  2692. // 五次方的缓动(t^5)
  2693. /**
  2694. * @param {number} k
  2695. * @return {number}
  2696. */
  2697. quinticIn: function (k) {
  2698. return k * k * k * k * k;
  2699. },
  2700. /**
  2701. * @param {number} k
  2702. * @return {number}
  2703. */
  2704. quinticOut: function (k) {
  2705. return --k * k * k * k * k + 1;
  2706. },
  2707. /**
  2708. * @param {number} k
  2709. * @return {number}
  2710. */
  2711. quinticInOut: function (k) {
  2712. if ((k *= 2) < 1) {
  2713. return 0.5 * k * k * k * k * k;
  2714. }
  2715. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2716. },
  2717. // 正弦曲线的缓动(sin(t))
  2718. /**
  2719. * @param {number} k
  2720. * @return {number}
  2721. */
  2722. sinusoidalIn: function (k) {
  2723. return 1 - Math.cos(k * Math.PI / 2);
  2724. },
  2725. /**
  2726. * @param {number} k
  2727. * @return {number}
  2728. */
  2729. sinusoidalOut: function (k) {
  2730. return Math.sin(k * Math.PI / 2);
  2731. },
  2732. /**
  2733. * @param {number} k
  2734. * @return {number}
  2735. */
  2736. sinusoidalInOut: function (k) {
  2737. return 0.5 * (1 - Math.cos(Math.PI * k));
  2738. },
  2739. // 指数曲线的缓动(2^t)
  2740. /**
  2741. * @param {number} k
  2742. * @return {number}
  2743. */
  2744. exponentialIn: function (k) {
  2745. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2746. },
  2747. /**
  2748. * @param {number} k
  2749. * @return {number}
  2750. */
  2751. exponentialOut: function (k) {
  2752. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2753. },
  2754. /**
  2755. * @param {number} k
  2756. * @return {number}
  2757. */
  2758. exponentialInOut: function (k) {
  2759. if (k === 0) {
  2760. return 0;
  2761. }
  2762. if (k === 1) {
  2763. return 1;
  2764. }
  2765. if ((k *= 2) < 1) {
  2766. return 0.5 * Math.pow(1024, k - 1);
  2767. }
  2768. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2769. },
  2770. // 圆形曲线的缓动(sqrt(1-t^2))
  2771. /**
  2772. * @param {number} k
  2773. * @return {number}
  2774. */
  2775. circularIn: function (k) {
  2776. return 1 - Math.sqrt(1 - k * k);
  2777. },
  2778. /**
  2779. * @param {number} k
  2780. * @return {number}
  2781. */
  2782. circularOut: function (k) {
  2783. return Math.sqrt(1 - (--k * k));
  2784. },
  2785. /**
  2786. * @param {number} k
  2787. * @return {number}
  2788. */
  2789. circularInOut: function (k) {
  2790. if ((k *= 2) < 1) {
  2791. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2792. }
  2793. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2794. },
  2795. // 创建类似于弹簧在停止前来回振荡的动画
  2796. /**
  2797. * @param {number} k
  2798. * @return {number}
  2799. */
  2800. elasticIn: function (k) {
  2801. var s;
  2802. var a = 0.1;
  2803. var p = 0.4;
  2804. if (k === 0) {
  2805. return 0;
  2806. }
  2807. if (k === 1) {
  2808. return 1;
  2809. }
  2810. if (!a || a < 1) {
  2811. a = 1;
  2812. s = p / 4;
  2813. }
  2814. else {
  2815. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2816. }
  2817. return -(a * Math.pow(2, 10 * (k -= 1))
  2818. * Math.sin((k - s) * (2 * Math.PI) / p));
  2819. },
  2820. /**
  2821. * @param {number} k
  2822. * @return {number}
  2823. */
  2824. elasticOut: function (k) {
  2825. var s;
  2826. var a = 0.1;
  2827. var p = 0.4;
  2828. if (k === 0) {
  2829. return 0;
  2830. }
  2831. if (k === 1) {
  2832. return 1;
  2833. }
  2834. if (!a || a < 1) {
  2835. a = 1;
  2836. s = p / 4;
  2837. }
  2838. else {
  2839. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2840. }
  2841. return (a * Math.pow(2, -10 * k)
  2842. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. elasticInOut: function (k) {
  2849. var s;
  2850. var a = 0.1;
  2851. var p = 0.4;
  2852. if (k === 0) {
  2853. return 0;
  2854. }
  2855. if (k === 1) {
  2856. return 1;
  2857. }
  2858. if (!a || a < 1) {
  2859. a = 1;
  2860. s = p / 4;
  2861. }
  2862. else {
  2863. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2864. }
  2865. if ((k *= 2) < 1) {
  2866. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2867. * Math.sin((k - s) * (2 * Math.PI) / p));
  2868. }
  2869. return a * Math.pow(2, -10 * (k -= 1))
  2870. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2871. },
  2872. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2873. /**
  2874. * @param {number} k
  2875. * @return {number}
  2876. */
  2877. backIn: function (k) {
  2878. var s = 1.70158;
  2879. return k * k * ((s + 1) * k - s);
  2880. },
  2881. /**
  2882. * @param {number} k
  2883. * @return {number}
  2884. */
  2885. backOut: function (k) {
  2886. var s = 1.70158;
  2887. return --k * k * ((s + 1) * k + s) + 1;
  2888. },
  2889. /**
  2890. * @param {number} k
  2891. * @return {number}
  2892. */
  2893. backInOut: function (k) {
  2894. var s = 1.70158 * 1.525;
  2895. if ((k *= 2) < 1) {
  2896. return 0.5 * (k * k * ((s + 1) * k - s));
  2897. }
  2898. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2899. },
  2900. // 创建弹跳效果
  2901. /**
  2902. * @param {number} k
  2903. * @return {number}
  2904. */
  2905. bounceIn: function (k) {
  2906. return 1 - easing.bounceOut(1 - k);
  2907. },
  2908. /**
  2909. * @param {number} k
  2910. * @return {number}
  2911. */
  2912. bounceOut: function (k) {
  2913. if (k < (1 / 2.75)) {
  2914. return 7.5625 * k * k;
  2915. }
  2916. else if (k < (2 / 2.75)) {
  2917. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2918. }
  2919. else if (k < (2.5 / 2.75)) {
  2920. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2921. }
  2922. else {
  2923. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2924. }
  2925. },
  2926. /**
  2927. * @param {number} k
  2928. * @return {number}
  2929. */
  2930. bounceInOut: function (k) {
  2931. if (k < 0.5) {
  2932. return easing.bounceIn(k * 2) * 0.5;
  2933. }
  2934. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2935. }
  2936. };
  2937. /**
  2938. * 动画主控制器
  2939. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2940. * @config life(1000) 动画时长
  2941. * @config delay(0) 动画延迟时间
  2942. * @config loop(true)
  2943. * @config gap(0) 循环的间隔时间
  2944. * @config onframe
  2945. * @config easing(optional)
  2946. * @config ondestroy(optional)
  2947. * @config onrestart(optional)
  2948. *
  2949. * TODO pause
  2950. */
  2951. function Clip(options) {
  2952. this._target = options.target;
  2953. // 生命周期
  2954. this._life = options.life || 1000;
  2955. // 延时
  2956. this._delay = options.delay || 0;
  2957. // 开始时间
  2958. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2959. this._initialized = false;
  2960. // 是否循环
  2961. this.loop = options.loop == null ? false : options.loop;
  2962. this.gap = options.gap || 0;
  2963. this.easing = options.easing || 'Linear';
  2964. this.onframe = options.onframe;
  2965. this.ondestroy = options.ondestroy;
  2966. this.onrestart = options.onrestart;
  2967. this._pausedTime = 0;
  2968. this._paused = false;
  2969. }
  2970. Clip.prototype = {
  2971. constructor: Clip,
  2972. step: function (globalTime, deltaTime) {
  2973. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2974. // PENDING
  2975. if (!this._initialized) {
  2976. this._startTime = globalTime + this._delay;
  2977. this._initialized = true;
  2978. }
  2979. if (this._paused) {
  2980. this._pausedTime += deltaTime;
  2981. return;
  2982. }
  2983. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2984. // 还没开始
  2985. if (percent < 0) {
  2986. return;
  2987. }
  2988. percent = Math.min(percent, 1);
  2989. var easing$$1 = this.easing;
  2990. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  2991. var schedule = typeof easingFunc === 'function'
  2992. ? easingFunc(percent)
  2993. : percent;
  2994. this.fire('frame', schedule);
  2995. // 结束
  2996. if (percent === 1) {
  2997. if (this.loop) {
  2998. this.restart(globalTime);
  2999. // 重新开始周期
  3000. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3001. return 'restart';
  3002. }
  3003. // 动画完成将这个控制器标识为待删除
  3004. // 在Animation.update中进行批量删除
  3005. this._needsRemove = true;
  3006. return 'destroy';
  3007. }
  3008. return null;
  3009. },
  3010. restart: function (globalTime) {
  3011. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3012. this._startTime = globalTime - remainder + this.gap;
  3013. this._pausedTime = 0;
  3014. this._needsRemove = false;
  3015. },
  3016. fire: function (eventType, arg) {
  3017. eventType = 'on' + eventType;
  3018. if (this[eventType]) {
  3019. this[eventType](this._target, arg);
  3020. }
  3021. },
  3022. pause: function () {
  3023. this._paused = true;
  3024. },
  3025. resume: function () {
  3026. this._paused = false;
  3027. }
  3028. };
  3029. // Simple LRU cache use doubly linked list
  3030. // @module zrender/core/LRU
  3031. /**
  3032. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3033. * @constructor
  3034. */
  3035. var LinkedList = function () {
  3036. /**
  3037. * @type {module:zrender/core/LRU~Entry}
  3038. */
  3039. this.head = null;
  3040. /**
  3041. * @type {module:zrender/core/LRU~Entry}
  3042. */
  3043. this.tail = null;
  3044. this._len = 0;
  3045. };
  3046. var linkedListProto = LinkedList.prototype;
  3047. /**
  3048. * Insert a new value at the tail
  3049. * @param {} val
  3050. * @return {module:zrender/core/LRU~Entry}
  3051. */
  3052. linkedListProto.insert = function (val) {
  3053. var entry = new Entry(val);
  3054. this.insertEntry(entry);
  3055. return entry;
  3056. };
  3057. /**
  3058. * Insert an entry at the tail
  3059. * @param {module:zrender/core/LRU~Entry} entry
  3060. */
  3061. linkedListProto.insertEntry = function (entry) {
  3062. if (!this.head) {
  3063. this.head = this.tail = entry;
  3064. }
  3065. else {
  3066. this.tail.next = entry;
  3067. entry.prev = this.tail;
  3068. entry.next = null;
  3069. this.tail = entry;
  3070. }
  3071. this._len++;
  3072. };
  3073. /**
  3074. * Remove entry.
  3075. * @param {module:zrender/core/LRU~Entry} entry
  3076. */
  3077. linkedListProto.remove = function (entry) {
  3078. var prev = entry.prev;
  3079. var next = entry.next;
  3080. if (prev) {
  3081. prev.next = next;
  3082. }
  3083. else {
  3084. // Is head
  3085. this.head = next;
  3086. }
  3087. if (next) {
  3088. next.prev = prev;
  3089. }
  3090. else {
  3091. // Is tail
  3092. this.tail = prev;
  3093. }
  3094. entry.next = entry.prev = null;
  3095. this._len--;
  3096. };
  3097. /**
  3098. * @return {number}
  3099. */
  3100. linkedListProto.len = function () {
  3101. return this._len;
  3102. };
  3103. /**
  3104. * Clear list
  3105. */
  3106. linkedListProto.clear = function () {
  3107. this.head = this.tail = null;
  3108. this._len = 0;
  3109. };
  3110. /**
  3111. * @constructor
  3112. * @param {} val
  3113. */
  3114. var Entry = function (val) {
  3115. /**
  3116. * @type {}
  3117. */
  3118. this.value = val;
  3119. /**
  3120. * @type {module:zrender/core/LRU~Entry}
  3121. */
  3122. this.next;
  3123. /**
  3124. * @type {module:zrender/core/LRU~Entry}
  3125. */
  3126. this.prev;
  3127. };
  3128. /**
  3129. * LRU Cache
  3130. * @constructor
  3131. * @alias module:zrender/core/LRU
  3132. */
  3133. var LRU = function (maxSize) {
  3134. this._list = new LinkedList();
  3135. this._map = {};
  3136. this._maxSize = maxSize || 10;
  3137. this._lastRemovedEntry = null;
  3138. };
  3139. var LRUProto = LRU.prototype;
  3140. /**
  3141. * @param {string} key
  3142. * @param {} value
  3143. * @return {} Removed value
  3144. */
  3145. LRUProto.put = function (key, value) {
  3146. var list = this._list;
  3147. var map = this._map;
  3148. var removed = null;
  3149. if (map[key] == null) {
  3150. var len = list.len();
  3151. // Reuse last removed entry
  3152. var entry = this._lastRemovedEntry;
  3153. if (len >= this._maxSize && len > 0) {
  3154. // Remove the least recently used
  3155. var leastUsedEntry = list.head;
  3156. list.remove(leastUsedEntry);
  3157. delete map[leastUsedEntry.key];
  3158. removed = leastUsedEntry.value;
  3159. this._lastRemovedEntry = leastUsedEntry;
  3160. }
  3161. if (entry) {
  3162. entry.value = value;
  3163. }
  3164. else {
  3165. entry = new Entry(value);
  3166. }
  3167. entry.key = key;
  3168. list.insertEntry(entry);
  3169. map[key] = entry;
  3170. }
  3171. return removed;
  3172. };
  3173. /**
  3174. * @param {string} key
  3175. * @return {}
  3176. */
  3177. LRUProto.get = function (key) {
  3178. var entry = this._map[key];
  3179. var list = this._list;
  3180. if (entry != null) {
  3181. // Put the latest used entry in the tail
  3182. if (entry !== list.tail) {
  3183. list.remove(entry);
  3184. list.insertEntry(entry);
  3185. }
  3186. return entry.value;
  3187. }
  3188. };
  3189. /**
  3190. * Clear the cache
  3191. */
  3192. LRUProto.clear = function () {
  3193. this._list.clear();
  3194. this._map = {};
  3195. };
  3196. var kCSSColorTable = {
  3197. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3198. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3199. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3200. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3201. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3202. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3203. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3204. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3205. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3206. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3207. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3208. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3209. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3210. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3211. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3212. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3213. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3214. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3215. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3216. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3217. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3218. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3219. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3220. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3221. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3222. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3223. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3224. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3225. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3226. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3227. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3228. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3229. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3230. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3231. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3232. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3233. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3234. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3235. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3236. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3237. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3238. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3239. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3240. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3241. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3242. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3243. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3244. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3245. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3246. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3247. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3248. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3249. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3250. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3251. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3252. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3253. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3254. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3255. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3256. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3257. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3258. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3259. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3260. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3261. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3262. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3263. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3264. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3265. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3266. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3267. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3268. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3269. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3270. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3271. };
  3272. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3273. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3274. return i < 0 ? 0 : i > 255 ? 255 : i;
  3275. }
  3276. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3277. return f < 0 ? 0 : f > 1 ? 1 : f;
  3278. }
  3279. function parseCssInt(str) { // int or percentage.
  3280. if (str.length && str.charAt(str.length - 1) === '%') {
  3281. return clampCssByte(parseFloat(str) / 100 * 255);
  3282. }
  3283. return clampCssByte(parseInt(str, 10));
  3284. }
  3285. function parseCssFloat(str) { // float or percentage.
  3286. if (str.length && str.charAt(str.length - 1) === '%') {
  3287. return clampCssFloat(parseFloat(str) / 100);
  3288. }
  3289. return clampCssFloat(parseFloat(str));
  3290. }
  3291. function cssHueToRgb(m1, m2, h) {
  3292. if (h < 0) {
  3293. h += 1;
  3294. }
  3295. else if (h > 1) {
  3296. h -= 1;
  3297. }
  3298. if (h * 6 < 1) {
  3299. return m1 + (m2 - m1) * h * 6;
  3300. }
  3301. if (h * 2 < 1) {
  3302. return m2;
  3303. }
  3304. if (h * 3 < 2) {
  3305. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3306. }
  3307. return m1;
  3308. }
  3309. function setRgba(out, r, g, b, a) {
  3310. out[0] = r;
  3311. out[1] = g;
  3312. out[2] = b;
  3313. out[3] = a;
  3314. return out;
  3315. }
  3316. function copyRgba(out, a) {
  3317. out[0] = a[0];
  3318. out[1] = a[1];
  3319. out[2] = a[2];
  3320. out[3] = a[3];
  3321. return out;
  3322. }
  3323. var colorCache = new LRU(20);
  3324. var lastRemovedArr = null;
  3325. function putToCache(colorStr, rgbaArr) {
  3326. // Reuse removed array
  3327. if (lastRemovedArr) {
  3328. copyRgba(lastRemovedArr, rgbaArr);
  3329. }
  3330. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3331. }
  3332. /**
  3333. * @param {string} colorStr
  3334. * @param {Array.<number>} out
  3335. * @return {Array.<number>}
  3336. * @memberOf module:zrender/util/color
  3337. */
  3338. function parse(colorStr, rgbaArr) {
  3339. if (!colorStr) {
  3340. return;
  3341. }
  3342. rgbaArr = rgbaArr || [];
  3343. var cached = colorCache.get(colorStr);
  3344. if (cached) {
  3345. return copyRgba(rgbaArr, cached);
  3346. }
  3347. // colorStr may be not string
  3348. colorStr = colorStr + '';
  3349. // Remove all whitespace, not compliant, but should just be more accepting.
  3350. var str = colorStr.replace(/ /g, '').toLowerCase();
  3351. // Color keywords (and transparent) lookup.
  3352. if (str in kCSSColorTable) {
  3353. copyRgba(rgbaArr, kCSSColorTable[str]);
  3354. putToCache(colorStr, rgbaArr);
  3355. return rgbaArr;
  3356. }
  3357. // #abc and #abc123 syntax.
  3358. if (str.charAt(0) === '#') {
  3359. if (str.length === 4) {
  3360. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3361. if (!(iv >= 0 && iv <= 0xfff)) {
  3362. setRgba(rgbaArr, 0, 0, 0, 1);
  3363. return; // Covers NaN.
  3364. }
  3365. setRgba(rgbaArr,
  3366. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3367. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3368. (iv & 0xf) | ((iv & 0xf) << 4),
  3369. 1
  3370. );
  3371. putToCache(colorStr, rgbaArr);
  3372. return rgbaArr;
  3373. }
  3374. else if (str.length === 7) {
  3375. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3376. if (!(iv >= 0 && iv <= 0xffffff)) {
  3377. setRgba(rgbaArr, 0, 0, 0, 1);
  3378. return; // Covers NaN.
  3379. }
  3380. setRgba(rgbaArr,
  3381. (iv & 0xff0000) >> 16,
  3382. (iv & 0xff00) >> 8,
  3383. iv & 0xff,
  3384. 1
  3385. );
  3386. putToCache(colorStr, rgbaArr);
  3387. return rgbaArr;
  3388. }
  3389. return;
  3390. }
  3391. var op = str.indexOf('(');
  3392. var ep = str.indexOf(')');
  3393. if (op !== -1 && ep + 1 === str.length) {
  3394. var fname = str.substr(0, op);
  3395. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3396. var alpha = 1; // To allow case fallthrough.
  3397. switch (fname) {
  3398. case 'rgba':
  3399. if (params.length !== 4) {
  3400. setRgba(rgbaArr, 0, 0, 0, 1);
  3401. return;
  3402. }
  3403. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3404. // Fall through.
  3405. case 'rgb':
  3406. if (params.length !== 3) {
  3407. setRgba(rgbaArr, 0, 0, 0, 1);
  3408. return;
  3409. }
  3410. setRgba(rgbaArr,
  3411. parseCssInt(params[0]),
  3412. parseCssInt(params[1]),
  3413. parseCssInt(params[2]),
  3414. alpha
  3415. );
  3416. putToCache(colorStr, rgbaArr);
  3417. return rgbaArr;
  3418. case 'hsla':
  3419. if (params.length !== 4) {
  3420. setRgba(rgbaArr, 0, 0, 0, 1);
  3421. return;
  3422. }
  3423. params[3] = parseCssFloat(params[3]);
  3424. hsla2rgba(params, rgbaArr);
  3425. putToCache(colorStr, rgbaArr);
  3426. return rgbaArr;
  3427. case 'hsl':
  3428. if (params.length !== 3) {
  3429. setRgba(rgbaArr, 0, 0, 0, 1);
  3430. return;
  3431. }
  3432. hsla2rgba(params, rgbaArr);
  3433. putToCache(colorStr, rgbaArr);
  3434. return rgbaArr;
  3435. default:
  3436. return;
  3437. }
  3438. }
  3439. setRgba(rgbaArr, 0, 0, 0, 1);
  3440. return;
  3441. }
  3442. /**
  3443. * @param {Array.<number>} hsla
  3444. * @param {Array.<number>} rgba
  3445. * @return {Array.<number>} rgba
  3446. */
  3447. function hsla2rgba(hsla, rgba) {
  3448. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3449. // NOTE(deanm): According to the CSS spec s/l should only be
  3450. // percentages, but we don't bother and let float or percentage.
  3451. var s = parseCssFloat(hsla[1]);
  3452. var l = parseCssFloat(hsla[2]);
  3453. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3454. var m1 = l * 2 - m2;
  3455. rgba = rgba || [];
  3456. setRgba(rgba,
  3457. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3458. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3459. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3460. 1
  3461. );
  3462. if (hsla.length === 4) {
  3463. rgba[3] = hsla[3];
  3464. }
  3465. return rgba;
  3466. }
  3467. /**
  3468. * @param {string} color
  3469. * @param {number} level
  3470. * @return {string}
  3471. * @memberOf module:zrender/util/color
  3472. */
  3473. function lift(color, level) {
  3474. var colorArr = parse(color);
  3475. if (colorArr) {
  3476. for (var i = 0; i < 3; i++) {
  3477. if (level < 0) {
  3478. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3479. }
  3480. else {
  3481. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3482. }
  3483. if (colorArr[i] > 255) {
  3484. colorArr[i] = 255;
  3485. }
  3486. else if (color[i] < 0) {
  3487. colorArr[i] = 0;
  3488. }
  3489. }
  3490. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3491. }
  3492. }
  3493. /**
  3494. * @param {string} color
  3495. * @return {string}
  3496. * @memberOf module:zrender/util/color
  3497. */
  3498. /**
  3499. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3500. * @param {number} normalizedValue A float between 0 and 1.
  3501. * @param {Array.<Array.<number>>} colors List of rgba color array
  3502. * @param {Array.<number>} [out] Mapped gba color array
  3503. * @return {Array.<number>} will be null/undefined if input illegal.
  3504. */
  3505. /**
  3506. * @deprecated
  3507. */
  3508. /**
  3509. * @param {number} normalizedValue A float between 0 and 1.
  3510. * @param {Array.<string>} colors Color list.
  3511. * @param {boolean=} fullOutput Default false.
  3512. * @return {(string|Object)} Result color. If fullOutput,
  3513. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3514. * @memberOf module:zrender/util/color
  3515. */
  3516. /**
  3517. * @deprecated
  3518. */
  3519. /**
  3520. * @param {string} color
  3521. * @param {number=} h 0 ~ 360, ignore when null.
  3522. * @param {number=} s 0 ~ 1, ignore when null.
  3523. * @param {number=} l 0 ~ 1, ignore when null.
  3524. * @return {string} Color string in rgba format.
  3525. * @memberOf module:zrender/util/color
  3526. */
  3527. /**
  3528. * @param {string} color
  3529. * @param {number=} alpha 0 ~ 1
  3530. * @return {string} Color string in rgba format.
  3531. * @memberOf module:zrender/util/color
  3532. */
  3533. /**
  3534. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3535. * @param {string} type 'rgba', 'hsva', ...
  3536. * @return {string} Result color. (If input illegal, return undefined).
  3537. */
  3538. function stringify(arrColor, type) {
  3539. if (!arrColor || !arrColor.length) {
  3540. return;
  3541. }
  3542. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3543. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3544. colorStr += ',' + arrColor[3];
  3545. }
  3546. return type + '(' + colorStr + ')';
  3547. }
  3548. /**
  3549. * @module echarts/animation/Animator
  3550. */
  3551. var arraySlice = Array.prototype.slice;
  3552. function defaultGetter(target, key) {
  3553. return target[key];
  3554. }
  3555. function defaultSetter(target, key, value) {
  3556. target[key] = value;
  3557. }
  3558. /**
  3559. * @param {number} p0
  3560. * @param {number} p1
  3561. * @param {number} percent
  3562. * @return {number}
  3563. */
  3564. function interpolateNumber(p0, p1, percent) {
  3565. return (p1 - p0) * percent + p0;
  3566. }
  3567. /**
  3568. * @param {string} p0
  3569. * @param {string} p1
  3570. * @param {number} percent
  3571. * @return {string}
  3572. */
  3573. function interpolateString(p0, p1, percent) {
  3574. return percent > 0.5 ? p1 : p0;
  3575. }
  3576. /**
  3577. * @param {Array} p0
  3578. * @param {Array} p1
  3579. * @param {number} percent
  3580. * @param {Array} out
  3581. * @param {number} arrDim
  3582. */
  3583. function interpolateArray(p0, p1, percent, out, arrDim) {
  3584. var len = p0.length;
  3585. if (arrDim === 1) {
  3586. for (var i = 0; i < len; i++) {
  3587. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3588. }
  3589. }
  3590. else {
  3591. var len2 = len && p0[0].length;
  3592. for (var i = 0; i < len; i++) {
  3593. for (var j = 0; j < len2; j++) {
  3594. out[i][j] = interpolateNumber(
  3595. p0[i][j], p1[i][j], percent
  3596. );
  3597. }
  3598. }
  3599. }
  3600. }
  3601. // arr0 is source array, arr1 is target array.
  3602. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3603. function fillArr(arr0, arr1, arrDim) {
  3604. var arr0Len = arr0.length;
  3605. var arr1Len = arr1.length;
  3606. if (arr0Len !== arr1Len) {
  3607. // FIXME Not work for TypedArray
  3608. var isPreviousLarger = arr0Len > arr1Len;
  3609. if (isPreviousLarger) {
  3610. // Cut the previous
  3611. arr0.length = arr1Len;
  3612. }
  3613. else {
  3614. // Fill the previous
  3615. for (var i = arr0Len; i < arr1Len; i++) {
  3616. arr0.push(
  3617. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3618. );
  3619. }
  3620. }
  3621. }
  3622. // Handling NaN value
  3623. var len2 = arr0[0] && arr0[0].length;
  3624. for (var i = 0; i < arr0.length; i++) {
  3625. if (arrDim === 1) {
  3626. if (isNaN(arr0[i])) {
  3627. arr0[i] = arr1[i];
  3628. }
  3629. }
  3630. else {
  3631. for (var j = 0; j < len2; j++) {
  3632. if (isNaN(arr0[i][j])) {
  3633. arr0[i][j] = arr1[i][j];
  3634. }
  3635. }
  3636. }
  3637. }
  3638. }
  3639. /**
  3640. * @param {Array} arr0
  3641. * @param {Array} arr1
  3642. * @param {number} arrDim
  3643. * @return {boolean}
  3644. */
  3645. function isArraySame(arr0, arr1, arrDim) {
  3646. if (arr0 === arr1) {
  3647. return true;
  3648. }
  3649. var len = arr0.length;
  3650. if (len !== arr1.length) {
  3651. return false;
  3652. }
  3653. if (arrDim === 1) {
  3654. for (var i = 0; i < len; i++) {
  3655. if (arr0[i] !== arr1[i]) {
  3656. return false;
  3657. }
  3658. }
  3659. }
  3660. else {
  3661. var len2 = arr0[0].length;
  3662. for (var i = 0; i < len; i++) {
  3663. for (var j = 0; j < len2; j++) {
  3664. if (arr0[i][j] !== arr1[i][j]) {
  3665. return false;
  3666. }
  3667. }
  3668. }
  3669. }
  3670. return true;
  3671. }
  3672. /**
  3673. * Catmull Rom interpolate array
  3674. * @param {Array} p0
  3675. * @param {Array} p1
  3676. * @param {Array} p2
  3677. * @param {Array} p3
  3678. * @param {number} t
  3679. * @param {number} t2
  3680. * @param {number} t3
  3681. * @param {Array} out
  3682. * @param {number} arrDim
  3683. */
  3684. function catmullRomInterpolateArray(
  3685. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3686. ) {
  3687. var len = p0.length;
  3688. if (arrDim === 1) {
  3689. for (var i = 0; i < len; i++) {
  3690. out[i] = catmullRomInterpolate(
  3691. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3692. );
  3693. }
  3694. }
  3695. else {
  3696. var len2 = p0[0].length;
  3697. for (var i = 0; i < len; i++) {
  3698. for (var j = 0; j < len2; j++) {
  3699. out[i][j] = catmullRomInterpolate(
  3700. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3701. t, t2, t3
  3702. );
  3703. }
  3704. }
  3705. }
  3706. }
  3707. /**
  3708. * Catmull Rom interpolate number
  3709. * @param {number} p0
  3710. * @param {number} p1
  3711. * @param {number} p2
  3712. * @param {number} p3
  3713. * @param {number} t
  3714. * @param {number} t2
  3715. * @param {number} t3
  3716. * @return {number}
  3717. */
  3718. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3719. var v0 = (p2 - p0) * 0.5;
  3720. var v1 = (p3 - p1) * 0.5;
  3721. return (2 * (p1 - p2) + v0 + v1) * t3
  3722. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3723. + v0 * t + p1;
  3724. }
  3725. function cloneValue(value) {
  3726. if (isArrayLike(value)) {
  3727. var len = value.length;
  3728. if (isArrayLike(value[0])) {
  3729. var ret = [];
  3730. for (var i = 0; i < len; i++) {
  3731. ret.push(arraySlice.call(value[i]));
  3732. }
  3733. return ret;
  3734. }
  3735. return arraySlice.call(value);
  3736. }
  3737. return value;
  3738. }
  3739. function rgba2String(rgba) {
  3740. rgba[0] = Math.floor(rgba[0]);
  3741. rgba[1] = Math.floor(rgba[1]);
  3742. rgba[2] = Math.floor(rgba[2]);
  3743. return 'rgba(' + rgba.join(',') + ')';
  3744. }
  3745. function getArrayDim(keyframes) {
  3746. var lastValue = keyframes[keyframes.length - 1].value;
  3747. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3748. }
  3749. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3750. var getter = animator._getter;
  3751. var setter = animator._setter;
  3752. var useSpline = easing === 'spline';
  3753. var trackLen = keyframes.length;
  3754. if (!trackLen) {
  3755. return;
  3756. }
  3757. // Guess data type
  3758. var firstVal = keyframes[0].value;
  3759. var isValueArray = isArrayLike(firstVal);
  3760. var isValueColor = false;
  3761. var isValueString = false;
  3762. // For vertices morphing
  3763. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3764. var trackMaxTime;
  3765. // Sort keyframe as ascending
  3766. keyframes.sort(function (a, b) {
  3767. return a.time - b.time;
  3768. });
  3769. trackMaxTime = keyframes[trackLen - 1].time;
  3770. // Percents of each keyframe
  3771. var kfPercents = [];
  3772. // Value of each keyframe
  3773. var kfValues = [];
  3774. var prevValue = keyframes[0].value;
  3775. var isAllValueEqual = true;
  3776. for (var i = 0; i < trackLen; i++) {
  3777. kfPercents.push(keyframes[i].time / trackMaxTime);
  3778. // Assume value is a color when it is a string
  3779. var value = keyframes[i].value;
  3780. // Check if value is equal, deep check if value is array
  3781. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3782. || (!isValueArray && value === prevValue))) {
  3783. isAllValueEqual = false;
  3784. }
  3785. prevValue = value;
  3786. // Try converting a string to a color array
  3787. if (typeof value === 'string') {
  3788. var colorArray = parse(value);
  3789. if (colorArray) {
  3790. value = colorArray;
  3791. isValueColor = true;
  3792. }
  3793. else {
  3794. isValueString = true;
  3795. }
  3796. }
  3797. kfValues.push(value);
  3798. }
  3799. if (!forceAnimate && isAllValueEqual) {
  3800. return;
  3801. }
  3802. var lastValue = kfValues[trackLen - 1];
  3803. // Polyfill array and NaN value
  3804. for (var i = 0; i < trackLen - 1; i++) {
  3805. if (isValueArray) {
  3806. fillArr(kfValues[i], lastValue, arrDim);
  3807. }
  3808. else {
  3809. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3810. kfValues[i] = lastValue;
  3811. }
  3812. }
  3813. }
  3814. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3815. // Cache the key of last frame to speed up when
  3816. // animation playback is sequency
  3817. var lastFrame = 0;
  3818. var lastFramePercent = 0;
  3819. var start;
  3820. var w;
  3821. var p0;
  3822. var p1;
  3823. var p2;
  3824. var p3;
  3825. if (isValueColor) {
  3826. var rgba = [0, 0, 0, 0];
  3827. }
  3828. var onframe = function (target, percent) {
  3829. // Find the range keyframes
  3830. // kf1-----kf2---------current--------kf3
  3831. // find kf2 and kf3 and do interpolation
  3832. var frame;
  3833. // In the easing function like elasticOut, percent may less than 0
  3834. if (percent < 0) {
  3835. frame = 0;
  3836. }
  3837. else if (percent < lastFramePercent) {
  3838. // Start from next key
  3839. // PENDING start from lastFrame ?
  3840. start = Math.min(lastFrame + 1, trackLen - 1);
  3841. for (frame = start; frame >= 0; frame--) {
  3842. if (kfPercents[frame] <= percent) {
  3843. break;
  3844. }
  3845. }
  3846. // PENDING really need to do this ?
  3847. frame = Math.min(frame, trackLen - 2);
  3848. }
  3849. else {
  3850. for (frame = lastFrame; frame < trackLen; frame++) {
  3851. if (kfPercents[frame] > percent) {
  3852. break;
  3853. }
  3854. }
  3855. frame = Math.min(frame - 1, trackLen - 2);
  3856. }
  3857. lastFrame = frame;
  3858. lastFramePercent = percent;
  3859. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3860. if (range === 0) {
  3861. return;
  3862. }
  3863. else {
  3864. w = (percent - kfPercents[frame]) / range;
  3865. }
  3866. if (useSpline) {
  3867. p1 = kfValues[frame];
  3868. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3869. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3870. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3871. if (isValueArray) {
  3872. catmullRomInterpolateArray(
  3873. p0, p1, p2, p3, w, w * w, w * w * w,
  3874. getter(target, propName),
  3875. arrDim
  3876. );
  3877. }
  3878. else {
  3879. var value;
  3880. if (isValueColor) {
  3881. value = catmullRomInterpolateArray(
  3882. p0, p1, p2, p3, w, w * w, w * w * w,
  3883. rgba, 1
  3884. );
  3885. value = rgba2String(rgba);
  3886. }
  3887. else if (isValueString) {
  3888. // String is step(0.5)
  3889. return interpolateString(p1, p2, w);
  3890. }
  3891. else {
  3892. value = catmullRomInterpolate(
  3893. p0, p1, p2, p3, w, w * w, w * w * w
  3894. );
  3895. }
  3896. setter(
  3897. target,
  3898. propName,
  3899. value
  3900. );
  3901. }
  3902. }
  3903. else {
  3904. if (isValueArray) {
  3905. interpolateArray(
  3906. kfValues[frame], kfValues[frame + 1], w,
  3907. getter(target, propName),
  3908. arrDim
  3909. );
  3910. }
  3911. else {
  3912. var value;
  3913. if (isValueColor) {
  3914. interpolateArray(
  3915. kfValues[frame], kfValues[frame + 1], w,
  3916. rgba, 1
  3917. );
  3918. value = rgba2String(rgba);
  3919. }
  3920. else if (isValueString) {
  3921. // String is step(0.5)
  3922. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3923. }
  3924. else {
  3925. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3926. }
  3927. setter(
  3928. target,
  3929. propName,
  3930. value
  3931. );
  3932. }
  3933. }
  3934. };
  3935. var clip = new Clip({
  3936. target: animator._target,
  3937. life: trackMaxTime,
  3938. loop: animator._loop,
  3939. delay: animator._delay,
  3940. onframe: onframe,
  3941. ondestroy: oneTrackDone
  3942. });
  3943. if (easing && easing !== 'spline') {
  3944. clip.easing = easing;
  3945. }
  3946. return clip;
  3947. }
  3948. /**
  3949. * @alias module:zrender/animation/Animator
  3950. * @constructor
  3951. * @param {Object} target
  3952. * @param {boolean} loop
  3953. * @param {Function} getter
  3954. * @param {Function} setter
  3955. */
  3956. var Animator = function (target, loop, getter, setter) {
  3957. this._tracks = {};
  3958. this._target = target;
  3959. this._loop = loop || false;
  3960. this._getter = getter || defaultGetter;
  3961. this._setter = setter || defaultSetter;
  3962. this._clipCount = 0;
  3963. this._delay = 0;
  3964. this._doneList = [];
  3965. this._onframeList = [];
  3966. this._clipList = [];
  3967. };
  3968. Animator.prototype = {
  3969. /**
  3970. * 设置动画关键帧
  3971. * @param {number} time 关键帧时间,单位是ms
  3972. * @param {Object} props 关键帧的属性值,key-value表示
  3973. * @return {module:zrender/animation/Animator}
  3974. */
  3975. when: function (time /* ms */, props) {
  3976. var tracks = this._tracks;
  3977. for (var propName in props) {
  3978. if (!props.hasOwnProperty(propName)) {
  3979. continue;
  3980. }
  3981. if (!tracks[propName]) {
  3982. tracks[propName] = [];
  3983. // Invalid value
  3984. var value = this._getter(this._target, propName);
  3985. if (value == null) {
  3986. // zrLog('Invalid property ' + propName);
  3987. continue;
  3988. }
  3989. // If time is 0
  3990. // Then props is given initialize value
  3991. // Else
  3992. // Initialize value from current prop value
  3993. if (time !== 0) {
  3994. tracks[propName].push({
  3995. time: 0,
  3996. value: cloneValue(value)
  3997. });
  3998. }
  3999. }
  4000. tracks[propName].push({
  4001. time: time,
  4002. value: props[propName]
  4003. });
  4004. }
  4005. return this;
  4006. },
  4007. /**
  4008. * 添加动画每一帧的回调函数
  4009. * @param {Function} callback
  4010. * @return {module:zrender/animation/Animator}
  4011. */
  4012. during: function (callback) {
  4013. this._onframeList.push(callback);
  4014. return this;
  4015. },
  4016. pause: function () {
  4017. for (var i = 0; i < this._clipList.length; i++) {
  4018. this._clipList[i].pause();
  4019. }
  4020. this._paused = true;
  4021. },
  4022. resume: function () {
  4023. for (var i = 0; i < this._clipList.length; i++) {
  4024. this._clipList[i].resume();
  4025. }
  4026. this._paused = false;
  4027. },
  4028. isPaused: function () {
  4029. return !!this._paused;
  4030. },
  4031. _doneCallback: function () {
  4032. // Clear all tracks
  4033. this._tracks = {};
  4034. // Clear all clips
  4035. this._clipList.length = 0;
  4036. var doneList = this._doneList;
  4037. var len = doneList.length;
  4038. for (var i = 0; i < len; i++) {
  4039. doneList[i].call(this);
  4040. }
  4041. },
  4042. /**
  4043. * 开始执行动画
  4044. * @param {string|Function} [easing]
  4045. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4046. * @param {boolean} forceAnimate
  4047. * @return {module:zrender/animation/Animator}
  4048. */
  4049. start: function (easing, forceAnimate) {
  4050. var self = this;
  4051. var clipCount = 0;
  4052. var oneTrackDone = function () {
  4053. clipCount--;
  4054. if (!clipCount) {
  4055. self._doneCallback();
  4056. }
  4057. };
  4058. var lastClip;
  4059. for (var propName in this._tracks) {
  4060. if (!this._tracks.hasOwnProperty(propName)) {
  4061. continue;
  4062. }
  4063. var clip = createTrackClip(
  4064. this, easing, oneTrackDone,
  4065. this._tracks[propName], propName, forceAnimate
  4066. );
  4067. if (clip) {
  4068. this._clipList.push(clip);
  4069. clipCount++;
  4070. // If start after added to animation
  4071. if (this.animation) {
  4072. this.animation.addClip(clip);
  4073. }
  4074. lastClip = clip;
  4075. }
  4076. }
  4077. // Add during callback on the last clip
  4078. if (lastClip) {
  4079. var oldOnFrame = lastClip.onframe;
  4080. lastClip.onframe = function (target, percent) {
  4081. oldOnFrame(target, percent);
  4082. for (var i = 0; i < self._onframeList.length; i++) {
  4083. self._onframeList[i](target, percent);
  4084. }
  4085. };
  4086. }
  4087. // This optimization will help the case that in the upper application
  4088. // the view may be refreshed frequently, where animation will be
  4089. // called repeatly but nothing changed.
  4090. if (!clipCount) {
  4091. this._doneCallback();
  4092. }
  4093. return this;
  4094. },
  4095. /**
  4096. * 停止动画
  4097. * @param {boolean} forwardToLast If move to last frame before stop
  4098. */
  4099. stop: function (forwardToLast) {
  4100. var clipList = this._clipList;
  4101. var animation = this.animation;
  4102. for (var i = 0; i < clipList.length; i++) {
  4103. var clip = clipList[i];
  4104. if (forwardToLast) {
  4105. // Move to last frame before stop
  4106. clip.onframe(this._target, 1);
  4107. }
  4108. animation && animation.removeClip(clip);
  4109. }
  4110. clipList.length = 0;
  4111. },
  4112. /**
  4113. * 设置动画延迟开始的时间
  4114. * @param {number} time 单位ms
  4115. * @return {module:zrender/animation/Animator}
  4116. */
  4117. delay: function (time) {
  4118. this._delay = time;
  4119. return this;
  4120. },
  4121. /**
  4122. * 添加动画结束的回调
  4123. * @param {Function} cb
  4124. * @return {module:zrender/animation/Animator}
  4125. */
  4126. done: function (cb) {
  4127. if (cb) {
  4128. this._doneList.push(cb);
  4129. }
  4130. return this;
  4131. },
  4132. /**
  4133. * @return {Array.<module:zrender/animation/Clip>}
  4134. */
  4135. getClips: function () {
  4136. return this._clipList;
  4137. }
  4138. };
  4139. var dpr = 1;
  4140. // If in browser environment
  4141. if (typeof window !== 'undefined') {
  4142. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4143. }
  4144. /**
  4145. * config默认配置项
  4146. * @exports zrender/config
  4147. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4148. */
  4149. /**
  4150. * Debug log mode:
  4151. * 0: Do nothing, for release.
  4152. * 1: console.error, for debug.
  4153. */
  4154. var debugMode = 0;
  4155. // retina 屏幕优化
  4156. var devicePixelRatio = dpr;
  4157. var logError = function () {
  4158. };
  4159. if (debugMode === 1) {
  4160. logError = console.error;
  4161. }
  4162. var logError$1 = logError;
  4163. /**
  4164. * @alias modue:zrender/mixin/Animatable
  4165. * @constructor
  4166. */
  4167. var Animatable = function () {
  4168. /**
  4169. * @type {Array.<module:zrender/animation/Animator>}
  4170. * @readOnly
  4171. */
  4172. this.animators = [];
  4173. };
  4174. Animatable.prototype = {
  4175. constructor: Animatable,
  4176. /**
  4177. * 动画
  4178. *
  4179. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4180. * @param {boolean} [loop] Whether to loop animation.
  4181. * @return {module:zrender/animation/Animator}
  4182. * @example:
  4183. * el.animate('style', false)
  4184. * .when(1000, {x: 10} )
  4185. * .done(function(){ // Animation done })
  4186. * .start()
  4187. */
  4188. animate: function (path, loop) {
  4189. var target;
  4190. var animatingShape = false;
  4191. var el = this;
  4192. var zr = this.__zr;
  4193. if (path) {
  4194. var pathSplitted = path.split('.');
  4195. var prop = el;
  4196. // If animating shape
  4197. animatingShape = pathSplitted[0] === 'shape';
  4198. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4199. if (!prop) {
  4200. continue;
  4201. }
  4202. prop = prop[pathSplitted[i]];
  4203. }
  4204. if (prop) {
  4205. target = prop;
  4206. }
  4207. }
  4208. else {
  4209. target = el;
  4210. }
  4211. if (!target) {
  4212. logError$1(
  4213. 'Property "'
  4214. + path
  4215. + '" is not existed in element '
  4216. + el.id
  4217. );
  4218. return;
  4219. }
  4220. var animators = el.animators;
  4221. var animator = new Animator(target, loop);
  4222. animator.during(function (target) {
  4223. el.dirty(animatingShape);
  4224. })
  4225. .done(function () {
  4226. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4227. animators.splice(indexOf(animators, animator), 1);
  4228. });
  4229. animators.push(animator);
  4230. // If animate after added to the zrender
  4231. if (zr) {
  4232. zr.animation.addAnimator(animator);
  4233. }
  4234. return animator;
  4235. },
  4236. /**
  4237. * 停止动画
  4238. * @param {boolean} forwardToLast If move to last frame before stop
  4239. */
  4240. stopAnimation: function (forwardToLast) {
  4241. var animators = this.animators;
  4242. var len = animators.length;
  4243. for (var i = 0; i < len; i++) {
  4244. animators[i].stop(forwardToLast);
  4245. }
  4246. animators.length = 0;
  4247. return this;
  4248. },
  4249. /**
  4250. * Caution: this method will stop previous animation.
  4251. * So do not use this method to one element twice before
  4252. * animation starts, unless you know what you are doing.
  4253. * @param {Object} target
  4254. * @param {number} [time=500] Time in ms
  4255. * @param {string} [easing='linear']
  4256. * @param {number} [delay=0]
  4257. * @param {Function} [callback]
  4258. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4259. * immediently when target values are the same as current values.
  4260. *
  4261. * @example
  4262. * // Animate position
  4263. * el.animateTo({
  4264. * position: [10, 10]
  4265. * }, function () { // done })
  4266. *
  4267. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4268. * el.animateTo({
  4269. * shape: {
  4270. * width: 500
  4271. * },
  4272. * style: {
  4273. * fill: 'red'
  4274. * }
  4275. * position: [10, 10]
  4276. * }, 100, 100, 'cubicOut', function () { // done })
  4277. */
  4278. // TODO Return animation key
  4279. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4280. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4281. },
  4282. /**
  4283. * Animate from the target state to current state.
  4284. * The params and the return value are the same as `this.animateTo`.
  4285. */
  4286. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4287. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4288. }
  4289. };
  4290. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4291. // animateTo(target, time, easing, callback);
  4292. if (isString(delay)) {
  4293. callback = easing;
  4294. easing = delay;
  4295. delay = 0;
  4296. }
  4297. // animateTo(target, time, delay, callback);
  4298. else if (isFunction$1(easing)) {
  4299. callback = easing;
  4300. easing = 'linear';
  4301. delay = 0;
  4302. }
  4303. // animateTo(target, time, callback);
  4304. else if (isFunction$1(delay)) {
  4305. callback = delay;
  4306. delay = 0;
  4307. }
  4308. // animateTo(target, callback)
  4309. else if (isFunction$1(time)) {
  4310. callback = time;
  4311. time = 500;
  4312. }
  4313. // animateTo(target)
  4314. else if (!time) {
  4315. time = 500;
  4316. }
  4317. // Stop all previous animations
  4318. animatable.stopAnimation();
  4319. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4320. // Animators may be removed immediately after start
  4321. // if there is nothing to animate
  4322. var animators = animatable.animators.slice();
  4323. var count = animators.length;
  4324. function done() {
  4325. count--;
  4326. if (!count) {
  4327. callback && callback();
  4328. }
  4329. }
  4330. // No animators. This should be checked before animators[i].start(),
  4331. // because 'done' may be executed immediately if no need to animate.
  4332. if (!count) {
  4333. callback && callback();
  4334. }
  4335. // Start after all animators created
  4336. // Incase any animator is done immediately when all animation properties are not changed
  4337. for (var i = 0; i < animators.length; i++) {
  4338. animators[i]
  4339. .done(done)
  4340. .start(easing, forceAnimate);
  4341. }
  4342. }
  4343. /**
  4344. * @param {string} path=''
  4345. * @param {Object} source=animatable
  4346. * @param {Object} target
  4347. * @param {number} [time=500]
  4348. * @param {number} [delay=0]
  4349. * @param {boolean} [reverse] If `true`, animate
  4350. * from the `target` to current state.
  4351. *
  4352. * @example
  4353. * // Animate position
  4354. * el._animateToShallow({
  4355. * position: [10, 10]
  4356. * })
  4357. *
  4358. * // Animate shape, style and position in 100ms, delayed 100ms
  4359. * el._animateToShallow({
  4360. * shape: {
  4361. * width: 500
  4362. * },
  4363. * style: {
  4364. * fill: 'red'
  4365. * }
  4366. * position: [10, 10]
  4367. * }, 100, 100)
  4368. */
  4369. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4370. var objShallow = {};
  4371. var propertyCount = 0;
  4372. for (var name in target) {
  4373. if (!target.hasOwnProperty(name)) {
  4374. continue;
  4375. }
  4376. if (source[name] != null) {
  4377. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4378. animateToShallow(
  4379. animatable,
  4380. path ? path + '.' + name : name,
  4381. source[name],
  4382. target[name],
  4383. time,
  4384. delay,
  4385. reverse
  4386. );
  4387. }
  4388. else {
  4389. if (reverse) {
  4390. objShallow[name] = source[name];
  4391. setAttrByPath(animatable, path, name, target[name]);
  4392. }
  4393. else {
  4394. objShallow[name] = target[name];
  4395. }
  4396. propertyCount++;
  4397. }
  4398. }
  4399. else if (target[name] != null && !reverse) {
  4400. setAttrByPath(animatable, path, name, target[name]);
  4401. }
  4402. }
  4403. if (propertyCount > 0) {
  4404. animatable.animate(path, false)
  4405. .when(time == null ? 500 : time, objShallow)
  4406. .delay(delay || 0);
  4407. }
  4408. }
  4409. function setAttrByPath(el, path, name, value) {
  4410. // Attr directly if not has property
  4411. // FIXME, if some property not needed for element ?
  4412. if (!path) {
  4413. el.attr(name, value);
  4414. }
  4415. else {
  4416. // Only support set shape or style
  4417. var props = {};
  4418. props[path] = {};
  4419. props[path][name] = value;
  4420. el.attr(props);
  4421. }
  4422. }
  4423. /**
  4424. * @alias module:zrender/Element
  4425. * @constructor
  4426. * @extends {module:zrender/mixin/Animatable}
  4427. * @extends {module:zrender/mixin/Transformable}
  4428. * @extends {module:zrender/mixin/Eventful}
  4429. */
  4430. var Element = function (opts) { // jshint ignore:line
  4431. Transformable.call(this, opts);
  4432. Eventful.call(this, opts);
  4433. Animatable.call(this, opts);
  4434. /**
  4435. * 画布元素ID
  4436. * @type {string}
  4437. */
  4438. this.id = opts.id || guid();
  4439. };
  4440. Element.prototype = {
  4441. /**
  4442. * 元素类型
  4443. * Element type
  4444. * @type {string}
  4445. */
  4446. type: 'element',
  4447. /**
  4448. * 元素名字
  4449. * Element name
  4450. * @type {string}
  4451. */
  4452. name: '',
  4453. /**
  4454. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4455. * ZRender instance will be assigned when element is associated with zrender
  4456. * @name module:/zrender/Element#__zr
  4457. * @type {module:zrender/ZRender}
  4458. */
  4459. __zr: null,
  4460. /**
  4461. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4462. * If ignore drawing and events of the element object
  4463. * @name module:/zrender/Element#ignore
  4464. * @type {boolean}
  4465. * @default false
  4466. */
  4467. ignore: false,
  4468. /**
  4469. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4470. * 该路径会继承被裁减对象的变换
  4471. * @type {module:zrender/graphic/Path}
  4472. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4473. * @readOnly
  4474. */
  4475. clipPath: null,
  4476. /**
  4477. * 是否是 Group
  4478. * @type {boolean}
  4479. */
  4480. isGroup: false,
  4481. /**
  4482. * Drift element
  4483. * @param {number} dx dx on the global space
  4484. * @param {number} dy dy on the global space
  4485. */
  4486. drift: function (dx, dy) {
  4487. switch (this.draggable) {
  4488. case 'horizontal':
  4489. dy = 0;
  4490. break;
  4491. case 'vertical':
  4492. dx = 0;
  4493. break;
  4494. }
  4495. var m = this.transform;
  4496. if (!m) {
  4497. m = this.transform = [1, 0, 0, 1, 0, 0];
  4498. }
  4499. m[4] += dx;
  4500. m[5] += dy;
  4501. this.decomposeTransform();
  4502. this.dirty(false);
  4503. },
  4504. /**
  4505. * Hook before update
  4506. */
  4507. beforeUpdate: function () {},
  4508. /**
  4509. * Hook after update
  4510. */
  4511. afterUpdate: function () {},
  4512. /**
  4513. * Update each frame
  4514. */
  4515. update: function () {
  4516. this.updateTransform();
  4517. },
  4518. /**
  4519. * @param {Function} cb
  4520. * @param {} context
  4521. */
  4522. traverse: function (cb, context) {},
  4523. /**
  4524. * @protected
  4525. */
  4526. attrKV: function (key, value) {
  4527. if (key === 'position' || key === 'scale' || key === 'origin') {
  4528. // Copy the array
  4529. if (value) {
  4530. var target = this[key];
  4531. if (!target) {
  4532. target = this[key] = [];
  4533. }
  4534. target[0] = value[0];
  4535. target[1] = value[1];
  4536. }
  4537. }
  4538. else {
  4539. this[key] = value;
  4540. }
  4541. },
  4542. /**
  4543. * Hide the element
  4544. */
  4545. hide: function () {
  4546. this.ignore = true;
  4547. this.__zr && this.__zr.refresh();
  4548. },
  4549. /**
  4550. * Show the element
  4551. */
  4552. show: function () {
  4553. this.ignore = false;
  4554. this.__zr && this.__zr.refresh();
  4555. },
  4556. /**
  4557. * @param {string|Object} key
  4558. * @param {*} value
  4559. */
  4560. attr: function (key, value) {
  4561. if (typeof key === 'string') {
  4562. this.attrKV(key, value);
  4563. }
  4564. else if (isObject$1(key)) {
  4565. for (var name in key) {
  4566. if (key.hasOwnProperty(name)) {
  4567. this.attrKV(name, key[name]);
  4568. }
  4569. }
  4570. }
  4571. this.dirty(false);
  4572. return this;
  4573. },
  4574. /**
  4575. * @param {module:zrender/graphic/Path} clipPath
  4576. */
  4577. setClipPath: function (clipPath) {
  4578. var zr = this.__zr;
  4579. if (zr) {
  4580. clipPath.addSelfToZr(zr);
  4581. }
  4582. // Remove previous clip path
  4583. if (this.clipPath && this.clipPath !== clipPath) {
  4584. this.removeClipPath();
  4585. }
  4586. this.clipPath = clipPath;
  4587. clipPath.__zr = zr;
  4588. clipPath.__clipTarget = this;
  4589. this.dirty(false);
  4590. },
  4591. /**
  4592. */
  4593. removeClipPath: function () {
  4594. var clipPath = this.clipPath;
  4595. if (clipPath) {
  4596. if (clipPath.__zr) {
  4597. clipPath.removeSelfFromZr(clipPath.__zr);
  4598. }
  4599. clipPath.__zr = null;
  4600. clipPath.__clipTarget = null;
  4601. this.clipPath = null;
  4602. this.dirty(false);
  4603. }
  4604. },
  4605. /**
  4606. * Add self from zrender instance.
  4607. * Not recursively because it will be invoked when element added to storage.
  4608. * @param {module:zrender/ZRender} zr
  4609. */
  4610. addSelfToZr: function (zr) {
  4611. this.__zr = zr;
  4612. // 添加动画
  4613. var animators = this.animators;
  4614. if (animators) {
  4615. for (var i = 0; i < animators.length; i++) {
  4616. zr.animation.addAnimator(animators[i]);
  4617. }
  4618. }
  4619. if (this.clipPath) {
  4620. this.clipPath.addSelfToZr(zr);
  4621. }
  4622. },
  4623. /**
  4624. * Remove self from zrender instance.
  4625. * Not recursively because it will be invoked when element added to storage.
  4626. * @param {module:zrender/ZRender} zr
  4627. */
  4628. removeSelfFromZr: function (zr) {
  4629. this.__zr = null;
  4630. // 移除动画
  4631. var animators = this.animators;
  4632. if (animators) {
  4633. for (var i = 0; i < animators.length; i++) {
  4634. zr.animation.removeAnimator(animators[i]);
  4635. }
  4636. }
  4637. if (this.clipPath) {
  4638. this.clipPath.removeSelfFromZr(zr);
  4639. }
  4640. }
  4641. };
  4642. mixin(Element, Animatable);
  4643. mixin(Element, Transformable);
  4644. mixin(Element, Eventful);
  4645. /**
  4646. * @module echarts/core/BoundingRect
  4647. */
  4648. var v2ApplyTransform = applyTransform;
  4649. var mathMin = Math.min;
  4650. var mathMax = Math.max;
  4651. /**
  4652. * @alias module:echarts/core/BoundingRect
  4653. */
  4654. function BoundingRect(x, y, width, height) {
  4655. if (width < 0) {
  4656. x = x + width;
  4657. width = -width;
  4658. }
  4659. if (height < 0) {
  4660. y = y + height;
  4661. height = -height;
  4662. }
  4663. /**
  4664. * @type {number}
  4665. */
  4666. this.x = x;
  4667. /**
  4668. * @type {number}
  4669. */
  4670. this.y = y;
  4671. /**
  4672. * @type {number}
  4673. */
  4674. this.width = width;
  4675. /**
  4676. * @type {number}
  4677. */
  4678. this.height = height;
  4679. }
  4680. BoundingRect.prototype = {
  4681. constructor: BoundingRect,
  4682. /**
  4683. * @param {module:echarts/core/BoundingRect} other
  4684. */
  4685. union: function (other) {
  4686. var x = mathMin(other.x, this.x);
  4687. var y = mathMin(other.y, this.y);
  4688. this.width = mathMax(
  4689. other.x + other.width,
  4690. this.x + this.width
  4691. ) - x;
  4692. this.height = mathMax(
  4693. other.y + other.height,
  4694. this.y + this.height
  4695. ) - y;
  4696. this.x = x;
  4697. this.y = y;
  4698. },
  4699. /**
  4700. * @param {Array.<number>} m
  4701. * @methods
  4702. */
  4703. applyTransform: (function () {
  4704. var lt = [];
  4705. var rb = [];
  4706. var lb = [];
  4707. var rt = [];
  4708. return function (m) {
  4709. // In case usage like this
  4710. // el.getBoundingRect().applyTransform(el.transform)
  4711. // And element has no transform
  4712. if (!m) {
  4713. return;
  4714. }
  4715. lt[0] = lb[0] = this.x;
  4716. lt[1] = rt[1] = this.y;
  4717. rb[0] = rt[0] = this.x + this.width;
  4718. rb[1] = lb[1] = this.y + this.height;
  4719. v2ApplyTransform(lt, lt, m);
  4720. v2ApplyTransform(rb, rb, m);
  4721. v2ApplyTransform(lb, lb, m);
  4722. v2ApplyTransform(rt, rt, m);
  4723. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4724. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4725. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4726. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4727. this.width = maxX - this.x;
  4728. this.height = maxY - this.y;
  4729. };
  4730. })(),
  4731. /**
  4732. * Calculate matrix of transforming from self to target rect
  4733. * @param {module:zrender/core/BoundingRect} b
  4734. * @return {Array.<number>}
  4735. */
  4736. calculateTransform: function (b) {
  4737. var a = this;
  4738. var sx = b.width / a.width;
  4739. var sy = b.height / a.height;
  4740. var m = create$1();
  4741. // 矩阵右乘
  4742. translate(m, m, [-a.x, -a.y]);
  4743. scale$1(m, m, [sx, sy]);
  4744. translate(m, m, [b.x, b.y]);
  4745. return m;
  4746. },
  4747. /**
  4748. * @param {(module:echarts/core/BoundingRect|Object)} b
  4749. * @return {boolean}
  4750. */
  4751. intersect: function (b) {
  4752. if (!b) {
  4753. return false;
  4754. }
  4755. if (!(b instanceof BoundingRect)) {
  4756. // Normalize negative width/height.
  4757. b = BoundingRect.create(b);
  4758. }
  4759. var a = this;
  4760. var ax0 = a.x;
  4761. var ax1 = a.x + a.width;
  4762. var ay0 = a.y;
  4763. var ay1 = a.y + a.height;
  4764. var bx0 = b.x;
  4765. var bx1 = b.x + b.width;
  4766. var by0 = b.y;
  4767. var by1 = b.y + b.height;
  4768. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4769. },
  4770. contain: function (x, y) {
  4771. var rect = this;
  4772. return x >= rect.x
  4773. && x <= (rect.x + rect.width)
  4774. && y >= rect.y
  4775. && y <= (rect.y + rect.height);
  4776. },
  4777. /**
  4778. * @return {module:echarts/core/BoundingRect}
  4779. */
  4780. clone: function () {
  4781. return new BoundingRect(this.x, this.y, this.width, this.height);
  4782. },
  4783. /**
  4784. * Copy from another rect
  4785. */
  4786. copy: function (other) {
  4787. this.x = other.x;
  4788. this.y = other.y;
  4789. this.width = other.width;
  4790. this.height = other.height;
  4791. },
  4792. plain: function () {
  4793. return {
  4794. x: this.x,
  4795. y: this.y,
  4796. width: this.width,
  4797. height: this.height
  4798. };
  4799. }
  4800. };
  4801. /**
  4802. * @param {Object|module:zrender/core/BoundingRect} rect
  4803. * @param {number} rect.x
  4804. * @param {number} rect.y
  4805. * @param {number} rect.width
  4806. * @param {number} rect.height
  4807. * @return {module:zrender/core/BoundingRect}
  4808. */
  4809. BoundingRect.create = function (rect) {
  4810. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4811. };
  4812. /**
  4813. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4814. * @module zrender/graphic/Group
  4815. * @example
  4816. * var Group = require('zrender/container/Group');
  4817. * var Circle = require('zrender/graphic/shape/Circle');
  4818. * var g = new Group();
  4819. * g.position[0] = 100;
  4820. * g.position[1] = 100;
  4821. * g.add(new Circle({
  4822. * style: {
  4823. * x: 100,
  4824. * y: 100,
  4825. * r: 20,
  4826. * }
  4827. * }));
  4828. * zr.add(g);
  4829. */
  4830. /**
  4831. * @alias module:zrender/graphic/Group
  4832. * @constructor
  4833. * @extends module:zrender/mixin/Transformable
  4834. * @extends module:zrender/mixin/Eventful
  4835. */
  4836. var Group = function (opts) {
  4837. opts = opts || {};
  4838. Element.call(this, opts);
  4839. for (var key in opts) {
  4840. if (opts.hasOwnProperty(key)) {
  4841. this[key] = opts[key];
  4842. }
  4843. }
  4844. this._children = [];
  4845. this.__storage = null;
  4846. this.__dirty = true;
  4847. };
  4848. Group.prototype = {
  4849. constructor: Group,
  4850. isGroup: true,
  4851. /**
  4852. * @type {string}
  4853. */
  4854. type: 'group',
  4855. /**
  4856. * 所有子孙元素是否响应鼠标事件
  4857. * @name module:/zrender/container/Group#silent
  4858. * @type {boolean}
  4859. * @default false
  4860. */
  4861. silent: false,
  4862. /**
  4863. * @return {Array.<module:zrender/Element>}
  4864. */
  4865. children: function () {
  4866. return this._children.slice();
  4867. },
  4868. /**
  4869. * 获取指定 index 的儿子节点
  4870. * @param {number} idx
  4871. * @return {module:zrender/Element}
  4872. */
  4873. childAt: function (idx) {
  4874. return this._children[idx];
  4875. },
  4876. /**
  4877. * 获取指定名字的儿子节点
  4878. * @param {string} name
  4879. * @return {module:zrender/Element}
  4880. */
  4881. childOfName: function (name) {
  4882. var children = this._children;
  4883. for (var i = 0; i < children.length; i++) {
  4884. if (children[i].name === name) {
  4885. return children[i];
  4886. }
  4887. }
  4888. },
  4889. /**
  4890. * @return {number}
  4891. */
  4892. childCount: function () {
  4893. return this._children.length;
  4894. },
  4895. /**
  4896. * 添加子节点到最后
  4897. * @param {module:zrender/Element} child
  4898. */
  4899. add: function (child) {
  4900. if (child && child !== this && child.parent !== this) {
  4901. this._children.push(child);
  4902. this._doAdd(child);
  4903. }
  4904. return this;
  4905. },
  4906. /**
  4907. * 添加子节点在 nextSibling 之前
  4908. * @param {module:zrender/Element} child
  4909. * @param {module:zrender/Element} nextSibling
  4910. */
  4911. addBefore: function (child, nextSibling) {
  4912. if (child && child !== this && child.parent !== this
  4913. && nextSibling && nextSibling.parent === this) {
  4914. var children = this._children;
  4915. var idx = children.indexOf(nextSibling);
  4916. if (idx >= 0) {
  4917. children.splice(idx, 0, child);
  4918. this._doAdd(child);
  4919. }
  4920. }
  4921. return this;
  4922. },
  4923. _doAdd: function (child) {
  4924. if (child.parent) {
  4925. child.parent.remove(child);
  4926. }
  4927. child.parent = this;
  4928. var storage = this.__storage;
  4929. var zr = this.__zr;
  4930. if (storage && storage !== child.__storage) {
  4931. storage.addToStorage(child);
  4932. if (child instanceof Group) {
  4933. child.addChildrenToStorage(storage);
  4934. }
  4935. }
  4936. zr && zr.refresh();
  4937. },
  4938. /**
  4939. * 移除子节点
  4940. * @param {module:zrender/Element} child
  4941. */
  4942. remove: function (child) {
  4943. var zr = this.__zr;
  4944. var storage = this.__storage;
  4945. var children = this._children;
  4946. var idx = indexOf(children, child);
  4947. if (idx < 0) {
  4948. return this;
  4949. }
  4950. children.splice(idx, 1);
  4951. child.parent = null;
  4952. if (storage) {
  4953. storage.delFromStorage(child);
  4954. if (child instanceof Group) {
  4955. child.delChildrenFromStorage(storage);
  4956. }
  4957. }
  4958. zr && zr.refresh();
  4959. return this;
  4960. },
  4961. /**
  4962. * 移除所有子节点
  4963. */
  4964. removeAll: function () {
  4965. var children = this._children;
  4966. var storage = this.__storage;
  4967. var child;
  4968. var i;
  4969. for (i = 0; i < children.length; i++) {
  4970. child = children[i];
  4971. if (storage) {
  4972. storage.delFromStorage(child);
  4973. if (child instanceof Group) {
  4974. child.delChildrenFromStorage(storage);
  4975. }
  4976. }
  4977. child.parent = null;
  4978. }
  4979. children.length = 0;
  4980. return this;
  4981. },
  4982. /**
  4983. * 遍历所有子节点
  4984. * @param {Function} cb
  4985. * @param {} context
  4986. */
  4987. eachChild: function (cb, context) {
  4988. var children = this._children;
  4989. for (var i = 0; i < children.length; i++) {
  4990. var child = children[i];
  4991. cb.call(context, child, i);
  4992. }
  4993. return this;
  4994. },
  4995. /**
  4996. * 深度优先遍历所有子孙节点
  4997. * @param {Function} cb
  4998. * @param {} context
  4999. */
  5000. traverse: function (cb, context) {
  5001. for (var i = 0; i < this._children.length; i++) {
  5002. var child = this._children[i];
  5003. cb.call(context, child);
  5004. if (child.type === 'group') {
  5005. child.traverse(cb, context);
  5006. }
  5007. }
  5008. return this;
  5009. },
  5010. addChildrenToStorage: function (storage) {
  5011. for (var i = 0; i < this._children.length; i++) {
  5012. var child = this._children[i];
  5013. storage.addToStorage(child);
  5014. if (child instanceof Group) {
  5015. child.addChildrenToStorage(storage);
  5016. }
  5017. }
  5018. },
  5019. delChildrenFromStorage: function (storage) {
  5020. for (var i = 0; i < this._children.length; i++) {
  5021. var child = this._children[i];
  5022. storage.delFromStorage(child);
  5023. if (child instanceof Group) {
  5024. child.delChildrenFromStorage(storage);
  5025. }
  5026. }
  5027. },
  5028. dirty: function () {
  5029. this.__dirty = true;
  5030. this.__zr && this.__zr.refresh();
  5031. return this;
  5032. },
  5033. /**
  5034. * @return {module:zrender/core/BoundingRect}
  5035. */
  5036. getBoundingRect: function (includeChildren) {
  5037. // TODO Caching
  5038. var rect = null;
  5039. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5040. var children = includeChildren || this._children;
  5041. var tmpMat = [];
  5042. for (var i = 0; i < children.length; i++) {
  5043. var child = children[i];
  5044. if (child.ignore || child.invisible) {
  5045. continue;
  5046. }
  5047. var childRect = child.getBoundingRect();
  5048. var transform = child.getLocalTransform(tmpMat);
  5049. // TODO
  5050. // The boundingRect cacluated by transforming original
  5051. // rect may be bigger than the actual bundingRect when rotation
  5052. // is used. (Consider a circle rotated aginst its center, where
  5053. // the actual boundingRect should be the same as that not be
  5054. // rotated.) But we can not find better approach to calculate
  5055. // actual boundingRect yet, considering performance.
  5056. if (transform) {
  5057. tmpRect.copy(childRect);
  5058. tmpRect.applyTransform(transform);
  5059. rect = rect || tmpRect.clone();
  5060. rect.union(tmpRect);
  5061. }
  5062. else {
  5063. rect = rect || childRect.clone();
  5064. rect.union(childRect);
  5065. }
  5066. }
  5067. return rect || tmpRect;
  5068. }
  5069. };
  5070. inherits(Group, Element);
  5071. // https://github.com/mziccard/node-timsort
  5072. var DEFAULT_MIN_MERGE = 32;
  5073. var DEFAULT_MIN_GALLOPING = 7;
  5074. function minRunLength(n) {
  5075. var r = 0;
  5076. while (n >= DEFAULT_MIN_MERGE) {
  5077. r |= n & 1;
  5078. n >>= 1;
  5079. }
  5080. return n + r;
  5081. }
  5082. function makeAscendingRun(array, lo, hi, compare) {
  5083. var runHi = lo + 1;
  5084. if (runHi === hi) {
  5085. return 1;
  5086. }
  5087. if (compare(array[runHi++], array[lo]) < 0) {
  5088. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5089. runHi++;
  5090. }
  5091. reverseRun(array, lo, runHi);
  5092. }
  5093. else {
  5094. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5095. runHi++;
  5096. }
  5097. }
  5098. return runHi - lo;
  5099. }
  5100. function reverseRun(array, lo, hi) {
  5101. hi--;
  5102. while (lo < hi) {
  5103. var t = array[lo];
  5104. array[lo++] = array[hi];
  5105. array[hi--] = t;
  5106. }
  5107. }
  5108. function binaryInsertionSort(array, lo, hi, start, compare) {
  5109. if (start === lo) {
  5110. start++;
  5111. }
  5112. for (; start < hi; start++) {
  5113. var pivot = array[start];
  5114. var left = lo;
  5115. var right = start;
  5116. var mid;
  5117. while (left < right) {
  5118. mid = left + right >>> 1;
  5119. if (compare(pivot, array[mid]) < 0) {
  5120. right = mid;
  5121. }
  5122. else {
  5123. left = mid + 1;
  5124. }
  5125. }
  5126. var n = start - left;
  5127. switch (n) {
  5128. case 3:
  5129. array[left + 3] = array[left + 2];
  5130. case 2:
  5131. array[left + 2] = array[left + 1];
  5132. case 1:
  5133. array[left + 1] = array[left];
  5134. break;
  5135. default:
  5136. while (n > 0) {
  5137. array[left + n] = array[left + n - 1];
  5138. n--;
  5139. }
  5140. }
  5141. array[left] = pivot;
  5142. }
  5143. }
  5144. function gallopLeft(value, array, start, length, hint, compare) {
  5145. var lastOffset = 0;
  5146. var maxOffset = 0;
  5147. var offset = 1;
  5148. if (compare(value, array[start + hint]) > 0) {
  5149. maxOffset = length - hint;
  5150. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5151. lastOffset = offset;
  5152. offset = (offset << 1) + 1;
  5153. if (offset <= 0) {
  5154. offset = maxOffset;
  5155. }
  5156. }
  5157. if (offset > maxOffset) {
  5158. offset = maxOffset;
  5159. }
  5160. lastOffset += hint;
  5161. offset += hint;
  5162. }
  5163. else {
  5164. maxOffset = hint + 1;
  5165. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5166. lastOffset = offset;
  5167. offset = (offset << 1) + 1;
  5168. if (offset <= 0) {
  5169. offset = maxOffset;
  5170. }
  5171. }
  5172. if (offset > maxOffset) {
  5173. offset = maxOffset;
  5174. }
  5175. var tmp = lastOffset;
  5176. lastOffset = hint - offset;
  5177. offset = hint - tmp;
  5178. }
  5179. lastOffset++;
  5180. while (lastOffset < offset) {
  5181. var m = lastOffset + (offset - lastOffset >>> 1);
  5182. if (compare(value, array[start + m]) > 0) {
  5183. lastOffset = m + 1;
  5184. }
  5185. else {
  5186. offset = m;
  5187. }
  5188. }
  5189. return offset;
  5190. }
  5191. function gallopRight(value, array, start, length, hint, compare) {
  5192. var lastOffset = 0;
  5193. var maxOffset = 0;
  5194. var offset = 1;
  5195. if (compare(value, array[start + hint]) < 0) {
  5196. maxOffset = hint + 1;
  5197. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5198. lastOffset = offset;
  5199. offset = (offset << 1) + 1;
  5200. if (offset <= 0) {
  5201. offset = maxOffset;
  5202. }
  5203. }
  5204. if (offset > maxOffset) {
  5205. offset = maxOffset;
  5206. }
  5207. var tmp = lastOffset;
  5208. lastOffset = hint - offset;
  5209. offset = hint - tmp;
  5210. }
  5211. else {
  5212. maxOffset = length - hint;
  5213. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5214. lastOffset = offset;
  5215. offset = (offset << 1) + 1;
  5216. if (offset <= 0) {
  5217. offset = maxOffset;
  5218. }
  5219. }
  5220. if (offset > maxOffset) {
  5221. offset = maxOffset;
  5222. }
  5223. lastOffset += hint;
  5224. offset += hint;
  5225. }
  5226. lastOffset++;
  5227. while (lastOffset < offset) {
  5228. var m = lastOffset + (offset - lastOffset >>> 1);
  5229. if (compare(value, array[start + m]) < 0) {
  5230. offset = m;
  5231. }
  5232. else {
  5233. lastOffset = m + 1;
  5234. }
  5235. }
  5236. return offset;
  5237. }
  5238. function TimSort(array, compare) {
  5239. var minGallop = DEFAULT_MIN_GALLOPING;
  5240. var runStart;
  5241. var runLength;
  5242. var stackSize = 0;
  5243. var tmp = [];
  5244. runStart = [];
  5245. runLength = [];
  5246. function pushRun(_runStart, _runLength) {
  5247. runStart[stackSize] = _runStart;
  5248. runLength[stackSize] = _runLength;
  5249. stackSize += 1;
  5250. }
  5251. function mergeRuns() {
  5252. while (stackSize > 1) {
  5253. var n = stackSize - 2;
  5254. if (
  5255. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5256. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5257. ) {
  5258. if (runLength[n - 1] < runLength[n + 1]) {
  5259. n--;
  5260. }
  5261. }
  5262. else if (runLength[n] > runLength[n + 1]) {
  5263. break;
  5264. }
  5265. mergeAt(n);
  5266. }
  5267. }
  5268. function forceMergeRuns() {
  5269. while (stackSize > 1) {
  5270. var n = stackSize - 2;
  5271. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5272. n--;
  5273. }
  5274. mergeAt(n);
  5275. }
  5276. }
  5277. function mergeAt(i) {
  5278. var start1 = runStart[i];
  5279. var length1 = runLength[i];
  5280. var start2 = runStart[i + 1];
  5281. var length2 = runLength[i + 1];
  5282. runLength[i] = length1 + length2;
  5283. if (i === stackSize - 3) {
  5284. runStart[i + 1] = runStart[i + 2];
  5285. runLength[i + 1] = runLength[i + 2];
  5286. }
  5287. stackSize--;
  5288. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5289. start1 += k;
  5290. length1 -= k;
  5291. if (length1 === 0) {
  5292. return;
  5293. }
  5294. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5295. if (length2 === 0) {
  5296. return;
  5297. }
  5298. if (length1 <= length2) {
  5299. mergeLow(start1, length1, start2, length2);
  5300. }
  5301. else {
  5302. mergeHigh(start1, length1, start2, length2);
  5303. }
  5304. }
  5305. function mergeLow(start1, length1, start2, length2) {
  5306. var i = 0;
  5307. for (i = 0; i < length1; i++) {
  5308. tmp[i] = array[start1 + i];
  5309. }
  5310. var cursor1 = 0;
  5311. var cursor2 = start2;
  5312. var dest = start1;
  5313. array[dest++] = array[cursor2++];
  5314. if (--length2 === 0) {
  5315. for (i = 0; i < length1; i++) {
  5316. array[dest + i] = tmp[cursor1 + i];
  5317. }
  5318. return;
  5319. }
  5320. if (length1 === 1) {
  5321. for (i = 0; i < length2; i++) {
  5322. array[dest + i] = array[cursor2 + i];
  5323. }
  5324. array[dest + length2] = tmp[cursor1];
  5325. return;
  5326. }
  5327. var _minGallop = minGallop;
  5328. var count1;
  5329. var count2;
  5330. var exit;
  5331. while (1) {
  5332. count1 = 0;
  5333. count2 = 0;
  5334. exit = false;
  5335. do {
  5336. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5337. array[dest++] = array[cursor2++];
  5338. count2++;
  5339. count1 = 0;
  5340. if (--length2 === 0) {
  5341. exit = true;
  5342. break;
  5343. }
  5344. }
  5345. else {
  5346. array[dest++] = tmp[cursor1++];
  5347. count1++;
  5348. count2 = 0;
  5349. if (--length1 === 1) {
  5350. exit = true;
  5351. break;
  5352. }
  5353. }
  5354. } while ((count1 | count2) < _minGallop);
  5355. if (exit) {
  5356. break;
  5357. }
  5358. do {
  5359. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5360. if (count1 !== 0) {
  5361. for (i = 0; i < count1; i++) {
  5362. array[dest + i] = tmp[cursor1 + i];
  5363. }
  5364. dest += count1;
  5365. cursor1 += count1;
  5366. length1 -= count1;
  5367. if (length1 <= 1) {
  5368. exit = true;
  5369. break;
  5370. }
  5371. }
  5372. array[dest++] = array[cursor2++];
  5373. if (--length2 === 0) {
  5374. exit = true;
  5375. break;
  5376. }
  5377. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5378. if (count2 !== 0) {
  5379. for (i = 0; i < count2; i++) {
  5380. array[dest + i] = array[cursor2 + i];
  5381. }
  5382. dest += count2;
  5383. cursor2 += count2;
  5384. length2 -= count2;
  5385. if (length2 === 0) {
  5386. exit = true;
  5387. break;
  5388. }
  5389. }
  5390. array[dest++] = tmp[cursor1++];
  5391. if (--length1 === 1) {
  5392. exit = true;
  5393. break;
  5394. }
  5395. _minGallop--;
  5396. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5397. if (exit) {
  5398. break;
  5399. }
  5400. if (_minGallop < 0) {
  5401. _minGallop = 0;
  5402. }
  5403. _minGallop += 2;
  5404. }
  5405. minGallop = _minGallop;
  5406. minGallop < 1 && (minGallop = 1);
  5407. if (length1 === 1) {
  5408. for (i = 0; i < length2; i++) {
  5409. array[dest + i] = array[cursor2 + i];
  5410. }
  5411. array[dest + length2] = tmp[cursor1];
  5412. }
  5413. else if (length1 === 0) {
  5414. throw new Error();
  5415. // throw new Error('mergeLow preconditions were not respected');
  5416. }
  5417. else {
  5418. for (i = 0; i < length1; i++) {
  5419. array[dest + i] = tmp[cursor1 + i];
  5420. }
  5421. }
  5422. }
  5423. function mergeHigh(start1, length1, start2, length2) {
  5424. var i = 0;
  5425. for (i = 0; i < length2; i++) {
  5426. tmp[i] = array[start2 + i];
  5427. }
  5428. var cursor1 = start1 + length1 - 1;
  5429. var cursor2 = length2 - 1;
  5430. var dest = start2 + length2 - 1;
  5431. var customCursor = 0;
  5432. var customDest = 0;
  5433. array[dest--] = array[cursor1--];
  5434. if (--length1 === 0) {
  5435. customCursor = dest - (length2 - 1);
  5436. for (i = 0; i < length2; i++) {
  5437. array[customCursor + i] = tmp[i];
  5438. }
  5439. return;
  5440. }
  5441. if (length2 === 1) {
  5442. dest -= length1;
  5443. cursor1 -= length1;
  5444. customDest = dest + 1;
  5445. customCursor = cursor1 + 1;
  5446. for (i = length1 - 1; i >= 0; i--) {
  5447. array[customDest + i] = array[customCursor + i];
  5448. }
  5449. array[dest] = tmp[cursor2];
  5450. return;
  5451. }
  5452. var _minGallop = minGallop;
  5453. while (true) {
  5454. var count1 = 0;
  5455. var count2 = 0;
  5456. var exit = false;
  5457. do {
  5458. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5459. array[dest--] = array[cursor1--];
  5460. count1++;
  5461. count2 = 0;
  5462. if (--length1 === 0) {
  5463. exit = true;
  5464. break;
  5465. }
  5466. }
  5467. else {
  5468. array[dest--] = tmp[cursor2--];
  5469. count2++;
  5470. count1 = 0;
  5471. if (--length2 === 1) {
  5472. exit = true;
  5473. break;
  5474. }
  5475. }
  5476. } while ((count1 | count2) < _minGallop);
  5477. if (exit) {
  5478. break;
  5479. }
  5480. do {
  5481. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5482. if (count1 !== 0) {
  5483. dest -= count1;
  5484. cursor1 -= count1;
  5485. length1 -= count1;
  5486. customDest = dest + 1;
  5487. customCursor = cursor1 + 1;
  5488. for (i = count1 - 1; i >= 0; i--) {
  5489. array[customDest + i] = array[customCursor + i];
  5490. }
  5491. if (length1 === 0) {
  5492. exit = true;
  5493. break;
  5494. }
  5495. }
  5496. array[dest--] = tmp[cursor2--];
  5497. if (--length2 === 1) {
  5498. exit = true;
  5499. break;
  5500. }
  5501. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5502. if (count2 !== 0) {
  5503. dest -= count2;
  5504. cursor2 -= count2;
  5505. length2 -= count2;
  5506. customDest = dest + 1;
  5507. customCursor = cursor2 + 1;
  5508. for (i = 0; i < count2; i++) {
  5509. array[customDest + i] = tmp[customCursor + i];
  5510. }
  5511. if (length2 <= 1) {
  5512. exit = true;
  5513. break;
  5514. }
  5515. }
  5516. array[dest--] = array[cursor1--];
  5517. if (--length1 === 0) {
  5518. exit = true;
  5519. break;
  5520. }
  5521. _minGallop--;
  5522. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5523. if (exit) {
  5524. break;
  5525. }
  5526. if (_minGallop < 0) {
  5527. _minGallop = 0;
  5528. }
  5529. _minGallop += 2;
  5530. }
  5531. minGallop = _minGallop;
  5532. if (minGallop < 1) {
  5533. minGallop = 1;
  5534. }
  5535. if (length2 === 1) {
  5536. dest -= length1;
  5537. cursor1 -= length1;
  5538. customDest = dest + 1;
  5539. customCursor = cursor1 + 1;
  5540. for (i = length1 - 1; i >= 0; i--) {
  5541. array[customDest + i] = array[customCursor + i];
  5542. }
  5543. array[dest] = tmp[cursor2];
  5544. }
  5545. else if (length2 === 0) {
  5546. throw new Error();
  5547. // throw new Error('mergeHigh preconditions were not respected');
  5548. }
  5549. else {
  5550. customCursor = dest - (length2 - 1);
  5551. for (i = 0; i < length2; i++) {
  5552. array[customCursor + i] = tmp[i];
  5553. }
  5554. }
  5555. }
  5556. this.mergeRuns = mergeRuns;
  5557. this.forceMergeRuns = forceMergeRuns;
  5558. this.pushRun = pushRun;
  5559. }
  5560. function sort(array, compare, lo, hi) {
  5561. if (!lo) {
  5562. lo = 0;
  5563. }
  5564. if (!hi) {
  5565. hi = array.length;
  5566. }
  5567. var remaining = hi - lo;
  5568. if (remaining < 2) {
  5569. return;
  5570. }
  5571. var runLength = 0;
  5572. if (remaining < DEFAULT_MIN_MERGE) {
  5573. runLength = makeAscendingRun(array, lo, hi, compare);
  5574. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5575. return;
  5576. }
  5577. var ts = new TimSort(array, compare);
  5578. var minRun = minRunLength(remaining);
  5579. do {
  5580. runLength = makeAscendingRun(array, lo, hi, compare);
  5581. if (runLength < minRun) {
  5582. var force = remaining;
  5583. if (force > minRun) {
  5584. force = minRun;
  5585. }
  5586. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5587. runLength = force;
  5588. }
  5589. ts.pushRun(lo, runLength);
  5590. ts.mergeRuns();
  5591. remaining -= runLength;
  5592. lo += runLength;
  5593. } while (remaining !== 0);
  5594. ts.forceMergeRuns();
  5595. }
  5596. // Use timsort because in most case elements are partially sorted
  5597. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5598. function shapeCompareFunc(a, b) {
  5599. if (a.zlevel === b.zlevel) {
  5600. if (a.z === b.z) {
  5601. // if (a.z2 === b.z2) {
  5602. // // FIXME Slow has renderidx compare
  5603. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5604. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5605. // return a.__renderidx - b.__renderidx;
  5606. // }
  5607. return a.z2 - b.z2;
  5608. }
  5609. return a.z - b.z;
  5610. }
  5611. return a.zlevel - b.zlevel;
  5612. }
  5613. /**
  5614. * 内容仓库 (M)
  5615. * @alias module:zrender/Storage
  5616. * @constructor
  5617. */
  5618. var Storage = function () { // jshint ignore:line
  5619. this._roots = [];
  5620. this._displayList = [];
  5621. this._displayListLen = 0;
  5622. };
  5623. Storage.prototype = {
  5624. constructor: Storage,
  5625. /**
  5626. * @param {Function} cb
  5627. *
  5628. */
  5629. traverse: function (cb, context) {
  5630. for (var i = 0; i < this._roots.length; i++) {
  5631. this._roots[i].traverse(cb, context);
  5632. }
  5633. },
  5634. /**
  5635. * 返回所有图形的绘制队列
  5636. * @param {boolean} [update=false] 是否在返回前更新该数组
  5637. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5638. *
  5639. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5640. * @return {Array.<module:zrender/graphic/Displayable>}
  5641. */
  5642. getDisplayList: function (update, includeIgnore) {
  5643. includeIgnore = includeIgnore || false;
  5644. if (update) {
  5645. this.updateDisplayList(includeIgnore);
  5646. }
  5647. return this._displayList;
  5648. },
  5649. /**
  5650. * 更新图形的绘制队列。
  5651. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5652. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5653. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5654. */
  5655. updateDisplayList: function (includeIgnore) {
  5656. this._displayListLen = 0;
  5657. var roots = this._roots;
  5658. var displayList = this._displayList;
  5659. for (var i = 0, len = roots.length; i < len; i++) {
  5660. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5661. }
  5662. displayList.length = this._displayListLen;
  5663. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5664. },
  5665. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5666. if (el.ignore && !includeIgnore) {
  5667. return;
  5668. }
  5669. el.beforeUpdate();
  5670. if (el.__dirty) {
  5671. el.update();
  5672. }
  5673. el.afterUpdate();
  5674. var userSetClipPath = el.clipPath;
  5675. if (userSetClipPath) {
  5676. // FIXME 效率影响
  5677. if (clipPaths) {
  5678. clipPaths = clipPaths.slice();
  5679. }
  5680. else {
  5681. clipPaths = [];
  5682. }
  5683. var currentClipPath = userSetClipPath;
  5684. var parentClipPath = el;
  5685. // Recursively add clip path
  5686. while (currentClipPath) {
  5687. // clipPath 的变换是基于使用这个 clipPath 的元素
  5688. currentClipPath.parent = parentClipPath;
  5689. currentClipPath.updateTransform();
  5690. clipPaths.push(currentClipPath);
  5691. parentClipPath = currentClipPath;
  5692. currentClipPath = currentClipPath.clipPath;
  5693. }
  5694. }
  5695. if (el.isGroup) {
  5696. var children = el._children;
  5697. for (var i = 0; i < children.length; i++) {
  5698. var child = children[i];
  5699. // Force to mark as dirty if group is dirty
  5700. // FIXME __dirtyPath ?
  5701. if (el.__dirty) {
  5702. child.__dirty = true;
  5703. }
  5704. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5705. }
  5706. // Mark group clean here
  5707. el.__dirty = false;
  5708. }
  5709. else {
  5710. el.__clipPaths = clipPaths;
  5711. this._displayList[this._displayListLen++] = el;
  5712. }
  5713. },
  5714. /**
  5715. * 添加图形(Shape)或者组(Group)到根节点
  5716. * @param {module:zrender/Element} el
  5717. */
  5718. addRoot: function (el) {
  5719. if (el.__storage === this) {
  5720. return;
  5721. }
  5722. if (el instanceof Group) {
  5723. el.addChildrenToStorage(this);
  5724. }
  5725. this.addToStorage(el);
  5726. this._roots.push(el);
  5727. },
  5728. /**
  5729. * 删除指定的图形(Shape)或者组(Group)
  5730. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5731. */
  5732. delRoot: function (el) {
  5733. if (el == null) {
  5734. // 不指定el清空
  5735. for (var i = 0; i < this._roots.length; i++) {
  5736. var root = this._roots[i];
  5737. if (root instanceof Group) {
  5738. root.delChildrenFromStorage(this);
  5739. }
  5740. }
  5741. this._roots = [];
  5742. this._displayList = [];
  5743. this._displayListLen = 0;
  5744. return;
  5745. }
  5746. if (el instanceof Array) {
  5747. for (var i = 0, l = el.length; i < l; i++) {
  5748. this.delRoot(el[i]);
  5749. }
  5750. return;
  5751. }
  5752. var idx = indexOf(this._roots, el);
  5753. if (idx >= 0) {
  5754. this.delFromStorage(el);
  5755. this._roots.splice(idx, 1);
  5756. if (el instanceof Group) {
  5757. el.delChildrenFromStorage(this);
  5758. }
  5759. }
  5760. },
  5761. addToStorage: function (el) {
  5762. if (el) {
  5763. el.__storage = this;
  5764. el.dirty(false);
  5765. }
  5766. return this;
  5767. },
  5768. delFromStorage: function (el) {
  5769. if (el) {
  5770. el.__storage = null;
  5771. }
  5772. return this;
  5773. },
  5774. /**
  5775. * 清空并且释放Storage
  5776. */
  5777. dispose: function () {
  5778. this._renderList =
  5779. this._roots = null;
  5780. },
  5781. displayableSortFunc: shapeCompareFunc
  5782. };
  5783. var SHADOW_PROPS = {
  5784. 'shadowBlur': 1,
  5785. 'shadowOffsetX': 1,
  5786. 'shadowOffsetY': 1,
  5787. 'textShadowBlur': 1,
  5788. 'textShadowOffsetX': 1,
  5789. 'textShadowOffsetY': 1,
  5790. 'textBoxShadowBlur': 1,
  5791. 'textBoxShadowOffsetX': 1,
  5792. 'textBoxShadowOffsetY': 1
  5793. };
  5794. var fixShadow = function (ctx, propName, value) {
  5795. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5796. return value *= ctx.dpr;
  5797. }
  5798. return value;
  5799. };
  5800. var ContextCachedBy = {
  5801. NONE: 0,
  5802. STYLE_BIND: 1,
  5803. PLAIN_TEXT: 2
  5804. };
  5805. // Avoid confused with 0/false.
  5806. var WILL_BE_RESTORED = 9;
  5807. var STYLE_COMMON_PROPS = [
  5808. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5809. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5810. ];
  5811. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5812. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5813. var Style = function (opts) {
  5814. this.extendFrom(opts, false);
  5815. };
  5816. function createLinearGradient(ctx, obj, rect) {
  5817. var x = obj.x == null ? 0 : obj.x;
  5818. var x2 = obj.x2 == null ? 1 : obj.x2;
  5819. var y = obj.y == null ? 0 : obj.y;
  5820. var y2 = obj.y2 == null ? 0 : obj.y2;
  5821. if (!obj.global) {
  5822. x = x * rect.width + rect.x;
  5823. x2 = x2 * rect.width + rect.x;
  5824. y = y * rect.height + rect.y;
  5825. y2 = y2 * rect.height + rect.y;
  5826. }
  5827. // Fix NaN when rect is Infinity
  5828. x = isNaN(x) ? 0 : x;
  5829. x2 = isNaN(x2) ? 1 : x2;
  5830. y = isNaN(y) ? 0 : y;
  5831. y2 = isNaN(y2) ? 0 : y2;
  5832. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5833. return canvasGradient;
  5834. }
  5835. function createRadialGradient(ctx, obj, rect) {
  5836. var width = rect.width;
  5837. var height = rect.height;
  5838. var min = Math.min(width, height);
  5839. var x = obj.x == null ? 0.5 : obj.x;
  5840. var y = obj.y == null ? 0.5 : obj.y;
  5841. var r = obj.r == null ? 0.5 : obj.r;
  5842. if (!obj.global) {
  5843. x = x * width + rect.x;
  5844. y = y * height + rect.y;
  5845. r = r * min;
  5846. }
  5847. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5848. return canvasGradient;
  5849. }
  5850. Style.prototype = {
  5851. constructor: Style,
  5852. /**
  5853. * @type {string}
  5854. */
  5855. fill: '#000',
  5856. /**
  5857. * @type {string}
  5858. */
  5859. stroke: null,
  5860. /**
  5861. * @type {number}
  5862. */
  5863. opacity: 1,
  5864. /**
  5865. * @type {number}
  5866. */
  5867. fillOpacity: null,
  5868. /**
  5869. * @type {number}
  5870. */
  5871. strokeOpacity: null,
  5872. /**
  5873. * `true` is not supported.
  5874. * `false`/`null`/`undefined` are the same.
  5875. * `false` is used to remove lineDash in some
  5876. * case that `null`/`undefined` can not be set.
  5877. * (e.g., emphasis.lineStyle in echarts)
  5878. * @type {Array.<number>|boolean}
  5879. */
  5880. lineDash: null,
  5881. /**
  5882. * @type {number}
  5883. */
  5884. lineDashOffset: 0,
  5885. /**
  5886. * @type {number}
  5887. */
  5888. shadowBlur: 0,
  5889. /**
  5890. * @type {number}
  5891. */
  5892. shadowOffsetX: 0,
  5893. /**
  5894. * @type {number}
  5895. */
  5896. shadowOffsetY: 0,
  5897. /**
  5898. * @type {number}
  5899. */
  5900. lineWidth: 1,
  5901. /**
  5902. * If stroke ignore scale
  5903. * @type {Boolean}
  5904. */
  5905. strokeNoScale: false,
  5906. // Bounding rect text configuration
  5907. // Not affected by element transform
  5908. /**
  5909. * @type {string}
  5910. */
  5911. text: null,
  5912. /**
  5913. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5914. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5915. * So do not visit it directly in upper application (like echarts),
  5916. * but use `contain/text#makeFont` instead.
  5917. * @type {string}
  5918. */
  5919. font: null,
  5920. /**
  5921. * The same as font. Use font please.
  5922. * @deprecated
  5923. * @type {string}
  5924. */
  5925. textFont: null,
  5926. /**
  5927. * It helps merging respectively, rather than parsing an entire font string.
  5928. * @type {string}
  5929. */
  5930. fontStyle: null,
  5931. /**
  5932. * It helps merging respectively, rather than parsing an entire font string.
  5933. * @type {string}
  5934. */
  5935. fontWeight: null,
  5936. /**
  5937. * It helps merging respectively, rather than parsing an entire font string.
  5938. * Should be 12 but not '12px'.
  5939. * @type {number}
  5940. */
  5941. fontSize: null,
  5942. /**
  5943. * It helps merging respectively, rather than parsing an entire font string.
  5944. * @type {string}
  5945. */
  5946. fontFamily: null,
  5947. /**
  5948. * Reserved for special functinality, like 'hr'.
  5949. * @type {string}
  5950. */
  5951. textTag: null,
  5952. /**
  5953. * @type {string}
  5954. */
  5955. textFill: '#000',
  5956. /**
  5957. * @type {string}
  5958. */
  5959. textStroke: null,
  5960. /**
  5961. * @type {number}
  5962. */
  5963. textWidth: null,
  5964. /**
  5965. * Only for textBackground.
  5966. * @type {number}
  5967. */
  5968. textHeight: null,
  5969. /**
  5970. * textStroke may be set as some color as a default
  5971. * value in upper applicaion, where the default value
  5972. * of textStrokeWidth should be 0 to make sure that
  5973. * user can choose to do not use text stroke.
  5974. * @type {number}
  5975. */
  5976. textStrokeWidth: 0,
  5977. /**
  5978. * @type {number}
  5979. */
  5980. textLineHeight: null,
  5981. /**
  5982. * 'inside', 'left', 'right', 'top', 'bottom'
  5983. * [x, y]
  5984. * Based on x, y of rect.
  5985. * @type {string|Array.<number>}
  5986. * @default 'inside'
  5987. */
  5988. textPosition: 'inside',
  5989. /**
  5990. * If not specified, use the boundingRect of a `displayable`.
  5991. * @type {Object}
  5992. */
  5993. textRect: null,
  5994. /**
  5995. * [x, y]
  5996. * @type {Array.<number>}
  5997. */
  5998. textOffset: null,
  5999. /**
  6000. * @type {string}
  6001. */
  6002. textAlign: null,
  6003. /**
  6004. * @type {string}
  6005. */
  6006. textVerticalAlign: null,
  6007. /**
  6008. * @type {number}
  6009. */
  6010. textDistance: 5,
  6011. /**
  6012. * @type {string}
  6013. */
  6014. textShadowColor: 'transparent',
  6015. /**
  6016. * @type {number}
  6017. */
  6018. textShadowBlur: 0,
  6019. /**
  6020. * @type {number}
  6021. */
  6022. textShadowOffsetX: 0,
  6023. /**
  6024. * @type {number}
  6025. */
  6026. textShadowOffsetY: 0,
  6027. /**
  6028. * @type {string}
  6029. */
  6030. textBoxShadowColor: 'transparent',
  6031. /**
  6032. * @type {number}
  6033. */
  6034. textBoxShadowBlur: 0,
  6035. /**
  6036. * @type {number}
  6037. */
  6038. textBoxShadowOffsetX: 0,
  6039. /**
  6040. * @type {number}
  6041. */
  6042. textBoxShadowOffsetY: 0,
  6043. /**
  6044. * Whether transform text.
  6045. * Only available in Path and Image element,
  6046. * where the text is called as `RectText`.
  6047. * @type {boolean}
  6048. */
  6049. transformText: false,
  6050. /**
  6051. * Text rotate around position of Path or Image.
  6052. * The origin of the rotation can be specified by `textOrigin`.
  6053. * Only available in Path and Image element,
  6054. * where the text is called as `RectText`.
  6055. */
  6056. textRotation: 0,
  6057. /**
  6058. * Text origin of text rotation.
  6059. * Useful in the case like label rotation of circular symbol.
  6060. * Only available in Path and Image element, where the text is called
  6061. * as `RectText` and the element is called as "host element".
  6062. * The value can be:
  6063. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6064. * base on the left-top corner of the rect of its host element.
  6065. * + If specified as a string `center`, it is the center of the rect of
  6066. * its host element.
  6067. * + By default, this origin is the `textPosition`.
  6068. * @type {string|Array.<number>}
  6069. */
  6070. textOrigin: null,
  6071. /**
  6072. * @type {string}
  6073. */
  6074. textBackgroundColor: null,
  6075. /**
  6076. * @type {string}
  6077. */
  6078. textBorderColor: null,
  6079. /**
  6080. * @type {number}
  6081. */
  6082. textBorderWidth: 0,
  6083. /**
  6084. * @type {number}
  6085. */
  6086. textBorderRadius: 0,
  6087. /**
  6088. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6089. * @type {number|Array.<number>}
  6090. */
  6091. textPadding: null,
  6092. /**
  6093. * Text styles for rich text.
  6094. * @type {Object}
  6095. */
  6096. rich: null,
  6097. /**
  6098. * {outerWidth, outerHeight, ellipsis, placeholder}
  6099. * @type {Object}
  6100. */
  6101. truncate: null,
  6102. /**
  6103. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6104. * @type {string}
  6105. */
  6106. blend: null,
  6107. /**
  6108. * @param {CanvasRenderingContext2D} ctx
  6109. */
  6110. bind: function (ctx, el, prevEl) {
  6111. var style = this;
  6112. var prevStyle = prevEl && prevEl.style;
  6113. // If no prevStyle, it means first draw.
  6114. // Only apply cache if the last time cachced by this function.
  6115. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6116. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6117. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6118. var prop = STYLE_COMMON_PROPS[i];
  6119. var styleName = prop[0];
  6120. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6121. // FIXME Invalid property value will cause style leak from previous element.
  6122. ctx[styleName] =
  6123. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6124. }
  6125. }
  6126. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6127. ctx.fillStyle = style.fill;
  6128. }
  6129. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6130. ctx.strokeStyle = style.stroke;
  6131. }
  6132. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6133. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6134. }
  6135. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6136. ctx.globalCompositeOperation = style.blend || 'source-over';
  6137. }
  6138. if (this.hasStroke()) {
  6139. var lineWidth = style.lineWidth;
  6140. ctx.lineWidth = lineWidth / (
  6141. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6142. );
  6143. }
  6144. },
  6145. hasFill: function () {
  6146. var fill = this.fill;
  6147. return fill != null && fill !== 'none';
  6148. },
  6149. hasStroke: function () {
  6150. var stroke = this.stroke;
  6151. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6152. },
  6153. /**
  6154. * Extend from other style
  6155. * @param {zrender/graphic/Style} otherStyle
  6156. * @param {boolean} overwrite true: overwrirte any way.
  6157. * false: overwrite only when !target.hasOwnProperty
  6158. * others: overwrite when property is not null/undefined.
  6159. */
  6160. extendFrom: function (otherStyle, overwrite) {
  6161. if (otherStyle) {
  6162. for (var name in otherStyle) {
  6163. if (otherStyle.hasOwnProperty(name)
  6164. && (overwrite === true
  6165. || (
  6166. overwrite === false
  6167. ? !this.hasOwnProperty(name)
  6168. : otherStyle[name] != null
  6169. )
  6170. )
  6171. ) {
  6172. this[name] = otherStyle[name];
  6173. }
  6174. }
  6175. }
  6176. },
  6177. /**
  6178. * Batch setting style with a given object
  6179. * @param {Object|string} obj
  6180. * @param {*} [obj]
  6181. */
  6182. set: function (obj, value) {
  6183. if (typeof obj === 'string') {
  6184. this[obj] = value;
  6185. }
  6186. else {
  6187. this.extendFrom(obj, true);
  6188. }
  6189. },
  6190. /**
  6191. * Clone
  6192. * @return {zrender/graphic/Style} [description]
  6193. */
  6194. clone: function () {
  6195. var newStyle = new this.constructor();
  6196. newStyle.extendFrom(this, true);
  6197. return newStyle;
  6198. },
  6199. getGradient: function (ctx, obj, rect) {
  6200. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6201. var canvasGradient = method(ctx, obj, rect);
  6202. var colorStops = obj.colorStops;
  6203. for (var i = 0; i < colorStops.length; i++) {
  6204. canvasGradient.addColorStop(
  6205. colorStops[i].offset, colorStops[i].color
  6206. );
  6207. }
  6208. return canvasGradient;
  6209. }
  6210. };
  6211. var styleProto = Style.prototype;
  6212. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6213. var prop = STYLE_COMMON_PROPS[i];
  6214. if (!(prop[0] in styleProto)) {
  6215. styleProto[prop[0]] = prop[1];
  6216. }
  6217. }
  6218. // Provide for others
  6219. Style.getGradient = styleProto.getGradient;
  6220. var Pattern = function (image, repeat) {
  6221. // Should do nothing more in this constructor. Because gradient can be
  6222. // declard by `color: {image: ...}`, where this constructor will not be called.
  6223. this.image = image;
  6224. this.repeat = repeat;
  6225. // Can be cloned
  6226. this.type = 'pattern';
  6227. };
  6228. Pattern.prototype.getCanvasPattern = function (ctx) {
  6229. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6230. };
  6231. /**
  6232. * @module zrender/Layer
  6233. * @author pissang(https://www.github.com/pissang)
  6234. */
  6235. function returnFalse() {
  6236. return false;
  6237. }
  6238. /**
  6239. * 创建dom
  6240. *
  6241. * @inner
  6242. * @param {string} id dom id 待用
  6243. * @param {Painter} painter painter instance
  6244. * @param {number} number
  6245. */
  6246. function createDom(id, painter, dpr) {
  6247. var newDom = createCanvas();
  6248. var width = painter.getWidth();
  6249. var height = painter.getHeight();
  6250. var newDomStyle = newDom.style;
  6251. if (newDomStyle) { // In node or some other non-browser environment
  6252. newDomStyle.position = 'absolute';
  6253. newDomStyle.left = 0;
  6254. newDomStyle.top = 0;
  6255. newDomStyle.width = width + 'px';
  6256. newDomStyle.height = height + 'px';
  6257. newDom.setAttribute('data-zr-dom-id', id);
  6258. }
  6259. newDom.width = width * dpr;
  6260. newDom.height = height * dpr;
  6261. return newDom;
  6262. }
  6263. /**
  6264. * @alias module:zrender/Layer
  6265. * @constructor
  6266. * @extends module:zrender/mixin/Transformable
  6267. * @param {string} id
  6268. * @param {module:zrender/Painter} painter
  6269. * @param {number} [dpr]
  6270. */
  6271. var Layer = function (id, painter, dpr) {
  6272. var dom;
  6273. dpr = dpr || devicePixelRatio;
  6274. if (typeof id === 'string') {
  6275. dom = createDom(id, painter, dpr);
  6276. }
  6277. // Not using isDom because in node it will return false
  6278. else if (isObject$1(id)) {
  6279. dom = id;
  6280. id = dom.id;
  6281. }
  6282. this.id = id;
  6283. this.dom = dom;
  6284. var domStyle = dom.style;
  6285. if (domStyle) { // Not in node
  6286. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6287. domStyle['-webkit-user-select'] = 'none';
  6288. domStyle['user-select'] = 'none';
  6289. domStyle['-webkit-touch-callout'] = 'none';
  6290. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6291. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6292. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6293. domStyle['border-width'] = 0;
  6294. }
  6295. this.domBack = null;
  6296. this.ctxBack = null;
  6297. this.painter = painter;
  6298. this.config = null;
  6299. // Configs
  6300. /**
  6301. * 每次清空画布的颜色
  6302. * @type {string}
  6303. * @default 0
  6304. */
  6305. this.clearColor = 0;
  6306. /**
  6307. * 是否开启动态模糊
  6308. * @type {boolean}
  6309. * @default false
  6310. */
  6311. this.motionBlur = false;
  6312. /**
  6313. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6314. * @type {number}
  6315. * @default 0.7
  6316. */
  6317. this.lastFrameAlpha = 0.7;
  6318. /**
  6319. * Layer dpr
  6320. * @type {number}
  6321. */
  6322. this.dpr = dpr;
  6323. };
  6324. Layer.prototype = {
  6325. constructor: Layer,
  6326. __dirty: true,
  6327. __used: false,
  6328. __drawIndex: 0,
  6329. __startIndex: 0,
  6330. __endIndex: 0,
  6331. incremental: false,
  6332. getElementCount: function () {
  6333. return this.__endIndex - this.__startIndex;
  6334. },
  6335. initContext: function () {
  6336. this.ctx = this.dom.getContext('2d');
  6337. this.ctx.dpr = this.dpr;
  6338. },
  6339. createBackBuffer: function () {
  6340. var dpr = this.dpr;
  6341. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6342. this.ctxBack = this.domBack.getContext('2d');
  6343. if (dpr !== 1) {
  6344. this.ctxBack.scale(dpr, dpr);
  6345. }
  6346. },
  6347. /**
  6348. * @param {number} width
  6349. * @param {number} height
  6350. */
  6351. resize: function (width, height) {
  6352. var dpr = this.dpr;
  6353. var dom = this.dom;
  6354. var domStyle = dom.style;
  6355. var domBack = this.domBack;
  6356. if (domStyle) {
  6357. domStyle.width = width + 'px';
  6358. domStyle.height = height + 'px';
  6359. }
  6360. dom.width = width * dpr;
  6361. dom.height = height * dpr;
  6362. if (domBack) {
  6363. domBack.width = width * dpr;
  6364. domBack.height = height * dpr;
  6365. if (dpr !== 1) {
  6366. this.ctxBack.scale(dpr, dpr);
  6367. }
  6368. }
  6369. },
  6370. /**
  6371. * 清空该层画布
  6372. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6373. * @param {Color} [clearColor]
  6374. */
  6375. clear: function (clearAll, clearColor) {
  6376. var dom = this.dom;
  6377. var ctx = this.ctx;
  6378. var width = dom.width;
  6379. var height = dom.height;
  6380. var clearColor = clearColor || this.clearColor;
  6381. var haveMotionBLur = this.motionBlur && !clearAll;
  6382. var lastFrameAlpha = this.lastFrameAlpha;
  6383. var dpr = this.dpr;
  6384. if (haveMotionBLur) {
  6385. if (!this.domBack) {
  6386. this.createBackBuffer();
  6387. }
  6388. this.ctxBack.globalCompositeOperation = 'copy';
  6389. this.ctxBack.drawImage(
  6390. dom, 0, 0,
  6391. width / dpr,
  6392. height / dpr
  6393. );
  6394. }
  6395. ctx.clearRect(0, 0, width, height);
  6396. if (clearColor && clearColor !== 'transparent') {
  6397. var clearColorGradientOrPattern;
  6398. // Gradient
  6399. if (clearColor.colorStops) {
  6400. // Cache canvas gradient
  6401. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6402. x: 0,
  6403. y: 0,
  6404. width: width,
  6405. height: height
  6406. });
  6407. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6408. }
  6409. // Pattern
  6410. else if (clearColor.image) {
  6411. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6412. }
  6413. ctx.save();
  6414. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6415. ctx.fillRect(0, 0, width, height);
  6416. ctx.restore();
  6417. }
  6418. if (haveMotionBLur) {
  6419. var domBack = this.domBack;
  6420. ctx.save();
  6421. ctx.globalAlpha = lastFrameAlpha;
  6422. ctx.drawImage(domBack, 0, 0, width, height);
  6423. ctx.restore();
  6424. }
  6425. }
  6426. };
  6427. var requestAnimationFrame = (
  6428. typeof window !== 'undefined'
  6429. && (
  6430. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6431. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6432. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6433. || window.mozRequestAnimationFrame
  6434. || window.webkitRequestAnimationFrame
  6435. )
  6436. ) || function (func) {
  6437. setTimeout(func, 16);
  6438. };
  6439. var globalImageCache = new LRU(50);
  6440. /**
  6441. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6442. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6443. */
  6444. function findExistImage(newImageOrSrc) {
  6445. if (typeof newImageOrSrc === 'string') {
  6446. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6447. return cachedImgObj && cachedImgObj.image;
  6448. }
  6449. else {
  6450. return newImageOrSrc;
  6451. }
  6452. }
  6453. /**
  6454. * Caution: User should cache loaded images, but not just count on LRU.
  6455. * Consider if required images more than LRU size, will dead loop occur?
  6456. *
  6457. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6458. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6459. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6460. * @param {Function} [cb] params: (image, cbPayload)
  6461. * @param {Object} [cbPayload] Payload on cb calling.
  6462. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6463. */
  6464. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6465. if (!newImageOrSrc) {
  6466. return image;
  6467. }
  6468. else if (typeof newImageOrSrc === 'string') {
  6469. // Image should not be loaded repeatly.
  6470. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6471. return image;
  6472. }
  6473. // Only when there is no existent image or existent image src
  6474. // is different, this method is responsible for load.
  6475. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6476. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6477. if (cachedImgObj) {
  6478. image = cachedImgObj.image;
  6479. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6480. }
  6481. else {
  6482. image = new Image();
  6483. image.onload = image.onerror = imageOnLoad;
  6484. globalImageCache.put(
  6485. newImageOrSrc,
  6486. image.__cachedImgObj = {
  6487. image: image,
  6488. pending: [pendingWrap]
  6489. }
  6490. );
  6491. image.src = image.__zrImageSrc = newImageOrSrc;
  6492. }
  6493. return image;
  6494. }
  6495. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6496. else {
  6497. return newImageOrSrc;
  6498. }
  6499. }
  6500. function imageOnLoad() {
  6501. var cachedImgObj = this.__cachedImgObj;
  6502. this.onload = this.onerror = this.__cachedImgObj = null;
  6503. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6504. var pendingWrap = cachedImgObj.pending[i];
  6505. var cb = pendingWrap.cb;
  6506. cb && cb(this, pendingWrap.cbPayload);
  6507. pendingWrap.hostEl.dirty();
  6508. }
  6509. cachedImgObj.pending.length = 0;
  6510. }
  6511. function isImageReady(image) {
  6512. return image && image.width && image.height;
  6513. }
  6514. var textWidthCache = {};
  6515. var textWidthCacheCounter = 0;
  6516. var TEXT_CACHE_MAX = 5000;
  6517. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6518. var DEFAULT_FONT$1 = '12px sans-serif';
  6519. // Avoid assign to an exported variable, for transforming to cjs.
  6520. var methods$1 = {};
  6521. /**
  6522. * @public
  6523. * @param {string} text
  6524. * @param {string} font
  6525. * @return {number} width
  6526. */
  6527. function getWidth(text, font) {
  6528. font = font || DEFAULT_FONT$1;
  6529. var key = text + ':' + font;
  6530. if (textWidthCache[key]) {
  6531. return textWidthCache[key];
  6532. }
  6533. var textLines = (text + '').split('\n');
  6534. var width = 0;
  6535. for (var i = 0, l = textLines.length; i < l; i++) {
  6536. // textContain.measureText may be overrided in SVG or VML
  6537. width = Math.max(measureText(textLines[i], font).width, width);
  6538. }
  6539. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6540. textWidthCacheCounter = 0;
  6541. textWidthCache = {};
  6542. }
  6543. textWidthCacheCounter++;
  6544. textWidthCache[key] = width;
  6545. return width;
  6546. }
  6547. /**
  6548. * @public
  6549. * @param {string} text
  6550. * @param {string} font
  6551. * @param {string} [textAlign='left']
  6552. * @param {string} [textVerticalAlign='top']
  6553. * @param {Array.<number>} [textPadding]
  6554. * @param {Object} [rich]
  6555. * @param {Object} [truncate]
  6556. * @return {Object} {x, y, width, height, lineHeight}
  6557. */
  6558. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6559. return rich
  6560. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6561. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6562. }
  6563. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6564. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6565. var outerWidth = getWidth(text, font);
  6566. if (textPadding) {
  6567. outerWidth += textPadding[1] + textPadding[3];
  6568. }
  6569. var outerHeight = contentBlock.outerHeight;
  6570. var x = adjustTextX(0, outerWidth, textAlign);
  6571. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6572. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6573. rect.lineHeight = contentBlock.lineHeight;
  6574. return rect;
  6575. }
  6576. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6577. var contentBlock = parseRichText(text, {
  6578. rich: rich,
  6579. truncate: truncate,
  6580. font: font,
  6581. textAlign: textAlign,
  6582. textPadding: textPadding,
  6583. textLineHeight: textLineHeight
  6584. });
  6585. var outerWidth = contentBlock.outerWidth;
  6586. var outerHeight = contentBlock.outerHeight;
  6587. var x = adjustTextX(0, outerWidth, textAlign);
  6588. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6589. return new BoundingRect(x, y, outerWidth, outerHeight);
  6590. }
  6591. /**
  6592. * @public
  6593. * @param {number} x
  6594. * @param {number} width
  6595. * @param {string} [textAlign='left']
  6596. * @return {number} Adjusted x.
  6597. */
  6598. function adjustTextX(x, width, textAlign) {
  6599. // FIXME Right to left language
  6600. if (textAlign === 'right') {
  6601. x -= width;
  6602. }
  6603. else if (textAlign === 'center') {
  6604. x -= width / 2;
  6605. }
  6606. return x;
  6607. }
  6608. /**
  6609. * @public
  6610. * @param {number} y
  6611. * @param {number} height
  6612. * @param {string} [textVerticalAlign='top']
  6613. * @return {number} Adjusted y.
  6614. */
  6615. function adjustTextY(y, height, textVerticalAlign) {
  6616. if (textVerticalAlign === 'middle') {
  6617. y -= height / 2;
  6618. }
  6619. else if (textVerticalAlign === 'bottom') {
  6620. y -= height;
  6621. }
  6622. return y;
  6623. }
  6624. /**
  6625. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6626. * @public
  6627. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6628. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6629. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6630. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6631. */
  6632. function calculateTextPosition(out, style, rect) {
  6633. var textPosition = style.textPosition;
  6634. var distance = style.textDistance;
  6635. var x = rect.x;
  6636. var y = rect.y;
  6637. distance = distance || 0;
  6638. var height = rect.height;
  6639. var width = rect.width;
  6640. var halfHeight = height / 2;
  6641. var textAlign = 'left';
  6642. var textVerticalAlign = 'top';
  6643. switch (textPosition) {
  6644. case 'left':
  6645. x -= distance;
  6646. y += halfHeight;
  6647. textAlign = 'right';
  6648. textVerticalAlign = 'middle';
  6649. break;
  6650. case 'right':
  6651. x += distance + width;
  6652. y += halfHeight;
  6653. textVerticalAlign = 'middle';
  6654. break;
  6655. case 'top':
  6656. x += width / 2;
  6657. y -= distance;
  6658. textAlign = 'center';
  6659. textVerticalAlign = 'bottom';
  6660. break;
  6661. case 'bottom':
  6662. x += width / 2;
  6663. y += height + distance;
  6664. textAlign = 'center';
  6665. break;
  6666. case 'inside':
  6667. x += width / 2;
  6668. y += halfHeight;
  6669. textAlign = 'center';
  6670. textVerticalAlign = 'middle';
  6671. break;
  6672. case 'insideLeft':
  6673. x += distance;
  6674. y += halfHeight;
  6675. textVerticalAlign = 'middle';
  6676. break;
  6677. case 'insideRight':
  6678. x += width - distance;
  6679. y += halfHeight;
  6680. textAlign = 'right';
  6681. textVerticalAlign = 'middle';
  6682. break;
  6683. case 'insideTop':
  6684. x += width / 2;
  6685. y += distance;
  6686. textAlign = 'center';
  6687. break;
  6688. case 'insideBottom':
  6689. x += width / 2;
  6690. y += height - distance;
  6691. textAlign = 'center';
  6692. textVerticalAlign = 'bottom';
  6693. break;
  6694. case 'insideTopLeft':
  6695. x += distance;
  6696. y += distance;
  6697. break;
  6698. case 'insideTopRight':
  6699. x += width - distance;
  6700. y += distance;
  6701. textAlign = 'right';
  6702. break;
  6703. case 'insideBottomLeft':
  6704. x += distance;
  6705. y += height - distance;
  6706. textVerticalAlign = 'bottom';
  6707. break;
  6708. case 'insideBottomRight':
  6709. x += width - distance;
  6710. y += height - distance;
  6711. textAlign = 'right';
  6712. textVerticalAlign = 'bottom';
  6713. break;
  6714. }
  6715. out = out || {};
  6716. out.x = x;
  6717. out.y = y;
  6718. out.textAlign = textAlign;
  6719. out.textVerticalAlign = textVerticalAlign;
  6720. return out;
  6721. }
  6722. /**
  6723. * To be removed. But still do not remove in case that some one has imported it.
  6724. * @deprecated
  6725. * @public
  6726. * @param {stirng} textPosition
  6727. * @param {Object} rect {x, y, width, height}
  6728. * @param {number} distance
  6729. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6730. */
  6731. /**
  6732. * Show ellipsis if overflow.
  6733. *
  6734. * @public
  6735. * @param {string} text
  6736. * @param {string} containerWidth
  6737. * @param {string} font
  6738. * @param {number} [ellipsis='...']
  6739. * @param {Object} [options]
  6740. * @param {number} [options.maxIterations=3]
  6741. * @param {number} [options.minChar=0] If truncate result are less
  6742. * then minChar, ellipsis will not show, which is
  6743. * better for user hint in some cases.
  6744. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6745. * @return {string}
  6746. */
  6747. function truncateText(text, containerWidth, font, ellipsis, options) {
  6748. if (!containerWidth) {
  6749. return '';
  6750. }
  6751. var textLines = (text + '').split('\n');
  6752. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6753. // FIXME
  6754. // It is not appropriate that every line has '...' when truncate multiple lines.
  6755. for (var i = 0, len = textLines.length; i < len; i++) {
  6756. textLines[i] = truncateSingleLine(textLines[i], options);
  6757. }
  6758. return textLines.join('\n');
  6759. }
  6760. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6761. options = extend({}, options);
  6762. options.font = font;
  6763. var ellipsis = retrieve2(ellipsis, '...');
  6764. options.maxIterations = retrieve2(options.maxIterations, 2);
  6765. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6766. // FIXME
  6767. // Other languages?
  6768. options.cnCharWidth = getWidth('国', font);
  6769. // FIXME
  6770. // Consider proportional font?
  6771. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6772. options.placeholder = retrieve2(options.placeholder, '');
  6773. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6774. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6775. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6776. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6777. contentWidth -= ascCharWidth;
  6778. }
  6779. var ellipsisWidth = getWidth(ellipsis, font);
  6780. if (ellipsisWidth > contentWidth) {
  6781. ellipsis = '';
  6782. ellipsisWidth = 0;
  6783. }
  6784. contentWidth = containerWidth - ellipsisWidth;
  6785. options.ellipsis = ellipsis;
  6786. options.ellipsisWidth = ellipsisWidth;
  6787. options.contentWidth = contentWidth;
  6788. options.containerWidth = containerWidth;
  6789. return options;
  6790. }
  6791. function truncateSingleLine(textLine, options) {
  6792. var containerWidth = options.containerWidth;
  6793. var font = options.font;
  6794. var contentWidth = options.contentWidth;
  6795. if (!containerWidth) {
  6796. return '';
  6797. }
  6798. var lineWidth = getWidth(textLine, font);
  6799. if (lineWidth <= containerWidth) {
  6800. return textLine;
  6801. }
  6802. for (var j = 0; ; j++) {
  6803. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6804. textLine += options.ellipsis;
  6805. break;
  6806. }
  6807. var subLength = j === 0
  6808. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6809. : lineWidth > 0
  6810. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6811. : 0;
  6812. textLine = textLine.substr(0, subLength);
  6813. lineWidth = getWidth(textLine, font);
  6814. }
  6815. if (textLine === '') {
  6816. textLine = options.placeholder;
  6817. }
  6818. return textLine;
  6819. }
  6820. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6821. var width = 0;
  6822. var i = 0;
  6823. for (var len = text.length; i < len && width < contentWidth; i++) {
  6824. var charCode = text.charCodeAt(i);
  6825. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6826. }
  6827. return i;
  6828. }
  6829. /**
  6830. * @public
  6831. * @param {string} font
  6832. * @return {number} line height
  6833. */
  6834. function getLineHeight(font) {
  6835. // FIXME A rough approach.
  6836. return getWidth('国', font);
  6837. }
  6838. /**
  6839. * @public
  6840. * @param {string} text
  6841. * @param {string} font
  6842. * @return {Object} width
  6843. */
  6844. function measureText(text, font) {
  6845. return methods$1.measureText(text, font);
  6846. }
  6847. // Avoid assign to an exported variable, for transforming to cjs.
  6848. methods$1.measureText = function (text, font) {
  6849. var ctx = getContext();
  6850. ctx.font = font || DEFAULT_FONT$1;
  6851. return ctx.measureText(text);
  6852. };
  6853. /**
  6854. * @public
  6855. * @param {string} text
  6856. * @param {string} font
  6857. * @param {Object} [truncate]
  6858. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  6859. * Notice: for performance, do not calculate outerWidth util needed.
  6860. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  6861. * Thus we can simply comparing the `input` text to determin whether the result changed,
  6862. * without travel the result `lines`.
  6863. */
  6864. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6865. text != null && (text += '');
  6866. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6867. var lines = text ? text.split('\n') : [];
  6868. var height = lines.length * lineHeight;
  6869. var outerHeight = height;
  6870. var canCacheByTextString = true;
  6871. if (padding) {
  6872. outerHeight += padding[0] + padding[2];
  6873. }
  6874. if (text && truncate) {
  6875. canCacheByTextString = false;
  6876. var truncOuterHeight = truncate.outerHeight;
  6877. var truncOuterWidth = truncate.outerWidth;
  6878. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6879. text = '';
  6880. lines = [];
  6881. }
  6882. else if (truncOuterWidth != null) {
  6883. var options = prepareTruncateOptions(
  6884. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6885. font,
  6886. truncate.ellipsis,
  6887. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6888. );
  6889. // FIXME
  6890. // It is not appropriate that every line has '...' when truncate multiple lines.
  6891. for (var i = 0, len = lines.length; i < len; i++) {
  6892. lines[i] = truncateSingleLine(lines[i], options);
  6893. }
  6894. }
  6895. }
  6896. return {
  6897. lines: lines,
  6898. height: height,
  6899. outerHeight: outerHeight,
  6900. lineHeight: lineHeight,
  6901. canCacheByTextString: canCacheByTextString
  6902. };
  6903. }
  6904. /**
  6905. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6906. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6907. *
  6908. * @public
  6909. * @param {string} text
  6910. * @param {Object} style
  6911. * @return {Object} block
  6912. * {
  6913. * width,
  6914. * height,
  6915. * lines: [{
  6916. * lineHeight,
  6917. * width,
  6918. * tokens: [[{
  6919. * styleName,
  6920. * text,
  6921. * width, // include textPadding
  6922. * height, // include textPadding
  6923. * textWidth, // pure text width
  6924. * textHeight, // pure text height
  6925. * lineHeihgt,
  6926. * font,
  6927. * textAlign,
  6928. * textVerticalAlign
  6929. * }], [...], ...]
  6930. * }, ...]
  6931. * }
  6932. * If styleName is undefined, it is plain text.
  6933. */
  6934. function parseRichText(text, style) {
  6935. var contentBlock = {lines: [], width: 0, height: 0};
  6936. text != null && (text += '');
  6937. if (!text) {
  6938. return contentBlock;
  6939. }
  6940. var lastIndex = STYLE_REG.lastIndex = 0;
  6941. var result;
  6942. while ((result = STYLE_REG.exec(text)) != null) {
  6943. var matchedIndex = result.index;
  6944. if (matchedIndex > lastIndex) {
  6945. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6946. }
  6947. pushTokens(contentBlock, result[2], result[1]);
  6948. lastIndex = STYLE_REG.lastIndex;
  6949. }
  6950. if (lastIndex < text.length) {
  6951. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6952. }
  6953. var lines = contentBlock.lines;
  6954. var contentHeight = 0;
  6955. var contentWidth = 0;
  6956. // For `textWidth: 100%`
  6957. var pendingList = [];
  6958. var stlPadding = style.textPadding;
  6959. var truncate = style.truncate;
  6960. var truncateWidth = truncate && truncate.outerWidth;
  6961. var truncateHeight = truncate && truncate.outerHeight;
  6962. if (stlPadding) {
  6963. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6964. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6965. }
  6966. // Calculate layout info of tokens.
  6967. for (var i = 0; i < lines.length; i++) {
  6968. var line = lines[i];
  6969. var lineHeight = 0;
  6970. var lineWidth = 0;
  6971. for (var j = 0; j < line.tokens.length; j++) {
  6972. var token = line.tokens[j];
  6973. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6974. // textPadding should not inherit from style.
  6975. var textPadding = token.textPadding = tokenStyle.textPadding;
  6976. // textFont has been asigned to font by `normalizeStyle`.
  6977. var font = token.font = tokenStyle.font || style.font;
  6978. // textHeight can be used when textVerticalAlign is specified in token.
  6979. var tokenHeight = token.textHeight = retrieve2(
  6980. // textHeight should not be inherited, consider it can be specified
  6981. // as box height of the block.
  6982. tokenStyle.textHeight, getLineHeight(font)
  6983. );
  6984. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6985. token.height = tokenHeight;
  6986. token.lineHeight = retrieve3(
  6987. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6988. );
  6989. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6990. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6991. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6992. return {lines: [], width: 0, height: 0};
  6993. }
  6994. token.textWidth = getWidth(token.text, font);
  6995. var tokenWidth = tokenStyle.textWidth;
  6996. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6997. // Percent width, can be `100%`, can be used in drawing separate
  6998. // line when box width is needed to be auto.
  6999. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7000. token.percentWidth = tokenWidth;
  7001. pendingList.push(token);
  7002. tokenWidth = 0;
  7003. // Do not truncate in this case, because there is no user case
  7004. // and it is too complicated.
  7005. }
  7006. else {
  7007. if (tokenWidthNotSpecified) {
  7008. tokenWidth = token.textWidth;
  7009. // FIXME: If image is not loaded and textWidth is not specified, calling
  7010. // `getBoundingRect()` will not get correct result.
  7011. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7012. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7013. // Use cases:
  7014. // (1) If image is not loaded, it will be loaded at render phase and call
  7015. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7016. // image, and then the right size will be calculated here at the next tick.
  7017. // See `graphic/helper/text.js`.
  7018. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7019. // use `imageHelper.findExistImage` to find cached image.
  7020. // `imageHelper.findExistImage` will always be called here before
  7021. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7022. // which ensures that image will not be rendered before correct size calcualted.
  7023. if (bgImg) {
  7024. bgImg = findExistImage(bgImg);
  7025. if (isImageReady(bgImg)) {
  7026. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7027. }
  7028. }
  7029. }
  7030. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7031. tokenWidth += paddingW;
  7032. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7033. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7034. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7035. token.text = '';
  7036. token.textWidth = tokenWidth = 0;
  7037. }
  7038. else {
  7039. token.text = truncateText(
  7040. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7041. {minChar: truncate.minChar}
  7042. );
  7043. token.textWidth = getWidth(token.text, font);
  7044. tokenWidth = token.textWidth + paddingW;
  7045. }
  7046. }
  7047. }
  7048. lineWidth += (token.width = tokenWidth);
  7049. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7050. }
  7051. line.width = lineWidth;
  7052. line.lineHeight = lineHeight;
  7053. contentHeight += lineHeight;
  7054. contentWidth = Math.max(contentWidth, lineWidth);
  7055. }
  7056. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7057. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7058. if (stlPadding) {
  7059. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7060. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7061. }
  7062. for (var i = 0; i < pendingList.length; i++) {
  7063. var token = pendingList[i];
  7064. var percentWidth = token.percentWidth;
  7065. // Should not base on outerWidth, because token can not be placed out of padding.
  7066. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7067. }
  7068. return contentBlock;
  7069. }
  7070. function pushTokens(block, str, styleName) {
  7071. var isEmptyStr = str === '';
  7072. var strs = str.split('\n');
  7073. var lines = block.lines;
  7074. for (var i = 0; i < strs.length; i++) {
  7075. var text = strs[i];
  7076. var token = {
  7077. styleName: styleName,
  7078. text: text,
  7079. isLineHolder: !text && !isEmptyStr
  7080. };
  7081. // The first token should be appended to the last line.
  7082. if (!i) {
  7083. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7084. // Consider cases:
  7085. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7086. // (which is a placeholder) should be replaced by new token.
  7087. // (2) A image backage, where token likes {a|}.
  7088. // (3) A redundant '' will affect textAlign in line.
  7089. // (4) tokens with the same tplName should not be merged, because
  7090. // they should be displayed in different box (with border and padding).
  7091. var tokensLen = tokens.length;
  7092. (tokensLen === 1 && tokens[0].isLineHolder)
  7093. ? (tokens[0] = token)
  7094. // Consider text is '', only insert when it is the "lineHolder" or
  7095. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7096. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7097. }
  7098. // Other tokens always start a new line.
  7099. else {
  7100. // If there is '', insert it as a placeholder.
  7101. lines.push({tokens: [token]});
  7102. }
  7103. }
  7104. }
  7105. function makeFont(style) {
  7106. // FIXME in node-canvas fontWeight is before fontStyle
  7107. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7108. var font = (style.fontSize || style.fontFamily) && [
  7109. style.fontStyle,
  7110. style.fontWeight,
  7111. (style.fontSize || 12) + 'px',
  7112. // If font properties are defined, `fontFamily` should not be ignored.
  7113. style.fontFamily || 'sans-serif'
  7114. ].join(' ');
  7115. return font && trim(font) || style.textFont || style.font;
  7116. }
  7117. /**
  7118. * @param {Object} ctx
  7119. * @param {Object} shape
  7120. * @param {number} shape.x
  7121. * @param {number} shape.y
  7122. * @param {number} shape.width
  7123. * @param {number} shape.height
  7124. * @param {number} shape.r
  7125. */
  7126. function buildPath(ctx, shape) {
  7127. var x = shape.x;
  7128. var y = shape.y;
  7129. var width = shape.width;
  7130. var height = shape.height;
  7131. var r = shape.r;
  7132. var r1;
  7133. var r2;
  7134. var r3;
  7135. var r4;
  7136. // Convert width and height to positive for better borderRadius
  7137. if (width < 0) {
  7138. x = x + width;
  7139. width = -width;
  7140. }
  7141. if (height < 0) {
  7142. y = y + height;
  7143. height = -height;
  7144. }
  7145. if (typeof r === 'number') {
  7146. r1 = r2 = r3 = r4 = r;
  7147. }
  7148. else if (r instanceof Array) {
  7149. if (r.length === 1) {
  7150. r1 = r2 = r3 = r4 = r[0];
  7151. }
  7152. else if (r.length === 2) {
  7153. r1 = r3 = r[0];
  7154. r2 = r4 = r[1];
  7155. }
  7156. else if (r.length === 3) {
  7157. r1 = r[0];
  7158. r2 = r4 = r[1];
  7159. r3 = r[2];
  7160. }
  7161. else {
  7162. r1 = r[0];
  7163. r2 = r[1];
  7164. r3 = r[2];
  7165. r4 = r[3];
  7166. }
  7167. }
  7168. else {
  7169. r1 = r2 = r3 = r4 = 0;
  7170. }
  7171. var total;
  7172. if (r1 + r2 > width) {
  7173. total = r1 + r2;
  7174. r1 *= width / total;
  7175. r2 *= width / total;
  7176. }
  7177. if (r3 + r4 > width) {
  7178. total = r3 + r4;
  7179. r3 *= width / total;
  7180. r4 *= width / total;
  7181. }
  7182. if (r2 + r3 > height) {
  7183. total = r2 + r3;
  7184. r2 *= height / total;
  7185. r3 *= height / total;
  7186. }
  7187. if (r1 + r4 > height) {
  7188. total = r1 + r4;
  7189. r1 *= height / total;
  7190. r4 *= height / total;
  7191. }
  7192. ctx.moveTo(x + r1, y);
  7193. ctx.lineTo(x + width - r2, y);
  7194. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7195. ctx.lineTo(x + width, y + height - r3);
  7196. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7197. ctx.lineTo(x + r4, y + height);
  7198. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7199. ctx.lineTo(x, y + r1);
  7200. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7201. }
  7202. var DEFAULT_FONT = DEFAULT_FONT$1;
  7203. // TODO: Have not support 'start', 'end' yet.
  7204. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7205. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7206. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7207. // the default value of shadowColor is `'transparent'`.
  7208. var SHADOW_STYLE_COMMON_PROPS = [
  7209. ['textShadowBlur', 'shadowBlur', 0],
  7210. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7211. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7212. ['textShadowColor', 'shadowColor', 'transparent']
  7213. ];
  7214. var _tmpTextPositionResult = {};
  7215. var _tmpBoxPositionResult = {};
  7216. /**
  7217. * @param {module:zrender/graphic/Style} style
  7218. * @return {module:zrender/graphic/Style} The input style.
  7219. */
  7220. function normalizeTextStyle(style) {
  7221. normalizeStyle(style);
  7222. each$1(style.rich, normalizeStyle);
  7223. return style;
  7224. }
  7225. function normalizeStyle(style) {
  7226. if (style) {
  7227. style.font = makeFont(style);
  7228. var textAlign = style.textAlign;
  7229. textAlign === 'middle' && (textAlign = 'center');
  7230. style.textAlign = (
  7231. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7232. ) ? textAlign : 'left';
  7233. // Compatible with textBaseline.
  7234. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7235. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7236. style.textVerticalAlign = (
  7237. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7238. ) ? textVerticalAlign : 'top';
  7239. var textPadding = style.textPadding;
  7240. if (textPadding) {
  7241. style.textPadding = normalizeCssArray(style.textPadding);
  7242. }
  7243. }
  7244. }
  7245. /**
  7246. * @param {CanvasRenderingContext2D} ctx
  7247. * @param {string} text
  7248. * @param {module:zrender/graphic/Style} style
  7249. * @param {Object|boolean} [rect] {x, y, width, height}
  7250. * If set false, rect text is not used.
  7251. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7252. */
  7253. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7254. style.rich
  7255. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7256. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7257. }
  7258. // Avoid setting to ctx according to prevEl if possible for
  7259. // performance in scenarios of large amount text.
  7260. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7261. 'use strict';
  7262. var needDrawBg = needDrawBackground(style);
  7263. var prevStyle;
  7264. var checkCache = false;
  7265. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7266. // Only take and check cache for `Text` el, but not RectText.
  7267. if (prevEl !== WILL_BE_RESTORED) {
  7268. if (prevEl) {
  7269. prevStyle = prevEl.style;
  7270. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7271. }
  7272. // Prevent from using cache in `Style::bind`, because of the case:
  7273. // ctx property is modified by other properties than `Style::bind`
  7274. // used, and Style::bind is called next.
  7275. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7276. }
  7277. // Since this will be restored, prevent from using these props to check cache in the next
  7278. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7279. else if (cachedByMe) {
  7280. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7281. }
  7282. var styleFont = style.font || DEFAULT_FONT;
  7283. // PENDING
  7284. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7285. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7286. // But layer save/restore needed to be considered.
  7287. // if (styleFont !== ctx.__fontCache) {
  7288. // ctx.font = styleFont;
  7289. // if (prevEl !== WILL_BE_RESTORED) {
  7290. // ctx.__fontCache = styleFont;
  7291. // }
  7292. // }
  7293. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7294. ctx.font = styleFont;
  7295. }
  7296. // Use the final font from context-2d, because the final
  7297. // font might not be the style.font when it is illegal.
  7298. // But get `ctx.font` might be time consuming.
  7299. var computedFont = hostEl.__computedFont;
  7300. if (hostEl.__styleFont !== styleFont) {
  7301. hostEl.__styleFont = styleFont;
  7302. computedFont = hostEl.__computedFont = ctx.font;
  7303. }
  7304. var textPadding = style.textPadding;
  7305. var textLineHeight = style.textLineHeight;
  7306. var contentBlock = hostEl.__textCotentBlock;
  7307. if (!contentBlock || hostEl.__dirtyText) {
  7308. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7309. text, computedFont, textPadding, textLineHeight, style.truncate
  7310. );
  7311. }
  7312. var outerHeight = contentBlock.outerHeight;
  7313. var textLines = contentBlock.lines;
  7314. var lineHeight = contentBlock.lineHeight;
  7315. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7316. var baseX = boxPos.baseX;
  7317. var baseY = boxPos.baseY;
  7318. var textAlign = boxPos.textAlign || 'left';
  7319. var textVerticalAlign = boxPos.textVerticalAlign;
  7320. // Origin of textRotation should be the base point of text drawing.
  7321. applyTextRotation(ctx, style, rect, baseX, baseY);
  7322. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7323. var textX = baseX;
  7324. var textY = boxY;
  7325. if (needDrawBg || textPadding) {
  7326. // Consider performance, do not call getTextWidth util necessary.
  7327. var textWidth = getWidth(text, computedFont);
  7328. var outerWidth = textWidth;
  7329. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7330. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7331. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7332. if (textPadding) {
  7333. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7334. textY += textPadding[0];
  7335. }
  7336. }
  7337. // Always set textAlign and textBase line, because it is difficute to calculate
  7338. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7339. // font set happened.
  7340. ctx.textAlign = textAlign;
  7341. // Force baseline to be "middle". Otherwise, if using "top", the
  7342. // text will offset downward a little bit in font "Microsoft YaHei".
  7343. ctx.textBaseline = 'middle';
  7344. // Set text opacity
  7345. ctx.globalAlpha = style.opacity || 1;
  7346. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7347. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7348. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7349. var styleProp = propItem[0];
  7350. var ctxProp = propItem[1];
  7351. var val = style[styleProp];
  7352. if (!checkCache || val !== prevStyle[styleProp]) {
  7353. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7354. }
  7355. }
  7356. // `textBaseline` is set as 'middle'.
  7357. textY += lineHeight / 2;
  7358. var textStrokeWidth = style.textStrokeWidth;
  7359. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7360. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7361. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7362. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7363. var textFill = getFill(style.textFill);
  7364. if (textStroke) {
  7365. if (strokeWidthChanged) {
  7366. ctx.lineWidth = textStrokeWidth;
  7367. }
  7368. if (strokeChanged) {
  7369. ctx.strokeStyle = textStroke;
  7370. }
  7371. }
  7372. if (textFill) {
  7373. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7374. ctx.fillStyle = textFill;
  7375. }
  7376. }
  7377. // Optimize simply, in most cases only one line exists.
  7378. if (textLines.length === 1) {
  7379. // Fill after stroke so the outline will not cover the main part.
  7380. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7381. textFill && ctx.fillText(textLines[0], textX, textY);
  7382. }
  7383. else {
  7384. for (var i = 0; i < textLines.length; i++) {
  7385. // Fill after stroke so the outline will not cover the main part.
  7386. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7387. textFill && ctx.fillText(textLines[i], textX, textY);
  7388. textY += lineHeight;
  7389. }
  7390. }
  7391. }
  7392. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7393. // Do not do cache for rich text because of the complexity.
  7394. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7395. if (prevEl !== WILL_BE_RESTORED) {
  7396. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7397. }
  7398. var contentBlock = hostEl.__textCotentBlock;
  7399. if (!contentBlock || hostEl.__dirtyText) {
  7400. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7401. }
  7402. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7403. }
  7404. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7405. var contentWidth = contentBlock.width;
  7406. var outerWidth = contentBlock.outerWidth;
  7407. var outerHeight = contentBlock.outerHeight;
  7408. var textPadding = style.textPadding;
  7409. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7410. var baseX = boxPos.baseX;
  7411. var baseY = boxPos.baseY;
  7412. var textAlign = boxPos.textAlign;
  7413. var textVerticalAlign = boxPos.textVerticalAlign;
  7414. // Origin of textRotation should be the base point of text drawing.
  7415. applyTextRotation(ctx, style, rect, baseX, baseY);
  7416. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7417. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7418. var xLeft = boxX;
  7419. var lineTop = boxY;
  7420. if (textPadding) {
  7421. xLeft += textPadding[3];
  7422. lineTop += textPadding[0];
  7423. }
  7424. var xRight = xLeft + contentWidth;
  7425. needDrawBackground(style) && drawBackground(
  7426. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7427. );
  7428. for (var i = 0; i < contentBlock.lines.length; i++) {
  7429. var line = contentBlock.lines[i];
  7430. var tokens = line.tokens;
  7431. var tokenCount = tokens.length;
  7432. var lineHeight = line.lineHeight;
  7433. var usedWidth = line.width;
  7434. var leftIndex = 0;
  7435. var lineXLeft = xLeft;
  7436. var lineXRight = xRight;
  7437. var rightIndex = tokenCount - 1;
  7438. var token;
  7439. while (
  7440. leftIndex < tokenCount
  7441. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7442. ) {
  7443. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7444. usedWidth -= token.width;
  7445. lineXLeft += token.width;
  7446. leftIndex++;
  7447. }
  7448. while (
  7449. rightIndex >= 0
  7450. && (token = tokens[rightIndex], token.textAlign === 'right')
  7451. ) {
  7452. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7453. usedWidth -= token.width;
  7454. lineXRight -= token.width;
  7455. rightIndex--;
  7456. }
  7457. // The other tokens are placed as textAlign 'center' if there is enough space.
  7458. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7459. while (leftIndex <= rightIndex) {
  7460. token = tokens[leftIndex];
  7461. // Consider width specified by user, use 'center' rather than 'left'.
  7462. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7463. lineXLeft += token.width;
  7464. leftIndex++;
  7465. }
  7466. lineTop += lineHeight;
  7467. }
  7468. }
  7469. function applyTextRotation(ctx, style, rect, x, y) {
  7470. // textRotation only apply in RectText.
  7471. if (rect && style.textRotation) {
  7472. var origin = style.textOrigin;
  7473. if (origin === 'center') {
  7474. x = rect.width / 2 + rect.x;
  7475. y = rect.height / 2 + rect.y;
  7476. }
  7477. else if (origin) {
  7478. x = origin[0] + rect.x;
  7479. y = origin[1] + rect.y;
  7480. }
  7481. ctx.translate(x, y);
  7482. // Positive: anticlockwise
  7483. ctx.rotate(-style.textRotation);
  7484. ctx.translate(-x, -y);
  7485. }
  7486. }
  7487. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7488. var tokenStyle = style.rich[token.styleName] || {};
  7489. tokenStyle.text = token.text;
  7490. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7491. // the bias of "Microsoft YaHei".
  7492. var textVerticalAlign = token.textVerticalAlign;
  7493. var y = lineTop + lineHeight / 2;
  7494. if (textVerticalAlign === 'top') {
  7495. y = lineTop + token.height / 2;
  7496. }
  7497. else if (textVerticalAlign === 'bottom') {
  7498. y = lineTop + lineHeight - token.height / 2;
  7499. }
  7500. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7501. hostEl,
  7502. ctx,
  7503. tokenStyle,
  7504. textAlign === 'right'
  7505. ? x - token.width
  7506. : textAlign === 'center'
  7507. ? x - token.width / 2
  7508. : x,
  7509. y - token.height / 2,
  7510. token.width,
  7511. token.height
  7512. );
  7513. var textPadding = token.textPadding;
  7514. if (textPadding) {
  7515. x = getTextXForPadding(x, textAlign, textPadding);
  7516. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7517. }
  7518. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7519. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7520. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7521. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7522. setCtx(ctx, 'textAlign', textAlign);
  7523. // Force baseline to be "middle". Otherwise, if using "top", the
  7524. // text will offset downward a little bit in font "Microsoft YaHei".
  7525. setCtx(ctx, 'textBaseline', 'middle');
  7526. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7527. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7528. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7529. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7530. // Fill after stroke so the outline will not cover the main part.
  7531. if (textStroke) {
  7532. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7533. setCtx(ctx, 'strokeStyle', textStroke);
  7534. ctx.strokeText(token.text, x, y);
  7535. }
  7536. if (textFill) {
  7537. setCtx(ctx, 'fillStyle', textFill);
  7538. ctx.fillText(token.text, x, y);
  7539. }
  7540. }
  7541. function needDrawBackground(style) {
  7542. return !!(
  7543. style.textBackgroundColor
  7544. || (style.textBorderWidth && style.textBorderColor)
  7545. );
  7546. }
  7547. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7548. // shape: {x, y, width, height}
  7549. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7550. var textBackgroundColor = style.textBackgroundColor;
  7551. var textBorderWidth = style.textBorderWidth;
  7552. var textBorderColor = style.textBorderColor;
  7553. var isPlainBg = isString(textBackgroundColor);
  7554. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7555. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7556. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7557. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7558. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7559. ctx.beginPath();
  7560. var textBorderRadius = style.textBorderRadius;
  7561. if (!textBorderRadius) {
  7562. ctx.rect(x, y, width, height);
  7563. }
  7564. else {
  7565. buildPath(ctx, {
  7566. x: x, y: y, width: width, height: height, r: textBorderRadius
  7567. });
  7568. }
  7569. ctx.closePath();
  7570. }
  7571. if (isPlainBg) {
  7572. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7573. if (style.fillOpacity != null) {
  7574. var originalGlobalAlpha = ctx.globalAlpha;
  7575. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7576. ctx.fill();
  7577. ctx.globalAlpha = originalGlobalAlpha;
  7578. }
  7579. else {
  7580. ctx.fill();
  7581. }
  7582. }
  7583. else if (isObject$1(textBackgroundColor)) {
  7584. var image = textBackgroundColor.image;
  7585. image = createOrUpdateImage(
  7586. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7587. );
  7588. if (image && isImageReady(image)) {
  7589. ctx.drawImage(image, x, y, width, height);
  7590. }
  7591. }
  7592. if (textBorderWidth && textBorderColor) {
  7593. setCtx(ctx, 'lineWidth', textBorderWidth);
  7594. setCtx(ctx, 'strokeStyle', textBorderColor);
  7595. if (style.strokeOpacity != null) {
  7596. var originalGlobalAlpha = ctx.globalAlpha;
  7597. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7598. ctx.stroke();
  7599. ctx.globalAlpha = originalGlobalAlpha;
  7600. }
  7601. else {
  7602. ctx.stroke();
  7603. }
  7604. }
  7605. }
  7606. function onBgImageLoaded(image, textBackgroundColor) {
  7607. // Replace image, so that `contain/text.js#parseRichText`
  7608. // will get correct result in next tick.
  7609. textBackgroundColor.image = image;
  7610. }
  7611. function getBoxPosition(out, hostEl, style, rect) {
  7612. var baseX = style.x || 0;
  7613. var baseY = style.y || 0;
  7614. var textAlign = style.textAlign;
  7615. var textVerticalAlign = style.textVerticalAlign;
  7616. // Text position represented by coord
  7617. if (rect) {
  7618. var textPosition = style.textPosition;
  7619. if (textPosition instanceof Array) {
  7620. // Percent
  7621. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7622. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7623. }
  7624. else {
  7625. var res = (hostEl && hostEl.calculateTextPosition)
  7626. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7627. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7628. baseX = res.x;
  7629. baseY = res.y;
  7630. // Default align and baseline when has textPosition
  7631. textAlign = textAlign || res.textAlign;
  7632. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7633. }
  7634. // textOffset is only support in RectText, otherwise
  7635. // we have to adjust boundingRect for textOffset.
  7636. var textOffset = style.textOffset;
  7637. if (textOffset) {
  7638. baseX += textOffset[0];
  7639. baseY += textOffset[1];
  7640. }
  7641. }
  7642. out = out || {};
  7643. out.baseX = baseX;
  7644. out.baseY = baseY;
  7645. out.textAlign = textAlign;
  7646. out.textVerticalAlign = textVerticalAlign;
  7647. return out;
  7648. }
  7649. function setCtx(ctx, prop, value) {
  7650. ctx[prop] = fixShadow(ctx, prop, value);
  7651. return ctx[prop];
  7652. }
  7653. /**
  7654. * @param {string} [stroke] If specified, do not check style.textStroke.
  7655. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7656. * @param {number} style
  7657. */
  7658. function getStroke(stroke, lineWidth) {
  7659. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7660. ? null
  7661. // TODO pattern and gradient?
  7662. : (stroke.image || stroke.colorStops)
  7663. ? '#000'
  7664. : stroke;
  7665. }
  7666. function getFill(fill) {
  7667. return (fill == null || fill === 'none')
  7668. ? null
  7669. // TODO pattern and gradient?
  7670. : (fill.image || fill.colorStops)
  7671. ? '#000'
  7672. : fill;
  7673. }
  7674. function parsePercent(value, maxValue) {
  7675. if (typeof value === 'string') {
  7676. if (value.lastIndexOf('%') >= 0) {
  7677. return parseFloat(value) / 100 * maxValue;
  7678. }
  7679. return parseFloat(value);
  7680. }
  7681. return value;
  7682. }
  7683. function getTextXForPadding(x, textAlign, textPadding) {
  7684. return textAlign === 'right'
  7685. ? (x - textPadding[1])
  7686. : textAlign === 'center'
  7687. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7688. : (x + textPadding[3]);
  7689. }
  7690. /**
  7691. * @param {string} text
  7692. * @param {module:zrender/Style} style
  7693. * @return {boolean}
  7694. */
  7695. function needDrawText(text, style) {
  7696. return text != null
  7697. && (text
  7698. || style.textBackgroundColor
  7699. || (style.textBorderWidth && style.textBorderColor)
  7700. || style.textPadding
  7701. );
  7702. }
  7703. /**
  7704. * Mixin for drawing text in a element bounding rect
  7705. * @module zrender/mixin/RectText
  7706. */
  7707. var tmpRect$1 = new BoundingRect();
  7708. var RectText = function () {};
  7709. RectText.prototype = {
  7710. constructor: RectText,
  7711. /**
  7712. * Draw text in a rect with specified position.
  7713. * @param {CanvasRenderingContext2D} ctx
  7714. * @param {Object} rect Displayable rect
  7715. */
  7716. drawRectText: function (ctx, rect) {
  7717. var style = this.style;
  7718. rect = style.textRect || rect;
  7719. // Optimize, avoid normalize every time.
  7720. this.__dirty && normalizeTextStyle(style, true);
  7721. var text = style.text;
  7722. // Convert to string
  7723. text != null && (text += '');
  7724. if (!needDrawText(text, style)) {
  7725. return;
  7726. }
  7727. // FIXME
  7728. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7729. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7730. // text propably break the cache for its host elements.
  7731. ctx.save();
  7732. // Transform rect to view space
  7733. var transform = this.transform;
  7734. if (!style.transformText) {
  7735. if (transform) {
  7736. tmpRect$1.copy(rect);
  7737. tmpRect$1.applyTransform(transform);
  7738. rect = tmpRect$1;
  7739. }
  7740. }
  7741. else {
  7742. this.setTransform(ctx);
  7743. }
  7744. // transformText and textRotation can not be used at the same time.
  7745. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7746. ctx.restore();
  7747. }
  7748. };
  7749. /**
  7750. * Base class of all displayable graphic objects
  7751. * @module zrender/graphic/Displayable
  7752. */
  7753. /**
  7754. * @alias module:zrender/graphic/Displayable
  7755. * @extends module:zrender/Element
  7756. * @extends module:zrender/graphic/mixin/RectText
  7757. */
  7758. function Displayable(opts) {
  7759. opts = opts || {};
  7760. Element.call(this, opts);
  7761. // Extend properties
  7762. for (var name in opts) {
  7763. if (
  7764. opts.hasOwnProperty(name)
  7765. && name !== 'style'
  7766. ) {
  7767. this[name] = opts[name];
  7768. }
  7769. }
  7770. /**
  7771. * @type {module:zrender/graphic/Style}
  7772. */
  7773. this.style = new Style(opts.style, this);
  7774. this._rect = null;
  7775. // Shapes for cascade clipping.
  7776. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  7777. // because it is easy to only using null to check whether clipPaths changed.
  7778. this.__clipPaths = null;
  7779. // FIXME Stateful must be mixined after style is setted
  7780. // Stateful.call(this, opts);
  7781. }
  7782. Displayable.prototype = {
  7783. constructor: Displayable,
  7784. type: 'displayable',
  7785. /**
  7786. * Dirty flag. From which painter will determine if this displayable object needs brush.
  7787. * @name module:zrender/graphic/Displayable#__dirty
  7788. * @type {boolean}
  7789. */
  7790. __dirty: true,
  7791. /**
  7792. * Whether the displayable object is visible. when it is true, the displayable object
  7793. * is not drawn, but the mouse event can still trigger the object.
  7794. * @name module:/zrender/graphic/Displayable#invisible
  7795. * @type {boolean}
  7796. * @default false
  7797. */
  7798. invisible: false,
  7799. /**
  7800. * @name module:/zrender/graphic/Displayable#z
  7801. * @type {number}
  7802. * @default 0
  7803. */
  7804. z: 0,
  7805. /**
  7806. * @name module:/zrender/graphic/Displayable#z
  7807. * @type {number}
  7808. * @default 0
  7809. */
  7810. z2: 0,
  7811. /**
  7812. * The z level determines the displayable object can be drawn in which layer canvas.
  7813. * @name module:/zrender/graphic/Displayable#zlevel
  7814. * @type {number}
  7815. * @default 0
  7816. */
  7817. zlevel: 0,
  7818. /**
  7819. * Whether it can be dragged.
  7820. * @name module:/zrender/graphic/Displayable#draggable
  7821. * @type {boolean}
  7822. * @default false
  7823. */
  7824. draggable: false,
  7825. /**
  7826. * Whether is it dragging.
  7827. * @name module:/zrender/graphic/Displayable#draggable
  7828. * @type {boolean}
  7829. * @default false
  7830. */
  7831. dragging: false,
  7832. /**
  7833. * Whether to respond to mouse events.
  7834. * @name module:/zrender/graphic/Displayable#silent
  7835. * @type {boolean}
  7836. * @default false
  7837. */
  7838. silent: false,
  7839. /**
  7840. * If enable culling
  7841. * @type {boolean}
  7842. * @default false
  7843. */
  7844. culling: false,
  7845. /**
  7846. * Mouse cursor when hovered
  7847. * @name module:/zrender/graphic/Displayable#cursor
  7848. * @type {string}
  7849. */
  7850. cursor: 'pointer',
  7851. /**
  7852. * If hover area is bounding rect
  7853. * @name module:/zrender/graphic/Displayable#rectHover
  7854. * @type {string}
  7855. */
  7856. rectHover: false,
  7857. /**
  7858. * Render the element progressively when the value >= 0,
  7859. * usefull for large data.
  7860. * @type {boolean}
  7861. */
  7862. progressive: false,
  7863. /**
  7864. * @type {boolean}
  7865. */
  7866. incremental: false,
  7867. /**
  7868. * Scale ratio for global scale.
  7869. * @type {boolean}
  7870. */
  7871. globalScaleRatio: 1,
  7872. beforeBrush: function (ctx) {},
  7873. afterBrush: function (ctx) {},
  7874. /**
  7875. * Graphic drawing method.
  7876. * @param {CanvasRenderingContext2D} ctx
  7877. */
  7878. // Interface
  7879. brush: function (ctx, prevEl) {},
  7880. /**
  7881. * Get the minimum bounding box.
  7882. * @return {module:zrender/core/BoundingRect}
  7883. */
  7884. // Interface
  7885. getBoundingRect: function () {},
  7886. /**
  7887. * If displayable element contain coord x, y
  7888. * @param {number} x
  7889. * @param {number} y
  7890. * @return {boolean}
  7891. */
  7892. contain: function (x, y) {
  7893. return this.rectContain(x, y);
  7894. },
  7895. /**
  7896. * @param {Function} cb
  7897. * @param {} context
  7898. */
  7899. traverse: function (cb, context) {
  7900. cb.call(context, this);
  7901. },
  7902. /**
  7903. * If bounding rect of element contain coord x, y
  7904. * @param {number} x
  7905. * @param {number} y
  7906. * @return {boolean}
  7907. */
  7908. rectContain: function (x, y) {
  7909. var coord = this.transformCoordToLocal(x, y);
  7910. var rect = this.getBoundingRect();
  7911. return rect.contain(coord[0], coord[1]);
  7912. },
  7913. /**
  7914. * Mark displayable element dirty and refresh next frame
  7915. */
  7916. dirty: function () {
  7917. this.__dirty = this.__dirtyText = true;
  7918. this._rect = null;
  7919. this.__zr && this.__zr.refresh();
  7920. },
  7921. /**
  7922. * If displayable object binded any event
  7923. * @return {boolean}
  7924. */
  7925. // TODO, events bound by bind
  7926. // isSilent: function () {
  7927. // return !(
  7928. // this.hoverable || this.draggable
  7929. // || this.onmousemove || this.onmouseover || this.onmouseout
  7930. // || this.onmousedown || this.onmouseup || this.onclick
  7931. // || this.ondragenter || this.ondragover || this.ondragleave
  7932. // || this.ondrop
  7933. // );
  7934. // },
  7935. /**
  7936. * Alias for animate('style')
  7937. * @param {boolean} loop
  7938. */
  7939. animateStyle: function (loop) {
  7940. return this.animate('style', loop);
  7941. },
  7942. attrKV: function (key, value) {
  7943. if (key !== 'style') {
  7944. Element.prototype.attrKV.call(this, key, value);
  7945. }
  7946. else {
  7947. this.style.set(value);
  7948. }
  7949. },
  7950. /**
  7951. * @param {Object|string} key
  7952. * @param {*} value
  7953. */
  7954. setStyle: function (key, value) {
  7955. this.style.set(key, value);
  7956. this.dirty(false);
  7957. return this;
  7958. },
  7959. /**
  7960. * Use given style object
  7961. * @param {Object} obj
  7962. */
  7963. useStyle: function (obj) {
  7964. this.style = new Style(obj, this);
  7965. this.dirty(false);
  7966. return this;
  7967. },
  7968. /**
  7969. * The string value of `textPosition` needs to be calculated to a real postion.
  7970. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  7971. * by default. See `contain/text.js#calculateTextPosition` for more details.
  7972. * But some coutom shapes like "pin", "flag" have center that is not exactly
  7973. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  7974. * for those shapes. It will be called if the `style.textPosition` is a string.
  7975. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  7976. * be responsible for creating one.
  7977. * @param {module:zrender/graphic/Style} style
  7978. * @param {Object} rect {x, y, width, height}
  7979. * @return {Obejct} out The same as the input out.
  7980. * {
  7981. * x: number. mandatory.
  7982. * y: number. mandatory.
  7983. * textAlign: string. optional. use style.textAlign by default.
  7984. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  7985. * }
  7986. */
  7987. calculateTextPosition: null
  7988. };
  7989. inherits(Displayable, Element);
  7990. mixin(Displayable, RectText);
  7991. /**
  7992. * @alias zrender/graphic/Image
  7993. * @extends module:zrender/graphic/Displayable
  7994. * @constructor
  7995. * @param {Object} opts
  7996. */
  7997. function ZImage(opts) {
  7998. Displayable.call(this, opts);
  7999. }
  8000. ZImage.prototype = {
  8001. constructor: ZImage,
  8002. type: 'image',
  8003. brush: function (ctx, prevEl) {
  8004. var style = this.style;
  8005. var src = style.image;
  8006. // Must bind each time
  8007. style.bind(ctx, this, prevEl);
  8008. var image = this._image = createOrUpdateImage(
  8009. src,
  8010. this._image,
  8011. this,
  8012. this.onload
  8013. );
  8014. if (!image || !isImageReady(image)) {
  8015. return;
  8016. }
  8017. // 图片已经加载完成
  8018. // if (image.nodeName.toUpperCase() == 'IMG') {
  8019. // if (!image.complete) {
  8020. // return;
  8021. // }
  8022. // }
  8023. // Else is canvas
  8024. var x = style.x || 0;
  8025. var y = style.y || 0;
  8026. var width = style.width;
  8027. var height = style.height;
  8028. var aspect = image.width / image.height;
  8029. if (width == null && height != null) {
  8030. // Keep image/height ratio
  8031. width = height * aspect;
  8032. }
  8033. else if (height == null && width != null) {
  8034. height = width / aspect;
  8035. }
  8036. else if (width == null && height == null) {
  8037. width = image.width;
  8038. height = image.height;
  8039. }
  8040. // 设置transform
  8041. this.setTransform(ctx);
  8042. if (style.sWidth && style.sHeight) {
  8043. var sx = style.sx || 0;
  8044. var sy = style.sy || 0;
  8045. ctx.drawImage(
  8046. image,
  8047. sx, sy, style.sWidth, style.sHeight,
  8048. x, y, width, height
  8049. );
  8050. }
  8051. else if (style.sx && style.sy) {
  8052. var sx = style.sx;
  8053. var sy = style.sy;
  8054. var sWidth = width - sx;
  8055. var sHeight = height - sy;
  8056. ctx.drawImage(
  8057. image,
  8058. sx, sy, sWidth, sHeight,
  8059. x, y, width, height
  8060. );
  8061. }
  8062. else {
  8063. ctx.drawImage(image, x, y, width, height);
  8064. }
  8065. // Draw rect text
  8066. if (style.text != null) {
  8067. // Only restore transform when needs draw text.
  8068. this.restoreTransform(ctx);
  8069. this.drawRectText(ctx, this.getBoundingRect());
  8070. }
  8071. },
  8072. getBoundingRect: function () {
  8073. var style = this.style;
  8074. if (!this._rect) {
  8075. this._rect = new BoundingRect(
  8076. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8077. );
  8078. }
  8079. return this._rect;
  8080. }
  8081. };
  8082. inherits(ZImage, Displayable);
  8083. var HOVER_LAYER_ZLEVEL = 1e5;
  8084. var CANVAS_ZLEVEL = 314159;
  8085. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8086. var INCREMENTAL_INC = 0.001;
  8087. function parseInt10(val) {
  8088. return parseInt(val, 10);
  8089. }
  8090. function isLayerValid(layer) {
  8091. if (!layer) {
  8092. return false;
  8093. }
  8094. if (layer.__builtin__) {
  8095. return true;
  8096. }
  8097. if (typeof (layer.resize) !== 'function'
  8098. || typeof (layer.refresh) !== 'function'
  8099. ) {
  8100. return false;
  8101. }
  8102. return true;
  8103. }
  8104. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8105. var viewRect = new BoundingRect(0, 0, 0, 0);
  8106. function isDisplayableCulled(el, width, height) {
  8107. tmpRect.copy(el.getBoundingRect());
  8108. if (el.transform) {
  8109. tmpRect.applyTransform(el.transform);
  8110. }
  8111. viewRect.width = width;
  8112. viewRect.height = height;
  8113. return !tmpRect.intersect(viewRect);
  8114. }
  8115. function isClipPathChanged(clipPaths, prevClipPaths) {
  8116. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8117. if (clipPaths === prevClipPaths) {
  8118. return false;
  8119. }
  8120. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8121. return true;
  8122. }
  8123. for (var i = 0; i < clipPaths.length; i++) {
  8124. if (clipPaths[i] !== prevClipPaths[i]) {
  8125. return true;
  8126. }
  8127. }
  8128. return false;
  8129. }
  8130. function doClip(clipPaths, ctx) {
  8131. for (var i = 0; i < clipPaths.length; i++) {
  8132. var clipPath = clipPaths[i];
  8133. clipPath.setTransform(ctx);
  8134. ctx.beginPath();
  8135. clipPath.buildPath(ctx, clipPath.shape);
  8136. ctx.clip();
  8137. // Transform back
  8138. clipPath.restoreTransform(ctx);
  8139. }
  8140. }
  8141. function createRoot(width, height) {
  8142. var domRoot = document.createElement('div');
  8143. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8144. domRoot.style.cssText = [
  8145. 'position:relative',
  8146. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8147. // dom does not act as expected) when some of the parent dom has
  8148. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8149. // the canvas is not at the top part of the page.
  8150. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8151. // this `overflow:hidden` to avoid the bug.
  8152. // 'overflow:hidden',
  8153. 'width:' + width + 'px',
  8154. 'height:' + height + 'px',
  8155. 'padding:0',
  8156. 'margin:0',
  8157. 'border-width:0'
  8158. ].join(';') + ';';
  8159. return domRoot;
  8160. }
  8161. /**
  8162. * @alias module:zrender/Painter
  8163. * @constructor
  8164. * @param {HTMLElement} root 绘图容器
  8165. * @param {module:zrender/Storage} storage
  8166. * @param {Object} opts
  8167. */
  8168. var Painter = function (root, storage, opts) {
  8169. this.type = 'canvas';
  8170. // In node environment using node-canvas
  8171. var singleCanvas = !root.nodeName // In node ?
  8172. || root.nodeName.toUpperCase() === 'CANVAS';
  8173. this._opts = opts = extend({}, opts || {});
  8174. /**
  8175. * @type {number}
  8176. */
  8177. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8178. /**
  8179. * @type {boolean}
  8180. * @private
  8181. */
  8182. this._singleCanvas = singleCanvas;
  8183. /**
  8184. * 绘图容器
  8185. * @type {HTMLElement}
  8186. */
  8187. this.root = root;
  8188. var rootStyle = root.style;
  8189. if (rootStyle) {
  8190. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8191. rootStyle['-webkit-user-select'] =
  8192. rootStyle['user-select'] =
  8193. rootStyle['-webkit-touch-callout'] = 'none';
  8194. root.innerHTML = '';
  8195. }
  8196. /**
  8197. * @type {module:zrender/Storage}
  8198. */
  8199. this.storage = storage;
  8200. /**
  8201. * @type {Array.<number>}
  8202. * @private
  8203. */
  8204. var zlevelList = this._zlevelList = [];
  8205. /**
  8206. * @type {Object.<string, module:zrender/Layer>}
  8207. * @private
  8208. */
  8209. var layers = this._layers = {};
  8210. /**
  8211. * @type {Object.<string, Object>}
  8212. * @private
  8213. */
  8214. this._layerConfig = {};
  8215. /**
  8216. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8217. */
  8218. this._needsManuallyCompositing = false;
  8219. if (!singleCanvas) {
  8220. this._width = this._getSize(0);
  8221. this._height = this._getSize(1);
  8222. var domRoot = this._domRoot = createRoot(
  8223. this._width, this._height
  8224. );
  8225. root.appendChild(domRoot);
  8226. }
  8227. else {
  8228. var width = root.width;
  8229. var height = root.height;
  8230. if (opts.width != null) {
  8231. width = opts.width;
  8232. }
  8233. if (opts.height != null) {
  8234. height = opts.height;
  8235. }
  8236. this.dpr = opts.devicePixelRatio || 1;
  8237. // Use canvas width and height directly
  8238. root.width = width * this.dpr;
  8239. root.height = height * this.dpr;
  8240. this._width = width;
  8241. this._height = height;
  8242. // Create layer if only one given canvas
  8243. // Device can be specified to create a high dpi image.
  8244. var mainLayer = new Layer(root, this, this.dpr);
  8245. mainLayer.__builtin__ = true;
  8246. mainLayer.initContext();
  8247. // FIXME Use canvas width and height
  8248. // mainLayer.resize(width, height);
  8249. layers[CANVAS_ZLEVEL] = mainLayer;
  8250. mainLayer.zlevel = CANVAS_ZLEVEL;
  8251. // Not use common zlevel.
  8252. zlevelList.push(CANVAS_ZLEVEL);
  8253. this._domRoot = root;
  8254. }
  8255. /**
  8256. * @type {module:zrender/Layer}
  8257. * @private
  8258. */
  8259. this._hoverlayer = null;
  8260. this._hoverElements = [];
  8261. };
  8262. Painter.prototype = {
  8263. constructor: Painter,
  8264. getType: function () {
  8265. return 'canvas';
  8266. },
  8267. /**
  8268. * If painter use a single canvas
  8269. * @return {boolean}
  8270. */
  8271. isSingleCanvas: function () {
  8272. return this._singleCanvas;
  8273. },
  8274. /**
  8275. * @return {HTMLDivElement}
  8276. */
  8277. getViewportRoot: function () {
  8278. return this._domRoot;
  8279. },
  8280. getViewportRootOffset: function () {
  8281. var viewportRoot = this.getViewportRoot();
  8282. if (viewportRoot) {
  8283. return {
  8284. offsetLeft: viewportRoot.offsetLeft || 0,
  8285. offsetTop: viewportRoot.offsetTop || 0
  8286. };
  8287. }
  8288. },
  8289. /**
  8290. * 刷新
  8291. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8292. */
  8293. refresh: function (paintAll) {
  8294. var list = this.storage.getDisplayList(true);
  8295. var zlevelList = this._zlevelList;
  8296. this._redrawId = Math.random();
  8297. this._paintList(list, paintAll, this._redrawId);
  8298. // Paint custum layers
  8299. for (var i = 0; i < zlevelList.length; i++) {
  8300. var z = zlevelList[i];
  8301. var layer = this._layers[z];
  8302. if (!layer.__builtin__ && layer.refresh) {
  8303. var clearColor = i === 0 ? this._backgroundColor : null;
  8304. layer.refresh(clearColor);
  8305. }
  8306. }
  8307. this.refreshHover();
  8308. return this;
  8309. },
  8310. addHover: function (el, hoverStyle) {
  8311. if (el.__hoverMir) {
  8312. return;
  8313. }
  8314. var elMirror = new el.constructor({
  8315. style: el.style,
  8316. shape: el.shape,
  8317. z: el.z,
  8318. z2: el.z2,
  8319. silent: el.silent
  8320. });
  8321. elMirror.__from = el;
  8322. el.__hoverMir = elMirror;
  8323. hoverStyle && elMirror.setStyle(hoverStyle);
  8324. this._hoverElements.push(elMirror);
  8325. return elMirror;
  8326. },
  8327. removeHover: function (el) {
  8328. var elMirror = el.__hoverMir;
  8329. var hoverElements = this._hoverElements;
  8330. var idx = indexOf(hoverElements, elMirror);
  8331. if (idx >= 0) {
  8332. hoverElements.splice(idx, 1);
  8333. }
  8334. el.__hoverMir = null;
  8335. },
  8336. clearHover: function (el) {
  8337. var hoverElements = this._hoverElements;
  8338. for (var i = 0; i < hoverElements.length; i++) {
  8339. var from = hoverElements[i].__from;
  8340. if (from) {
  8341. from.__hoverMir = null;
  8342. }
  8343. }
  8344. hoverElements.length = 0;
  8345. },
  8346. refreshHover: function () {
  8347. var hoverElements = this._hoverElements;
  8348. var len = hoverElements.length;
  8349. var hoverLayer = this._hoverlayer;
  8350. hoverLayer && hoverLayer.clear();
  8351. if (!len) {
  8352. return;
  8353. }
  8354. sort(hoverElements, this.storage.displayableSortFunc);
  8355. // Use a extream large zlevel
  8356. // FIXME?
  8357. if (!hoverLayer) {
  8358. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8359. }
  8360. var scope = {};
  8361. hoverLayer.ctx.save();
  8362. for (var i = 0; i < len;) {
  8363. var el = hoverElements[i];
  8364. var originalEl = el.__from;
  8365. // Original el is removed
  8366. // PENDING
  8367. if (!(originalEl && originalEl.__zr)) {
  8368. hoverElements.splice(i, 1);
  8369. originalEl.__hoverMir = null;
  8370. len--;
  8371. continue;
  8372. }
  8373. i++;
  8374. // Use transform
  8375. // FIXME style and shape ?
  8376. if (!originalEl.invisible) {
  8377. el.transform = originalEl.transform;
  8378. el.invTransform = originalEl.invTransform;
  8379. el.__clipPaths = originalEl.__clipPaths;
  8380. // el.
  8381. this._doPaintEl(el, hoverLayer, true, scope);
  8382. }
  8383. }
  8384. hoverLayer.ctx.restore();
  8385. },
  8386. getHoverLayer: function () {
  8387. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8388. },
  8389. _paintList: function (list, paintAll, redrawId) {
  8390. if (this._redrawId !== redrawId) {
  8391. return;
  8392. }
  8393. paintAll = paintAll || false;
  8394. this._updateLayerStatus(list);
  8395. var finished = this._doPaintList(list, paintAll);
  8396. if (this._needsManuallyCompositing) {
  8397. this._compositeManually();
  8398. }
  8399. if (!finished) {
  8400. var self = this;
  8401. requestAnimationFrame(function () {
  8402. self._paintList(list, paintAll, redrawId);
  8403. });
  8404. }
  8405. },
  8406. _compositeManually: function () {
  8407. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8408. var width = this._domRoot.width;
  8409. var height = this._domRoot.height;
  8410. ctx.clearRect(0, 0, width, height);
  8411. // PENDING, If only builtin layer?
  8412. this.eachBuiltinLayer(function (layer) {
  8413. if (layer.virtual) {
  8414. ctx.drawImage(layer.dom, 0, 0, width, height);
  8415. }
  8416. });
  8417. },
  8418. _doPaintList: function (list, paintAll) {
  8419. var layerList = [];
  8420. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8421. var zlevel = this._zlevelList[zi];
  8422. var layer = this._layers[zlevel];
  8423. if (layer.__builtin__
  8424. && layer !== this._hoverlayer
  8425. && (layer.__dirty || paintAll)
  8426. ) {
  8427. layerList.push(layer);
  8428. }
  8429. }
  8430. var finished = true;
  8431. for (var k = 0; k < layerList.length; k++) {
  8432. var layer = layerList[k];
  8433. var ctx = layer.ctx;
  8434. var scope = {};
  8435. ctx.save();
  8436. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8437. var useTimer = !paintAll && layer.incremental && Date.now;
  8438. var startTime = useTimer && Date.now();
  8439. var clearColor = layer.zlevel === this._zlevelList[0]
  8440. ? this._backgroundColor : null;
  8441. // All elements in this layer are cleared.
  8442. if (layer.__startIndex === layer.__endIndex) {
  8443. layer.clear(false, clearColor);
  8444. }
  8445. else if (start === layer.__startIndex) {
  8446. var firstEl = list[start];
  8447. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8448. layer.clear(false, clearColor);
  8449. }
  8450. }
  8451. if (start === -1) {
  8452. console.error('For some unknown reason. drawIndex is -1');
  8453. start = layer.__startIndex;
  8454. }
  8455. for (var i = start; i < layer.__endIndex; i++) {
  8456. var el = list[i];
  8457. this._doPaintEl(el, layer, paintAll, scope);
  8458. el.__dirty = el.__dirtyText = false;
  8459. if (useTimer) {
  8460. // Date.now can be executed in 13,025,305 ops/second.
  8461. var dTime = Date.now() - startTime;
  8462. // Give 15 millisecond to draw.
  8463. // The rest elements will be drawn in the next frame.
  8464. if (dTime > 15) {
  8465. break;
  8466. }
  8467. }
  8468. }
  8469. layer.__drawIndex = i;
  8470. if (layer.__drawIndex < layer.__endIndex) {
  8471. finished = false;
  8472. }
  8473. if (scope.prevElClipPaths) {
  8474. // Needs restore the state. If last drawn element is in the clipping area.
  8475. ctx.restore();
  8476. }
  8477. ctx.restore();
  8478. }
  8479. if (env$1.wxa) {
  8480. // Flush for weixin application
  8481. each$1(this._layers, function (layer) {
  8482. if (layer && layer.ctx && layer.ctx.draw) {
  8483. layer.ctx.draw();
  8484. }
  8485. });
  8486. }
  8487. return finished;
  8488. },
  8489. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8490. var ctx = currentLayer.ctx;
  8491. var m = el.transform;
  8492. if (
  8493. (currentLayer.__dirty || forcePaint)
  8494. // Ignore invisible element
  8495. && !el.invisible
  8496. // Ignore transparent element
  8497. && el.style.opacity !== 0
  8498. // Ignore scale 0 element, in some environment like node-canvas
  8499. // Draw a scale 0 element can cause all following draw wrong
  8500. // And setTransform with scale 0 will cause set back transform failed.
  8501. && !(m && !m[0] && !m[3])
  8502. // Ignore culled element
  8503. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8504. ) {
  8505. var clipPaths = el.__clipPaths;
  8506. var prevElClipPaths = scope.prevElClipPaths;
  8507. // Optimize when clipping on group with several elements
  8508. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8509. // If has previous clipping state, restore from it
  8510. if (prevElClipPaths) {
  8511. ctx.restore();
  8512. scope.prevElClipPaths = null;
  8513. // Reset prevEl since context has been restored
  8514. scope.prevEl = null;
  8515. }
  8516. // New clipping state
  8517. if (clipPaths) {
  8518. ctx.save();
  8519. doClip(clipPaths, ctx);
  8520. scope.prevElClipPaths = clipPaths;
  8521. }
  8522. }
  8523. el.beforeBrush && el.beforeBrush(ctx);
  8524. el.brush(ctx, scope.prevEl || null);
  8525. scope.prevEl = el;
  8526. el.afterBrush && el.afterBrush(ctx);
  8527. }
  8528. },
  8529. /**
  8530. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8531. * @param {number} zlevel
  8532. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8533. * @return {module:zrender/Layer}
  8534. */
  8535. getLayer: function (zlevel, virtual) {
  8536. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8537. zlevel = CANVAS_ZLEVEL;
  8538. }
  8539. var layer = this._layers[zlevel];
  8540. if (!layer) {
  8541. // Create a new layer
  8542. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8543. layer.zlevel = zlevel;
  8544. layer.__builtin__ = true;
  8545. if (this._layerConfig[zlevel]) {
  8546. merge(layer, this._layerConfig[zlevel], true);
  8547. }
  8548. if (virtual) {
  8549. layer.virtual = virtual;
  8550. }
  8551. this.insertLayer(zlevel, layer);
  8552. // Context is created after dom inserted to document
  8553. // Or excanvas will get 0px clientWidth and clientHeight
  8554. layer.initContext();
  8555. }
  8556. return layer;
  8557. },
  8558. insertLayer: function (zlevel, layer) {
  8559. var layersMap = this._layers;
  8560. var zlevelList = this._zlevelList;
  8561. var len = zlevelList.length;
  8562. var prevLayer = null;
  8563. var i = -1;
  8564. var domRoot = this._domRoot;
  8565. if (layersMap[zlevel]) {
  8566. logError$1('ZLevel ' + zlevel + ' has been used already');
  8567. return;
  8568. }
  8569. // Check if is a valid layer
  8570. if (!isLayerValid(layer)) {
  8571. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8572. return;
  8573. }
  8574. if (len > 0 && zlevel > zlevelList[0]) {
  8575. for (i = 0; i < len - 1; i++) {
  8576. if (
  8577. zlevelList[i] < zlevel
  8578. && zlevelList[i + 1] > zlevel
  8579. ) {
  8580. break;
  8581. }
  8582. }
  8583. prevLayer = layersMap[zlevelList[i]];
  8584. }
  8585. zlevelList.splice(i + 1, 0, zlevel);
  8586. layersMap[zlevel] = layer;
  8587. // Vitual layer will not directly show on the screen.
  8588. // (It can be a WebGL layer and assigned to a ZImage element)
  8589. // But it still under management of zrender.
  8590. if (!layer.virtual) {
  8591. if (prevLayer) {
  8592. var prevDom = prevLayer.dom;
  8593. if (prevDom.nextSibling) {
  8594. domRoot.insertBefore(
  8595. layer.dom,
  8596. prevDom.nextSibling
  8597. );
  8598. }
  8599. else {
  8600. domRoot.appendChild(layer.dom);
  8601. }
  8602. }
  8603. else {
  8604. if (domRoot.firstChild) {
  8605. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8606. }
  8607. else {
  8608. domRoot.appendChild(layer.dom);
  8609. }
  8610. }
  8611. }
  8612. },
  8613. // Iterate each layer
  8614. eachLayer: function (cb, context) {
  8615. var zlevelList = this._zlevelList;
  8616. var z;
  8617. var i;
  8618. for (i = 0; i < zlevelList.length; i++) {
  8619. z = zlevelList[i];
  8620. cb.call(context, this._layers[z], z);
  8621. }
  8622. },
  8623. // Iterate each buildin layer
  8624. eachBuiltinLayer: function (cb, context) {
  8625. var zlevelList = this._zlevelList;
  8626. var layer;
  8627. var z;
  8628. var i;
  8629. for (i = 0; i < zlevelList.length; i++) {
  8630. z = zlevelList[i];
  8631. layer = this._layers[z];
  8632. if (layer.__builtin__) {
  8633. cb.call(context, layer, z);
  8634. }
  8635. }
  8636. },
  8637. // Iterate each other layer except buildin layer
  8638. eachOtherLayer: function (cb, context) {
  8639. var zlevelList = this._zlevelList;
  8640. var layer;
  8641. var z;
  8642. var i;
  8643. for (i = 0; i < zlevelList.length; i++) {
  8644. z = zlevelList[i];
  8645. layer = this._layers[z];
  8646. if (!layer.__builtin__) {
  8647. cb.call(context, layer, z);
  8648. }
  8649. }
  8650. },
  8651. /**
  8652. * 获取所有已创建的层
  8653. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8654. */
  8655. getLayers: function () {
  8656. return this._layers;
  8657. },
  8658. _updateLayerStatus: function (list) {
  8659. this.eachBuiltinLayer(function (layer, z) {
  8660. layer.__dirty = layer.__used = false;
  8661. });
  8662. function updatePrevLayer(idx) {
  8663. if (prevLayer) {
  8664. if (prevLayer.__endIndex !== idx) {
  8665. prevLayer.__dirty = true;
  8666. }
  8667. prevLayer.__endIndex = idx;
  8668. }
  8669. }
  8670. if (this._singleCanvas) {
  8671. for (var i = 1; i < list.length; i++) {
  8672. var el = list[i];
  8673. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8674. this._needsManuallyCompositing = true;
  8675. break;
  8676. }
  8677. }
  8678. }
  8679. var prevLayer = null;
  8680. var incrementalLayerCount = 0;
  8681. for (var i = 0; i < list.length; i++) {
  8682. var el = list[i];
  8683. var zlevel = el.zlevel;
  8684. var layer;
  8685. // PENDING If change one incremental element style ?
  8686. // TODO Where there are non-incremental elements between incremental elements.
  8687. if (el.incremental) {
  8688. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8689. layer.incremental = true;
  8690. incrementalLayerCount = 1;
  8691. }
  8692. else {
  8693. layer = this.getLayer(
  8694. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8695. this._needsManuallyCompositing
  8696. );
  8697. }
  8698. if (!layer.__builtin__) {
  8699. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8700. }
  8701. if (layer !== prevLayer) {
  8702. layer.__used = true;
  8703. if (layer.__startIndex !== i) {
  8704. layer.__dirty = true;
  8705. }
  8706. layer.__startIndex = i;
  8707. if (!layer.incremental) {
  8708. layer.__drawIndex = i;
  8709. }
  8710. else {
  8711. // Mark layer draw index needs to update.
  8712. layer.__drawIndex = -1;
  8713. }
  8714. updatePrevLayer(i);
  8715. prevLayer = layer;
  8716. }
  8717. if (el.__dirty) {
  8718. layer.__dirty = true;
  8719. if (layer.incremental && layer.__drawIndex < 0) {
  8720. // Start draw from the first dirty element.
  8721. layer.__drawIndex = i;
  8722. }
  8723. }
  8724. }
  8725. updatePrevLayer(i);
  8726. this.eachBuiltinLayer(function (layer, z) {
  8727. // Used in last frame but not in this frame. Needs clear
  8728. if (!layer.__used && layer.getElementCount() > 0) {
  8729. layer.__dirty = true;
  8730. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8731. }
  8732. // For incremental layer. In case start index changed and no elements are dirty.
  8733. if (layer.__dirty && layer.__drawIndex < 0) {
  8734. layer.__drawIndex = layer.__startIndex;
  8735. }
  8736. });
  8737. },
  8738. /**
  8739. * 清除hover层外所有内容
  8740. */
  8741. clear: function () {
  8742. this.eachBuiltinLayer(this._clearLayer);
  8743. return this;
  8744. },
  8745. _clearLayer: function (layer) {
  8746. layer.clear();
  8747. },
  8748. setBackgroundColor: function (backgroundColor) {
  8749. this._backgroundColor = backgroundColor;
  8750. },
  8751. /**
  8752. * 修改指定zlevel的绘制参数
  8753. *
  8754. * @param {string} zlevel
  8755. * @param {Object} config 配置对象
  8756. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8757. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8758. * @param {number} [config.lastFrameAlpha=0.7]
  8759. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8760. */
  8761. configLayer: function (zlevel, config) {
  8762. if (config) {
  8763. var layerConfig = this._layerConfig;
  8764. if (!layerConfig[zlevel]) {
  8765. layerConfig[zlevel] = config;
  8766. }
  8767. else {
  8768. merge(layerConfig[zlevel], config, true);
  8769. }
  8770. for (var i = 0; i < this._zlevelList.length; i++) {
  8771. var _zlevel = this._zlevelList[i];
  8772. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8773. var layer = this._layers[_zlevel];
  8774. merge(layer, layerConfig[zlevel], true);
  8775. }
  8776. }
  8777. }
  8778. },
  8779. /**
  8780. * 删除指定层
  8781. * @param {number} zlevel 层所在的zlevel
  8782. */
  8783. delLayer: function (zlevel) {
  8784. var layers = this._layers;
  8785. var zlevelList = this._zlevelList;
  8786. var layer = layers[zlevel];
  8787. if (!layer) {
  8788. return;
  8789. }
  8790. layer.dom.parentNode.removeChild(layer.dom);
  8791. delete layers[zlevel];
  8792. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8793. },
  8794. /**
  8795. * 区域大小变化后重绘
  8796. */
  8797. resize: function (width, height) {
  8798. if (!this._domRoot.style) { // Maybe in node or worker
  8799. if (width == null || height == null) {
  8800. return;
  8801. }
  8802. this._width = width;
  8803. this._height = height;
  8804. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8805. }
  8806. else {
  8807. var domRoot = this._domRoot;
  8808. // FIXME Why ?
  8809. domRoot.style.display = 'none';
  8810. // Save input w/h
  8811. var opts = this._opts;
  8812. width != null && (opts.width = width);
  8813. height != null && (opts.height = height);
  8814. width = this._getSize(0);
  8815. height = this._getSize(1);
  8816. domRoot.style.display = '';
  8817. // 优化没有实际改变的resize
  8818. if (this._width !== width || height !== this._height) {
  8819. domRoot.style.width = width + 'px';
  8820. domRoot.style.height = height + 'px';
  8821. for (var id in this._layers) {
  8822. if (this._layers.hasOwnProperty(id)) {
  8823. this._layers[id].resize(width, height);
  8824. }
  8825. }
  8826. each$1(this._progressiveLayers, function (layer) {
  8827. layer.resize(width, height);
  8828. });
  8829. this.refresh(true);
  8830. }
  8831. this._width = width;
  8832. this._height = height;
  8833. }
  8834. return this;
  8835. },
  8836. /**
  8837. * 清除单独的一个层
  8838. * @param {number} zlevel
  8839. */
  8840. clearLayer: function (zlevel) {
  8841. var layer = this._layers[zlevel];
  8842. if (layer) {
  8843. layer.clear();
  8844. }
  8845. },
  8846. /**
  8847. * 释放
  8848. */
  8849. dispose: function () {
  8850. this.root.innerHTML = '';
  8851. this.root =
  8852. this.storage =
  8853. this._domRoot =
  8854. this._layers = null;
  8855. },
  8856. /**
  8857. * Get canvas which has all thing rendered
  8858. * @param {Object} opts
  8859. * @param {string} [opts.backgroundColor]
  8860. * @param {number} [opts.pixelRatio]
  8861. */
  8862. getRenderedCanvas: function (opts) {
  8863. opts = opts || {};
  8864. if (this._singleCanvas && !this._compositeManually) {
  8865. return this._layers[CANVAS_ZLEVEL].dom;
  8866. }
  8867. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8868. imageLayer.initContext();
  8869. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8870. if (opts.pixelRatio <= this.dpr) {
  8871. this.refresh();
  8872. var width = imageLayer.dom.width;
  8873. var height = imageLayer.dom.height;
  8874. var ctx = imageLayer.ctx;
  8875. this.eachLayer(function (layer) {
  8876. if (layer.__builtin__) {
  8877. ctx.drawImage(layer.dom, 0, 0, width, height);
  8878. }
  8879. else if (layer.renderToCanvas) {
  8880. imageLayer.ctx.save();
  8881. layer.renderToCanvas(imageLayer.ctx);
  8882. imageLayer.ctx.restore();
  8883. }
  8884. });
  8885. }
  8886. else {
  8887. // PENDING, echarts-gl and incremental rendering.
  8888. var scope = {};
  8889. var displayList = this.storage.getDisplayList(true);
  8890. for (var i = 0; i < displayList.length; i++) {
  8891. var el = displayList[i];
  8892. this._doPaintEl(el, imageLayer, true, scope);
  8893. }
  8894. }
  8895. return imageLayer.dom;
  8896. },
  8897. /**
  8898. * 获取绘图区域宽度
  8899. */
  8900. getWidth: function () {
  8901. return this._width;
  8902. },
  8903. /**
  8904. * 获取绘图区域高度
  8905. */
  8906. getHeight: function () {
  8907. return this._height;
  8908. },
  8909. _getSize: function (whIdx) {
  8910. var opts = this._opts;
  8911. var wh = ['width', 'height'][whIdx];
  8912. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8913. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8914. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8915. if (opts[wh] != null && opts[wh] !== 'auto') {
  8916. return parseFloat(opts[wh]);
  8917. }
  8918. var root = this.root;
  8919. // IE8 does not support getComputedStyle, but it use VML.
  8920. var stl = document.defaultView.getComputedStyle(root);
  8921. return (
  8922. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8923. - (parseInt10(stl[plt]) || 0)
  8924. - (parseInt10(stl[prb]) || 0)
  8925. ) | 0;
  8926. },
  8927. pathToImage: function (path, dpr) {
  8928. dpr = dpr || this.dpr;
  8929. var canvas = document.createElement('canvas');
  8930. var ctx = canvas.getContext('2d');
  8931. var rect = path.getBoundingRect();
  8932. var style = path.style;
  8933. var shadowBlurSize = style.shadowBlur * dpr;
  8934. var shadowOffsetX = style.shadowOffsetX * dpr;
  8935. var shadowOffsetY = style.shadowOffsetY * dpr;
  8936. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8937. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8938. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8939. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8940. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8941. var width = rect.width + leftMargin + rightMargin;
  8942. var height = rect.height + topMargin + bottomMargin;
  8943. canvas.width = width * dpr;
  8944. canvas.height = height * dpr;
  8945. ctx.scale(dpr, dpr);
  8946. ctx.clearRect(0, 0, width, height);
  8947. ctx.dpr = dpr;
  8948. var pathTransform = {
  8949. position: path.position,
  8950. rotation: path.rotation,
  8951. scale: path.scale
  8952. };
  8953. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8954. path.rotation = 0;
  8955. path.scale = [1, 1];
  8956. path.updateTransform();
  8957. if (path) {
  8958. path.brush(ctx);
  8959. }
  8960. var ImageShape = ZImage;
  8961. var imgShape = new ImageShape({
  8962. style: {
  8963. x: 0,
  8964. y: 0,
  8965. image: canvas
  8966. }
  8967. });
  8968. if (pathTransform.position != null) {
  8969. imgShape.position = path.position = pathTransform.position;
  8970. }
  8971. if (pathTransform.rotation != null) {
  8972. imgShape.rotation = path.rotation = pathTransform.rotation;
  8973. }
  8974. if (pathTransform.scale != null) {
  8975. imgShape.scale = path.scale = pathTransform.scale;
  8976. }
  8977. return imgShape;
  8978. }
  8979. };
  8980. /**
  8981. * 动画主类, 调度和管理所有动画控制器
  8982. *
  8983. * @module zrender/animation/Animation
  8984. * @author pissang(https://github.com/pissang)
  8985. */
  8986. // TODO Additive animation
  8987. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8988. // https://developer.apple.com/videos/wwdc2014/#236
  8989. /**
  8990. * @typedef {Object} IZRenderStage
  8991. * @property {Function} update
  8992. */
  8993. /**
  8994. * @alias module:zrender/animation/Animation
  8995. * @constructor
  8996. * @param {Object} [options]
  8997. * @param {Function} [options.onframe]
  8998. * @param {IZRenderStage} [options.stage]
  8999. * @example
  9000. * var animation = new Animation();
  9001. * var obj = {
  9002. * x: 100,
  9003. * y: 100
  9004. * };
  9005. * animation.animate(node.position)
  9006. * .when(1000, {
  9007. * x: 500,
  9008. * y: 500
  9009. * })
  9010. * .when(2000, {
  9011. * x: 100,
  9012. * y: 100
  9013. * })
  9014. * .start('spline');
  9015. */
  9016. var Animation = function (options) {
  9017. options = options || {};
  9018. this.stage = options.stage || {};
  9019. this.onframe = options.onframe || function () {};
  9020. // private properties
  9021. this._clips = [];
  9022. this._running = false;
  9023. this._time;
  9024. this._pausedTime;
  9025. this._pauseStart;
  9026. this._paused = false;
  9027. Eventful.call(this);
  9028. };
  9029. Animation.prototype = {
  9030. constructor: Animation,
  9031. /**
  9032. * 添加 clip
  9033. * @param {module:zrender/animation/Clip} clip
  9034. */
  9035. addClip: function (clip) {
  9036. this._clips.push(clip);
  9037. },
  9038. /**
  9039. * 添加 animator
  9040. * @param {module:zrender/animation/Animator} animator
  9041. */
  9042. addAnimator: function (animator) {
  9043. animator.animation = this;
  9044. var clips = animator.getClips();
  9045. for (var i = 0; i < clips.length; i++) {
  9046. this.addClip(clips[i]);
  9047. }
  9048. },
  9049. /**
  9050. * 删除动画片段
  9051. * @param {module:zrender/animation/Clip} clip
  9052. */
  9053. removeClip: function (clip) {
  9054. var idx = indexOf(this._clips, clip);
  9055. if (idx >= 0) {
  9056. this._clips.splice(idx, 1);
  9057. }
  9058. },
  9059. /**
  9060. * 删除动画片段
  9061. * @param {module:zrender/animation/Animator} animator
  9062. */
  9063. removeAnimator: function (animator) {
  9064. var clips = animator.getClips();
  9065. for (var i = 0; i < clips.length; i++) {
  9066. this.removeClip(clips[i]);
  9067. }
  9068. animator.animation = null;
  9069. },
  9070. _update: function () {
  9071. var time = new Date().getTime() - this._pausedTime;
  9072. var delta = time - this._time;
  9073. var clips = this._clips;
  9074. var len = clips.length;
  9075. var deferredEvents = [];
  9076. var deferredClips = [];
  9077. for (var i = 0; i < len; i++) {
  9078. var clip = clips[i];
  9079. var e = clip.step(time, delta);
  9080. // Throw out the events need to be called after
  9081. // stage.update, like destroy
  9082. if (e) {
  9083. deferredEvents.push(e);
  9084. deferredClips.push(clip);
  9085. }
  9086. }
  9087. // Remove the finished clip
  9088. for (var i = 0; i < len;) {
  9089. if (clips[i]._needsRemove) {
  9090. clips[i] = clips[len - 1];
  9091. clips.pop();
  9092. len--;
  9093. }
  9094. else {
  9095. i++;
  9096. }
  9097. }
  9098. len = deferredEvents.length;
  9099. for (var i = 0; i < len; i++) {
  9100. deferredClips[i].fire(deferredEvents[i]);
  9101. }
  9102. this._time = time;
  9103. this.onframe(delta);
  9104. // 'frame' should be triggered before stage, because upper application
  9105. // depends on the sequence (e.g., echarts-stream and finish
  9106. // event judge)
  9107. this.trigger('frame', delta);
  9108. if (this.stage.update) {
  9109. this.stage.update();
  9110. }
  9111. },
  9112. _startLoop: function () {
  9113. var self = this;
  9114. this._running = true;
  9115. function step() {
  9116. if (self._running) {
  9117. requestAnimationFrame(step);
  9118. !self._paused && self._update();
  9119. }
  9120. }
  9121. requestAnimationFrame(step);
  9122. },
  9123. /**
  9124. * Start animation.
  9125. */
  9126. start: function () {
  9127. this._time = new Date().getTime();
  9128. this._pausedTime = 0;
  9129. this._startLoop();
  9130. },
  9131. /**
  9132. * Stop animation.
  9133. */
  9134. stop: function () {
  9135. this._running = false;
  9136. },
  9137. /**
  9138. * Pause animation.
  9139. */
  9140. pause: function () {
  9141. if (!this._paused) {
  9142. this._pauseStart = new Date().getTime();
  9143. this._paused = true;
  9144. }
  9145. },
  9146. /**
  9147. * Resume animation.
  9148. */
  9149. resume: function () {
  9150. if (this._paused) {
  9151. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9152. this._paused = false;
  9153. }
  9154. },
  9155. /**
  9156. * Clear animation.
  9157. */
  9158. clear: function () {
  9159. this._clips = [];
  9160. },
  9161. /**
  9162. * Whether animation finished.
  9163. */
  9164. isFinished: function () {
  9165. return !this._clips.length;
  9166. },
  9167. /**
  9168. * Creat animator for a target, whose props can be animated.
  9169. *
  9170. * @param {Object} target
  9171. * @param {Object} options
  9172. * @param {boolean} [options.loop=false] Whether loop animation.
  9173. * @param {Function} [options.getter=null] Get value from target.
  9174. * @param {Function} [options.setter=null] Set value to target.
  9175. * @return {module:zrender/animation/Animation~Animator}
  9176. */
  9177. // TODO Gap
  9178. animate: function (target, options) {
  9179. options = options || {};
  9180. var animator = new Animator(
  9181. target,
  9182. options.loop,
  9183. options.getter,
  9184. options.setter
  9185. );
  9186. this.addAnimator(animator);
  9187. return animator;
  9188. }
  9189. };
  9190. mixin(Animation, Eventful);
  9191. /* global document */
  9192. var TOUCH_CLICK_DELAY = 300;
  9193. var globalEventSupported = env$1.domSupported;
  9194. var localNativeListenerNames = (function () {
  9195. var mouseHandlerNames = [
  9196. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9197. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9198. ];
  9199. var touchHandlerNames = [
  9200. 'touchstart', 'touchend', 'touchmove'
  9201. ];
  9202. var pointerEventNameMap = {
  9203. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9204. };
  9205. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9206. var nm = name.replace('mouse', 'pointer');
  9207. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9208. });
  9209. return {
  9210. mouse: mouseHandlerNames,
  9211. touch: touchHandlerNames,
  9212. pointer: pointerHandlerNames
  9213. };
  9214. })();
  9215. var globalNativeListenerNames = {
  9216. mouse: ['mousemove', 'mouseup'],
  9217. pointer: ['pointermove', 'pointerup']
  9218. };
  9219. function eventNameFix(name) {
  9220. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9221. }
  9222. function isPointerFromTouch(event) {
  9223. var pointerType = event.pointerType;
  9224. return pointerType === 'pen' || pointerType === 'touch';
  9225. }
  9226. // function useMSGuesture(handlerProxy, event) {
  9227. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9228. // }
  9229. // function onMSGestureChange(proxy, event) {
  9230. // if (event.translationX || event.translationY) {
  9231. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9232. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9233. // }
  9234. // if (event.scale !== 1) {
  9235. // event.pinchX = event.offsetX;
  9236. // event.pinchY = event.offsetY;
  9237. // event.pinchScale = event.scale;
  9238. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9239. // }
  9240. // }
  9241. /**
  9242. * Prevent mouse event from being dispatched after Touch Events action
  9243. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9244. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9245. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9246. * Result: Blocking Mouse Events for 700ms.
  9247. *
  9248. * @param {DOMHandlerScope} scope
  9249. */
  9250. function setTouchTimer(scope) {
  9251. scope.touching = true;
  9252. if (scope.touchTimer != null) {
  9253. clearTimeout(scope.touchTimer);
  9254. scope.touchTimer = null;
  9255. }
  9256. scope.touchTimer = setTimeout(function () {
  9257. scope.touching = false;
  9258. scope.touchTimer = null;
  9259. }, 700);
  9260. }
  9261. // Mark touch, which is useful in distinguish touch and
  9262. // mouse event in upper applicatoin.
  9263. function markTouch(event) {
  9264. event && (event.zrByTouch = true);
  9265. }
  9266. // function markTriggeredFromLocal(event) {
  9267. // event && (event.__zrIsFromLocal = true);
  9268. // }
  9269. // function isTriggeredFromLocal(instance, event) {
  9270. // return !!(event && event.__zrIsFromLocal);
  9271. // }
  9272. function normalizeGlobalEvent(instance, event) {
  9273. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9274. // handlers of the upper applications. Set `true` to force calculate them.
  9275. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9276. }
  9277. /**
  9278. * Detect whether the given el is in `painterRoot`.
  9279. */
  9280. function isLocalEl(instance, el) {
  9281. var isLocal = false;
  9282. do {
  9283. el = el && el.parentNode;
  9284. }
  9285. while (el && el.nodeType !== 9 && !(
  9286. isLocal = el === instance.painterRoot
  9287. ));
  9288. return isLocal;
  9289. }
  9290. /**
  9291. * Make a fake event but not change the original event,
  9292. * becuase the global event probably be used by other
  9293. * listeners not belonging to zrender.
  9294. * @class
  9295. */
  9296. function FakeGlobalEvent(instance, event) {
  9297. this.type = event.type;
  9298. this.target = this.currentTarget = instance.dom;
  9299. this.pointerType = event.pointerType;
  9300. // Necessray for the force calculation of zrX, zrY
  9301. this.clientX = event.clientX;
  9302. this.clientY = event.clientY;
  9303. // Because we do not mount global listeners to touch events,
  9304. // we do not copy `targetTouches` and `changedTouches` here.
  9305. }
  9306. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9307. // we make the default methods on the event do nothing,
  9308. // otherwise it is dangerous. See more details in
  9309. // [Drag outside] in `Handler.js`.
  9310. fakeGlobalEventProto.stopPropagation =
  9311. fakeGlobalEventProto.stopImmediatePropagation =
  9312. fakeGlobalEventProto.preventDefault = noop;
  9313. /**
  9314. * Local DOM Handlers
  9315. * @this {HandlerProxy}
  9316. */
  9317. var localDOMHandlers = {
  9318. mousedown: function (event) {
  9319. event = normalizeEvent(this.dom, event);
  9320. this._mayPointerCapture = [event.zrX, event.zrY];
  9321. this.trigger('mousedown', event);
  9322. },
  9323. mousemove: function (event) {
  9324. event = normalizeEvent(this.dom, event);
  9325. var downPoint = this._mayPointerCapture;
  9326. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9327. togglePointerCapture(this, true);
  9328. }
  9329. this.trigger('mousemove', event);
  9330. },
  9331. mouseup: function (event) {
  9332. event = normalizeEvent(this.dom, event);
  9333. togglePointerCapture(this, false);
  9334. this.trigger('mouseup', event);
  9335. },
  9336. mouseout: function (event) {
  9337. event = normalizeEvent(this.dom, event);
  9338. // Similarly to the browser did on `document` and touch event,
  9339. // `globalout` will be delayed to final pointer cature release.
  9340. if (this._pointerCapturing) {
  9341. event.zrEventControl = 'no_globalout';
  9342. }
  9343. // There might be some doms created by upper layer application
  9344. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9345. // dom created by echarts), where 'globalout' event should not
  9346. // be triggered when mouse enters these doms. (But 'mouseout'
  9347. // should be triggered at the original hovered element as usual).
  9348. var element = event.toElement || event.relatedTarget;
  9349. event.zrIsToLocalDOM = isLocalEl(this, element);
  9350. this.trigger('mouseout', event);
  9351. },
  9352. touchstart: function (event) {
  9353. // Default mouse behaviour should not be disabled here.
  9354. // For example, page may needs to be slided.
  9355. event = normalizeEvent(this.dom, event);
  9356. markTouch(event);
  9357. this._lastTouchMoment = new Date();
  9358. this.handler.processGesture(event, 'start');
  9359. // For consistent event listener for both touch device and mouse device,
  9360. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9361. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9362. // `mousedown`.
  9363. localDOMHandlers.mousemove.call(this, event);
  9364. localDOMHandlers.mousedown.call(this, event);
  9365. },
  9366. touchmove: function (event) {
  9367. event = normalizeEvent(this.dom, event);
  9368. markTouch(event);
  9369. this.handler.processGesture(event, 'change');
  9370. // Mouse move should always be triggered no matter whether
  9371. // there is gestrue event, because mouse move and pinch may
  9372. // be used at the same time.
  9373. localDOMHandlers.mousemove.call(this, event);
  9374. },
  9375. touchend: function (event) {
  9376. event = normalizeEvent(this.dom, event);
  9377. markTouch(event);
  9378. this.handler.processGesture(event, 'end');
  9379. localDOMHandlers.mouseup.call(this, event);
  9380. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9381. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9382. // we can conveniently implement "hover style" in both PC and touch device just
  9383. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9384. // to remove "hover style" on an element, without any additional code for
  9385. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9386. // style" will remain for user view)
  9387. // click event should always be triggered no matter whether
  9388. // there is gestrue event. System click can not be prevented.
  9389. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9390. localDOMHandlers.click.call(this, event);
  9391. }
  9392. },
  9393. pointerdown: function (event) {
  9394. localDOMHandlers.mousedown.call(this, event);
  9395. // if (useMSGuesture(this, event)) {
  9396. // this._msGesture.addPointer(event.pointerId);
  9397. // }
  9398. },
  9399. pointermove: function (event) {
  9400. // FIXME
  9401. // pointermove is so sensitive that it always triggered when
  9402. // tap(click) on touch screen, which affect some judgement in
  9403. // upper application. So, we dont support mousemove on MS touch
  9404. // device yet.
  9405. if (!isPointerFromTouch(event)) {
  9406. localDOMHandlers.mousemove.call(this, event);
  9407. }
  9408. },
  9409. pointerup: function (event) {
  9410. localDOMHandlers.mouseup.call(this, event);
  9411. },
  9412. pointerout: function (event) {
  9413. // pointerout will be triggered when tap on touch screen
  9414. // (IE11+/Edge on MS Surface) after click event triggered,
  9415. // which is inconsistent with the mousout behavior we defined
  9416. // in touchend. So we unify them.
  9417. // (check localDOMHandlers.touchend for detailed explanation)
  9418. if (!isPointerFromTouch(event)) {
  9419. localDOMHandlers.mouseout.call(this, event);
  9420. }
  9421. }
  9422. };
  9423. /**
  9424. * Othere DOM UI Event handlers for zr dom.
  9425. * @this {HandlerProxy}
  9426. */
  9427. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9428. localDOMHandlers[name] = function (event) {
  9429. event = normalizeEvent(this.dom, event);
  9430. this.trigger(name, event);
  9431. };
  9432. });
  9433. /**
  9434. * DOM UI Event handlers for global page.
  9435. *
  9436. * [Caution]:
  9437. * those handlers should both support in capture phase and bubble phase!
  9438. *
  9439. * @this {HandlerProxy}
  9440. */
  9441. var globalDOMHandlers = {
  9442. pointermove: function (event) {
  9443. // FIXME
  9444. // pointermove is so sensitive that it always triggered when
  9445. // tap(click) on touch screen, which affect some judgement in
  9446. // upper application. So, we dont support mousemove on MS touch
  9447. // device yet.
  9448. if (!isPointerFromTouch(event)) {
  9449. globalDOMHandlers.mousemove.call(this, event);
  9450. }
  9451. },
  9452. pointerup: function (event) {
  9453. globalDOMHandlers.mouseup.call(this, event);
  9454. },
  9455. mousemove: function (event) {
  9456. this.trigger('mousemove', event);
  9457. },
  9458. mouseup: function (event) {
  9459. var pointerCaptureReleasing = this._pointerCapturing;
  9460. togglePointerCapture(this, false);
  9461. this.trigger('mouseup', event);
  9462. if (pointerCaptureReleasing) {
  9463. event.zrEventControl = 'only_globalout';
  9464. this.trigger('mouseout', event);
  9465. }
  9466. }
  9467. };
  9468. /**
  9469. * @param {HandlerProxy} instance
  9470. * @param {DOMHandlerScope} scope
  9471. */
  9472. function mountLocalDOMEventListeners(instance, scope) {
  9473. var domHandlers = scope.domHandlers;
  9474. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9475. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9476. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9477. // at the same time.
  9478. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9479. // screen, which do not occurs in pointer event.
  9480. // So we use pointer event to both detect touch gesture and mouse behavior.
  9481. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9482. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9483. // markTriggeredFromLocal(event);
  9484. domHandlers[nativeEventName].call(instance, event);
  9485. });
  9486. });
  9487. // FIXME
  9488. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9489. // which does not prevent defuault behavior occasionally (which may cause view port
  9490. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9491. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9492. // touch screen. And we only support click behavior on MS touch screen now.
  9493. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9494. // We dont support touch on IE on win7.
  9495. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9496. // if (typeof MSGesture === 'function') {
  9497. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9498. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9499. // }
  9500. }
  9501. else {
  9502. if (env$1.touchEventsSupported) {
  9503. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9504. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9505. // markTriggeredFromLocal(event);
  9506. domHandlers[nativeEventName].call(instance, event);
  9507. setTouchTimer(scope);
  9508. });
  9509. });
  9510. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9511. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9512. }
  9513. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9514. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9515. // mouse event can not be handle in those devices.
  9516. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9517. // mouseevent after touch event triggered, see `setTouchTimer`.
  9518. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9519. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9520. event = getNativeEvent(event);
  9521. if (!scope.touching) {
  9522. // markTriggeredFromLocal(event);
  9523. domHandlers[nativeEventName].call(instance, event);
  9524. }
  9525. });
  9526. });
  9527. }
  9528. }
  9529. /**
  9530. * @param {HandlerProxy} instance
  9531. * @param {DOMHandlerScope} scope
  9532. */
  9533. function mountGlobalDOMEventListeners(instance, scope) {
  9534. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9535. if (env$1.pointerEventsSupported) {
  9536. each$1(globalNativeListenerNames.pointer, mount);
  9537. }
  9538. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9539. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9540. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9541. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9542. else if (!env$1.touchEventsSupported) {
  9543. each$1(globalNativeListenerNames.mouse, mount);
  9544. }
  9545. function mount(nativeEventName) {
  9546. function nativeEventListener(event) {
  9547. event = getNativeEvent(event);
  9548. // See the reason in [Drag outside] in `Handler.js`
  9549. // This checking supports both `useCapture` or not.
  9550. // PENDING: if there is performance issue in some devices,
  9551. // we probably can not use `useCapture` and change a easier
  9552. // to judes whether local (mark).
  9553. if (!isLocalEl(instance, event.target)) {
  9554. event = normalizeGlobalEvent(instance, event);
  9555. scope.domHandlers[nativeEventName].call(instance, event);
  9556. }
  9557. }
  9558. mountSingleDOMEventListener(
  9559. scope, nativeEventName, nativeEventListener,
  9560. {capture: true} // See [Drag Outside] in `Handler.js`
  9561. );
  9562. }
  9563. }
  9564. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9565. scope.mounted[nativeEventName] = listener;
  9566. scope.listenerOpts[nativeEventName] = opt;
  9567. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9568. }
  9569. function unmountDOMEventListeners(scope) {
  9570. var mounted = scope.mounted;
  9571. for (var nativeEventName in mounted) {
  9572. if (mounted.hasOwnProperty(nativeEventName)) {
  9573. removeEventListener(
  9574. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9575. scope.listenerOpts[nativeEventName]
  9576. );
  9577. }
  9578. }
  9579. scope.mounted = {};
  9580. }
  9581. /**
  9582. * See [Drag Outside] in `Handler.js`.
  9583. * @implement
  9584. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9585. * `true`: start to capture pointer if it is not capturing.
  9586. * `false`: end the capture if it is capturing.
  9587. */
  9588. function togglePointerCapture(instance, isPointerCapturing) {
  9589. instance._mayPointerCapture = null;
  9590. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9591. instance._pointerCapturing = isPointerCapturing;
  9592. var globalHandlerScope = instance._globalHandlerScope;
  9593. isPointerCapturing
  9594. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9595. : unmountDOMEventListeners(globalHandlerScope);
  9596. }
  9597. }
  9598. /**
  9599. * @inner
  9600. * @class
  9601. */
  9602. function DOMHandlerScope(domTarget, domHandlers) {
  9603. this.domTarget = domTarget;
  9604. this.domHandlers = domHandlers;
  9605. // Key: eventName, value: mounted handler funcitons.
  9606. // Used for unmount.
  9607. this.mounted = {};
  9608. this.listenerOpts = {};
  9609. this.touchTimer = null;
  9610. this.touching = false;
  9611. }
  9612. /**
  9613. * @public
  9614. * @class
  9615. */
  9616. function HandlerDomProxy(dom, painterRoot) {
  9617. Eventful.call(this);
  9618. this.dom = dom;
  9619. this.painterRoot = painterRoot;
  9620. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9621. if (globalEventSupported) {
  9622. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9623. }
  9624. /**
  9625. * @type {boolean}
  9626. */
  9627. this._pointerCapturing = false;
  9628. /**
  9629. * @type {Array.<number>} [x, y] or null.
  9630. */
  9631. this._mayPointerCapture = null;
  9632. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9633. }
  9634. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9635. handlerDomProxyProto.dispose = function () {
  9636. unmountDOMEventListeners(this._localHandlerScope);
  9637. if (globalEventSupported) {
  9638. unmountDOMEventListeners(this._globalHandlerScope);
  9639. }
  9640. };
  9641. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9642. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9643. };
  9644. mixin(HandlerDomProxy, Eventful);
  9645. /*!
  9646. * ZRender, a high performance 2d drawing library.
  9647. *
  9648. * Copyright (c) 2013, Baidu Inc.
  9649. * All rights reserved.
  9650. *
  9651. * LICENSE
  9652. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9653. */
  9654. var useVML = !env$1.canvasSupported;
  9655. var painterCtors = {
  9656. canvas: Painter
  9657. };
  9658. /**
  9659. * @type {string}
  9660. */
  9661. var version$1 = '4.2.0';
  9662. /**
  9663. * Initializing a zrender instance
  9664. * @param {HTMLElement} dom
  9665. * @param {Object} [opts]
  9666. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9667. * @param {number} [opts.devicePixelRatio]
  9668. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9669. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9670. * @return {module:zrender/ZRender}
  9671. */
  9672. function init$1(dom, opts) {
  9673. var zr = new ZRender(guid(), dom, opts);
  9674. return zr;
  9675. }
  9676. /**
  9677. * Dispose zrender instance
  9678. * @param {module:zrender/ZRender} zr
  9679. */
  9680. /**
  9681. * Get zrender instance by id
  9682. * @param {string} id zrender instance id
  9683. * @return {module:zrender/ZRender}
  9684. */
  9685. /**
  9686. * @module zrender/ZRender
  9687. */
  9688. /**
  9689. * @constructor
  9690. * @alias module:zrender/ZRender
  9691. * @param {string} id
  9692. * @param {HTMLElement} dom
  9693. * @param {Object} opts
  9694. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9695. * @param {number} [opts.devicePixelRatio]
  9696. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9697. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9698. */
  9699. var ZRender = function (id, dom, opts) {
  9700. opts = opts || {};
  9701. /**
  9702. * @type {HTMLDomElement}
  9703. */
  9704. this.dom = dom;
  9705. /**
  9706. * @type {string}
  9707. */
  9708. this.id = id;
  9709. var self = this;
  9710. var storage = new Storage();
  9711. var rendererType = opts.renderer;
  9712. // TODO WebGL
  9713. if (useVML) {
  9714. if (!painterCtors.vml) {
  9715. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9716. }
  9717. rendererType = 'vml';
  9718. }
  9719. else if (!rendererType || !painterCtors[rendererType]) {
  9720. rendererType = 'canvas';
  9721. }
  9722. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9723. this.storage = storage;
  9724. this.painter = painter;
  9725. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  9726. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9727. /**
  9728. * @type {module:zrender/animation/Animation}
  9729. */
  9730. this.animation = new Animation({
  9731. stage: {
  9732. update: bind(this.flush, this)
  9733. }
  9734. });
  9735. this.animation.start();
  9736. /**
  9737. * @type {boolean}
  9738. * @private
  9739. */
  9740. this._needsRefresh;
  9741. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9742. // FIXME 有点ugly
  9743. var oldDelFromStorage = storage.delFromStorage;
  9744. var oldAddToStorage = storage.addToStorage;
  9745. storage.delFromStorage = function (el) {
  9746. oldDelFromStorage.call(storage, el);
  9747. el && el.removeSelfFromZr(self);
  9748. };
  9749. storage.addToStorage = function (el) {
  9750. oldAddToStorage.call(storage, el);
  9751. el.addSelfToZr(self);
  9752. };
  9753. };
  9754. ZRender.prototype = {
  9755. constructor: ZRender,
  9756. /**
  9757. * 获取实例唯一标识
  9758. * @return {string}
  9759. */
  9760. getId: function () {
  9761. return this.id;
  9762. },
  9763. /**
  9764. * 添加元素
  9765. * @param {module:zrender/Element} el
  9766. */
  9767. add: function (el) {
  9768. this.storage.addRoot(el);
  9769. this._needsRefresh = true;
  9770. },
  9771. /**
  9772. * 删除元素
  9773. * @param {module:zrender/Element} el
  9774. */
  9775. remove: function (el) {
  9776. this.storage.delRoot(el);
  9777. this._needsRefresh = true;
  9778. },
  9779. /**
  9780. * Change configuration of layer
  9781. * @param {string} zLevel
  9782. * @param {Object} config
  9783. * @param {string} [config.clearColor=0] Clear color
  9784. * @param {string} [config.motionBlur=false] If enable motion blur
  9785. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9786. */
  9787. configLayer: function (zLevel, config) {
  9788. if (this.painter.configLayer) {
  9789. this.painter.configLayer(zLevel, config);
  9790. }
  9791. this._needsRefresh = true;
  9792. },
  9793. /**
  9794. * Set background color
  9795. * @param {string} backgroundColor
  9796. */
  9797. setBackgroundColor: function (backgroundColor) {
  9798. if (this.painter.setBackgroundColor) {
  9799. this.painter.setBackgroundColor(backgroundColor);
  9800. }
  9801. this._needsRefresh = true;
  9802. },
  9803. /**
  9804. * Repaint the canvas immediately
  9805. */
  9806. refreshImmediately: function () {
  9807. // var start = new Date();
  9808. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9809. // Or it will cause zrender refreshes again and again.
  9810. this._needsRefresh = this._needsRefreshHover = false;
  9811. this.painter.refresh();
  9812. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  9813. this._needsRefresh = this._needsRefreshHover = false;
  9814. // var end = new Date();
  9815. // var log = document.getElementById('log');
  9816. // if (log) {
  9817. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9818. // }
  9819. },
  9820. /**
  9821. * Mark and repaint the canvas in the next frame of browser
  9822. */
  9823. refresh: function () {
  9824. this._needsRefresh = true;
  9825. },
  9826. /**
  9827. * Perform all refresh
  9828. */
  9829. flush: function () {
  9830. var triggerRendered;
  9831. if (this._needsRefresh) {
  9832. triggerRendered = true;
  9833. this.refreshImmediately();
  9834. }
  9835. if (this._needsRefreshHover) {
  9836. triggerRendered = true;
  9837. this.refreshHoverImmediately();
  9838. }
  9839. triggerRendered && this.trigger('rendered');
  9840. },
  9841. /**
  9842. * Add element to hover layer
  9843. * @param {module:zrender/Element} el
  9844. * @param {Object} style
  9845. */
  9846. addHover: function (el, style) {
  9847. if (this.painter.addHover) {
  9848. var elMirror = this.painter.addHover(el, style);
  9849. this.refreshHover();
  9850. return elMirror;
  9851. }
  9852. },
  9853. /**
  9854. * Add element from hover layer
  9855. * @param {module:zrender/Element} el
  9856. */
  9857. removeHover: function (el) {
  9858. if (this.painter.removeHover) {
  9859. this.painter.removeHover(el);
  9860. this.refreshHover();
  9861. }
  9862. },
  9863. /**
  9864. * Clear all hover elements in hover layer
  9865. * @param {module:zrender/Element} el
  9866. */
  9867. clearHover: function () {
  9868. if (this.painter.clearHover) {
  9869. this.painter.clearHover();
  9870. this.refreshHover();
  9871. }
  9872. },
  9873. /**
  9874. * Refresh hover in next frame
  9875. */
  9876. refreshHover: function () {
  9877. this._needsRefreshHover = true;
  9878. },
  9879. /**
  9880. * Refresh hover immediately
  9881. */
  9882. refreshHoverImmediately: function () {
  9883. this._needsRefreshHover = false;
  9884. this.painter.refreshHover && this.painter.refreshHover();
  9885. },
  9886. /**
  9887. * Resize the canvas.
  9888. * Should be invoked when container size is changed
  9889. * @param {Object} [opts]
  9890. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9891. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9892. */
  9893. resize: function (opts) {
  9894. opts = opts || {};
  9895. this.painter.resize(opts.width, opts.height);
  9896. this.handler.resize();
  9897. },
  9898. /**
  9899. * Stop and clear all animation immediately
  9900. */
  9901. clearAnimation: function () {
  9902. this.animation.clear();
  9903. },
  9904. /**
  9905. * Get container width
  9906. */
  9907. getWidth: function () {
  9908. return this.painter.getWidth();
  9909. },
  9910. /**
  9911. * Get container height
  9912. */
  9913. getHeight: function () {
  9914. return this.painter.getHeight();
  9915. },
  9916. /**
  9917. * Export the canvas as Base64 URL
  9918. * @param {string} type
  9919. * @param {string} [backgroundColor='#fff']
  9920. * @return {string} Base64 URL
  9921. */
  9922. // toDataURL: function(type, backgroundColor) {
  9923. // return this.painter.getRenderedCanvas({
  9924. // backgroundColor: backgroundColor
  9925. // }).toDataURL(type);
  9926. // },
  9927. /**
  9928. * Converting a path to image.
  9929. * It has much better performance of drawing image rather than drawing a vector path.
  9930. * @param {module:zrender/graphic/Path} e
  9931. * @param {number} width
  9932. * @param {number} height
  9933. */
  9934. pathToImage: function (e, dpr) {
  9935. return this.painter.pathToImage(e, dpr);
  9936. },
  9937. /**
  9938. * Set default cursor
  9939. * @param {string} [cursorStyle='default'] 例如 crosshair
  9940. */
  9941. setCursorStyle: function (cursorStyle) {
  9942. this.handler.setCursorStyle(cursorStyle);
  9943. },
  9944. /**
  9945. * Find hovered element
  9946. * @param {number} x
  9947. * @param {number} y
  9948. * @return {Object} {target, topTarget}
  9949. */
  9950. findHover: function (x, y) {
  9951. return this.handler.findHover(x, y);
  9952. },
  9953. /**
  9954. * Bind event
  9955. *
  9956. * @param {string} eventName Event name
  9957. * @param {Function} eventHandler Handler function
  9958. * @param {Object} [context] Context object
  9959. */
  9960. on: function (eventName, eventHandler, context) {
  9961. this.handler.on(eventName, eventHandler, context);
  9962. },
  9963. /**
  9964. * Unbind event
  9965. * @param {string} eventName Event name
  9966. * @param {Function} [eventHandler] Handler function
  9967. */
  9968. off: function (eventName, eventHandler) {
  9969. this.handler.off(eventName, eventHandler);
  9970. },
  9971. /**
  9972. * Trigger event manually
  9973. *
  9974. * @param {string} eventName Event name
  9975. * @param {event=} event Event object
  9976. */
  9977. trigger: function (eventName, event) {
  9978. this.handler.trigger(eventName, event);
  9979. },
  9980. /**
  9981. * Clear all objects and the canvas.
  9982. */
  9983. clear: function () {
  9984. this.storage.delRoot();
  9985. this.painter.clear();
  9986. },
  9987. /**
  9988. * Dispose self.
  9989. */
  9990. dispose: function () {
  9991. this.animation.stop();
  9992. this.clear();
  9993. this.storage.dispose();
  9994. this.painter.dispose();
  9995. this.handler.dispose();
  9996. this.animation =
  9997. this.storage =
  9998. this.painter =
  9999. this.handler = null;
  10000. }
  10001. };
  10002. /*
  10003. * Licensed to the Apache Software Foundation (ASF) under one
  10004. * or more contributor license agreements. See the NOTICE file
  10005. * distributed with this work for additional information
  10006. * regarding copyright ownership. The ASF licenses this file
  10007. * to you under the Apache License, Version 2.0 (the
  10008. * "License"); you may not use this file except in compliance
  10009. * with the License. You may obtain a copy of the License at
  10010. *
  10011. * http://www.apache.org/licenses/LICENSE-2.0
  10012. *
  10013. * Unless required by applicable law or agreed to in writing,
  10014. * software distributed under the License is distributed on an
  10015. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10016. * KIND, either express or implied. See the License for the
  10017. * specific language governing permissions and limitations
  10018. * under the License.
  10019. */
  10020. var each$2 = each$1;
  10021. var isObject$2 = isObject$1;
  10022. var isArray$1 = isArray;
  10023. /**
  10024. * Make the name displayable. But we should
  10025. * make sure it is not duplicated with user
  10026. * specified name, so use '\0';
  10027. */
  10028. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10029. /**
  10030. * If value is not array, then translate it to array.
  10031. * @param {*} value
  10032. * @return {Array} [value] or value
  10033. */
  10034. function normalizeToArray(value) {
  10035. return value instanceof Array
  10036. ? value
  10037. : value == null
  10038. ? []
  10039. : [value];
  10040. }
  10041. /**
  10042. * Sync default option between normal and emphasis like `position` and `show`
  10043. * In case some one will write code like
  10044. * label: {
  10045. * show: false,
  10046. * position: 'outside',
  10047. * fontSize: 18
  10048. * },
  10049. * emphasis: {
  10050. * label: { show: true }
  10051. * }
  10052. * @param {Object} opt
  10053. * @param {string} key
  10054. * @param {Array.<string>} subOpts
  10055. */
  10056. function defaultEmphasis(opt, key, subOpts) {
  10057. // Caution: performance sensitive.
  10058. if (opt) {
  10059. opt[key] = opt[key] || {};
  10060. opt.emphasis = opt.emphasis || {};
  10061. opt.emphasis[key] = opt.emphasis[key] || {};
  10062. // Default emphasis option from normal
  10063. for (var i = 0, len = subOpts.length; i < len; i++) {
  10064. var subOptName = subOpts[i];
  10065. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10066. && opt[key].hasOwnProperty(subOptName)
  10067. ) {
  10068. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10069. }
  10070. }
  10071. }
  10072. }
  10073. var TEXT_STYLE_OPTIONS = [
  10074. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10075. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10076. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10077. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10078. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10079. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10080. ];
  10081. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10082. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10083. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10084. // // FIXME: deprecated, check and remove it.
  10085. // 'textStyle'
  10086. // ]);
  10087. /**
  10088. * The method do not ensure performance.
  10089. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10090. * This helper method retieves value from data.
  10091. * @param {string|number|Date|Array|Object} dataItem
  10092. * @return {number|string|Date|Array.<number|string|Date>}
  10093. */
  10094. function getDataItemValue(dataItem) {
  10095. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10096. ? dataItem.value : dataItem;
  10097. }
  10098. /**
  10099. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10100. * This helper method determine if dataItem has extra option besides value
  10101. * @param {string|number|Date|Array|Object} dataItem
  10102. */
  10103. function isDataItemOption(dataItem) {
  10104. return isObject$2(dataItem)
  10105. && !(dataItem instanceof Array);
  10106. // // markLine data can be array
  10107. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10108. }
  10109. /**
  10110. * Mapping to exists for merge.
  10111. *
  10112. * @public
  10113. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10114. * @param {Object|Array.<Object>} newCptOptions
  10115. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10116. * index of which is the same as exists.
  10117. */
  10118. function mappingToExists(exists, newCptOptions) {
  10119. // Mapping by the order by original option (but not order of
  10120. // new option) in merge mode. Because we should ensure
  10121. // some specified index (like xAxisIndex) is consistent with
  10122. // original option, which is easy to understand, espatially in
  10123. // media query. And in most case, merge option is used to
  10124. // update partial option but not be expected to change order.
  10125. newCptOptions = (newCptOptions || []).slice();
  10126. var result = map(exists || [], function (obj, index) {
  10127. return {exist: obj};
  10128. });
  10129. // Mapping by id or name if specified.
  10130. each$2(newCptOptions, function (cptOption, index) {
  10131. if (!isObject$2(cptOption)) {
  10132. return;
  10133. }
  10134. // id has highest priority.
  10135. for (var i = 0; i < result.length; i++) {
  10136. if (!result[i].option // Consider name: two map to one.
  10137. && cptOption.id != null
  10138. && result[i].exist.id === cptOption.id + ''
  10139. ) {
  10140. result[i].option = cptOption;
  10141. newCptOptions[index] = null;
  10142. return;
  10143. }
  10144. }
  10145. for (var i = 0; i < result.length; i++) {
  10146. var exist = result[i].exist;
  10147. if (!result[i].option // Consider name: two map to one.
  10148. // Can not match when both ids exist but different.
  10149. && (exist.id == null || cptOption.id == null)
  10150. && cptOption.name != null
  10151. && !isIdInner(cptOption)
  10152. && !isIdInner(exist)
  10153. && exist.name === cptOption.name + ''
  10154. ) {
  10155. result[i].option = cptOption;
  10156. newCptOptions[index] = null;
  10157. return;
  10158. }
  10159. }
  10160. });
  10161. // Otherwise mapping by index.
  10162. each$2(newCptOptions, function (cptOption, index) {
  10163. if (!isObject$2(cptOption)) {
  10164. return;
  10165. }
  10166. var i = 0;
  10167. for (; i < result.length; i++) {
  10168. var exist = result[i].exist;
  10169. if (!result[i].option
  10170. // Existing model that already has id should be able to
  10171. // mapped to (because after mapping performed model may
  10172. // be assigned with a id, whish should not affect next
  10173. // mapping), except those has inner id.
  10174. && !isIdInner(exist)
  10175. // Caution:
  10176. // Do not overwrite id. But name can be overwritten,
  10177. // because axis use name as 'show label text'.
  10178. // 'exist' always has id and name and we dont
  10179. // need to check it.
  10180. && cptOption.id == null
  10181. ) {
  10182. result[i].option = cptOption;
  10183. break;
  10184. }
  10185. }
  10186. if (i >= result.length) {
  10187. result.push({option: cptOption});
  10188. }
  10189. });
  10190. return result;
  10191. }
  10192. /**
  10193. * Make id and name for mapping result (result of mappingToExists)
  10194. * into `keyInfo` field.
  10195. *
  10196. * @public
  10197. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10198. * which order is the same as exists.
  10199. * @return {Array.<Object>} The input.
  10200. */
  10201. function makeIdAndName(mapResult) {
  10202. // We use this id to hash component models and view instances
  10203. // in echarts. id can be specified by user, or auto generated.
  10204. // The id generation rule ensures new view instance are able
  10205. // to mapped to old instance when setOption are called in
  10206. // no-merge mode. So we generate model id by name and plus
  10207. // type in view id.
  10208. // name can be duplicated among components, which is convenient
  10209. // to specify multi components (like series) by one name.
  10210. // Ensure that each id is distinct.
  10211. var idMap = createHashMap();
  10212. each$2(mapResult, function (item, index) {
  10213. var existCpt = item.exist;
  10214. existCpt && idMap.set(existCpt.id, item);
  10215. });
  10216. each$2(mapResult, function (item, index) {
  10217. var opt = item.option;
  10218. assert$1(
  10219. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10220. 'id duplicates: ' + (opt && opt.id)
  10221. );
  10222. opt && opt.id != null && idMap.set(opt.id, item);
  10223. !item.keyInfo && (item.keyInfo = {});
  10224. });
  10225. // Make name and id.
  10226. each$2(mapResult, function (item, index) {
  10227. var existCpt = item.exist;
  10228. var opt = item.option;
  10229. var keyInfo = item.keyInfo;
  10230. if (!isObject$2(opt)) {
  10231. return;
  10232. }
  10233. // name can be overwitten. Consider case: axis.name = '20km'.
  10234. // But id generated by name will not be changed, which affect
  10235. // only in that case: setOption with 'not merge mode' and view
  10236. // instance will be recreated, which can be accepted.
  10237. keyInfo.name = opt.name != null
  10238. ? opt.name + ''
  10239. : existCpt
  10240. ? existCpt.name
  10241. // Avoid diffferent series has the same name,
  10242. // because name may be used like in color pallet.
  10243. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10244. if (existCpt) {
  10245. keyInfo.id = existCpt.id;
  10246. }
  10247. else if (opt.id != null) {
  10248. keyInfo.id = opt.id + '';
  10249. }
  10250. else {
  10251. // Consider this situatoin:
  10252. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10253. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10254. // Series with the same name between optionA and optionB
  10255. // should be mapped.
  10256. var idNum = 0;
  10257. do {
  10258. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10259. }
  10260. while (idMap.get(keyInfo.id));
  10261. }
  10262. idMap.set(keyInfo.id, item);
  10263. });
  10264. }
  10265. function isNameSpecified(componentModel) {
  10266. var name = componentModel.name;
  10267. // Is specified when `indexOf` get -1 or > 0.
  10268. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10269. }
  10270. /**
  10271. * @public
  10272. * @param {Object} cptOption
  10273. * @return {boolean}
  10274. */
  10275. function isIdInner(cptOption) {
  10276. return isObject$2(cptOption)
  10277. && cptOption.id
  10278. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10279. }
  10280. /**
  10281. * A helper for removing duplicate items between batchA and batchB,
  10282. * and in themselves, and categorize by series.
  10283. *
  10284. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10285. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10286. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10287. */
  10288. /**
  10289. * @param {module:echarts/data/List} data
  10290. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10291. * each of which can be Array or primary type.
  10292. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10293. */
  10294. function queryDataIndex(data, payload) {
  10295. if (payload.dataIndexInside != null) {
  10296. return payload.dataIndexInside;
  10297. }
  10298. else if (payload.dataIndex != null) {
  10299. return isArray(payload.dataIndex)
  10300. ? map(payload.dataIndex, function (value) {
  10301. return data.indexOfRawIndex(value);
  10302. })
  10303. : data.indexOfRawIndex(payload.dataIndex);
  10304. }
  10305. else if (payload.name != null) {
  10306. return isArray(payload.name)
  10307. ? map(payload.name, function (value) {
  10308. return data.indexOfName(value);
  10309. })
  10310. : data.indexOfName(payload.name);
  10311. }
  10312. }
  10313. /**
  10314. * Enable property storage to any host object.
  10315. * Notice: Serialization is not supported.
  10316. *
  10317. * For example:
  10318. * var inner = zrUitl.makeInner();
  10319. *
  10320. * function some1(hostObj) {
  10321. * inner(hostObj).someProperty = 1212;
  10322. * ...
  10323. * }
  10324. * function some2() {
  10325. * var fields = inner(this);
  10326. * fields.someProperty1 = 1212;
  10327. * fields.someProperty2 = 'xx';
  10328. * ...
  10329. * }
  10330. *
  10331. * @return {Function}
  10332. */
  10333. function makeInner() {
  10334. // Consider different scope by es module import.
  10335. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10336. return function (hostObj) {
  10337. return hostObj[key] || (hostObj[key] = {});
  10338. };
  10339. }
  10340. var innerUniqueIndex = 0;
  10341. /**
  10342. * @param {module:echarts/model/Global} ecModel
  10343. * @param {string|Object} finder
  10344. * If string, e.g., 'geo', means {geoIndex: 0}.
  10345. * If Object, could contain some of these properties below:
  10346. * {
  10347. * seriesIndex, seriesId, seriesName,
  10348. * geoIndex, geoId, geoName,
  10349. * bmapIndex, bmapId, bmapName,
  10350. * xAxisIndex, xAxisId, xAxisName,
  10351. * yAxisIndex, yAxisId, yAxisName,
  10352. * gridIndex, gridId, gridName,
  10353. * ... (can be extended)
  10354. * }
  10355. * Each properties can be number|string|Array.<number>|Array.<string>
  10356. * For example, a finder could be
  10357. * {
  10358. * seriesIndex: 3,
  10359. * geoId: ['aa', 'cc'],
  10360. * gridName: ['xx', 'rr']
  10361. * }
  10362. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10363. * If nothing or null/undefined specified, return nothing.
  10364. * @param {Object} [opt]
  10365. * @param {string} [opt.defaultMainType]
  10366. * @param {Array.<string>} [opt.includeMainTypes]
  10367. * @return {Object} result like:
  10368. * {
  10369. * seriesModels: [seriesModel1, seriesModel2],
  10370. * seriesModel: seriesModel1, // The first model
  10371. * geoModels: [geoModel1, geoModel2],
  10372. * geoModel: geoModel1, // The first model
  10373. * ...
  10374. * }
  10375. */
  10376. function parseFinder(ecModel, finder, opt) {
  10377. if (isString(finder)) {
  10378. var obj = {};
  10379. obj[finder + 'Index'] = 0;
  10380. finder = obj;
  10381. }
  10382. var defaultMainType = opt && opt.defaultMainType;
  10383. if (defaultMainType
  10384. && !has(finder, defaultMainType + 'Index')
  10385. && !has(finder, defaultMainType + 'Id')
  10386. && !has(finder, defaultMainType + 'Name')
  10387. ) {
  10388. finder[defaultMainType + 'Index'] = 0;
  10389. }
  10390. var result = {};
  10391. each$2(finder, function (value, key) {
  10392. var value = finder[key];
  10393. // Exclude 'dataIndex' and other illgal keys.
  10394. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10395. result[key] = value;
  10396. return;
  10397. }
  10398. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10399. var mainType = parsedKey[1];
  10400. var queryType = (parsedKey[2] || '').toLowerCase();
  10401. if (!mainType
  10402. || !queryType
  10403. || value == null
  10404. || (queryType === 'index' && value === 'none')
  10405. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10406. ) {
  10407. return;
  10408. }
  10409. var queryParam = {mainType: mainType};
  10410. if (queryType !== 'index' || value !== 'all') {
  10411. queryParam[queryType] = value;
  10412. }
  10413. var models = ecModel.queryComponents(queryParam);
  10414. result[mainType + 'Models'] = models;
  10415. result[mainType + 'Model'] = models[0];
  10416. });
  10417. return result;
  10418. }
  10419. function has(obj, prop) {
  10420. return obj && obj.hasOwnProperty(prop);
  10421. }
  10422. function setAttribute(dom, key, value) {
  10423. dom.setAttribute
  10424. ? dom.setAttribute(key, value)
  10425. : (dom[key] = value);
  10426. }
  10427. function getAttribute(dom, key) {
  10428. return dom.getAttribute
  10429. ? dom.getAttribute(key)
  10430. : dom[key];
  10431. }
  10432. function getTooltipRenderMode(renderModeOption) {
  10433. if (renderModeOption === 'auto') {
  10434. // Using html when `document` exists, use richText otherwise
  10435. return env$1.domSupported ? 'html' : 'richText';
  10436. }
  10437. else {
  10438. return renderModeOption || 'html';
  10439. }
  10440. }
  10441. /**
  10442. * Group a list by key.
  10443. *
  10444. * @param {Array} array
  10445. * @param {Function} getKey
  10446. * param {*} Array item
  10447. * return {string} key
  10448. * @return {Object} Result
  10449. * {Array}: keys,
  10450. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10451. */
  10452. /*
  10453. * Licensed to the Apache Software Foundation (ASF) under one
  10454. * or more contributor license agreements. See the NOTICE file
  10455. * distributed with this work for additional information
  10456. * regarding copyright ownership. The ASF licenses this file
  10457. * to you under the Apache License, Version 2.0 (the
  10458. * "License"); you may not use this file except in compliance
  10459. * with the License. You may obtain a copy of the License at
  10460. *
  10461. * http://www.apache.org/licenses/LICENSE-2.0
  10462. *
  10463. * Unless required by applicable law or agreed to in writing,
  10464. * software distributed under the License is distributed on an
  10465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10466. * KIND, either express or implied. See the License for the
  10467. * specific language governing permissions and limitations
  10468. * under the License.
  10469. */
  10470. var TYPE_DELIMITER = '.';
  10471. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10472. /**
  10473. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10474. * @public
  10475. */
  10476. function parseClassType$1(componentType) {
  10477. var ret = {main: '', sub: ''};
  10478. if (componentType) {
  10479. componentType = componentType.split(TYPE_DELIMITER);
  10480. ret.main = componentType[0] || '';
  10481. ret.sub = componentType[1] || '';
  10482. }
  10483. return ret;
  10484. }
  10485. /**
  10486. * @public
  10487. */
  10488. function checkClassType(componentType) {
  10489. assert$1(
  10490. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10491. 'componentType "' + componentType + '" illegal'
  10492. );
  10493. }
  10494. /**
  10495. * @public
  10496. */
  10497. function enableClassExtend(RootClass, mandatoryMethods) {
  10498. RootClass.$constructor = RootClass;
  10499. RootClass.extend = function (proto) {
  10500. if (__DEV__) {
  10501. each$1(mandatoryMethods, function (method) {
  10502. if (!proto[method]) {
  10503. console.warn(
  10504. 'Method `' + method + '` should be implemented'
  10505. + (proto.type ? ' in ' + proto.type : '') + '.'
  10506. );
  10507. }
  10508. });
  10509. }
  10510. var superClass = this;
  10511. var ExtendedClass = function () {
  10512. if (!proto.$constructor) {
  10513. superClass.apply(this, arguments);
  10514. }
  10515. else {
  10516. proto.$constructor.apply(this, arguments);
  10517. }
  10518. };
  10519. extend(ExtendedClass.prototype, proto);
  10520. ExtendedClass.extend = this.extend;
  10521. ExtendedClass.superCall = superCall;
  10522. ExtendedClass.superApply = superApply;
  10523. inherits(ExtendedClass, this);
  10524. ExtendedClass.superClass = superClass;
  10525. return ExtendedClass;
  10526. };
  10527. }
  10528. var classBase = 0;
  10529. /**
  10530. * Can not use instanceof, consider different scope by
  10531. * cross domain or es module import in ec extensions.
  10532. * Mount a method "isInstance()" to Clz.
  10533. */
  10534. function enableClassCheck(Clz) {
  10535. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10536. Clz.prototype[classAttr] = true;
  10537. if (__DEV__) {
  10538. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10539. }
  10540. Clz.isInstance = function (obj) {
  10541. return !!(obj && obj[classAttr]);
  10542. };
  10543. }
  10544. // superCall should have class info, which can not be fetch from 'this'.
  10545. // Consider this case:
  10546. // class A has method f,
  10547. // class B inherits class A, overrides method f, f call superApply('f'),
  10548. // class C inherits class B, do not overrides method f,
  10549. // then when method of class C is called, dead loop occured.
  10550. function superCall(context, methodName) {
  10551. var args = slice(arguments, 2);
  10552. return this.superClass.prototype[methodName].apply(context, args);
  10553. }
  10554. function superApply(context, methodName, args) {
  10555. return this.superClass.prototype[methodName].apply(context, args);
  10556. }
  10557. /**
  10558. * @param {Object} entity
  10559. * @param {Object} options
  10560. * @param {boolean} [options.registerWhenExtend]
  10561. * @public
  10562. */
  10563. function enableClassManagement(entity, options) {
  10564. options = options || {};
  10565. /**
  10566. * Component model classes
  10567. * key: componentType,
  10568. * value:
  10569. * componentClass, when componentType is 'xxx'
  10570. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10571. * @type {Object}
  10572. */
  10573. var storage = {};
  10574. entity.registerClass = function (Clazz, componentType) {
  10575. if (componentType) {
  10576. checkClassType(componentType);
  10577. componentType = parseClassType$1(componentType);
  10578. if (!componentType.sub) {
  10579. if (__DEV__) {
  10580. if (storage[componentType.main]) {
  10581. console.warn(componentType.main + ' exists.');
  10582. }
  10583. }
  10584. storage[componentType.main] = Clazz;
  10585. }
  10586. else if (componentType.sub !== IS_CONTAINER) {
  10587. var container = makeContainer(componentType);
  10588. container[componentType.sub] = Clazz;
  10589. }
  10590. }
  10591. return Clazz;
  10592. };
  10593. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10594. var Clazz = storage[componentMainType];
  10595. if (Clazz && Clazz[IS_CONTAINER]) {
  10596. Clazz = subType ? Clazz[subType] : null;
  10597. }
  10598. if (throwWhenNotFound && !Clazz) {
  10599. throw new Error(
  10600. !subType
  10601. ? componentMainType + '.' + 'type should be specified.'
  10602. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10603. );
  10604. }
  10605. return Clazz;
  10606. };
  10607. entity.getClassesByMainType = function (componentType) {
  10608. componentType = parseClassType$1(componentType);
  10609. var result = [];
  10610. var obj = storage[componentType.main];
  10611. if (obj && obj[IS_CONTAINER]) {
  10612. each$1(obj, function (o, type) {
  10613. type !== IS_CONTAINER && result.push(o);
  10614. });
  10615. }
  10616. else {
  10617. result.push(obj);
  10618. }
  10619. return result;
  10620. };
  10621. entity.hasClass = function (componentType) {
  10622. // Just consider componentType.main.
  10623. componentType = parseClassType$1(componentType);
  10624. return !!storage[componentType.main];
  10625. };
  10626. /**
  10627. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10628. */
  10629. entity.getAllClassMainTypes = function () {
  10630. var types = [];
  10631. each$1(storage, function (obj, type) {
  10632. types.push(type);
  10633. });
  10634. return types;
  10635. };
  10636. /**
  10637. * If a main type is container and has sub types
  10638. * @param {string} mainType
  10639. * @return {boolean}
  10640. */
  10641. entity.hasSubTypes = function (componentType) {
  10642. componentType = parseClassType$1(componentType);
  10643. var obj = storage[componentType.main];
  10644. return obj && obj[IS_CONTAINER];
  10645. };
  10646. entity.parseClassType = parseClassType$1;
  10647. function makeContainer(componentType) {
  10648. var container = storage[componentType.main];
  10649. if (!container || !container[IS_CONTAINER]) {
  10650. container = storage[componentType.main] = {};
  10651. container[IS_CONTAINER] = true;
  10652. }
  10653. return container;
  10654. }
  10655. if (options.registerWhenExtend) {
  10656. var originalExtend = entity.extend;
  10657. if (originalExtend) {
  10658. entity.extend = function (proto) {
  10659. var ExtendedClass = originalExtend.call(this, proto);
  10660. return entity.registerClass(ExtendedClass, proto.type);
  10661. };
  10662. }
  10663. }
  10664. return entity;
  10665. }
  10666. /**
  10667. * @param {string|Array.<string>} properties
  10668. */
  10669. /*
  10670. * Licensed to the Apache Software Foundation (ASF) under one
  10671. * or more contributor license agreements. See the NOTICE file
  10672. * distributed with this work for additional information
  10673. * regarding copyright ownership. The ASF licenses this file
  10674. * to you under the Apache License, Version 2.0 (the
  10675. * "License"); you may not use this file except in compliance
  10676. * with the License. You may obtain a copy of the License at
  10677. *
  10678. * http://www.apache.org/licenses/LICENSE-2.0
  10679. *
  10680. * Unless required by applicable law or agreed to in writing,
  10681. * software distributed under the License is distributed on an
  10682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10683. * KIND, either express or implied. See the License for the
  10684. * specific language governing permissions and limitations
  10685. * under the License.
  10686. */
  10687. // TODO Parse shadow style
  10688. // TODO Only shallow path support
  10689. var makeStyleMapper = function (properties) {
  10690. // Normalize
  10691. for (var i = 0; i < properties.length; i++) {
  10692. if (!properties[i][1]) {
  10693. properties[i][1] = properties[i][0];
  10694. }
  10695. }
  10696. return function (model, excludes, includes) {
  10697. var style = {};
  10698. for (var i = 0; i < properties.length; i++) {
  10699. var propName = properties[i][1];
  10700. if ((excludes && indexOf(excludes, propName) >= 0)
  10701. || (includes && indexOf(includes, propName) < 0)
  10702. ) {
  10703. continue;
  10704. }
  10705. var val = model.getShallow(propName);
  10706. if (val != null) {
  10707. style[properties[i][0]] = val;
  10708. }
  10709. }
  10710. return style;
  10711. };
  10712. };
  10713. /*
  10714. * Licensed to the Apache Software Foundation (ASF) under one
  10715. * or more contributor license agreements. See the NOTICE file
  10716. * distributed with this work for additional information
  10717. * regarding copyright ownership. The ASF licenses this file
  10718. * to you under the Apache License, Version 2.0 (the
  10719. * "License"); you may not use this file except in compliance
  10720. * with the License. You may obtain a copy of the License at
  10721. *
  10722. * http://www.apache.org/licenses/LICENSE-2.0
  10723. *
  10724. * Unless required by applicable law or agreed to in writing,
  10725. * software distributed under the License is distributed on an
  10726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10727. * KIND, either express or implied. See the License for the
  10728. * specific language governing permissions and limitations
  10729. * under the License.
  10730. */
  10731. var getLineStyle = makeStyleMapper(
  10732. [
  10733. ['lineWidth', 'width'],
  10734. ['stroke', 'color'],
  10735. ['opacity'],
  10736. ['shadowBlur'],
  10737. ['shadowOffsetX'],
  10738. ['shadowOffsetY'],
  10739. ['shadowColor']
  10740. ]
  10741. );
  10742. var lineStyleMixin = {
  10743. getLineStyle: function (excludes) {
  10744. var style = getLineStyle(this, excludes);
  10745. // Always set lineDash whether dashed, otherwise we can not
  10746. // erase the previous style when assigning to el.style.
  10747. style.lineDash = this.getLineDash(style.lineWidth);
  10748. return style;
  10749. },
  10750. getLineDash: function (lineWidth) {
  10751. if (lineWidth == null) {
  10752. lineWidth = 1;
  10753. }
  10754. var lineType = this.get('type');
  10755. var dotSize = Math.max(lineWidth, 2);
  10756. var dashSize = lineWidth * 4;
  10757. return (lineType === 'solid' || lineType == null)
  10758. // Use `false` but not `null` for the solid line here, because `null` might be
  10759. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  10760. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  10761. // `lineDash` gotten form the latter one is not able to erase that from the former
  10762. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  10763. ? false
  10764. : lineType === 'dashed'
  10765. ? [dashSize, dashSize]
  10766. : [dotSize, dotSize];
  10767. }
  10768. };
  10769. /*
  10770. * Licensed to the Apache Software Foundation (ASF) under one
  10771. * or more contributor license agreements. See the NOTICE file
  10772. * distributed with this work for additional information
  10773. * regarding copyright ownership. The ASF licenses this file
  10774. * to you under the Apache License, Version 2.0 (the
  10775. * "License"); you may not use this file except in compliance
  10776. * with the License. You may obtain a copy of the License at
  10777. *
  10778. * http://www.apache.org/licenses/LICENSE-2.0
  10779. *
  10780. * Unless required by applicable law or agreed to in writing,
  10781. * software distributed under the License is distributed on an
  10782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10783. * KIND, either express or implied. See the License for the
  10784. * specific language governing permissions and limitations
  10785. * under the License.
  10786. */
  10787. var getAreaStyle = makeStyleMapper(
  10788. [
  10789. ['fill', 'color'],
  10790. ['shadowBlur'],
  10791. ['shadowOffsetX'],
  10792. ['shadowOffsetY'],
  10793. ['opacity'],
  10794. ['shadowColor']
  10795. ]
  10796. );
  10797. var areaStyleMixin = {
  10798. getAreaStyle: function (excludes, includes) {
  10799. return getAreaStyle(this, excludes, includes);
  10800. }
  10801. };
  10802. /**
  10803. * 曲线辅助模块
  10804. * @module zrender/core/curve
  10805. * @author pissang(https://www.github.com/pissang)
  10806. */
  10807. var mathPow = Math.pow;
  10808. var mathSqrt$2 = Math.sqrt;
  10809. var EPSILON$1 = 1e-8;
  10810. var EPSILON_NUMERIC = 1e-4;
  10811. var THREE_SQRT = mathSqrt$2(3);
  10812. var ONE_THIRD = 1 / 3;
  10813. // 临时变量
  10814. var _v0 = create();
  10815. var _v1 = create();
  10816. var _v2 = create();
  10817. function isAroundZero(val) {
  10818. return val > -EPSILON$1 && val < EPSILON$1;
  10819. }
  10820. function isNotAroundZero$1(val) {
  10821. return val > EPSILON$1 || val < -EPSILON$1;
  10822. }
  10823. /**
  10824. * 计算三次贝塞尔值
  10825. * @memberOf module:zrender/core/curve
  10826. * @param {number} p0
  10827. * @param {number} p1
  10828. * @param {number} p2
  10829. * @param {number} p3
  10830. * @param {number} t
  10831. * @return {number}
  10832. */
  10833. function cubicAt(p0, p1, p2, p3, t) {
  10834. var onet = 1 - t;
  10835. return onet * onet * (onet * p0 + 3 * t * p1)
  10836. + t * t * (t * p3 + 3 * onet * p2);
  10837. }
  10838. /**
  10839. * 计算三次贝塞尔导数值
  10840. * @memberOf module:zrender/core/curve
  10841. * @param {number} p0
  10842. * @param {number} p1
  10843. * @param {number} p2
  10844. * @param {number} p3
  10845. * @param {number} t
  10846. * @return {number}
  10847. */
  10848. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10849. var onet = 1 - t;
  10850. return 3 * (
  10851. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10852. + (p3 - p2) * t * t
  10853. );
  10854. }
  10855. /**
  10856. * 计算三次贝塞尔方程根,使用盛金公式
  10857. * @memberOf module:zrender/core/curve
  10858. * @param {number} p0
  10859. * @param {number} p1
  10860. * @param {number} p2
  10861. * @param {number} p3
  10862. * @param {number} val
  10863. * @param {Array.<number>} roots
  10864. * @return {number} 有效根数目
  10865. */
  10866. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10867. // Evaluate roots of cubic functions
  10868. var a = p3 + 3 * (p1 - p2) - p0;
  10869. var b = 3 * (p2 - p1 * 2 + p0);
  10870. var c = 3 * (p1 - p0);
  10871. var d = p0 - val;
  10872. var A = b * b - 3 * a * c;
  10873. var B = b * c - 9 * a * d;
  10874. var C = c * c - 3 * b * d;
  10875. var n = 0;
  10876. if (isAroundZero(A) && isAroundZero(B)) {
  10877. if (isAroundZero(b)) {
  10878. roots[0] = 0;
  10879. }
  10880. else {
  10881. var t1 = -c / b; //t1, t2, t3, b is not zero
  10882. if (t1 >= 0 && t1 <= 1) {
  10883. roots[n++] = t1;
  10884. }
  10885. }
  10886. }
  10887. else {
  10888. var disc = B * B - 4 * A * C;
  10889. if (isAroundZero(disc)) {
  10890. var K = B / A;
  10891. var t1 = -b / a + K; // t1, a is not zero
  10892. var t2 = -K / 2; // t2, t3
  10893. if (t1 >= 0 && t1 <= 1) {
  10894. roots[n++] = t1;
  10895. }
  10896. if (t2 >= 0 && t2 <= 1) {
  10897. roots[n++] = t2;
  10898. }
  10899. }
  10900. else if (disc > 0) {
  10901. var discSqrt = mathSqrt$2(disc);
  10902. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10903. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10904. if (Y1 < 0) {
  10905. Y1 = -mathPow(-Y1, ONE_THIRD);
  10906. }
  10907. else {
  10908. Y1 = mathPow(Y1, ONE_THIRD);
  10909. }
  10910. if (Y2 < 0) {
  10911. Y2 = -mathPow(-Y2, ONE_THIRD);
  10912. }
  10913. else {
  10914. Y2 = mathPow(Y2, ONE_THIRD);
  10915. }
  10916. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10917. if (t1 >= 0 && t1 <= 1) {
  10918. roots[n++] = t1;
  10919. }
  10920. }
  10921. else {
  10922. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10923. var theta = Math.acos(T) / 3;
  10924. var ASqrt = mathSqrt$2(A);
  10925. var tmp = Math.cos(theta);
  10926. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10927. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10928. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10929. if (t1 >= 0 && t1 <= 1) {
  10930. roots[n++] = t1;
  10931. }
  10932. if (t2 >= 0 && t2 <= 1) {
  10933. roots[n++] = t2;
  10934. }
  10935. if (t3 >= 0 && t3 <= 1) {
  10936. roots[n++] = t3;
  10937. }
  10938. }
  10939. }
  10940. return n;
  10941. }
  10942. /**
  10943. * 计算三次贝塞尔方程极限值的位置
  10944. * @memberOf module:zrender/core/curve
  10945. * @param {number} p0
  10946. * @param {number} p1
  10947. * @param {number} p2
  10948. * @param {number} p3
  10949. * @param {Array.<number>} extrema
  10950. * @return {number} 有效数目
  10951. */
  10952. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10953. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10954. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10955. var c = 3 * p1 - 3 * p0;
  10956. var n = 0;
  10957. if (isAroundZero(a)) {
  10958. if (isNotAroundZero$1(b)) {
  10959. var t1 = -c / b;
  10960. if (t1 >= 0 && t1 <= 1) {
  10961. extrema[n++] = t1;
  10962. }
  10963. }
  10964. }
  10965. else {
  10966. var disc = b * b - 4 * a * c;
  10967. if (isAroundZero(disc)) {
  10968. extrema[0] = -b / (2 * a);
  10969. }
  10970. else if (disc > 0) {
  10971. var discSqrt = mathSqrt$2(disc);
  10972. var t1 = (-b + discSqrt) / (2 * a);
  10973. var t2 = (-b - discSqrt) / (2 * a);
  10974. if (t1 >= 0 && t1 <= 1) {
  10975. extrema[n++] = t1;
  10976. }
  10977. if (t2 >= 0 && t2 <= 1) {
  10978. extrema[n++] = t2;
  10979. }
  10980. }
  10981. }
  10982. return n;
  10983. }
  10984. /**
  10985. * 细分三次贝塞尔曲线
  10986. * @memberOf module:zrender/core/curve
  10987. * @param {number} p0
  10988. * @param {number} p1
  10989. * @param {number} p2
  10990. * @param {number} p3
  10991. * @param {number} t
  10992. * @param {Array.<number>} out
  10993. */
  10994. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10995. var p01 = (p1 - p0) * t + p0;
  10996. var p12 = (p2 - p1) * t + p1;
  10997. var p23 = (p3 - p2) * t + p2;
  10998. var p012 = (p12 - p01) * t + p01;
  10999. var p123 = (p23 - p12) * t + p12;
  11000. var p0123 = (p123 - p012) * t + p012;
  11001. // Seg0
  11002. out[0] = p0;
  11003. out[1] = p01;
  11004. out[2] = p012;
  11005. out[3] = p0123;
  11006. // Seg1
  11007. out[4] = p0123;
  11008. out[5] = p123;
  11009. out[6] = p23;
  11010. out[7] = p3;
  11011. }
  11012. /**
  11013. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11014. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11015. * @param {number} x0
  11016. * @param {number} y0
  11017. * @param {number} x1
  11018. * @param {number} y1
  11019. * @param {number} x2
  11020. * @param {number} y2
  11021. * @param {number} x3
  11022. * @param {number} y3
  11023. * @param {number} x
  11024. * @param {number} y
  11025. * @param {Array.<number>} [out] 投射点
  11026. * @return {number}
  11027. */
  11028. function cubicProjectPoint(
  11029. x0, y0, x1, y1, x2, y2, x3, y3,
  11030. x, y, out
  11031. ) {
  11032. // http://pomax.github.io/bezierinfo/#projections
  11033. var t;
  11034. var interval = 0.005;
  11035. var d = Infinity;
  11036. var prev;
  11037. var next;
  11038. var d1;
  11039. var d2;
  11040. _v0[0] = x;
  11041. _v0[1] = y;
  11042. // 先粗略估计一下可能的最小距离的 t 值
  11043. // PENDING
  11044. for (var _t = 0; _t < 1; _t += 0.05) {
  11045. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11046. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11047. d1 = distSquare(_v0, _v1);
  11048. if (d1 < d) {
  11049. t = _t;
  11050. d = d1;
  11051. }
  11052. }
  11053. d = Infinity;
  11054. // At most 32 iteration
  11055. for (var i = 0; i < 32; i++) {
  11056. if (interval < EPSILON_NUMERIC) {
  11057. break;
  11058. }
  11059. prev = t - interval;
  11060. next = t + interval;
  11061. // t - interval
  11062. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11063. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11064. d1 = distSquare(_v1, _v0);
  11065. if (prev >= 0 && d1 < d) {
  11066. t = prev;
  11067. d = d1;
  11068. }
  11069. else {
  11070. // t + interval
  11071. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11072. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11073. d2 = distSquare(_v2, _v0);
  11074. if (next <= 1 && d2 < d) {
  11075. t = next;
  11076. d = d2;
  11077. }
  11078. else {
  11079. interval *= 0.5;
  11080. }
  11081. }
  11082. }
  11083. // t
  11084. if (out) {
  11085. out[0] = cubicAt(x0, x1, x2, x3, t);
  11086. out[1] = cubicAt(y0, y1, y2, y3, t);
  11087. }
  11088. // console.log(interval, i);
  11089. return mathSqrt$2(d);
  11090. }
  11091. /**
  11092. * 计算二次方贝塞尔值
  11093. * @param {number} p0
  11094. * @param {number} p1
  11095. * @param {number} p2
  11096. * @param {number} t
  11097. * @return {number}
  11098. */
  11099. function quadraticAt(p0, p1, p2, t) {
  11100. var onet = 1 - t;
  11101. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11102. }
  11103. /**
  11104. * 计算二次方贝塞尔导数值
  11105. * @param {number} p0
  11106. * @param {number} p1
  11107. * @param {number} p2
  11108. * @param {number} t
  11109. * @return {number}
  11110. */
  11111. function quadraticDerivativeAt(p0, p1, p2, t) {
  11112. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11113. }
  11114. /**
  11115. * 计算二次方贝塞尔方程根
  11116. * @param {number} p0
  11117. * @param {number} p1
  11118. * @param {number} p2
  11119. * @param {number} t
  11120. * @param {Array.<number>} roots
  11121. * @return {number} 有效根数目
  11122. */
  11123. function quadraticRootAt(p0, p1, p2, val, roots) {
  11124. var a = p0 - 2 * p1 + p2;
  11125. var b = 2 * (p1 - p0);
  11126. var c = p0 - val;
  11127. var n = 0;
  11128. if (isAroundZero(a)) {
  11129. if (isNotAroundZero$1(b)) {
  11130. var t1 = -c / b;
  11131. if (t1 >= 0 && t1 <= 1) {
  11132. roots[n++] = t1;
  11133. }
  11134. }
  11135. }
  11136. else {
  11137. var disc = b * b - 4 * a * c;
  11138. if (isAroundZero(disc)) {
  11139. var t1 = -b / (2 * a);
  11140. if (t1 >= 0 && t1 <= 1) {
  11141. roots[n++] = t1;
  11142. }
  11143. }
  11144. else if (disc > 0) {
  11145. var discSqrt = mathSqrt$2(disc);
  11146. var t1 = (-b + discSqrt) / (2 * a);
  11147. var t2 = (-b - discSqrt) / (2 * a);
  11148. if (t1 >= 0 && t1 <= 1) {
  11149. roots[n++] = t1;
  11150. }
  11151. if (t2 >= 0 && t2 <= 1) {
  11152. roots[n++] = t2;
  11153. }
  11154. }
  11155. }
  11156. return n;
  11157. }
  11158. /**
  11159. * 计算二次贝塞尔方程极限值
  11160. * @memberOf module:zrender/core/curve
  11161. * @param {number} p0
  11162. * @param {number} p1
  11163. * @param {number} p2
  11164. * @return {number}
  11165. */
  11166. function quadraticExtremum(p0, p1, p2) {
  11167. var divider = p0 + p2 - 2 * p1;
  11168. if (divider === 0) {
  11169. // p1 is center of p0 and p2
  11170. return 0.5;
  11171. }
  11172. else {
  11173. return (p0 - p1) / divider;
  11174. }
  11175. }
  11176. /**
  11177. * 细分二次贝塞尔曲线
  11178. * @memberOf module:zrender/core/curve
  11179. * @param {number} p0
  11180. * @param {number} p1
  11181. * @param {number} p2
  11182. * @param {number} t
  11183. * @param {Array.<number>} out
  11184. */
  11185. function quadraticSubdivide(p0, p1, p2, t, out) {
  11186. var p01 = (p1 - p0) * t + p0;
  11187. var p12 = (p2 - p1) * t + p1;
  11188. var p012 = (p12 - p01) * t + p01;
  11189. // Seg0
  11190. out[0] = p0;
  11191. out[1] = p01;
  11192. out[2] = p012;
  11193. // Seg1
  11194. out[3] = p012;
  11195. out[4] = p12;
  11196. out[5] = p2;
  11197. }
  11198. /**
  11199. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11200. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11201. * @param {number} x0
  11202. * @param {number} y0
  11203. * @param {number} x1
  11204. * @param {number} y1
  11205. * @param {number} x2
  11206. * @param {number} y2
  11207. * @param {number} x
  11208. * @param {number} y
  11209. * @param {Array.<number>} out 投射点
  11210. * @return {number}
  11211. */
  11212. function quadraticProjectPoint(
  11213. x0, y0, x1, y1, x2, y2,
  11214. x, y, out
  11215. ) {
  11216. // http://pomax.github.io/bezierinfo/#projections
  11217. var t;
  11218. var interval = 0.005;
  11219. var d = Infinity;
  11220. _v0[0] = x;
  11221. _v0[1] = y;
  11222. // 先粗略估计一下可能的最小距离的 t 值
  11223. // PENDING
  11224. for (var _t = 0; _t < 1; _t += 0.05) {
  11225. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11226. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11227. var d1 = distSquare(_v0, _v1);
  11228. if (d1 < d) {
  11229. t = _t;
  11230. d = d1;
  11231. }
  11232. }
  11233. d = Infinity;
  11234. // At most 32 iteration
  11235. for (var i = 0; i < 32; i++) {
  11236. if (interval < EPSILON_NUMERIC) {
  11237. break;
  11238. }
  11239. var prev = t - interval;
  11240. var next = t + interval;
  11241. // t - interval
  11242. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11243. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11244. var d1 = distSquare(_v1, _v0);
  11245. if (prev >= 0 && d1 < d) {
  11246. t = prev;
  11247. d = d1;
  11248. }
  11249. else {
  11250. // t + interval
  11251. _v2[0] = quadraticAt(x0, x1, x2, next);
  11252. _v2[1] = quadraticAt(y0, y1, y2, next);
  11253. var d2 = distSquare(_v2, _v0);
  11254. if (next <= 1 && d2 < d) {
  11255. t = next;
  11256. d = d2;
  11257. }
  11258. else {
  11259. interval *= 0.5;
  11260. }
  11261. }
  11262. }
  11263. // t
  11264. if (out) {
  11265. out[0] = quadraticAt(x0, x1, x2, t);
  11266. out[1] = quadraticAt(y0, y1, y2, t);
  11267. }
  11268. // console.log(interval, i);
  11269. return mathSqrt$2(d);
  11270. }
  11271. /**
  11272. * @author Yi Shen(https://github.com/pissang)
  11273. */
  11274. var mathMin$3 = Math.min;
  11275. var mathMax$3 = Math.max;
  11276. var mathSin$2 = Math.sin;
  11277. var mathCos$2 = Math.cos;
  11278. var PI2 = Math.PI * 2;
  11279. var start = create();
  11280. var end = create();
  11281. var extremity = create();
  11282. /**
  11283. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11284. * @module zrender/core/bbox
  11285. * @param {Array<Object>} points 顶点数组
  11286. * @param {number} min
  11287. * @param {number} max
  11288. */
  11289. /**
  11290. * @memberOf module:zrender/core/bbox
  11291. * @param {number} x0
  11292. * @param {number} y0
  11293. * @param {number} x1
  11294. * @param {number} y1
  11295. * @param {Array.<number>} min
  11296. * @param {Array.<number>} max
  11297. */
  11298. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11299. min$$1[0] = mathMin$3(x0, x1);
  11300. min$$1[1] = mathMin$3(y0, y1);
  11301. max$$1[0] = mathMax$3(x0, x1);
  11302. max$$1[1] = mathMax$3(y0, y1);
  11303. }
  11304. var xDim = [];
  11305. var yDim = [];
  11306. /**
  11307. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11308. * @memberOf module:zrender/core/bbox
  11309. * @param {number} x0
  11310. * @param {number} y0
  11311. * @param {number} x1
  11312. * @param {number} y1
  11313. * @param {number} x2
  11314. * @param {number} y2
  11315. * @param {number} x3
  11316. * @param {number} y3
  11317. * @param {Array.<number>} min
  11318. * @param {Array.<number>} max
  11319. */
  11320. function fromCubic(
  11321. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11322. ) {
  11323. var cubicExtrema$$1 = cubicExtrema;
  11324. var cubicAt$$1 = cubicAt;
  11325. var i;
  11326. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11327. min$$1[0] = Infinity;
  11328. min$$1[1] = Infinity;
  11329. max$$1[0] = -Infinity;
  11330. max$$1[1] = -Infinity;
  11331. for (i = 0; i < n; i++) {
  11332. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11333. min$$1[0] = mathMin$3(x, min$$1[0]);
  11334. max$$1[0] = mathMax$3(x, max$$1[0]);
  11335. }
  11336. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11337. for (i = 0; i < n; i++) {
  11338. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11339. min$$1[1] = mathMin$3(y, min$$1[1]);
  11340. max$$1[1] = mathMax$3(y, max$$1[1]);
  11341. }
  11342. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11343. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11344. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11345. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11346. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11347. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11348. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11349. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11350. }
  11351. /**
  11352. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11353. * @memberOf module:zrender/core/bbox
  11354. * @param {number} x0
  11355. * @param {number} y0
  11356. * @param {number} x1
  11357. * @param {number} y1
  11358. * @param {number} x2
  11359. * @param {number} y2
  11360. * @param {Array.<number>} min
  11361. * @param {Array.<number>} max
  11362. */
  11363. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11364. var quadraticExtremum$$1 = quadraticExtremum;
  11365. var quadraticAt$$1 = quadraticAt;
  11366. // Find extremities, where derivative in x dim or y dim is zero
  11367. var tx =
  11368. mathMax$3(
  11369. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11370. );
  11371. var ty =
  11372. mathMax$3(
  11373. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11374. );
  11375. var x = quadraticAt$$1(x0, x1, x2, tx);
  11376. var y = quadraticAt$$1(y0, y1, y2, ty);
  11377. min$$1[0] = mathMin$3(x0, x2, x);
  11378. min$$1[1] = mathMin$3(y0, y2, y);
  11379. max$$1[0] = mathMax$3(x0, x2, x);
  11380. max$$1[1] = mathMax$3(y0, y2, y);
  11381. }
  11382. /**
  11383. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11384. * @method
  11385. * @memberOf module:zrender/core/bbox
  11386. * @param {number} x
  11387. * @param {number} y
  11388. * @param {number} rx
  11389. * @param {number} ry
  11390. * @param {number} startAngle
  11391. * @param {number} endAngle
  11392. * @param {number} anticlockwise
  11393. * @param {Array.<number>} min
  11394. * @param {Array.<number>} max
  11395. */
  11396. function fromArc(
  11397. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11398. ) {
  11399. var vec2Min = min;
  11400. var vec2Max = max;
  11401. var diff = Math.abs(startAngle - endAngle);
  11402. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11403. // Is a circle
  11404. min$$1[0] = x - rx;
  11405. min$$1[1] = y - ry;
  11406. max$$1[0] = x + rx;
  11407. max$$1[1] = y + ry;
  11408. return;
  11409. }
  11410. start[0] = mathCos$2(startAngle) * rx + x;
  11411. start[1] = mathSin$2(startAngle) * ry + y;
  11412. end[0] = mathCos$2(endAngle) * rx + x;
  11413. end[1] = mathSin$2(endAngle) * ry + y;
  11414. vec2Min(min$$1, start, end);
  11415. vec2Max(max$$1, start, end);
  11416. // Thresh to [0, Math.PI * 2]
  11417. startAngle = startAngle % (PI2);
  11418. if (startAngle < 0) {
  11419. startAngle = startAngle + PI2;
  11420. }
  11421. endAngle = endAngle % (PI2);
  11422. if (endAngle < 0) {
  11423. endAngle = endAngle + PI2;
  11424. }
  11425. if (startAngle > endAngle && !anticlockwise) {
  11426. endAngle += PI2;
  11427. }
  11428. else if (startAngle < endAngle && anticlockwise) {
  11429. startAngle += PI2;
  11430. }
  11431. if (anticlockwise) {
  11432. var tmp = endAngle;
  11433. endAngle = startAngle;
  11434. startAngle = tmp;
  11435. }
  11436. // var number = 0;
  11437. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11438. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11439. if (angle > startAngle) {
  11440. extremity[0] = mathCos$2(angle) * rx + x;
  11441. extremity[1] = mathSin$2(angle) * ry + y;
  11442. vec2Min(min$$1, extremity, min$$1);
  11443. vec2Max(max$$1, extremity, max$$1);
  11444. }
  11445. }
  11446. }
  11447. /**
  11448. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11449. * 可以用于 isInsidePath 判断以及获取boundingRect
  11450. *
  11451. * @module zrender/core/PathProxy
  11452. * @author Yi Shen (http://www.github.com/pissang)
  11453. */
  11454. // TODO getTotalLength, getPointAtLength
  11455. /* global Float32Array */
  11456. var CMD = {
  11457. M: 1,
  11458. L: 2,
  11459. C: 3,
  11460. Q: 4,
  11461. A: 5,
  11462. Z: 6,
  11463. // Rect
  11464. R: 7
  11465. };
  11466. // var CMD_MEM_SIZE = {
  11467. // M: 3,
  11468. // L: 3,
  11469. // C: 7,
  11470. // Q: 5,
  11471. // A: 9,
  11472. // R: 5,
  11473. // Z: 1
  11474. // };
  11475. var min$1 = [];
  11476. var max$1 = [];
  11477. var min2 = [];
  11478. var max2 = [];
  11479. var mathMin$2 = Math.min;
  11480. var mathMax$2 = Math.max;
  11481. var mathCos$1 = Math.cos;
  11482. var mathSin$1 = Math.sin;
  11483. var mathSqrt$1 = Math.sqrt;
  11484. var mathAbs = Math.abs;
  11485. var hasTypedArray = typeof Float32Array !== 'undefined';
  11486. /**
  11487. * @alias module:zrender/core/PathProxy
  11488. * @constructor
  11489. */
  11490. var PathProxy = function (notSaveData) {
  11491. this._saveData = !(notSaveData || false);
  11492. if (this._saveData) {
  11493. /**
  11494. * Path data. Stored as flat array
  11495. * @type {Array.<Object>}
  11496. */
  11497. this.data = [];
  11498. }
  11499. this._ctx = null;
  11500. };
  11501. /**
  11502. * 快速计算Path包围盒(并不是最小包围盒)
  11503. * @return {Object}
  11504. */
  11505. PathProxy.prototype = {
  11506. constructor: PathProxy,
  11507. _xi: 0,
  11508. _yi: 0,
  11509. _x0: 0,
  11510. _y0: 0,
  11511. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11512. _ux: 0,
  11513. _uy: 0,
  11514. _len: 0,
  11515. _lineDash: null,
  11516. _dashOffset: 0,
  11517. _dashIdx: 0,
  11518. _dashSum: 0,
  11519. /**
  11520. * @readOnly
  11521. */
  11522. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11523. // Compat. Previously there is no segmentIgnoreThreshold.
  11524. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11525. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11526. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11527. },
  11528. getContext: function () {
  11529. return this._ctx;
  11530. },
  11531. /**
  11532. * @param {CanvasRenderingContext2D} ctx
  11533. * @return {module:zrender/core/PathProxy}
  11534. */
  11535. beginPath: function (ctx) {
  11536. this._ctx = ctx;
  11537. ctx && ctx.beginPath();
  11538. ctx && (this.dpr = ctx.dpr);
  11539. // Reset
  11540. if (this._saveData) {
  11541. this._len = 0;
  11542. }
  11543. if (this._lineDash) {
  11544. this._lineDash = null;
  11545. this._dashOffset = 0;
  11546. }
  11547. return this;
  11548. },
  11549. /**
  11550. * @param {number} x
  11551. * @param {number} y
  11552. * @return {module:zrender/core/PathProxy}
  11553. */
  11554. moveTo: function (x, y) {
  11555. this.addData(CMD.M, x, y);
  11556. this._ctx && this._ctx.moveTo(x, y);
  11557. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11558. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11559. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11560. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11561. this._x0 = x;
  11562. this._y0 = y;
  11563. this._xi = x;
  11564. this._yi = y;
  11565. return this;
  11566. },
  11567. /**
  11568. * @param {number} x
  11569. * @param {number} y
  11570. * @return {module:zrender/core/PathProxy}
  11571. */
  11572. lineTo: function (x, y) {
  11573. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11574. || mathAbs(y - this._yi) > this._uy
  11575. // Force draw the first segment
  11576. || this._len < 5;
  11577. this.addData(CMD.L, x, y);
  11578. if (this._ctx && exceedUnit) {
  11579. this._needsDash() ? this._dashedLineTo(x, y)
  11580. : this._ctx.lineTo(x, y);
  11581. }
  11582. if (exceedUnit) {
  11583. this._xi = x;
  11584. this._yi = y;
  11585. }
  11586. return this;
  11587. },
  11588. /**
  11589. * @param {number} x1
  11590. * @param {number} y1
  11591. * @param {number} x2
  11592. * @param {number} y2
  11593. * @param {number} x3
  11594. * @param {number} y3
  11595. * @return {module:zrender/core/PathProxy}
  11596. */
  11597. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11598. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11599. if (this._ctx) {
  11600. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11601. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11602. }
  11603. this._xi = x3;
  11604. this._yi = y3;
  11605. return this;
  11606. },
  11607. /**
  11608. * @param {number} x1
  11609. * @param {number} y1
  11610. * @param {number} x2
  11611. * @param {number} y2
  11612. * @return {module:zrender/core/PathProxy}
  11613. */
  11614. quadraticCurveTo: function (x1, y1, x2, y2) {
  11615. this.addData(CMD.Q, x1, y1, x2, y2);
  11616. if (this._ctx) {
  11617. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11618. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11619. }
  11620. this._xi = x2;
  11621. this._yi = y2;
  11622. return this;
  11623. },
  11624. /**
  11625. * @param {number} cx
  11626. * @param {number} cy
  11627. * @param {number} r
  11628. * @param {number} startAngle
  11629. * @param {number} endAngle
  11630. * @param {boolean} anticlockwise
  11631. * @return {module:zrender/core/PathProxy}
  11632. */
  11633. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11634. this.addData(
  11635. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11636. );
  11637. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11638. this._xi = mathCos$1(endAngle) * r + cx;
  11639. this._yi = mathSin$1(endAngle) * r + cy;
  11640. return this;
  11641. },
  11642. // TODO
  11643. arcTo: function (x1, y1, x2, y2, radius) {
  11644. if (this._ctx) {
  11645. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11646. }
  11647. return this;
  11648. },
  11649. // TODO
  11650. rect: function (x, y, w, h) {
  11651. this._ctx && this._ctx.rect(x, y, w, h);
  11652. this.addData(CMD.R, x, y, w, h);
  11653. return this;
  11654. },
  11655. /**
  11656. * @return {module:zrender/core/PathProxy}
  11657. */
  11658. closePath: function () {
  11659. this.addData(CMD.Z);
  11660. var ctx = this._ctx;
  11661. var x0 = this._x0;
  11662. var y0 = this._y0;
  11663. if (ctx) {
  11664. this._needsDash() && this._dashedLineTo(x0, y0);
  11665. ctx.closePath();
  11666. }
  11667. this._xi = x0;
  11668. this._yi = y0;
  11669. return this;
  11670. },
  11671. /**
  11672. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11673. * stroke 同样
  11674. * @param {CanvasRenderingContext2D} ctx
  11675. * @return {module:zrender/core/PathProxy}
  11676. */
  11677. fill: function (ctx) {
  11678. ctx && ctx.fill();
  11679. this.toStatic();
  11680. },
  11681. /**
  11682. * @param {CanvasRenderingContext2D} ctx
  11683. * @return {module:zrender/core/PathProxy}
  11684. */
  11685. stroke: function (ctx) {
  11686. ctx && ctx.stroke();
  11687. this.toStatic();
  11688. },
  11689. /**
  11690. * 必须在其它绘制命令前调用
  11691. * Must be invoked before all other path drawing methods
  11692. * @return {module:zrender/core/PathProxy}
  11693. */
  11694. setLineDash: function (lineDash) {
  11695. if (lineDash instanceof Array) {
  11696. this._lineDash = lineDash;
  11697. this._dashIdx = 0;
  11698. var lineDashSum = 0;
  11699. for (var i = 0; i < lineDash.length; i++) {
  11700. lineDashSum += lineDash[i];
  11701. }
  11702. this._dashSum = lineDashSum;
  11703. }
  11704. return this;
  11705. },
  11706. /**
  11707. * 必须在其它绘制命令前调用
  11708. * Must be invoked before all other path drawing methods
  11709. * @return {module:zrender/core/PathProxy}
  11710. */
  11711. setLineDashOffset: function (offset) {
  11712. this._dashOffset = offset;
  11713. return this;
  11714. },
  11715. /**
  11716. *
  11717. * @return {boolean}
  11718. */
  11719. len: function () {
  11720. return this._len;
  11721. },
  11722. /**
  11723. * 直接设置 Path 数据
  11724. */
  11725. setData: function (data) {
  11726. var len$$1 = data.length;
  11727. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11728. this.data = new Float32Array(len$$1);
  11729. }
  11730. for (var i = 0; i < len$$1; i++) {
  11731. this.data[i] = data[i];
  11732. }
  11733. this._len = len$$1;
  11734. },
  11735. /**
  11736. * 添加子路径
  11737. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11738. */
  11739. appendPath: function (path) {
  11740. if (!(path instanceof Array)) {
  11741. path = [path];
  11742. }
  11743. var len$$1 = path.length;
  11744. var appendSize = 0;
  11745. var offset = this._len;
  11746. for (var i = 0; i < len$$1; i++) {
  11747. appendSize += path[i].len();
  11748. }
  11749. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11750. this.data = new Float32Array(offset + appendSize);
  11751. }
  11752. for (var i = 0; i < len$$1; i++) {
  11753. var appendPathData = path[i].data;
  11754. for (var k = 0; k < appendPathData.length; k++) {
  11755. this.data[offset++] = appendPathData[k];
  11756. }
  11757. }
  11758. this._len = offset;
  11759. },
  11760. /**
  11761. * 填充 Path 数据。
  11762. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11763. */
  11764. addData: function (cmd) {
  11765. if (!this._saveData) {
  11766. return;
  11767. }
  11768. var data = this.data;
  11769. if (this._len + arguments.length > data.length) {
  11770. // 因为之前的数组已经转换成静态的 Float32Array
  11771. // 所以不够用时需要扩展一个新的动态数组
  11772. this._expandData();
  11773. data = this.data;
  11774. }
  11775. for (var i = 0; i < arguments.length; i++) {
  11776. data[this._len++] = arguments[i];
  11777. }
  11778. this._prevCmd = cmd;
  11779. },
  11780. _expandData: function () {
  11781. // Only if data is Float32Array
  11782. if (!(this.data instanceof Array)) {
  11783. var newData = [];
  11784. for (var i = 0; i < this._len; i++) {
  11785. newData[i] = this.data[i];
  11786. }
  11787. this.data = newData;
  11788. }
  11789. },
  11790. /**
  11791. * If needs js implemented dashed line
  11792. * @return {boolean}
  11793. * @private
  11794. */
  11795. _needsDash: function () {
  11796. return this._lineDash;
  11797. },
  11798. _dashedLineTo: function (x1, y1) {
  11799. var dashSum = this._dashSum;
  11800. var offset = this._dashOffset;
  11801. var lineDash = this._lineDash;
  11802. var ctx = this._ctx;
  11803. var x0 = this._xi;
  11804. var y0 = this._yi;
  11805. var dx = x1 - x0;
  11806. var dy = y1 - y0;
  11807. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11808. var x = x0;
  11809. var y = y0;
  11810. var dash;
  11811. var nDash = lineDash.length;
  11812. var idx;
  11813. dx /= dist$$1;
  11814. dy /= dist$$1;
  11815. if (offset < 0) {
  11816. // Convert to positive offset
  11817. offset = dashSum + offset;
  11818. }
  11819. offset %= dashSum;
  11820. x -= offset * dx;
  11821. y -= offset * dy;
  11822. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11823. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11824. idx = this._dashIdx;
  11825. dash = lineDash[idx];
  11826. x += dx * dash;
  11827. y += dy * dash;
  11828. this._dashIdx = (idx + 1) % nDash;
  11829. // Skip positive offset
  11830. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11831. continue;
  11832. }
  11833. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11834. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11835. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11836. );
  11837. }
  11838. // Offset for next lineTo
  11839. dx = x - x1;
  11840. dy = y - y1;
  11841. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11842. },
  11843. // Not accurate dashed line to
  11844. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11845. var dashSum = this._dashSum;
  11846. var offset = this._dashOffset;
  11847. var lineDash = this._lineDash;
  11848. var ctx = this._ctx;
  11849. var x0 = this._xi;
  11850. var y0 = this._yi;
  11851. var t;
  11852. var dx;
  11853. var dy;
  11854. var cubicAt$$1 = cubicAt;
  11855. var bezierLen = 0;
  11856. var idx = this._dashIdx;
  11857. var nDash = lineDash.length;
  11858. var x;
  11859. var y;
  11860. var tmpLen = 0;
  11861. if (offset < 0) {
  11862. // Convert to positive offset
  11863. offset = dashSum + offset;
  11864. }
  11865. offset %= dashSum;
  11866. // Bezier approx length
  11867. for (t = 0; t < 1; t += 0.1) {
  11868. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11869. - cubicAt$$1(x0, x1, x2, x3, t);
  11870. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11871. - cubicAt$$1(y0, y1, y2, y3, t);
  11872. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11873. }
  11874. // Find idx after add offset
  11875. for (; idx < nDash; idx++) {
  11876. tmpLen += lineDash[idx];
  11877. if (tmpLen > offset) {
  11878. break;
  11879. }
  11880. }
  11881. t = (tmpLen - offset) / bezierLen;
  11882. while (t <= 1) {
  11883. x = cubicAt$$1(x0, x1, x2, x3, t);
  11884. y = cubicAt$$1(y0, y1, y2, y3, t);
  11885. // Use line to approximate dashed bezier
  11886. // Bad result if dash is long
  11887. idx % 2 ? ctx.moveTo(x, y)
  11888. : ctx.lineTo(x, y);
  11889. t += lineDash[idx] / bezierLen;
  11890. idx = (idx + 1) % nDash;
  11891. }
  11892. // Finish the last segment and calculate the new offset
  11893. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11894. dx = x3 - x;
  11895. dy = y3 - y;
  11896. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11897. },
  11898. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11899. // Convert quadratic to cubic using degree elevation
  11900. var x3 = x2;
  11901. var y3 = y2;
  11902. x2 = (x2 + 2 * x1) / 3;
  11903. y2 = (y2 + 2 * y1) / 3;
  11904. x1 = (this._xi + 2 * x1) / 3;
  11905. y1 = (this._yi + 2 * y1) / 3;
  11906. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11907. },
  11908. /**
  11909. * 转成静态的 Float32Array 减少堆内存占用
  11910. * Convert dynamic array to static Float32Array
  11911. */
  11912. toStatic: function () {
  11913. var data = this.data;
  11914. if (data instanceof Array) {
  11915. data.length = this._len;
  11916. if (hasTypedArray) {
  11917. this.data = new Float32Array(data);
  11918. }
  11919. }
  11920. },
  11921. /**
  11922. * @return {module:zrender/core/BoundingRect}
  11923. */
  11924. getBoundingRect: function () {
  11925. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11926. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11927. var data = this.data;
  11928. var xi = 0;
  11929. var yi = 0;
  11930. var x0 = 0;
  11931. var y0 = 0;
  11932. for (var i = 0; i < data.length;) {
  11933. var cmd = data[i++];
  11934. if (i === 1) {
  11935. // 如果第一个命令是 L, C, Q
  11936. // 则 previous point 同绘制命令的第一个 point
  11937. //
  11938. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11939. xi = data[i];
  11940. yi = data[i + 1];
  11941. x0 = xi;
  11942. y0 = yi;
  11943. }
  11944. switch (cmd) {
  11945. case CMD.M:
  11946. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11947. // 在 closePath 的时候使用
  11948. x0 = data[i++];
  11949. y0 = data[i++];
  11950. xi = x0;
  11951. yi = y0;
  11952. min2[0] = x0;
  11953. min2[1] = y0;
  11954. max2[0] = x0;
  11955. max2[1] = y0;
  11956. break;
  11957. case CMD.L:
  11958. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11959. xi = data[i++];
  11960. yi = data[i++];
  11961. break;
  11962. case CMD.C:
  11963. fromCubic(
  11964. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11965. min2, max2
  11966. );
  11967. xi = data[i++];
  11968. yi = data[i++];
  11969. break;
  11970. case CMD.Q:
  11971. fromQuadratic(
  11972. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11973. min2, max2
  11974. );
  11975. xi = data[i++];
  11976. yi = data[i++];
  11977. break;
  11978. case CMD.A:
  11979. // TODO Arc 判断的开销比较大
  11980. var cx = data[i++];
  11981. var cy = data[i++];
  11982. var rx = data[i++];
  11983. var ry = data[i++];
  11984. var startAngle = data[i++];
  11985. var endAngle = data[i++] + startAngle;
  11986. // TODO Arc 旋转
  11987. i += 1;
  11988. var anticlockwise = 1 - data[i++];
  11989. if (i === 1) {
  11990. // 直接使用 arc 命令
  11991. // 第一个命令起点还未定义
  11992. x0 = mathCos$1(startAngle) * rx + cx;
  11993. y0 = mathSin$1(startAngle) * ry + cy;
  11994. }
  11995. fromArc(
  11996. cx, cy, rx, ry, startAngle, endAngle,
  11997. anticlockwise, min2, max2
  11998. );
  11999. xi = mathCos$1(endAngle) * rx + cx;
  12000. yi = mathSin$1(endAngle) * ry + cy;
  12001. break;
  12002. case CMD.R:
  12003. x0 = xi = data[i++];
  12004. y0 = yi = data[i++];
  12005. var width = data[i++];
  12006. var height = data[i++];
  12007. // Use fromLine
  12008. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12009. break;
  12010. case CMD.Z:
  12011. xi = x0;
  12012. yi = y0;
  12013. break;
  12014. }
  12015. // Union
  12016. min(min$1, min$1, min2);
  12017. max(max$1, max$1, max2);
  12018. }
  12019. // No data
  12020. if (i === 0) {
  12021. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12022. }
  12023. return new BoundingRect(
  12024. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12025. );
  12026. },
  12027. /**
  12028. * Rebuild path from current data
  12029. * Rebuild path will not consider javascript implemented line dash.
  12030. * @param {CanvasRenderingContext2D} ctx
  12031. */
  12032. rebuildPath: function (ctx) {
  12033. var d = this.data;
  12034. var x0;
  12035. var y0;
  12036. var xi;
  12037. var yi;
  12038. var x;
  12039. var y;
  12040. var ux = this._ux;
  12041. var uy = this._uy;
  12042. var len$$1 = this._len;
  12043. for (var i = 0; i < len$$1;) {
  12044. var cmd = d[i++];
  12045. if (i === 1) {
  12046. // 如果第一个命令是 L, C, Q
  12047. // 则 previous point 同绘制命令的第一个 point
  12048. //
  12049. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12050. xi = d[i];
  12051. yi = d[i + 1];
  12052. x0 = xi;
  12053. y0 = yi;
  12054. }
  12055. switch (cmd) {
  12056. case CMD.M:
  12057. x0 = xi = d[i++];
  12058. y0 = yi = d[i++];
  12059. ctx.moveTo(xi, yi);
  12060. break;
  12061. case CMD.L:
  12062. x = d[i++];
  12063. y = d[i++];
  12064. // Not draw too small seg between
  12065. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12066. ctx.lineTo(x, y);
  12067. xi = x;
  12068. yi = y;
  12069. }
  12070. break;
  12071. case CMD.C:
  12072. ctx.bezierCurveTo(
  12073. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12074. );
  12075. xi = d[i - 2];
  12076. yi = d[i - 1];
  12077. break;
  12078. case CMD.Q:
  12079. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12080. xi = d[i - 2];
  12081. yi = d[i - 1];
  12082. break;
  12083. case CMD.A:
  12084. var cx = d[i++];
  12085. var cy = d[i++];
  12086. var rx = d[i++];
  12087. var ry = d[i++];
  12088. var theta = d[i++];
  12089. var dTheta = d[i++];
  12090. var psi = d[i++];
  12091. var fs = d[i++];
  12092. var r = (rx > ry) ? rx : ry;
  12093. var scaleX = (rx > ry) ? 1 : rx / ry;
  12094. var scaleY = (rx > ry) ? ry / rx : 1;
  12095. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12096. var endAngle = theta + dTheta;
  12097. if (isEllipse) {
  12098. ctx.translate(cx, cy);
  12099. ctx.rotate(psi);
  12100. ctx.scale(scaleX, scaleY);
  12101. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12102. ctx.scale(1 / scaleX, 1 / scaleY);
  12103. ctx.rotate(-psi);
  12104. ctx.translate(-cx, -cy);
  12105. }
  12106. else {
  12107. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12108. }
  12109. if (i === 1) {
  12110. // 直接使用 arc 命令
  12111. // 第一个命令起点还未定义
  12112. x0 = mathCos$1(theta) * rx + cx;
  12113. y0 = mathSin$1(theta) * ry + cy;
  12114. }
  12115. xi = mathCos$1(endAngle) * rx + cx;
  12116. yi = mathSin$1(endAngle) * ry + cy;
  12117. break;
  12118. case CMD.R:
  12119. x0 = xi = d[i];
  12120. y0 = yi = d[i + 1];
  12121. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12122. break;
  12123. case CMD.Z:
  12124. ctx.closePath();
  12125. xi = x0;
  12126. yi = y0;
  12127. }
  12128. }
  12129. }
  12130. };
  12131. PathProxy.CMD = CMD;
  12132. /**
  12133. * 线段包含判断
  12134. * @param {number} x0
  12135. * @param {number} y0
  12136. * @param {number} x1
  12137. * @param {number} y1
  12138. * @param {number} lineWidth
  12139. * @param {number} x
  12140. * @param {number} y
  12141. * @return {boolean}
  12142. */
  12143. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12144. if (lineWidth === 0) {
  12145. return false;
  12146. }
  12147. var _l = lineWidth;
  12148. var _a = 0;
  12149. var _b = x0;
  12150. // Quick reject
  12151. if (
  12152. (y > y0 + _l && y > y1 + _l)
  12153. || (y < y0 - _l && y < y1 - _l)
  12154. || (x > x0 + _l && x > x1 + _l)
  12155. || (x < x0 - _l && x < x1 - _l)
  12156. ) {
  12157. return false;
  12158. }
  12159. if (x0 !== x1) {
  12160. _a = (y0 - y1) / (x0 - x1);
  12161. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12162. }
  12163. else {
  12164. return Math.abs(x - x0) <= _l / 2;
  12165. }
  12166. var tmp = _a * x - y + _b;
  12167. var _s = tmp * tmp / (_a * _a + 1);
  12168. return _s <= _l / 2 * _l / 2;
  12169. }
  12170. /**
  12171. * 三次贝塞尔曲线描边包含判断
  12172. * @param {number} x0
  12173. * @param {number} y0
  12174. * @param {number} x1
  12175. * @param {number} y1
  12176. * @param {number} x2
  12177. * @param {number} y2
  12178. * @param {number} x3
  12179. * @param {number} y3
  12180. * @param {number} lineWidth
  12181. * @param {number} x
  12182. * @param {number} y
  12183. * @return {boolean}
  12184. */
  12185. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12186. if (lineWidth === 0) {
  12187. return false;
  12188. }
  12189. var _l = lineWidth;
  12190. // Quick reject
  12191. if (
  12192. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12193. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12194. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12195. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12196. ) {
  12197. return false;
  12198. }
  12199. var d = cubicProjectPoint(
  12200. x0, y0, x1, y1, x2, y2, x3, y3,
  12201. x, y, null
  12202. );
  12203. return d <= _l / 2;
  12204. }
  12205. /**
  12206. * 二次贝塞尔曲线描边包含判断
  12207. * @param {number} x0
  12208. * @param {number} y0
  12209. * @param {number} x1
  12210. * @param {number} y1
  12211. * @param {number} x2
  12212. * @param {number} y2
  12213. * @param {number} lineWidth
  12214. * @param {number} x
  12215. * @param {number} y
  12216. * @return {boolean}
  12217. */
  12218. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12219. if (lineWidth === 0) {
  12220. return false;
  12221. }
  12222. var _l = lineWidth;
  12223. // Quick reject
  12224. if (
  12225. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12226. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12227. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12228. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12229. ) {
  12230. return false;
  12231. }
  12232. var d = quadraticProjectPoint(
  12233. x0, y0, x1, y1, x2, y2,
  12234. x, y, null
  12235. );
  12236. return d <= _l / 2;
  12237. }
  12238. var PI2$3 = Math.PI * 2;
  12239. function normalizeRadian(angle) {
  12240. angle %= PI2$3;
  12241. if (angle < 0) {
  12242. angle += PI2$3;
  12243. }
  12244. return angle;
  12245. }
  12246. var PI2$2 = Math.PI * 2;
  12247. /**
  12248. * 圆弧描边包含判断
  12249. * @param {number} cx
  12250. * @param {number} cy
  12251. * @param {number} r
  12252. * @param {number} startAngle
  12253. * @param {number} endAngle
  12254. * @param {boolean} anticlockwise
  12255. * @param {number} lineWidth
  12256. * @param {number} x
  12257. * @param {number} y
  12258. * @return {Boolean}
  12259. */
  12260. function containStroke$4(
  12261. cx, cy, r, startAngle, endAngle, anticlockwise,
  12262. lineWidth, x, y
  12263. ) {
  12264. if (lineWidth === 0) {
  12265. return false;
  12266. }
  12267. var _l = lineWidth;
  12268. x -= cx;
  12269. y -= cy;
  12270. var d = Math.sqrt(x * x + y * y);
  12271. if ((d - _l > r) || (d + _l < r)) {
  12272. return false;
  12273. }
  12274. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12275. // Is a circle
  12276. return true;
  12277. }
  12278. if (anticlockwise) {
  12279. var tmp = startAngle;
  12280. startAngle = normalizeRadian(endAngle);
  12281. endAngle = normalizeRadian(tmp);
  12282. }
  12283. else {
  12284. startAngle = normalizeRadian(startAngle);
  12285. endAngle = normalizeRadian(endAngle);
  12286. }
  12287. if (startAngle > endAngle) {
  12288. endAngle += PI2$2;
  12289. }
  12290. var angle = Math.atan2(y, x);
  12291. if (angle < 0) {
  12292. angle += PI2$2;
  12293. }
  12294. return (angle >= startAngle && angle <= endAngle)
  12295. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12296. }
  12297. function windingLine(x0, y0, x1, y1, x, y) {
  12298. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12299. return 0;
  12300. }
  12301. // Ignore horizontal line
  12302. if (y1 === y0) {
  12303. return 0;
  12304. }
  12305. var dir = y1 < y0 ? 1 : -1;
  12306. var t = (y - y0) / (y1 - y0);
  12307. // Avoid winding error when intersection point is the connect point of two line of polygon
  12308. if (t === 1 || t === 0) {
  12309. dir = y1 < y0 ? 0.5 : -0.5;
  12310. }
  12311. var x_ = t * (x1 - x0) + x0;
  12312. // If (x, y) on the line, considered as "contain".
  12313. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12314. }
  12315. var CMD$1 = PathProxy.CMD;
  12316. var PI2$1 = Math.PI * 2;
  12317. var EPSILON$2 = 1e-4;
  12318. function isAroundEqual(a, b) {
  12319. return Math.abs(a - b) < EPSILON$2;
  12320. }
  12321. // 临时数组
  12322. var roots = [-1, -1, -1];
  12323. var extrema = [-1, -1];
  12324. function swapExtrema() {
  12325. var tmp = extrema[0];
  12326. extrema[0] = extrema[1];
  12327. extrema[1] = tmp;
  12328. }
  12329. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12330. // Quick reject
  12331. if (
  12332. (y > y0 && y > y1 && y > y2 && y > y3)
  12333. || (y < y0 && y < y1 && y < y2 && y < y3)
  12334. ) {
  12335. return 0;
  12336. }
  12337. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12338. if (nRoots === 0) {
  12339. return 0;
  12340. }
  12341. else {
  12342. var w = 0;
  12343. var nExtrema = -1;
  12344. var y0_;
  12345. var y1_;
  12346. for (var i = 0; i < nRoots; i++) {
  12347. var t = roots[i];
  12348. // Avoid winding error when intersection point is the connect point of two line of polygon
  12349. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12350. var x_ = cubicAt(x0, x1, x2, x3, t);
  12351. if (x_ < x) { // Quick reject
  12352. continue;
  12353. }
  12354. if (nExtrema < 0) {
  12355. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12356. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12357. swapExtrema();
  12358. }
  12359. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12360. if (nExtrema > 1) {
  12361. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12362. }
  12363. }
  12364. if (nExtrema === 2) {
  12365. // 分成三段单调函数
  12366. if (t < extrema[0]) {
  12367. w += y0_ < y0 ? unit : -unit;
  12368. }
  12369. else if (t < extrema[1]) {
  12370. w += y1_ < y0_ ? unit : -unit;
  12371. }
  12372. else {
  12373. w += y3 < y1_ ? unit : -unit;
  12374. }
  12375. }
  12376. else {
  12377. // 分成两段单调函数
  12378. if (t < extrema[0]) {
  12379. w += y0_ < y0 ? unit : -unit;
  12380. }
  12381. else {
  12382. w += y3 < y0_ ? unit : -unit;
  12383. }
  12384. }
  12385. }
  12386. return w;
  12387. }
  12388. }
  12389. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12390. // Quick reject
  12391. if (
  12392. (y > y0 && y > y1 && y > y2)
  12393. || (y < y0 && y < y1 && y < y2)
  12394. ) {
  12395. return 0;
  12396. }
  12397. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12398. if (nRoots === 0) {
  12399. return 0;
  12400. }
  12401. else {
  12402. var t = quadraticExtremum(y0, y1, y2);
  12403. if (t >= 0 && t <= 1) {
  12404. var w = 0;
  12405. var y_ = quadraticAt(y0, y1, y2, t);
  12406. for (var i = 0; i < nRoots; i++) {
  12407. // Remove one endpoint.
  12408. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12409. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12410. if (x_ < x) { // Quick reject
  12411. continue;
  12412. }
  12413. if (roots[i] < t) {
  12414. w += y_ < y0 ? unit : -unit;
  12415. }
  12416. else {
  12417. w += y2 < y_ ? unit : -unit;
  12418. }
  12419. }
  12420. return w;
  12421. }
  12422. else {
  12423. // Remove one endpoint.
  12424. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12425. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12426. if (x_ < x) { // Quick reject
  12427. return 0;
  12428. }
  12429. return y2 < y0 ? unit : -unit;
  12430. }
  12431. }
  12432. }
  12433. // TODO
  12434. // Arc 旋转
  12435. function windingArc(
  12436. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12437. ) {
  12438. y -= cy;
  12439. if (y > r || y < -r) {
  12440. return 0;
  12441. }
  12442. var tmp = Math.sqrt(r * r - y * y);
  12443. roots[0] = -tmp;
  12444. roots[1] = tmp;
  12445. var diff = Math.abs(startAngle - endAngle);
  12446. if (diff < 1e-4) {
  12447. return 0;
  12448. }
  12449. if (diff % PI2$1 < 1e-4) {
  12450. // Is a circle
  12451. startAngle = 0;
  12452. endAngle = PI2$1;
  12453. var dir = anticlockwise ? 1 : -1;
  12454. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12455. return dir;
  12456. }
  12457. else {
  12458. return 0;
  12459. }
  12460. }
  12461. if (anticlockwise) {
  12462. var tmp = startAngle;
  12463. startAngle = normalizeRadian(endAngle);
  12464. endAngle = normalizeRadian(tmp);
  12465. }
  12466. else {
  12467. startAngle = normalizeRadian(startAngle);
  12468. endAngle = normalizeRadian(endAngle);
  12469. }
  12470. if (startAngle > endAngle) {
  12471. endAngle += PI2$1;
  12472. }
  12473. var w = 0;
  12474. for (var i = 0; i < 2; i++) {
  12475. var x_ = roots[i];
  12476. if (x_ + cx > x) {
  12477. var angle = Math.atan2(y, x_);
  12478. var dir = anticlockwise ? 1 : -1;
  12479. if (angle < 0) {
  12480. angle = PI2$1 + angle;
  12481. }
  12482. if (
  12483. (angle >= startAngle && angle <= endAngle)
  12484. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12485. ) {
  12486. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12487. dir = -dir;
  12488. }
  12489. w += dir;
  12490. }
  12491. }
  12492. }
  12493. return w;
  12494. }
  12495. function containPath(data, lineWidth, isStroke, x, y) {
  12496. var w = 0;
  12497. var xi = 0;
  12498. var yi = 0;
  12499. var x0 = 0;
  12500. var y0 = 0;
  12501. for (var i = 0; i < data.length;) {
  12502. var cmd = data[i++];
  12503. // Begin a new subpath
  12504. if (cmd === CMD$1.M && i > 1) {
  12505. // Close previous subpath
  12506. if (!isStroke) {
  12507. w += windingLine(xi, yi, x0, y0, x, y);
  12508. }
  12509. // 如果被任何一个 subpath 包含
  12510. // if (w !== 0) {
  12511. // return true;
  12512. // }
  12513. }
  12514. if (i === 1) {
  12515. // 如果第一个命令是 L, C, Q
  12516. // 则 previous point 同绘制命令的第一个 point
  12517. //
  12518. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12519. xi = data[i];
  12520. yi = data[i + 1];
  12521. x0 = xi;
  12522. y0 = yi;
  12523. }
  12524. switch (cmd) {
  12525. case CMD$1.M:
  12526. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12527. // 在 closePath 的时候使用
  12528. x0 = data[i++];
  12529. y0 = data[i++];
  12530. xi = x0;
  12531. yi = y0;
  12532. break;
  12533. case CMD$1.L:
  12534. if (isStroke) {
  12535. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12536. return true;
  12537. }
  12538. }
  12539. else {
  12540. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12541. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12542. }
  12543. xi = data[i++];
  12544. yi = data[i++];
  12545. break;
  12546. case CMD$1.C:
  12547. if (isStroke) {
  12548. if (containStroke$2(xi, yi,
  12549. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12550. lineWidth, x, y
  12551. )) {
  12552. return true;
  12553. }
  12554. }
  12555. else {
  12556. w += windingCubic(
  12557. xi, yi,
  12558. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12559. x, y
  12560. ) || 0;
  12561. }
  12562. xi = data[i++];
  12563. yi = data[i++];
  12564. break;
  12565. case CMD$1.Q:
  12566. if (isStroke) {
  12567. if (containStroke$3(xi, yi,
  12568. data[i++], data[i++], data[i], data[i + 1],
  12569. lineWidth, x, y
  12570. )) {
  12571. return true;
  12572. }
  12573. }
  12574. else {
  12575. w += windingQuadratic(
  12576. xi, yi,
  12577. data[i++], data[i++], data[i], data[i + 1],
  12578. x, y
  12579. ) || 0;
  12580. }
  12581. xi = data[i++];
  12582. yi = data[i++];
  12583. break;
  12584. case CMD$1.A:
  12585. // TODO Arc 判断的开销比较大
  12586. var cx = data[i++];
  12587. var cy = data[i++];
  12588. var rx = data[i++];
  12589. var ry = data[i++];
  12590. var theta = data[i++];
  12591. var dTheta = data[i++];
  12592. // TODO Arc 旋转
  12593. i += 1;
  12594. var anticlockwise = 1 - data[i++];
  12595. var x1 = Math.cos(theta) * rx + cx;
  12596. var y1 = Math.sin(theta) * ry + cy;
  12597. // 不是直接使用 arc 命令
  12598. if (i > 1) {
  12599. w += windingLine(xi, yi, x1, y1, x, y);
  12600. }
  12601. else {
  12602. // 第一个命令起点还未定义
  12603. x0 = x1;
  12604. y0 = y1;
  12605. }
  12606. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12607. var _x = (x - cx) * ry / rx + cx;
  12608. if (isStroke) {
  12609. if (containStroke$4(
  12610. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12611. lineWidth, _x, y
  12612. )) {
  12613. return true;
  12614. }
  12615. }
  12616. else {
  12617. w += windingArc(
  12618. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12619. _x, y
  12620. );
  12621. }
  12622. xi = Math.cos(theta + dTheta) * rx + cx;
  12623. yi = Math.sin(theta + dTheta) * ry + cy;
  12624. break;
  12625. case CMD$1.R:
  12626. x0 = xi = data[i++];
  12627. y0 = yi = data[i++];
  12628. var width = data[i++];
  12629. var height = data[i++];
  12630. var x1 = x0 + width;
  12631. var y1 = y0 + height;
  12632. if (isStroke) {
  12633. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12634. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12635. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12636. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12637. ) {
  12638. return true;
  12639. }
  12640. }
  12641. else {
  12642. // FIXME Clockwise ?
  12643. w += windingLine(x1, y0, x1, y1, x, y);
  12644. w += windingLine(x0, y1, x0, y0, x, y);
  12645. }
  12646. break;
  12647. case CMD$1.Z:
  12648. if (isStroke) {
  12649. if (containStroke$1(
  12650. xi, yi, x0, y0, lineWidth, x, y
  12651. )) {
  12652. return true;
  12653. }
  12654. }
  12655. else {
  12656. // Close a subpath
  12657. w += windingLine(xi, yi, x0, y0, x, y);
  12658. // 如果被任何一个 subpath 包含
  12659. // FIXME subpaths may overlap
  12660. // if (w !== 0) {
  12661. // return true;
  12662. // }
  12663. }
  12664. xi = x0;
  12665. yi = y0;
  12666. break;
  12667. }
  12668. }
  12669. if (!isStroke && !isAroundEqual(yi, y0)) {
  12670. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12671. }
  12672. return w !== 0;
  12673. }
  12674. function contain(pathData, x, y) {
  12675. return containPath(pathData, 0, false, x, y);
  12676. }
  12677. function containStroke(pathData, lineWidth, x, y) {
  12678. return containPath(pathData, lineWidth, true, x, y);
  12679. }
  12680. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12681. var abs = Math.abs;
  12682. var pathProxyForDraw = new PathProxy(true);
  12683. /**
  12684. * @alias module:zrender/graphic/Path
  12685. * @extends module:zrender/graphic/Displayable
  12686. * @constructor
  12687. * @param {Object} opts
  12688. */
  12689. function Path(opts) {
  12690. Displayable.call(this, opts);
  12691. /**
  12692. * @type {module:zrender/core/PathProxy}
  12693. * @readOnly
  12694. */
  12695. this.path = null;
  12696. }
  12697. Path.prototype = {
  12698. constructor: Path,
  12699. type: 'path',
  12700. __dirtyPath: true,
  12701. strokeContainThreshold: 5,
  12702. // This item default to be false. But in map series in echarts,
  12703. // in order to improve performance, it should be set to true,
  12704. // so the shorty segment won't draw.
  12705. segmentIgnoreThreshold: 0,
  12706. /**
  12707. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12708. * @type {boolean}
  12709. */
  12710. subPixelOptimize: false,
  12711. brush: function (ctx, prevEl) {
  12712. var style = this.style;
  12713. var path = this.path || pathProxyForDraw;
  12714. var hasStroke = style.hasStroke();
  12715. var hasFill = style.hasFill();
  12716. var fill = style.fill;
  12717. var stroke = style.stroke;
  12718. var hasFillGradient = hasFill && !!(fill.colorStops);
  12719. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12720. var hasFillPattern = hasFill && !!(fill.image);
  12721. var hasStrokePattern = hasStroke && !!(stroke.image);
  12722. style.bind(ctx, this, prevEl);
  12723. this.setTransform(ctx);
  12724. if (this.__dirty) {
  12725. var rect;
  12726. // Update gradient because bounding rect may changed
  12727. if (hasFillGradient) {
  12728. rect = rect || this.getBoundingRect();
  12729. this._fillGradient = style.getGradient(ctx, fill, rect);
  12730. }
  12731. if (hasStrokeGradient) {
  12732. rect = rect || this.getBoundingRect();
  12733. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12734. }
  12735. }
  12736. // Use the gradient or pattern
  12737. if (hasFillGradient) {
  12738. // PENDING If may have affect the state
  12739. ctx.fillStyle = this._fillGradient;
  12740. }
  12741. else if (hasFillPattern) {
  12742. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12743. }
  12744. if (hasStrokeGradient) {
  12745. ctx.strokeStyle = this._strokeGradient;
  12746. }
  12747. else if (hasStrokePattern) {
  12748. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12749. }
  12750. var lineDash = style.lineDash;
  12751. var lineDashOffset = style.lineDashOffset;
  12752. var ctxLineDash = !!ctx.setLineDash;
  12753. // Update path sx, sy
  12754. var scale = this.getGlobalScale();
  12755. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  12756. // Proxy context
  12757. // Rebuild path in following 2 cases
  12758. // 1. Path is dirty
  12759. // 2. Path needs javascript implemented lineDash stroking.
  12760. // In this case, lineDash information will not be saved in PathProxy
  12761. if (this.__dirtyPath
  12762. || (lineDash && !ctxLineDash && hasStroke)
  12763. ) {
  12764. path.beginPath(ctx);
  12765. // Setting line dash before build path
  12766. if (lineDash && !ctxLineDash) {
  12767. path.setLineDash(lineDash);
  12768. path.setLineDashOffset(lineDashOffset);
  12769. }
  12770. this.buildPath(path, this.shape, false);
  12771. // Clear path dirty flag
  12772. if (this.path) {
  12773. this.__dirtyPath = false;
  12774. }
  12775. }
  12776. else {
  12777. // Replay path building
  12778. ctx.beginPath();
  12779. this.path.rebuildPath(ctx);
  12780. }
  12781. if (hasFill) {
  12782. if (style.fillOpacity != null) {
  12783. var originalGlobalAlpha = ctx.globalAlpha;
  12784. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12785. path.fill(ctx);
  12786. ctx.globalAlpha = originalGlobalAlpha;
  12787. }
  12788. else {
  12789. path.fill(ctx);
  12790. }
  12791. }
  12792. if (lineDash && ctxLineDash) {
  12793. ctx.setLineDash(lineDash);
  12794. ctx.lineDashOffset = lineDashOffset;
  12795. }
  12796. if (hasStroke) {
  12797. if (style.strokeOpacity != null) {
  12798. var originalGlobalAlpha = ctx.globalAlpha;
  12799. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12800. path.stroke(ctx);
  12801. ctx.globalAlpha = originalGlobalAlpha;
  12802. }
  12803. else {
  12804. path.stroke(ctx);
  12805. }
  12806. }
  12807. if (lineDash && ctxLineDash) {
  12808. // PENDING
  12809. // Remove lineDash
  12810. ctx.setLineDash([]);
  12811. }
  12812. // Draw rect text
  12813. if (style.text != null) {
  12814. // Only restore transform when needs draw text.
  12815. this.restoreTransform(ctx);
  12816. this.drawRectText(ctx, this.getBoundingRect());
  12817. }
  12818. },
  12819. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12820. // Like in circle
  12821. buildPath: function (ctx, shapeCfg, inBundle) {},
  12822. createPathProxy: function () {
  12823. this.path = new PathProxy();
  12824. },
  12825. getBoundingRect: function () {
  12826. var rect = this._rect;
  12827. var style = this.style;
  12828. var needsUpdateRect = !rect;
  12829. if (needsUpdateRect) {
  12830. var path = this.path;
  12831. if (!path) {
  12832. // Create path on demand.
  12833. path = this.path = new PathProxy();
  12834. }
  12835. if (this.__dirtyPath) {
  12836. path.beginPath();
  12837. this.buildPath(path, this.shape, false);
  12838. }
  12839. rect = path.getBoundingRect();
  12840. }
  12841. this._rect = rect;
  12842. if (style.hasStroke()) {
  12843. // Needs update rect with stroke lineWidth when
  12844. // 1. Element changes scale or lineWidth
  12845. // 2. Shape is changed
  12846. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12847. if (this.__dirty || needsUpdateRect) {
  12848. rectWithStroke.copy(rect);
  12849. // FIXME Must after updateTransform
  12850. var w = style.lineWidth;
  12851. // PENDING, Min line width is needed when line is horizontal or vertical
  12852. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12853. // Only add extra hover lineWidth when there are no fill
  12854. if (!style.hasFill()) {
  12855. w = Math.max(w, this.strokeContainThreshold || 4);
  12856. }
  12857. // Consider line width
  12858. // Line scale can't be 0;
  12859. if (lineScale > 1e-10) {
  12860. rectWithStroke.width += w / lineScale;
  12861. rectWithStroke.height += w / lineScale;
  12862. rectWithStroke.x -= w / lineScale / 2;
  12863. rectWithStroke.y -= w / lineScale / 2;
  12864. }
  12865. }
  12866. // Return rect with stroke
  12867. return rectWithStroke;
  12868. }
  12869. return rect;
  12870. },
  12871. contain: function (x, y) {
  12872. var localPos = this.transformCoordToLocal(x, y);
  12873. var rect = this.getBoundingRect();
  12874. var style = this.style;
  12875. x = localPos[0];
  12876. y = localPos[1];
  12877. if (rect.contain(x, y)) {
  12878. var pathData = this.path.data;
  12879. if (style.hasStroke()) {
  12880. var lineWidth = style.lineWidth;
  12881. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12882. // Line scale can't be 0;
  12883. if (lineScale > 1e-10) {
  12884. // Only add extra hover lineWidth when there are no fill
  12885. if (!style.hasFill()) {
  12886. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12887. }
  12888. if (containStroke(
  12889. pathData, lineWidth / lineScale, x, y
  12890. )) {
  12891. return true;
  12892. }
  12893. }
  12894. }
  12895. if (style.hasFill()) {
  12896. return contain(pathData, x, y);
  12897. }
  12898. }
  12899. return false;
  12900. },
  12901. /**
  12902. * @param {boolean} dirtyPath
  12903. */
  12904. dirty: function (dirtyPath) {
  12905. if (dirtyPath == null) {
  12906. dirtyPath = true;
  12907. }
  12908. // Only mark dirty, not mark clean
  12909. if (dirtyPath) {
  12910. this.__dirtyPath = dirtyPath;
  12911. this._rect = null;
  12912. }
  12913. this.__dirty = this.__dirtyText = true;
  12914. this.__zr && this.__zr.refresh();
  12915. // Used as a clipping path
  12916. if (this.__clipTarget) {
  12917. this.__clipTarget.dirty();
  12918. }
  12919. },
  12920. /**
  12921. * Alias for animate('shape')
  12922. * @param {boolean} loop
  12923. */
  12924. animateShape: function (loop) {
  12925. return this.animate('shape', loop);
  12926. },
  12927. // Overwrite attrKV
  12928. attrKV: function (key, value) {
  12929. // FIXME
  12930. if (key === 'shape') {
  12931. this.setShape(value);
  12932. this.__dirtyPath = true;
  12933. this._rect = null;
  12934. }
  12935. else {
  12936. Displayable.prototype.attrKV.call(this, key, value);
  12937. }
  12938. },
  12939. /**
  12940. * @param {Object|string} key
  12941. * @param {*} value
  12942. */
  12943. setShape: function (key, value) {
  12944. var shape = this.shape;
  12945. // Path from string may not have shape
  12946. if (shape) {
  12947. if (isObject$1(key)) {
  12948. for (var name in key) {
  12949. if (key.hasOwnProperty(name)) {
  12950. shape[name] = key[name];
  12951. }
  12952. }
  12953. }
  12954. else {
  12955. shape[key] = value;
  12956. }
  12957. this.dirty(true);
  12958. }
  12959. return this;
  12960. },
  12961. getLineScale: function () {
  12962. var m = this.transform;
  12963. // Get the line scale.
  12964. // Determinant of `m` means how much the area is enlarged by the
  12965. // transformation. So its square root can be used as a scale factor
  12966. // for width.
  12967. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12968. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12969. : 1;
  12970. }
  12971. };
  12972. /**
  12973. * 扩展一个 Path element, 比如星形,圆等。
  12974. * Extend a path element
  12975. * @param {Object} props
  12976. * @param {string} props.type Path type
  12977. * @param {Function} props.init Initialize
  12978. * @param {Function} props.buildPath Overwrite buildPath method
  12979. * @param {Object} [props.style] Extended default style config
  12980. * @param {Object} [props.shape] Extended default shape config
  12981. */
  12982. Path.extend = function (defaults$$1) {
  12983. var Sub = function (opts) {
  12984. Path.call(this, opts);
  12985. if (defaults$$1.style) {
  12986. // Extend default style
  12987. this.style.extendFrom(defaults$$1.style, false);
  12988. }
  12989. // Extend default shape
  12990. var defaultShape = defaults$$1.shape;
  12991. if (defaultShape) {
  12992. this.shape = this.shape || {};
  12993. var thisShape = this.shape;
  12994. for (var name in defaultShape) {
  12995. if (
  12996. !thisShape.hasOwnProperty(name)
  12997. && defaultShape.hasOwnProperty(name)
  12998. ) {
  12999. thisShape[name] = defaultShape[name];
  13000. }
  13001. }
  13002. }
  13003. defaults$$1.init && defaults$$1.init.call(this, opts);
  13004. };
  13005. inherits(Sub, Path);
  13006. // FIXME 不能 extend position, rotation 等引用对象
  13007. for (var name in defaults$$1) {
  13008. // Extending prototype values and methods
  13009. if (name !== 'style' && name !== 'shape') {
  13010. Sub.prototype[name] = defaults$$1[name];
  13011. }
  13012. }
  13013. return Sub;
  13014. };
  13015. inherits(Path, Displayable);
  13016. var CMD$2 = PathProxy.CMD;
  13017. var points = [[], [], []];
  13018. var mathSqrt$3 = Math.sqrt;
  13019. var mathAtan2 = Math.atan2;
  13020. var transformPath = function (path, m) {
  13021. var data = path.data;
  13022. var cmd;
  13023. var nPoint;
  13024. var i;
  13025. var j;
  13026. var k;
  13027. var p;
  13028. var M = CMD$2.M;
  13029. var C = CMD$2.C;
  13030. var L = CMD$2.L;
  13031. var R = CMD$2.R;
  13032. var A = CMD$2.A;
  13033. var Q = CMD$2.Q;
  13034. for (i = 0, j = 0; i < data.length;) {
  13035. cmd = data[i++];
  13036. j = i;
  13037. nPoint = 0;
  13038. switch (cmd) {
  13039. case M:
  13040. nPoint = 1;
  13041. break;
  13042. case L:
  13043. nPoint = 1;
  13044. break;
  13045. case C:
  13046. nPoint = 3;
  13047. break;
  13048. case Q:
  13049. nPoint = 2;
  13050. break;
  13051. case A:
  13052. var x = m[4];
  13053. var y = m[5];
  13054. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13055. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13056. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13057. // cx
  13058. data[i] *= sx;
  13059. data[i++] += x;
  13060. // cy
  13061. data[i] *= sy;
  13062. data[i++] += y;
  13063. // Scale rx and ry
  13064. // FIXME Assume psi is 0 here
  13065. data[i++] *= sx;
  13066. data[i++] *= sy;
  13067. // Start angle
  13068. data[i++] += angle;
  13069. // end angle
  13070. data[i++] += angle;
  13071. // FIXME psi
  13072. i += 2;
  13073. j = i;
  13074. break;
  13075. case R:
  13076. // x0, y0
  13077. p[0] = data[i++];
  13078. p[1] = data[i++];
  13079. applyTransform(p, p, m);
  13080. data[j++] = p[0];
  13081. data[j++] = p[1];
  13082. // x1, y1
  13083. p[0] += data[i++];
  13084. p[1] += data[i++];
  13085. applyTransform(p, p, m);
  13086. data[j++] = p[0];
  13087. data[j++] = p[1];
  13088. }
  13089. for (k = 0; k < nPoint; k++) {
  13090. var p = points[k];
  13091. p[0] = data[i++];
  13092. p[1] = data[i++];
  13093. applyTransform(p, p, m);
  13094. // Write back
  13095. data[j++] = p[0];
  13096. data[j++] = p[1];
  13097. }
  13098. }
  13099. };
  13100. // command chars
  13101. // var cc = [
  13102. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13103. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13104. // ];
  13105. var mathSqrt = Math.sqrt;
  13106. var mathSin = Math.sin;
  13107. var mathCos = Math.cos;
  13108. var PI = Math.PI;
  13109. var vMag = function (v) {
  13110. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13111. };
  13112. var vRatio = function (u, v) {
  13113. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13114. };
  13115. var vAngle = function (u, v) {
  13116. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13117. * Math.acos(vRatio(u, v));
  13118. };
  13119. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13120. var psi = psiDeg * (PI / 180.0);
  13121. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13122. + mathSin(psi) * (y1 - y2) / 2.0;
  13123. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13124. + mathCos(psi) * (y1 - y2) / 2.0;
  13125. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13126. if (lambda > 1) {
  13127. rx *= mathSqrt(lambda);
  13128. ry *= mathSqrt(lambda);
  13129. }
  13130. var f = (fa === fs ? -1 : 1)
  13131. * mathSqrt((((rx * rx) * (ry * ry))
  13132. - ((rx * rx) * (yp * yp))
  13133. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13134. + (ry * ry) * (xp * xp))
  13135. ) || 0;
  13136. var cxp = f * rx * yp / ry;
  13137. var cyp = f * -ry * xp / rx;
  13138. var cx = (x1 + x2) / 2.0
  13139. + mathCos(psi) * cxp
  13140. - mathSin(psi) * cyp;
  13141. var cy = (y1 + y2) / 2.0
  13142. + mathSin(psi) * cxp
  13143. + mathCos(psi) * cyp;
  13144. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13145. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13146. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13147. var dTheta = vAngle(u, v);
  13148. if (vRatio(u, v) <= -1) {
  13149. dTheta = PI;
  13150. }
  13151. if (vRatio(u, v) >= 1) {
  13152. dTheta = 0;
  13153. }
  13154. if (fs === 0 && dTheta > 0) {
  13155. dTheta = dTheta - 2 * PI;
  13156. }
  13157. if (fs === 1 && dTheta < 0) {
  13158. dTheta = dTheta + 2 * PI;
  13159. }
  13160. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13161. }
  13162. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13163. // Consider case:
  13164. // (1) delimiter can be comma or space, where continuous commas
  13165. // or spaces should be seen as one comma.
  13166. // (2) value can be like:
  13167. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13168. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13169. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13170. // var valueSplitReg = /[\s,]+/;
  13171. function createPathProxyFromString(data) {
  13172. if (!data) {
  13173. return new PathProxy();
  13174. }
  13175. // var data = data.replace(/-/g, ' -')
  13176. // .replace(/ /g, ' ')
  13177. // .replace(/ /g, ',')
  13178. // .replace(/,,/g, ',');
  13179. // var n;
  13180. // create pipes so that we can split the data
  13181. // for (n = 0; n < cc.length; n++) {
  13182. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13183. // }
  13184. // data = data.replace(/-/g, ',-');
  13185. // create array
  13186. // var arr = cs.split('|');
  13187. // init context point
  13188. var cpx = 0;
  13189. var cpy = 0;
  13190. var subpathX = cpx;
  13191. var subpathY = cpy;
  13192. var prevCmd;
  13193. var path = new PathProxy();
  13194. var CMD = PathProxy.CMD;
  13195. // commandReg.lastIndex = 0;
  13196. // var cmdResult;
  13197. // while ((cmdResult = commandReg.exec(data)) != null) {
  13198. // var cmdStr = cmdResult[1];
  13199. // var cmdContent = cmdResult[2];
  13200. var cmdList = data.match(commandReg);
  13201. for (var l = 0; l < cmdList.length; l++) {
  13202. var cmdText = cmdList[l];
  13203. var cmdStr = cmdText.charAt(0);
  13204. var cmd;
  13205. // String#split is faster a little bit than String#replace or RegExp#exec.
  13206. // var p = cmdContent.split(valueSplitReg);
  13207. // var pLen = 0;
  13208. // for (var i = 0; i < p.length; i++) {
  13209. // // '' and other invalid str => NaN
  13210. // var val = parseFloat(p[i]);
  13211. // !isNaN(val) && (p[pLen++] = val);
  13212. // }
  13213. var p = cmdText.match(numberReg) || [];
  13214. var pLen = p.length;
  13215. for (var i = 0; i < pLen; i++) {
  13216. p[i] = parseFloat(p[i]);
  13217. }
  13218. var off = 0;
  13219. while (off < pLen) {
  13220. var ctlPtx;
  13221. var ctlPty;
  13222. var rx;
  13223. var ry;
  13224. var psi;
  13225. var fa;
  13226. var fs;
  13227. var x1 = cpx;
  13228. var y1 = cpy;
  13229. // convert l, H, h, V, and v to L
  13230. switch (cmdStr) {
  13231. case 'l':
  13232. cpx += p[off++];
  13233. cpy += p[off++];
  13234. cmd = CMD.L;
  13235. path.addData(cmd, cpx, cpy);
  13236. break;
  13237. case 'L':
  13238. cpx = p[off++];
  13239. cpy = p[off++];
  13240. cmd = CMD.L;
  13241. path.addData(cmd, cpx, cpy);
  13242. break;
  13243. case 'm':
  13244. cpx += p[off++];
  13245. cpy += p[off++];
  13246. cmd = CMD.M;
  13247. path.addData(cmd, cpx, cpy);
  13248. subpathX = cpx;
  13249. subpathY = cpy;
  13250. cmdStr = 'l';
  13251. break;
  13252. case 'M':
  13253. cpx = p[off++];
  13254. cpy = p[off++];
  13255. cmd = CMD.M;
  13256. path.addData(cmd, cpx, cpy);
  13257. subpathX = cpx;
  13258. subpathY = cpy;
  13259. cmdStr = 'L';
  13260. break;
  13261. case 'h':
  13262. cpx += p[off++];
  13263. cmd = CMD.L;
  13264. path.addData(cmd, cpx, cpy);
  13265. break;
  13266. case 'H':
  13267. cpx = p[off++];
  13268. cmd = CMD.L;
  13269. path.addData(cmd, cpx, cpy);
  13270. break;
  13271. case 'v':
  13272. cpy += p[off++];
  13273. cmd = CMD.L;
  13274. path.addData(cmd, cpx, cpy);
  13275. break;
  13276. case 'V':
  13277. cpy = p[off++];
  13278. cmd = CMD.L;
  13279. path.addData(cmd, cpx, cpy);
  13280. break;
  13281. case 'C':
  13282. cmd = CMD.C;
  13283. path.addData(
  13284. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13285. );
  13286. cpx = p[off - 2];
  13287. cpy = p[off - 1];
  13288. break;
  13289. case 'c':
  13290. cmd = CMD.C;
  13291. path.addData(
  13292. cmd,
  13293. p[off++] + cpx, p[off++] + cpy,
  13294. p[off++] + cpx, p[off++] + cpy,
  13295. p[off++] + cpx, p[off++] + cpy
  13296. );
  13297. cpx += p[off - 2];
  13298. cpy += p[off - 1];
  13299. break;
  13300. case 'S':
  13301. ctlPtx = cpx;
  13302. ctlPty = cpy;
  13303. var len = path.len();
  13304. var pathData = path.data;
  13305. if (prevCmd === CMD.C) {
  13306. ctlPtx += cpx - pathData[len - 4];
  13307. ctlPty += cpy - pathData[len - 3];
  13308. }
  13309. cmd = CMD.C;
  13310. x1 = p[off++];
  13311. y1 = p[off++];
  13312. cpx = p[off++];
  13313. cpy = p[off++];
  13314. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13315. break;
  13316. case 's':
  13317. ctlPtx = cpx;
  13318. ctlPty = cpy;
  13319. var len = path.len();
  13320. var pathData = path.data;
  13321. if (prevCmd === CMD.C) {
  13322. ctlPtx += cpx - pathData[len - 4];
  13323. ctlPty += cpy - pathData[len - 3];
  13324. }
  13325. cmd = CMD.C;
  13326. x1 = cpx + p[off++];
  13327. y1 = cpy + p[off++];
  13328. cpx += p[off++];
  13329. cpy += p[off++];
  13330. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13331. break;
  13332. case 'Q':
  13333. x1 = p[off++];
  13334. y1 = p[off++];
  13335. cpx = p[off++];
  13336. cpy = p[off++];
  13337. cmd = CMD.Q;
  13338. path.addData(cmd, x1, y1, cpx, cpy);
  13339. break;
  13340. case 'q':
  13341. x1 = p[off++] + cpx;
  13342. y1 = p[off++] + cpy;
  13343. cpx += p[off++];
  13344. cpy += p[off++];
  13345. cmd = CMD.Q;
  13346. path.addData(cmd, x1, y1, cpx, cpy);
  13347. break;
  13348. case 'T':
  13349. ctlPtx = cpx;
  13350. ctlPty = cpy;
  13351. var len = path.len();
  13352. var pathData = path.data;
  13353. if (prevCmd === CMD.Q) {
  13354. ctlPtx += cpx - pathData[len - 4];
  13355. ctlPty += cpy - pathData[len - 3];
  13356. }
  13357. cpx = p[off++];
  13358. cpy = p[off++];
  13359. cmd = CMD.Q;
  13360. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13361. break;
  13362. case 't':
  13363. ctlPtx = cpx;
  13364. ctlPty = cpy;
  13365. var len = path.len();
  13366. var pathData = path.data;
  13367. if (prevCmd === CMD.Q) {
  13368. ctlPtx += cpx - pathData[len - 4];
  13369. ctlPty += cpy - pathData[len - 3];
  13370. }
  13371. cpx += p[off++];
  13372. cpy += p[off++];
  13373. cmd = CMD.Q;
  13374. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13375. break;
  13376. case 'A':
  13377. rx = p[off++];
  13378. ry = p[off++];
  13379. psi = p[off++];
  13380. fa = p[off++];
  13381. fs = p[off++];
  13382. x1 = cpx, y1 = cpy;
  13383. cpx = p[off++];
  13384. cpy = p[off++];
  13385. cmd = CMD.A;
  13386. processArc(
  13387. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13388. );
  13389. break;
  13390. case 'a':
  13391. rx = p[off++];
  13392. ry = p[off++];
  13393. psi = p[off++];
  13394. fa = p[off++];
  13395. fs = p[off++];
  13396. x1 = cpx, y1 = cpy;
  13397. cpx += p[off++];
  13398. cpy += p[off++];
  13399. cmd = CMD.A;
  13400. processArc(
  13401. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13402. );
  13403. break;
  13404. }
  13405. }
  13406. if (cmdStr === 'z' || cmdStr === 'Z') {
  13407. cmd = CMD.Z;
  13408. path.addData(cmd);
  13409. // z may be in the middle of the path.
  13410. cpx = subpathX;
  13411. cpy = subpathY;
  13412. }
  13413. prevCmd = cmd;
  13414. }
  13415. path.toStatic();
  13416. return path;
  13417. }
  13418. // TODO Optimize double memory cost problem
  13419. function createPathOptions(str, opts) {
  13420. var pathProxy = createPathProxyFromString(str);
  13421. opts = opts || {};
  13422. opts.buildPath = function (path) {
  13423. if (path.setData) {
  13424. path.setData(pathProxy.data);
  13425. // Svg and vml renderer don't have context
  13426. var ctx = path.getContext();
  13427. if (ctx) {
  13428. path.rebuildPath(ctx);
  13429. }
  13430. }
  13431. else {
  13432. var ctx = path;
  13433. pathProxy.rebuildPath(ctx);
  13434. }
  13435. };
  13436. opts.applyTransform = function (m) {
  13437. transformPath(pathProxy, m);
  13438. this.dirty(true);
  13439. };
  13440. return opts;
  13441. }
  13442. /**
  13443. * Create a Path object from path string data
  13444. * http://www.w3.org/TR/SVG/paths.html#PathData
  13445. * @param {Object} opts Other options
  13446. */
  13447. function createFromString(str, opts) {
  13448. return new Path(createPathOptions(str, opts));
  13449. }
  13450. /**
  13451. * Create a Path class from path string data
  13452. * @param {string} str
  13453. * @param {Object} opts Other options
  13454. */
  13455. function extendFromString(str, opts) {
  13456. return Path.extend(createPathOptions(str, opts));
  13457. }
  13458. /**
  13459. * Merge multiple paths
  13460. */
  13461. // TODO Apply transform
  13462. // TODO stroke dash
  13463. // TODO Optimize double memory cost problem
  13464. function mergePath$1(pathEls, opts) {
  13465. var pathList = [];
  13466. var len = pathEls.length;
  13467. for (var i = 0; i < len; i++) {
  13468. var pathEl = pathEls[i];
  13469. if (!pathEl.path) {
  13470. pathEl.createPathProxy();
  13471. }
  13472. if (pathEl.__dirtyPath) {
  13473. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13474. }
  13475. pathList.push(pathEl.path);
  13476. }
  13477. var pathBundle = new Path(opts);
  13478. // Need path proxy.
  13479. pathBundle.createPathProxy();
  13480. pathBundle.buildPath = function (path) {
  13481. path.appendPath(pathList);
  13482. // Svg and vml renderer don't have context
  13483. var ctx = path.getContext();
  13484. if (ctx) {
  13485. path.rebuildPath(ctx);
  13486. }
  13487. };
  13488. return pathBundle;
  13489. }
  13490. /**
  13491. * @alias zrender/graphic/Text
  13492. * @extends module:zrender/graphic/Displayable
  13493. * @constructor
  13494. * @param {Object} opts
  13495. */
  13496. var Text = function (opts) { // jshint ignore:line
  13497. Displayable.call(this, opts);
  13498. };
  13499. Text.prototype = {
  13500. constructor: Text,
  13501. type: 'text',
  13502. brush: function (ctx, prevEl) {
  13503. var style = this.style;
  13504. // Optimize, avoid normalize every time.
  13505. this.__dirty && normalizeTextStyle(style, true);
  13506. // Use props with prefix 'text'.
  13507. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13508. style.shadowOffsetX = style.shadowOffsetY = null;
  13509. var text = style.text;
  13510. // Convert to string
  13511. text != null && (text += '');
  13512. // Do not apply style.bind in Text node. Because the real bind job
  13513. // is in textHelper.renderText, and performance of text render should
  13514. // be considered.
  13515. // style.bind(ctx, this, prevEl);
  13516. if (!needDrawText(text, style)) {
  13517. // The current el.style is not applied
  13518. // and should not be used as cache.
  13519. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13520. return;
  13521. }
  13522. this.setTransform(ctx);
  13523. renderText(this, ctx, text, style, null, prevEl);
  13524. this.restoreTransform(ctx);
  13525. },
  13526. getBoundingRect: function () {
  13527. var style = this.style;
  13528. // Optimize, avoid normalize every time.
  13529. this.__dirty && normalizeTextStyle(style, true);
  13530. if (!this._rect) {
  13531. var text = style.text;
  13532. text != null ? (text += '') : (text = '');
  13533. var rect = getBoundingRect(
  13534. style.text + '',
  13535. style.font,
  13536. style.textAlign,
  13537. style.textVerticalAlign,
  13538. style.textPadding,
  13539. style.textLineHeight,
  13540. style.rich
  13541. );
  13542. rect.x += style.x || 0;
  13543. rect.y += style.y || 0;
  13544. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13545. var w = style.textStrokeWidth;
  13546. rect.x -= w / 2;
  13547. rect.y -= w / 2;
  13548. rect.width += w;
  13549. rect.height += w;
  13550. }
  13551. this._rect = rect;
  13552. }
  13553. return this._rect;
  13554. }
  13555. };
  13556. inherits(Text, Displayable);
  13557. /**
  13558. * 圆形
  13559. * @module zrender/shape/Circle
  13560. */
  13561. var Circle = Path.extend({
  13562. type: 'circle',
  13563. shape: {
  13564. cx: 0,
  13565. cy: 0,
  13566. r: 0
  13567. },
  13568. buildPath: function (ctx, shape, inBundle) {
  13569. // Better stroking in ShapeBundle
  13570. // Always do it may have performence issue ( fill may be 2x more cost)
  13571. if (inBundle) {
  13572. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13573. }
  13574. // else {
  13575. // if (ctx.allocate && !ctx.data.length) {
  13576. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13577. // }
  13578. // }
  13579. // Better stroking in ShapeBundle
  13580. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13581. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13582. }
  13583. });
  13584. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13585. // where exception "unexpected call to method or property access"
  13586. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13587. // whose area size is zero is drawn and ctx.clip() is called and
  13588. // shadowBlur is set. See #4572, #3112, #5777.
  13589. // (e.g.,
  13590. // ctx.moveTo(10, 10);
  13591. // ctx.lineTo(20, 10);
  13592. // ctx.closePath();
  13593. // ctx.clip();
  13594. // ctx.shadowBlur = 10;
  13595. // ...
  13596. // ctx.fill();
  13597. // )
  13598. var shadowTemp = [
  13599. ['shadowBlur', 0],
  13600. ['shadowColor', '#000'],
  13601. ['shadowOffsetX', 0],
  13602. ['shadowOffsetY', 0]
  13603. ];
  13604. var fixClipWithShadow = function (orignalBrush) {
  13605. // version string can be: '11.0'
  13606. return (env$1.browser.ie && env$1.browser.version >= 11)
  13607. ? function () {
  13608. var clipPaths = this.__clipPaths;
  13609. var style = this.style;
  13610. var modified;
  13611. if (clipPaths) {
  13612. for (var i = 0; i < clipPaths.length; i++) {
  13613. var clipPath = clipPaths[i];
  13614. var shape = clipPath && clipPath.shape;
  13615. var type = clipPath && clipPath.type;
  13616. if (shape && (
  13617. (type === 'sector' && shape.startAngle === shape.endAngle)
  13618. || (type === 'rect' && (!shape.width || !shape.height))
  13619. )) {
  13620. for (var j = 0; j < shadowTemp.length; j++) {
  13621. // It is save to put shadowTemp static, because shadowTemp
  13622. // will be all modified each item brush called.
  13623. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13624. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13625. }
  13626. modified = true;
  13627. break;
  13628. }
  13629. }
  13630. }
  13631. orignalBrush.apply(this, arguments);
  13632. if (modified) {
  13633. for (var j = 0; j < shadowTemp.length; j++) {
  13634. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13635. }
  13636. }
  13637. }
  13638. : orignalBrush;
  13639. };
  13640. /**
  13641. * 扇形
  13642. * @module zrender/graphic/shape/Sector
  13643. */
  13644. var Sector = Path.extend({
  13645. type: 'sector',
  13646. shape: {
  13647. cx: 0,
  13648. cy: 0,
  13649. r0: 0,
  13650. r: 0,
  13651. startAngle: 0,
  13652. endAngle: Math.PI * 2,
  13653. clockwise: true
  13654. },
  13655. brush: fixClipWithShadow(Path.prototype.brush),
  13656. buildPath: function (ctx, shape) {
  13657. var x = shape.cx;
  13658. var y = shape.cy;
  13659. var r0 = Math.max(shape.r0 || 0, 0);
  13660. var r = Math.max(shape.r, 0);
  13661. var startAngle = shape.startAngle;
  13662. var endAngle = shape.endAngle;
  13663. var clockwise = shape.clockwise;
  13664. var unitX = Math.cos(startAngle);
  13665. var unitY = Math.sin(startAngle);
  13666. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13667. ctx.lineTo(unitX * r + x, unitY * r + y);
  13668. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13669. ctx.lineTo(
  13670. Math.cos(endAngle) * r0 + x,
  13671. Math.sin(endAngle) * r0 + y
  13672. );
  13673. if (r0 !== 0) {
  13674. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13675. }
  13676. ctx.closePath();
  13677. }
  13678. });
  13679. /**
  13680. * 圆环
  13681. * @module zrender/graphic/shape/Ring
  13682. */
  13683. var Ring = Path.extend({
  13684. type: 'ring',
  13685. shape: {
  13686. cx: 0,
  13687. cy: 0,
  13688. r: 0,
  13689. r0: 0
  13690. },
  13691. buildPath: function (ctx, shape) {
  13692. var x = shape.cx;
  13693. var y = shape.cy;
  13694. var PI2 = Math.PI * 2;
  13695. ctx.moveTo(x + shape.r, y);
  13696. ctx.arc(x, y, shape.r, 0, PI2, false);
  13697. ctx.moveTo(x + shape.r0, y);
  13698. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13699. }
  13700. });
  13701. /**
  13702. * Catmull-Rom spline 插值折线
  13703. * @module zrender/shape/util/smoothSpline
  13704. * @author pissang (https://www.github.com/pissang)
  13705. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13706. * errorrik (errorrik@gmail.com)
  13707. */
  13708. /**
  13709. * @inner
  13710. */
  13711. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13712. var v0 = (p2 - p0) * 0.5;
  13713. var v1 = (p3 - p1) * 0.5;
  13714. return (2 * (p1 - p2) + v0 + v1) * t3
  13715. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13716. + v0 * t + p1;
  13717. }
  13718. /**
  13719. * @alias module:zrender/shape/util/smoothSpline
  13720. * @param {Array} points 线段顶点数组
  13721. * @param {boolean} isLoop
  13722. * @return {Array}
  13723. */
  13724. var smoothSpline = function (points, isLoop) {
  13725. var len$$1 = points.length;
  13726. var ret = [];
  13727. var distance$$1 = 0;
  13728. for (var i = 1; i < len$$1; i++) {
  13729. distance$$1 += distance(points[i - 1], points[i]);
  13730. }
  13731. var segs = distance$$1 / 2;
  13732. segs = segs < len$$1 ? len$$1 : segs;
  13733. for (var i = 0; i < segs; i++) {
  13734. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13735. var idx = Math.floor(pos);
  13736. var w = pos - idx;
  13737. var p0;
  13738. var p1 = points[idx % len$$1];
  13739. var p2;
  13740. var p3;
  13741. if (!isLoop) {
  13742. p0 = points[idx === 0 ? idx : idx - 1];
  13743. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13744. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13745. }
  13746. else {
  13747. p0 = points[(idx - 1 + len$$1) % len$$1];
  13748. p2 = points[(idx + 1) % len$$1];
  13749. p3 = points[(idx + 2) % len$$1];
  13750. }
  13751. var w2 = w * w;
  13752. var w3 = w * w2;
  13753. ret.push([
  13754. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13755. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13756. ]);
  13757. }
  13758. return ret;
  13759. };
  13760. /**
  13761. * 贝塞尔平滑曲线
  13762. * @module zrender/shape/util/smoothBezier
  13763. * @author pissang (https://www.github.com/pissang)
  13764. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13765. * errorrik (errorrik@gmail.com)
  13766. */
  13767. /**
  13768. * 贝塞尔平滑曲线
  13769. * @alias module:zrender/shape/util/smoothBezier
  13770. * @param {Array} points 线段顶点数组
  13771. * @param {number} smooth 平滑等级, 0-1
  13772. * @param {boolean} isLoop
  13773. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13774. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13775. * 整个折线的包围盒做一个并集用来约束控制点。
  13776. * @param {Array} 计算出来的控制点数组
  13777. */
  13778. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13779. var cps = [];
  13780. var v = [];
  13781. var v1 = [];
  13782. var v2 = [];
  13783. var prevPoint;
  13784. var nextPoint;
  13785. var min$$1;
  13786. var max$$1;
  13787. if (constraint) {
  13788. min$$1 = [Infinity, Infinity];
  13789. max$$1 = [-Infinity, -Infinity];
  13790. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13791. min(min$$1, min$$1, points[i]);
  13792. max(max$$1, max$$1, points[i]);
  13793. }
  13794. // 与指定的包围盒做并集
  13795. min(min$$1, min$$1, constraint[0]);
  13796. max(max$$1, max$$1, constraint[1]);
  13797. }
  13798. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13799. var point = points[i];
  13800. if (isLoop) {
  13801. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13802. nextPoint = points[(i + 1) % len$$1];
  13803. }
  13804. else {
  13805. if (i === 0 || i === len$$1 - 1) {
  13806. cps.push(clone$1(points[i]));
  13807. continue;
  13808. }
  13809. else {
  13810. prevPoint = points[i - 1];
  13811. nextPoint = points[i + 1];
  13812. }
  13813. }
  13814. sub(v, nextPoint, prevPoint);
  13815. // use degree to scale the handle length
  13816. scale(v, v, smooth);
  13817. var d0 = distance(point, prevPoint);
  13818. var d1 = distance(point, nextPoint);
  13819. var sum = d0 + d1;
  13820. if (sum !== 0) {
  13821. d0 /= sum;
  13822. d1 /= sum;
  13823. }
  13824. scale(v1, v, -d0);
  13825. scale(v2, v, d1);
  13826. var cp0 = add([], point, v1);
  13827. var cp1 = add([], point, v2);
  13828. if (constraint) {
  13829. max(cp0, cp0, min$$1);
  13830. min(cp0, cp0, max$$1);
  13831. max(cp1, cp1, min$$1);
  13832. min(cp1, cp1, max$$1);
  13833. }
  13834. cps.push(cp0);
  13835. cps.push(cp1);
  13836. }
  13837. if (isLoop) {
  13838. cps.push(cps.shift());
  13839. }
  13840. return cps;
  13841. };
  13842. function buildPath$1(ctx, shape, closePath) {
  13843. var points = shape.points;
  13844. var smooth = shape.smooth;
  13845. if (points && points.length >= 2) {
  13846. if (smooth && smooth !== 'spline') {
  13847. var controlPoints = smoothBezier(
  13848. points, smooth, closePath, shape.smoothConstraint
  13849. );
  13850. ctx.moveTo(points[0][0], points[0][1]);
  13851. var len = points.length;
  13852. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13853. var cp1 = controlPoints[i * 2];
  13854. var cp2 = controlPoints[i * 2 + 1];
  13855. var p = points[(i + 1) % len];
  13856. ctx.bezierCurveTo(
  13857. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13858. );
  13859. }
  13860. }
  13861. else {
  13862. if (smooth === 'spline') {
  13863. points = smoothSpline(points, closePath);
  13864. }
  13865. ctx.moveTo(points[0][0], points[0][1]);
  13866. for (var i = 1, l = points.length; i < l; i++) {
  13867. ctx.lineTo(points[i][0], points[i][1]);
  13868. }
  13869. }
  13870. closePath && ctx.closePath();
  13871. }
  13872. }
  13873. /**
  13874. * 多边形
  13875. * @module zrender/shape/Polygon
  13876. */
  13877. var Polygon = Path.extend({
  13878. type: 'polygon',
  13879. shape: {
  13880. points: null,
  13881. smooth: false,
  13882. smoothConstraint: null
  13883. },
  13884. buildPath: function (ctx, shape) {
  13885. buildPath$1(ctx, shape, true);
  13886. }
  13887. });
  13888. /**
  13889. * @module zrender/graphic/shape/Polyline
  13890. */
  13891. var Polyline = Path.extend({
  13892. type: 'polyline',
  13893. shape: {
  13894. points: null,
  13895. smooth: false,
  13896. smoothConstraint: null
  13897. },
  13898. style: {
  13899. stroke: '#000',
  13900. fill: null
  13901. },
  13902. buildPath: function (ctx, shape) {
  13903. buildPath$1(ctx, shape, false);
  13904. }
  13905. });
  13906. /**
  13907. * Sub-pixel optimize for canvas rendering, prevent from blur
  13908. * when rendering a thin vertical/horizontal line.
  13909. */
  13910. var round = Math.round;
  13911. /**
  13912. * Sub pixel optimize line for canvas
  13913. *
  13914. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13915. * `outputShape` and `inputShape` can be the same object.
  13916. * `outputShape` object can be used repeatly, because all of
  13917. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13918. * @param {Object} [inputShape]
  13919. * @param {number} [inputShape.x1]
  13920. * @param {number} [inputShape.y1]
  13921. * @param {number} [inputShape.x2]
  13922. * @param {number} [inputShape.y2]
  13923. * @param {Object} [style]
  13924. * @param {number} [style.lineWidth]
  13925. */
  13926. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13927. var lineWidth = style && style.lineWidth;
  13928. if (!inputShape || !lineWidth) {
  13929. return;
  13930. }
  13931. var x1 = inputShape.x1;
  13932. var x2 = inputShape.x2;
  13933. var y1 = inputShape.y1;
  13934. var y2 = inputShape.y2;
  13935. if (round(x1 * 2) === round(x2 * 2)) {
  13936. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13937. }
  13938. else {
  13939. outputShape.x1 = x1;
  13940. outputShape.x2 = x2;
  13941. }
  13942. if (round(y1 * 2) === round(y2 * 2)) {
  13943. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13944. }
  13945. else {
  13946. outputShape.y1 = y1;
  13947. outputShape.y2 = y2;
  13948. }
  13949. }
  13950. /**
  13951. * Sub pixel optimize rect for canvas
  13952. *
  13953. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13954. * `outputShape` and `inputShape` can be the same object.
  13955. * `outputShape` object can be used repeatly, because all of
  13956. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13957. * @param {Object} [inputShape]
  13958. * @param {number} [inputShape.x]
  13959. * @param {number} [inputShape.y]
  13960. * @param {number} [inputShape.width]
  13961. * @param {number} [inputShape.height]
  13962. * @param {Object} [style]
  13963. * @param {number} [style.lineWidth]
  13964. */
  13965. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13966. var lineWidth = style && style.lineWidth;
  13967. if (!inputShape || !lineWidth) {
  13968. return;
  13969. }
  13970. var originX = inputShape.x;
  13971. var originY = inputShape.y;
  13972. var originWidth = inputShape.width;
  13973. var originHeight = inputShape.height;
  13974. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13975. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13976. outputShape.width = Math.max(
  13977. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13978. originWidth === 0 ? 0 : 1
  13979. );
  13980. outputShape.height = Math.max(
  13981. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13982. originHeight === 0 ? 0 : 1
  13983. );
  13984. }
  13985. /**
  13986. * Sub pixel optimize for canvas
  13987. *
  13988. * @param {number} position Coordinate, such as x, y
  13989. * @param {number} lineWidth Should be nonnegative integer.
  13990. * @param {boolean=} positiveOrNegative Default false (negative).
  13991. * @return {number} Optimized position.
  13992. */
  13993. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13994. // Assure that (position + lineWidth / 2) is near integer edge,
  13995. // otherwise line will be fuzzy in canvas.
  13996. var doubledPosition = round(position * 2);
  13997. return (doubledPosition + round(lineWidth)) % 2 === 0
  13998. ? doubledPosition / 2
  13999. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14000. }
  14001. /**
  14002. * 矩形
  14003. * @module zrender/graphic/shape/Rect
  14004. */
  14005. // Avoid create repeatly.
  14006. var subPixelOptimizeOutputShape = {};
  14007. var Rect = Path.extend({
  14008. type: 'rect',
  14009. shape: {
  14010. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14011. // r缩写为1 相当于 [1, 1, 1, 1]
  14012. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14013. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14014. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14015. r: 0,
  14016. x: 0,
  14017. y: 0,
  14018. width: 0,
  14019. height: 0
  14020. },
  14021. buildPath: function (ctx, shape) {
  14022. var x;
  14023. var y;
  14024. var width;
  14025. var height;
  14026. if (this.subPixelOptimize) {
  14027. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14028. x = subPixelOptimizeOutputShape.x;
  14029. y = subPixelOptimizeOutputShape.y;
  14030. width = subPixelOptimizeOutputShape.width;
  14031. height = subPixelOptimizeOutputShape.height;
  14032. subPixelOptimizeOutputShape.r = shape.r;
  14033. shape = subPixelOptimizeOutputShape;
  14034. }
  14035. else {
  14036. x = shape.x;
  14037. y = shape.y;
  14038. width = shape.width;
  14039. height = shape.height;
  14040. }
  14041. if (!shape.r) {
  14042. ctx.rect(x, y, width, height);
  14043. }
  14044. else {
  14045. buildPath(ctx, shape);
  14046. }
  14047. ctx.closePath();
  14048. return;
  14049. }
  14050. });
  14051. /**
  14052. * 直线
  14053. * @module zrender/graphic/shape/Line
  14054. */
  14055. // Avoid create repeatly.
  14056. var subPixelOptimizeOutputShape$1 = {};
  14057. var Line = Path.extend({
  14058. type: 'line',
  14059. shape: {
  14060. // Start point
  14061. x1: 0,
  14062. y1: 0,
  14063. // End point
  14064. x2: 0,
  14065. y2: 0,
  14066. percent: 1
  14067. },
  14068. style: {
  14069. stroke: '#000',
  14070. fill: null
  14071. },
  14072. buildPath: function (ctx, shape) {
  14073. var x1;
  14074. var y1;
  14075. var x2;
  14076. var y2;
  14077. if (this.subPixelOptimize) {
  14078. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14079. x1 = subPixelOptimizeOutputShape$1.x1;
  14080. y1 = subPixelOptimizeOutputShape$1.y1;
  14081. x2 = subPixelOptimizeOutputShape$1.x2;
  14082. y2 = subPixelOptimizeOutputShape$1.y2;
  14083. }
  14084. else {
  14085. x1 = shape.x1;
  14086. y1 = shape.y1;
  14087. x2 = shape.x2;
  14088. y2 = shape.y2;
  14089. }
  14090. var percent = shape.percent;
  14091. if (percent === 0) {
  14092. return;
  14093. }
  14094. ctx.moveTo(x1, y1);
  14095. if (percent < 1) {
  14096. x2 = x1 * (1 - percent) + x2 * percent;
  14097. y2 = y1 * (1 - percent) + y2 * percent;
  14098. }
  14099. ctx.lineTo(x2, y2);
  14100. },
  14101. /**
  14102. * Get point at percent
  14103. * @param {number} percent
  14104. * @return {Array.<number>}
  14105. */
  14106. pointAt: function (p) {
  14107. var shape = this.shape;
  14108. return [
  14109. shape.x1 * (1 - p) + shape.x2 * p,
  14110. shape.y1 * (1 - p) + shape.y2 * p
  14111. ];
  14112. }
  14113. });
  14114. /**
  14115. * 贝塞尔曲线
  14116. * @module zrender/shape/BezierCurve
  14117. */
  14118. var out = [];
  14119. function someVectorAt(shape, t, isTangent) {
  14120. var cpx2 = shape.cpx2;
  14121. var cpy2 = shape.cpy2;
  14122. if (cpx2 === null || cpy2 === null) {
  14123. return [
  14124. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14125. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14126. ];
  14127. }
  14128. else {
  14129. return [
  14130. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14131. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14132. ];
  14133. }
  14134. }
  14135. var BezierCurve = Path.extend({
  14136. type: 'bezier-curve',
  14137. shape: {
  14138. x1: 0,
  14139. y1: 0,
  14140. x2: 0,
  14141. y2: 0,
  14142. cpx1: 0,
  14143. cpy1: 0,
  14144. // cpx2: 0,
  14145. // cpy2: 0
  14146. // Curve show percent, for animating
  14147. percent: 1
  14148. },
  14149. style: {
  14150. stroke: '#000',
  14151. fill: null
  14152. },
  14153. buildPath: function (ctx, shape) {
  14154. var x1 = shape.x1;
  14155. var y1 = shape.y1;
  14156. var x2 = shape.x2;
  14157. var y2 = shape.y2;
  14158. var cpx1 = shape.cpx1;
  14159. var cpy1 = shape.cpy1;
  14160. var cpx2 = shape.cpx2;
  14161. var cpy2 = shape.cpy2;
  14162. var percent = shape.percent;
  14163. if (percent === 0) {
  14164. return;
  14165. }
  14166. ctx.moveTo(x1, y1);
  14167. if (cpx2 == null || cpy2 == null) {
  14168. if (percent < 1) {
  14169. quadraticSubdivide(
  14170. x1, cpx1, x2, percent, out
  14171. );
  14172. cpx1 = out[1];
  14173. x2 = out[2];
  14174. quadraticSubdivide(
  14175. y1, cpy1, y2, percent, out
  14176. );
  14177. cpy1 = out[1];
  14178. y2 = out[2];
  14179. }
  14180. ctx.quadraticCurveTo(
  14181. cpx1, cpy1,
  14182. x2, y2
  14183. );
  14184. }
  14185. else {
  14186. if (percent < 1) {
  14187. cubicSubdivide(
  14188. x1, cpx1, cpx2, x2, percent, out
  14189. );
  14190. cpx1 = out[1];
  14191. cpx2 = out[2];
  14192. x2 = out[3];
  14193. cubicSubdivide(
  14194. y1, cpy1, cpy2, y2, percent, out
  14195. );
  14196. cpy1 = out[1];
  14197. cpy2 = out[2];
  14198. y2 = out[3];
  14199. }
  14200. ctx.bezierCurveTo(
  14201. cpx1, cpy1,
  14202. cpx2, cpy2,
  14203. x2, y2
  14204. );
  14205. }
  14206. },
  14207. /**
  14208. * Get point at percent
  14209. * @param {number} t
  14210. * @return {Array.<number>}
  14211. */
  14212. pointAt: function (t) {
  14213. return someVectorAt(this.shape, t, false);
  14214. },
  14215. /**
  14216. * Get tangent at percent
  14217. * @param {number} t
  14218. * @return {Array.<number>}
  14219. */
  14220. tangentAt: function (t) {
  14221. var p = someVectorAt(this.shape, t, true);
  14222. return normalize(p, p);
  14223. }
  14224. });
  14225. /**
  14226. * 圆弧
  14227. * @module zrender/graphic/shape/Arc
  14228. */
  14229. var Arc = Path.extend({
  14230. type: 'arc',
  14231. shape: {
  14232. cx: 0,
  14233. cy: 0,
  14234. r: 0,
  14235. startAngle: 0,
  14236. endAngle: Math.PI * 2,
  14237. clockwise: true
  14238. },
  14239. style: {
  14240. stroke: '#000',
  14241. fill: null
  14242. },
  14243. buildPath: function (ctx, shape) {
  14244. var x = shape.cx;
  14245. var y = shape.cy;
  14246. var r = Math.max(shape.r, 0);
  14247. var startAngle = shape.startAngle;
  14248. var endAngle = shape.endAngle;
  14249. var clockwise = shape.clockwise;
  14250. var unitX = Math.cos(startAngle);
  14251. var unitY = Math.sin(startAngle);
  14252. ctx.moveTo(unitX * r + x, unitY * r + y);
  14253. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14254. }
  14255. });
  14256. // CompoundPath to improve performance
  14257. var CompoundPath = Path.extend({
  14258. type: 'compound',
  14259. shape: {
  14260. paths: null
  14261. },
  14262. _updatePathDirty: function () {
  14263. var dirtyPath = this.__dirtyPath;
  14264. var paths = this.shape.paths;
  14265. for (var i = 0; i < paths.length; i++) {
  14266. // Mark as dirty if any subpath is dirty
  14267. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14268. }
  14269. this.__dirtyPath = dirtyPath;
  14270. this.__dirty = this.__dirty || dirtyPath;
  14271. },
  14272. beforeBrush: function () {
  14273. this._updatePathDirty();
  14274. var paths = this.shape.paths || [];
  14275. var scale = this.getGlobalScale();
  14276. // Update path scale
  14277. for (var i = 0; i < paths.length; i++) {
  14278. if (!paths[i].path) {
  14279. paths[i].createPathProxy();
  14280. }
  14281. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14282. }
  14283. },
  14284. buildPath: function (ctx, shape) {
  14285. var paths = shape.paths || [];
  14286. for (var i = 0; i < paths.length; i++) {
  14287. paths[i].buildPath(ctx, paths[i].shape, true);
  14288. }
  14289. },
  14290. afterBrush: function () {
  14291. var paths = this.shape.paths || [];
  14292. for (var i = 0; i < paths.length; i++) {
  14293. paths[i].__dirtyPath = false;
  14294. }
  14295. },
  14296. getBoundingRect: function () {
  14297. this._updatePathDirty();
  14298. return Path.prototype.getBoundingRect.call(this);
  14299. }
  14300. });
  14301. /**
  14302. * @param {Array.<Object>} colorStops
  14303. */
  14304. var Gradient = function (colorStops) {
  14305. this.colorStops = colorStops || [];
  14306. };
  14307. Gradient.prototype = {
  14308. constructor: Gradient,
  14309. addColorStop: function (offset, color) {
  14310. this.colorStops.push({
  14311. offset: offset,
  14312. color: color
  14313. });
  14314. }
  14315. };
  14316. /**
  14317. * x, y, x2, y2 are all percent from 0 to 1
  14318. * @param {number} [x=0]
  14319. * @param {number} [y=0]
  14320. * @param {number} [x2=1]
  14321. * @param {number} [y2=0]
  14322. * @param {Array.<Object>} colorStops
  14323. * @param {boolean} [globalCoord=false]
  14324. */
  14325. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14326. // Should do nothing more in this constructor. Because gradient can be
  14327. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14328. // this constructor will not be called.
  14329. this.x = x == null ? 0 : x;
  14330. this.y = y == null ? 0 : y;
  14331. this.x2 = x2 == null ? 1 : x2;
  14332. this.y2 = y2 == null ? 0 : y2;
  14333. // Can be cloned
  14334. this.type = 'linear';
  14335. // If use global coord
  14336. this.global = globalCoord || false;
  14337. Gradient.call(this, colorStops);
  14338. };
  14339. LinearGradient.prototype = {
  14340. constructor: LinearGradient
  14341. };
  14342. inherits(LinearGradient, Gradient);
  14343. /**
  14344. * x, y, r are all percent from 0 to 1
  14345. * @param {number} [x=0.5]
  14346. * @param {number} [y=0.5]
  14347. * @param {number} [r=0.5]
  14348. * @param {Array.<Object>} [colorStops]
  14349. * @param {boolean} [globalCoord=false]
  14350. */
  14351. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14352. // Should do nothing more in this constructor. Because gradient can be
  14353. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14354. // this constructor will not be called.
  14355. this.x = x == null ? 0.5 : x;
  14356. this.y = y == null ? 0.5 : y;
  14357. this.r = r == null ? 0.5 : r;
  14358. // Can be cloned
  14359. this.type = 'radial';
  14360. // If use global coord
  14361. this.global = globalCoord || false;
  14362. Gradient.call(this, colorStops);
  14363. };
  14364. RadialGradient.prototype = {
  14365. constructor: RadialGradient
  14366. };
  14367. inherits(RadialGradient, Gradient);
  14368. /**
  14369. * Displayable for incremental rendering. It will be rendered in a separate layer
  14370. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14371. * addDisplayables will render the added displayables incremetally.
  14372. *
  14373. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14374. */
  14375. // TODO Style override ?
  14376. function IncrementalDisplayble(opts) {
  14377. Displayable.call(this, opts);
  14378. this._displayables = [];
  14379. this._temporaryDisplayables = [];
  14380. this._cursor = 0;
  14381. this.notClear = true;
  14382. }
  14383. IncrementalDisplayble.prototype.incremental = true;
  14384. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14385. this._displayables = [];
  14386. this._temporaryDisplayables = [];
  14387. this._cursor = 0;
  14388. this.dirty();
  14389. this.notClear = false;
  14390. };
  14391. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14392. if (notPersistent) {
  14393. this._temporaryDisplayables.push(displayable);
  14394. }
  14395. else {
  14396. this._displayables.push(displayable);
  14397. }
  14398. this.dirty();
  14399. };
  14400. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14401. notPersistent = notPersistent || false;
  14402. for (var i = 0; i < displayables.length; i++) {
  14403. this.addDisplayable(displayables[i], notPersistent);
  14404. }
  14405. };
  14406. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14407. for (var i = this._cursor; i < this._displayables.length; i++) {
  14408. cb && cb(this._displayables[i]);
  14409. }
  14410. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14411. cb && cb(this._temporaryDisplayables[i]);
  14412. }
  14413. };
  14414. IncrementalDisplayble.prototype.update = function () {
  14415. this.updateTransform();
  14416. for (var i = this._cursor; i < this._displayables.length; i++) {
  14417. var displayable = this._displayables[i];
  14418. // PENDING
  14419. displayable.parent = this;
  14420. displayable.update();
  14421. displayable.parent = null;
  14422. }
  14423. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14424. var displayable = this._temporaryDisplayables[i];
  14425. // PENDING
  14426. displayable.parent = this;
  14427. displayable.update();
  14428. displayable.parent = null;
  14429. }
  14430. };
  14431. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14432. // Render persistant displayables.
  14433. for (var i = this._cursor; i < this._displayables.length; i++) {
  14434. var displayable = this._displayables[i];
  14435. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14436. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14437. displayable.afterBrush && displayable.afterBrush(ctx);
  14438. }
  14439. this._cursor = i;
  14440. // Render temporary displayables.
  14441. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14442. var displayable = this._temporaryDisplayables[i];
  14443. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14444. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14445. displayable.afterBrush && displayable.afterBrush(ctx);
  14446. }
  14447. this._temporaryDisplayables = [];
  14448. this.notClear = true;
  14449. };
  14450. var m = [];
  14451. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14452. if (!this._rect) {
  14453. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14454. for (var i = 0; i < this._displayables.length; i++) {
  14455. var displayable = this._displayables[i];
  14456. var childRect = displayable.getBoundingRect().clone();
  14457. if (displayable.needLocalTransform()) {
  14458. childRect.applyTransform(displayable.getLocalTransform(m));
  14459. }
  14460. rect.union(childRect);
  14461. }
  14462. this._rect = rect;
  14463. }
  14464. return this._rect;
  14465. };
  14466. IncrementalDisplayble.prototype.contain = function (x, y) {
  14467. var localPos = this.transformCoordToLocal(x, y);
  14468. var rect = this.getBoundingRect();
  14469. if (rect.contain(localPos[0], localPos[1])) {
  14470. for (var i = 0; i < this._displayables.length; i++) {
  14471. var displayable = this._displayables[i];
  14472. if (displayable.contain(x, y)) {
  14473. return true;
  14474. }
  14475. }
  14476. }
  14477. return false;
  14478. };
  14479. inherits(IncrementalDisplayble, Displayable);
  14480. /*
  14481. * Licensed to the Apache Software Foundation (ASF) under one
  14482. * or more contributor license agreements. See the NOTICE file
  14483. * distributed with this work for additional information
  14484. * regarding copyright ownership. The ASF licenses this file
  14485. * to you under the Apache License, Version 2.0 (the
  14486. * "License"); you may not use this file except in compliance
  14487. * with the License. You may obtain a copy of the License at
  14488. *
  14489. * http://www.apache.org/licenses/LICENSE-2.0
  14490. *
  14491. * Unless required by applicable law or agreed to in writing,
  14492. * software distributed under the License is distributed on an
  14493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14494. * KIND, either express or implied. See the License for the
  14495. * specific language governing permissions and limitations
  14496. * under the License.
  14497. */
  14498. var mathMax$1 = Math.max;
  14499. var mathMin$1 = Math.min;
  14500. var EMPTY_OBJ = {};
  14501. var Z2_EMPHASIS_LIFT = 1;
  14502. // key: label model property nane, value: style property name.
  14503. var CACHED_LABEL_STYLE_PROPERTIES = {
  14504. color: 'textFill',
  14505. textBorderColor: 'textStroke',
  14506. textBorderWidth: 'textStrokeWidth'
  14507. };
  14508. var EMPHASIS = 'emphasis';
  14509. var NORMAL = 'normal';
  14510. // Reserve 0 as default.
  14511. var _highlightNextDigit = 1;
  14512. var _highlightKeyMap = {};
  14513. var _customShapeMap = {};
  14514. /**
  14515. * Extend shape with parameters
  14516. */
  14517. function extendShape(opts) {
  14518. return Path.extend(opts);
  14519. }
  14520. /**
  14521. * Extend path
  14522. */
  14523. function extendPath(pathData, opts) {
  14524. return extendFromString(pathData, opts);
  14525. }
  14526. /**
  14527. * Register a user defined shape.
  14528. * The shape class can be fetched by `getShapeClass`
  14529. * This method will overwrite the registered shapes, including
  14530. * the registered built-in shapes, if using the same `name`.
  14531. * The shape can be used in `custom series` and
  14532. * `graphic component` by declaring `{type: name}`.
  14533. *
  14534. * @param {string} name
  14535. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14536. */
  14537. function registerShape(name, ShapeClass) {
  14538. _customShapeMap[name] = ShapeClass;
  14539. }
  14540. /**
  14541. * Find shape class registered by `registerShape`. Usually used in
  14542. * fetching user defined shape.
  14543. *
  14544. * [Caution]:
  14545. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14546. * to use user registered shapes.
  14547. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14548. * `registerShape` by default. That enables users to get both built-in
  14549. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14550. * the built-in shapes by using names like 'circle', 'rect' via calling
  14551. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14552. * in case that it is overwritten by users, except that some features, like
  14553. * `custom series`, `graphic component`, do it deliberately.
  14554. *
  14555. * (2) In the features like `custom series`, `graphic component`, the user input
  14556. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14557. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14558. * are reserved names, that is, if some user register a shape named `'image'`,
  14559. * the shape will not be used. If we intending to add some more reserved names
  14560. * in feature, that might bring break changes (disable some existing user shape
  14561. * names). But that case probably rearly happen. So we dont make more mechanism
  14562. * to resolve this issue here.
  14563. *
  14564. * @param {string} name
  14565. * @return {Object} The shape class. If not found, return nothing.
  14566. */
  14567. function getShapeClass(name) {
  14568. if (_customShapeMap.hasOwnProperty(name)) {
  14569. return _customShapeMap[name];
  14570. }
  14571. }
  14572. /**
  14573. * Create a path element from path data string
  14574. * @param {string} pathData
  14575. * @param {Object} opts
  14576. * @param {module:zrender/core/BoundingRect} rect
  14577. * @param {string} [layout=cover] 'center' or 'cover'
  14578. */
  14579. function makePath(pathData, opts, rect, layout) {
  14580. var path = createFromString(pathData, opts);
  14581. if (rect) {
  14582. if (layout === 'center') {
  14583. rect = centerGraphic(rect, path.getBoundingRect());
  14584. }
  14585. resizePath(path, rect);
  14586. }
  14587. return path;
  14588. }
  14589. /**
  14590. * Create a image element from image url
  14591. * @param {string} imageUrl image url
  14592. * @param {Object} opts options
  14593. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14594. * @param {string} [layout=cover] 'center' or 'cover'
  14595. */
  14596. function makeImage(imageUrl, rect, layout) {
  14597. var path = new ZImage({
  14598. style: {
  14599. image: imageUrl,
  14600. x: rect.x,
  14601. y: rect.y,
  14602. width: rect.width,
  14603. height: rect.height
  14604. },
  14605. onload: function (img) {
  14606. if (layout === 'center') {
  14607. var boundingRect = {
  14608. width: img.width,
  14609. height: img.height
  14610. };
  14611. path.setStyle(centerGraphic(rect, boundingRect));
  14612. }
  14613. }
  14614. });
  14615. return path;
  14616. }
  14617. /**
  14618. * Get position of centered element in bounding box.
  14619. *
  14620. * @param {Object} rect element local bounding box
  14621. * @param {Object} boundingRect constraint bounding box
  14622. * @return {Object} element position containing x, y, width, and height
  14623. */
  14624. function centerGraphic(rect, boundingRect) {
  14625. // Set rect to center, keep width / height ratio.
  14626. var aspect = boundingRect.width / boundingRect.height;
  14627. var width = rect.height * aspect;
  14628. var height;
  14629. if (width <= rect.width) {
  14630. height = rect.height;
  14631. }
  14632. else {
  14633. width = rect.width;
  14634. height = width / aspect;
  14635. }
  14636. var cx = rect.x + rect.width / 2;
  14637. var cy = rect.y + rect.height / 2;
  14638. return {
  14639. x: cx - width / 2,
  14640. y: cy - height / 2,
  14641. width: width,
  14642. height: height
  14643. };
  14644. }
  14645. var mergePath = mergePath$1;
  14646. /**
  14647. * Resize a path to fit the rect
  14648. * @param {module:zrender/graphic/Path} path
  14649. * @param {Object} rect
  14650. */
  14651. function resizePath(path, rect) {
  14652. if (!path.applyTransform) {
  14653. return;
  14654. }
  14655. var pathRect = path.getBoundingRect();
  14656. var m = pathRect.calculateTransform(rect);
  14657. path.applyTransform(m);
  14658. }
  14659. /**
  14660. * Sub pixel optimize line for canvas
  14661. *
  14662. * @param {Object} param
  14663. * @param {Object} [param.shape]
  14664. * @param {number} [param.shape.x1]
  14665. * @param {number} [param.shape.y1]
  14666. * @param {number} [param.shape.x2]
  14667. * @param {number} [param.shape.y2]
  14668. * @param {Object} [param.style]
  14669. * @param {number} [param.style.lineWidth]
  14670. * @return {Object} Modified param
  14671. */
  14672. function subPixelOptimizeLine(param) {
  14673. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  14674. return param;
  14675. }
  14676. /**
  14677. * Sub pixel optimize rect for canvas
  14678. *
  14679. * @param {Object} param
  14680. * @param {Object} [param.shape]
  14681. * @param {number} [param.shape.x]
  14682. * @param {number} [param.shape.y]
  14683. * @param {number} [param.shape.width]
  14684. * @param {number} [param.shape.height]
  14685. * @param {Object} [param.style]
  14686. * @param {number} [param.style.lineWidth]
  14687. * @return {Object} Modified param
  14688. */
  14689. function subPixelOptimizeRect(param) {
  14690. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  14691. return param;
  14692. }
  14693. /**
  14694. * Sub pixel optimize for canvas
  14695. *
  14696. * @param {number} position Coordinate, such as x, y
  14697. * @param {number} lineWidth Should be nonnegative integer.
  14698. * @param {boolean=} positiveOrNegative Default false (negative).
  14699. * @return {number} Optimized position.
  14700. */
  14701. var subPixelOptimize = subPixelOptimize$1;
  14702. function hasFillOrStroke(fillOrStroke) {
  14703. return fillOrStroke != null && fillOrStroke !== 'none';
  14704. }
  14705. // Most lifted color are duplicated.
  14706. var liftedColorMap = createHashMap();
  14707. var liftedColorCount = 0;
  14708. function liftColor(color) {
  14709. if (typeof color !== 'string') {
  14710. return color;
  14711. }
  14712. var liftedColor = liftedColorMap.get(color);
  14713. if (!liftedColor) {
  14714. liftedColor = lift(color, -0.1);
  14715. if (liftedColorCount < 10000) {
  14716. liftedColorMap.set(color, liftedColor);
  14717. liftedColorCount++;
  14718. }
  14719. }
  14720. return liftedColor;
  14721. }
  14722. function cacheElementStl(el) {
  14723. if (!el.__hoverStlDirty) {
  14724. return;
  14725. }
  14726. el.__hoverStlDirty = false;
  14727. var hoverStyle = el.__hoverStl;
  14728. if (!hoverStyle) {
  14729. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14730. return;
  14731. }
  14732. var normalStyle = el.__cachedNormalStl = {};
  14733. el.__cachedNormalZ2 = el.z2;
  14734. var elStyle = el.style;
  14735. for (var name in hoverStyle) {
  14736. // See comment in `singleEnterEmphasis`.
  14737. if (hoverStyle[name] != null) {
  14738. normalStyle[name] = elStyle[name];
  14739. }
  14740. }
  14741. // Always cache fill and stroke to normalStyle for lifting color.
  14742. normalStyle.fill = elStyle.fill;
  14743. normalStyle.stroke = elStyle.stroke;
  14744. }
  14745. function singleEnterEmphasis(el) {
  14746. var hoverStl = el.__hoverStl;
  14747. if (!hoverStl || el.__highlighted) {
  14748. return;
  14749. }
  14750. var zr = el.__zr;
  14751. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  14752. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14753. if (el.isGroup || (!zr && el.useHoverLayer)) {
  14754. return;
  14755. }
  14756. var elTarget = el;
  14757. var targetStyle = el.style;
  14758. if (useHoverLayer) {
  14759. elTarget = zr.addHover(el);
  14760. targetStyle = elTarget.style;
  14761. }
  14762. rollbackDefaultTextStyle(targetStyle);
  14763. if (!useHoverLayer) {
  14764. cacheElementStl(elTarget);
  14765. }
  14766. // styles can be:
  14767. // {
  14768. // label: {
  14769. // show: false,
  14770. // position: 'outside',
  14771. // fontSize: 18
  14772. // },
  14773. // emphasis: {
  14774. // label: {
  14775. // show: true
  14776. // }
  14777. // }
  14778. // },
  14779. // where properties of `emphasis` may not appear in `normal`. We previously use
  14780. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14781. // But consider rich text and setOption in merge mode, it is impossible to cover
  14782. // all properties in merge. So we use merge mode when setting style here.
  14783. // But we choose the merge strategy that only properties that is not `null/undefined`.
  14784. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  14785. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  14786. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  14787. // style any more in `emphasis`. Users can both set properties directly on normal and
  14788. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  14789. targetStyle.extendFrom(hoverStl);
  14790. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14791. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14792. applyDefaultTextStyle(targetStyle);
  14793. if (!useHoverLayer) {
  14794. el.dirty(false);
  14795. el.z2 += Z2_EMPHASIS_LIFT;
  14796. }
  14797. }
  14798. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14799. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14800. targetStyle[prop] = liftColor(targetStyle[prop]);
  14801. }
  14802. }
  14803. function singleEnterNormal(el) {
  14804. var highlighted = el.__highlighted;
  14805. if (!highlighted) {
  14806. return;
  14807. }
  14808. el.__highlighted = false;
  14809. if (el.isGroup) {
  14810. return;
  14811. }
  14812. if (highlighted === 'layer') {
  14813. el.__zr && el.__zr.removeHover(el);
  14814. }
  14815. else {
  14816. var style = el.style;
  14817. var normalStl = el.__cachedNormalStl;
  14818. if (normalStl) {
  14819. rollbackDefaultTextStyle(style);
  14820. el.setStyle(normalStl);
  14821. applyDefaultTextStyle(style);
  14822. }
  14823. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14824. // when `el` is on emphasis state. So here by comparing with 1, we try
  14825. // hard to make the bug case rare.
  14826. var normalZ2 = el.__cachedNormalZ2;
  14827. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14828. el.z2 = normalZ2;
  14829. }
  14830. }
  14831. }
  14832. function traverseUpdate(el, updater, commonParam) {
  14833. // If root is group, also enter updater for `highDownOnUpdate`.
  14834. var fromState = NORMAL;
  14835. var toState = NORMAL;
  14836. var trigger;
  14837. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  14838. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  14839. updater(el, commonParam);
  14840. el.__highlighted && (toState = EMPHASIS, trigger = true);
  14841. el.isGroup && el.traverse(function (child) {
  14842. !child.isGroup && updater(child, commonParam);
  14843. });
  14844. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  14845. }
  14846. /**
  14847. * Set hover style (namely "emphasis style") of element, based on the current
  14848. * style of the given `el`.
  14849. * This method should be called after all of the normal styles have been adopted
  14850. * to the `el`. See the reason on `setHoverStyle`.
  14851. *
  14852. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14853. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  14854. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  14855. * Often used when item group has a label element and it's hoverStyle is different.
  14856. * @param {Object|boolean} [hoverStl] The specified hover style.
  14857. * If set as `false`, disable the hover style.
  14858. * Similarly, The `el.hoverStyle` can alse be set
  14859. * as `false` to disable the hover style.
  14860. * Otherwise, use the default hover style if not provided.
  14861. */
  14862. function setElementHoverStyle(el, hoverStl) {
  14863. // For performance consideration, it might be better to make the "hover style" only the
  14864. // difference properties from the "normal style", but not a entire copy of all styles.
  14865. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  14866. el.__hoverStlDirty = true;
  14867. // FIXME
  14868. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14869. // It probably should be saved on `data` of series. Consider the cases:
  14870. // (1) A highlighted elements are moved out of the view port and re-enter
  14871. // again by dataZoom.
  14872. // (2) call `setOption` and replace elements totally when they are highlighted.
  14873. if (el.__highlighted) {
  14874. // Consider the case:
  14875. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14876. // should be adapted to the `el`. Notice here new "normal styles" should have
  14877. // been set outside and the cached "normal style" is out of date.
  14878. el.__cachedNormalStl = null;
  14879. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14880. // of this method. In most cases, `z2` is not set and hover style should be able
  14881. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14882. // `doSingleLeaveHover` for details.
  14883. singleEnterNormal(el);
  14884. singleEnterEmphasis(el);
  14885. }
  14886. }
  14887. function onElementMouseOver(e) {
  14888. !shouldSilent(this, e)
  14889. // "emphasis" event highlight has higher priority than mouse highlight.
  14890. && !this.__highByOuter
  14891. && traverseUpdate(this, singleEnterEmphasis);
  14892. }
  14893. function onElementMouseOut(e) {
  14894. !shouldSilent(this, e)
  14895. // "emphasis" event highlight has higher priority than mouse highlight.
  14896. && !this.__highByOuter
  14897. && traverseUpdate(this, singleEnterNormal);
  14898. }
  14899. function onElementEmphasisEvent(highlightDigit) {
  14900. this.__highByOuter |= 1 << (highlightDigit || 0);
  14901. traverseUpdate(this, singleEnterEmphasis);
  14902. }
  14903. function onElementNormalEvent(highlightDigit) {
  14904. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  14905. && traverseUpdate(this, singleEnterNormal);
  14906. }
  14907. function shouldSilent(el, e) {
  14908. return el.__highDownSilentOnTouch && e.zrByTouch;
  14909. }
  14910. /**
  14911. * Set hover style (namely "emphasis style") of element,
  14912. * based on the current style of the given `el`.
  14913. *
  14914. * (1)
  14915. * **CONSTRAINTS** for this method:
  14916. * <A> This method MUST be called after all of the normal styles having been adopted
  14917. * to the `el`.
  14918. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14919. * "normal style" having been set to the el.
  14920. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14921. * a default hover style).
  14922. *
  14923. * The reason: this method treat the current style of the `el` as the "normal style"
  14924. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14925. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14926. * logic, where the el should shift from the original emphasis style to the new
  14927. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14928. *
  14929. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14930. * not found a better solution yet to fit the backward compatibility, performance and
  14931. * the current programming style.
  14932. *
  14933. * (2)
  14934. * Call the method for a "root" element once. Do not call it for each descendants.
  14935. * If the descendants elemenets of a group has itself hover style different from the
  14936. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14937. * not call this method for them.
  14938. *
  14939. * (3) These input parameters can be set directly on `el`:
  14940. *
  14941. * @param {module:zrender/Element} el
  14942. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  14943. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  14944. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  14945. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14946. */
  14947. function setHoverStyle(el, hoverStyle) {
  14948. setAsHighDownDispatcher(el, true);
  14949. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  14950. }
  14951. /**
  14952. * @param {module:zrender/Element} el
  14953. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  14954. * Since `setHoverStyle` has the constraint that it must be called after
  14955. * all of the normal style updated, `highDownOnUpdate` is not needed to
  14956. * trigger if both `fromState` and `toState` is 'normal', and needed to
  14957. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  14958. * to sync outside style settings to "emphasis" state.
  14959. * @this {string} This dispatcher `el`.
  14960. * @param {string} fromState Can be "normal" or "emphasis".
  14961. * `fromState` might equal to `toState`,
  14962. * for example, when this method is called when `el` is
  14963. * on "emphasis" state.
  14964. * @param {string} toState Can be "normal" or "emphasis".
  14965. *
  14966. * FIXME
  14967. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  14968. * Because it is not a complete solution. The update
  14969. * listener should not have been mount in element,
  14970. * and the normal/emphasis state should not have
  14971. * mantained on elements.
  14972. *
  14973. * @param {boolean} [el.highDownSilentOnTouch=false]
  14974. * In touch device, mouseover event will be trigger on touchstart event
  14975. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14976. * conveniently use hoverStyle when tap on touch screen without additional
  14977. * code for compatibility.
  14978. * But if the chart/component has select feature, which usually also use
  14979. * hoverStyle, there might be conflict between 'select-highlight' and
  14980. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14981. * In this case, `highDownSilentOnTouch` should be used to disable
  14982. * hover-highlight on touch device.
  14983. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  14984. */
  14985. function setAsHighDownDispatcher(el, asDispatcher) {
  14986. var disable = asDispatcher === false;
  14987. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  14988. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  14989. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  14990. el.__highDownOnUpdate = el.highDownOnUpdate;
  14991. // Simple optimize, since this method might be
  14992. // called for each elements of a group in some cases.
  14993. if (!disable || el.__highDownDispatcher) {
  14994. var method = disable ? 'off' : 'on';
  14995. // Duplicated function will be auto-ignored, see Eventful.js.
  14996. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14997. // Emphasis, normal can be triggered manually by API or other components like hover link.
  14998. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  14999. // Also keep previous record.
  15000. el.__highByOuter = el.__highByOuter || 0;
  15001. el.__highDownDispatcher = !disable;
  15002. }
  15003. }
  15004. /**
  15005. * @param {module:zrender/src/Element} el
  15006. * @return {boolean}
  15007. */
  15008. function isHighDownDispatcher(el) {
  15009. return !!(el && el.__highDownDispatcher);
  15010. }
  15011. /**
  15012. * Support hightlight/downplay record on each elements.
  15013. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15014. * user triggerred hightlight/downplay should not conflict.
  15015. * Only all of the highlightDigit cleared, return to normal.
  15016. * @param {string} highlightKey
  15017. * @return {number} highlightDigit
  15018. */
  15019. function getHighlightDigit(highlightKey) {
  15020. var highlightDigit = _highlightKeyMap[highlightKey];
  15021. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15022. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15023. }
  15024. return highlightDigit;
  15025. }
  15026. /**
  15027. * See more info in `setTextStyleCommon`.
  15028. * @param {Object|module:zrender/graphic/Style} normalStyle
  15029. * @param {Object} emphasisStyle
  15030. * @param {module:echarts/model/Model} normalModel
  15031. * @param {module:echarts/model/Model} emphasisModel
  15032. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15033. * @param {string|Function} [opt.defaultText]
  15034. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15035. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15036. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15037. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15038. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15039. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15040. * @param {Object} [normalSpecified]
  15041. * @param {Object} [emphasisSpecified]
  15042. */
  15043. function setLabelStyle(
  15044. normalStyle, emphasisStyle,
  15045. normalModel, emphasisModel,
  15046. opt,
  15047. normalSpecified, emphasisSpecified
  15048. ) {
  15049. opt = opt || EMPTY_OBJ;
  15050. var labelFetcher = opt.labelFetcher;
  15051. var labelDataIndex = opt.labelDataIndex;
  15052. var labelDimIndex = opt.labelDimIndex;
  15053. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15054. // is not supported util someone requests.
  15055. var showNormal = normalModel.getShallow('show');
  15056. var showEmphasis = emphasisModel.getShallow('show');
  15057. // Consider performance, only fetch label when necessary.
  15058. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15059. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15060. var baseText;
  15061. if (showNormal || showEmphasis) {
  15062. if (labelFetcher) {
  15063. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15064. }
  15065. if (baseText == null) {
  15066. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15067. }
  15068. }
  15069. var normalStyleText = showNormal ? baseText : null;
  15070. var emphasisStyleText = showEmphasis
  15071. ? retrieve2(
  15072. labelFetcher
  15073. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15074. : null,
  15075. baseText
  15076. )
  15077. : null;
  15078. // Optimize: If style.text is null, text will not be drawn.
  15079. if (normalStyleText != null || emphasisStyleText != null) {
  15080. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15081. // values have to be set on `normalStyle`.
  15082. // If we set default values on `emphasisStyle`, consider case:
  15083. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15084. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15085. // Then the 'red' will not work on emphasis.
  15086. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15087. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15088. }
  15089. normalStyle.text = normalStyleText;
  15090. emphasisStyle.text = emphasisStyleText;
  15091. }
  15092. /**
  15093. * Modify label style manually.
  15094. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15095. *
  15096. * @param {module:zrender/src/Element} el
  15097. * @param {Object} [normalStyleProps] optional
  15098. * @param {Object} [emphasisStyleProps] optional
  15099. */
  15100. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15101. var elStyle = el.style;
  15102. if (normalStyleProps) {
  15103. rollbackDefaultTextStyle(elStyle);
  15104. el.setStyle(normalStyleProps);
  15105. applyDefaultTextStyle(elStyle);
  15106. }
  15107. elStyle = el.__hoverStl;
  15108. if (emphasisStyleProps && elStyle) {
  15109. rollbackDefaultTextStyle(elStyle);
  15110. extend(elStyle, emphasisStyleProps);
  15111. applyDefaultTextStyle(elStyle);
  15112. }
  15113. }
  15114. /**
  15115. * Set basic textStyle properties.
  15116. * See more info in `setTextStyleCommon`.
  15117. * @param {Object|module:zrender/graphic/Style} textStyle
  15118. * @param {module:echarts/model/Model} model
  15119. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15120. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15121. * @param {boolean} [isEmphasis]
  15122. */
  15123. function setTextStyle(
  15124. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15125. ) {
  15126. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15127. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15128. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15129. return textStyle;
  15130. }
  15131. /**
  15132. * Set text option in the style.
  15133. * See more info in `setTextStyleCommon`.
  15134. * @deprecated
  15135. * @param {Object} textStyle
  15136. * @param {module:echarts/model/Model} labelModel
  15137. * @param {string|boolean} defaultColor Default text color.
  15138. * If set as false, it will be processed as a emphasis style.
  15139. */
  15140. function setText(textStyle, labelModel, defaultColor) {
  15141. var opt = {isRectText: true};
  15142. var isEmphasis;
  15143. if (defaultColor === false) {
  15144. isEmphasis = true;
  15145. }
  15146. else {
  15147. // Support setting color as 'auto' to get visual color.
  15148. opt.autoColor = defaultColor;
  15149. }
  15150. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15151. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15152. }
  15153. /**
  15154. * The uniform entry of set text style, that is, retrieve style definitions
  15155. * from `model` and set to `textStyle` object.
  15156. *
  15157. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15158. * properties will be set. (Consider the states of normal and emphasis and
  15159. * default value can be adopted, merge would make the logic too complicated
  15160. * to manage.)
  15161. *
  15162. * The `textStyle` object can either be a plain object or an instance of
  15163. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15164. * After this mothod called, the `textStyle` object can then be used in
  15165. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15166. *
  15167. * Default value will be adopted and `insideRollbackOpt` will be created.
  15168. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15169. *
  15170. * opt: {
  15171. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15172. * isRectText: boolean,
  15173. * autoColor: string, specify a color when color is 'auto',
  15174. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15175. * If autoColor specified, it is used as default textFill.
  15176. * useInsideStyle:
  15177. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15178. * if `textFill` is not specified.
  15179. * `false`: Do not use inside style.
  15180. * `null/undefined`: use inside style if `isRectText` is true and
  15181. * `textFill` is not specified and textPosition contains `'inside'`.
  15182. * forceRich: boolean
  15183. * }
  15184. */
  15185. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15186. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15187. opt = opt || EMPTY_OBJ;
  15188. if (opt.isRectText) {
  15189. var textPosition;
  15190. if (opt.getTextPosition) {
  15191. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15192. }
  15193. else {
  15194. textPosition = textStyleModel.getShallow('position')
  15195. || (isEmphasis ? null : 'inside');
  15196. // 'outside' is not a valid zr textPostion value, but used
  15197. // in bar series, and magric type should be considered.
  15198. textPosition === 'outside' && (textPosition = 'top');
  15199. }
  15200. textStyle.textPosition = textPosition;
  15201. textStyle.textOffset = textStyleModel.getShallow('offset');
  15202. var labelRotate = textStyleModel.getShallow('rotate');
  15203. labelRotate != null && (labelRotate *= Math.PI / 180);
  15204. textStyle.textRotation = labelRotate;
  15205. textStyle.textDistance = retrieve2(
  15206. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15207. );
  15208. }
  15209. var ecModel = textStyleModel.ecModel;
  15210. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15211. // Consider case:
  15212. // {
  15213. // data: [{
  15214. // value: 12,
  15215. // label: {
  15216. // rich: {
  15217. // // no 'a' here but using parent 'a'.
  15218. // }
  15219. // }
  15220. // }],
  15221. // rich: {
  15222. // a: { ... }
  15223. // }
  15224. // }
  15225. var richItemNames = getRichItemNames(textStyleModel);
  15226. var richResult;
  15227. if (richItemNames) {
  15228. richResult = {};
  15229. for (var name in richItemNames) {
  15230. if (richItemNames.hasOwnProperty(name)) {
  15231. // Cascade is supported in rich.
  15232. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15233. // In rich, never `disableBox`.
  15234. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15235. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15236. // That might confuses users. So probably we should put `textStyleModel` as the
  15237. // root ancestor of the `richTextStyle`. But that would be a break change.
  15238. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15239. }
  15240. }
  15241. }
  15242. textStyle.rich = richResult;
  15243. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15244. if (opt.forceRich && !opt.textStyle) {
  15245. opt.textStyle = {};
  15246. }
  15247. return textStyle;
  15248. }
  15249. // Consider case:
  15250. // {
  15251. // data: [{
  15252. // value: 12,
  15253. // label: {
  15254. // rich: {
  15255. // // no 'a' here but using parent 'a'.
  15256. // }
  15257. // }
  15258. // }],
  15259. // rich: {
  15260. // a: { ... }
  15261. // }
  15262. // }
  15263. function getRichItemNames(textStyleModel) {
  15264. // Use object to remove duplicated names.
  15265. var richItemNameMap;
  15266. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15267. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15268. if (rich) {
  15269. richItemNameMap = richItemNameMap || {};
  15270. for (var name in rich) {
  15271. if (rich.hasOwnProperty(name)) {
  15272. richItemNameMap[name] = 1;
  15273. }
  15274. }
  15275. }
  15276. textStyleModel = textStyleModel.parentModel;
  15277. }
  15278. return richItemNameMap;
  15279. }
  15280. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15281. // In merge mode, default value should not be given.
  15282. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15283. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15284. || globalTextStyle.color;
  15285. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15286. || globalTextStyle.textBorderColor;
  15287. textStyle.textStrokeWidth = retrieve2(
  15288. textStyleModel.getShallow('textBorderWidth'),
  15289. globalTextStyle.textBorderWidth
  15290. );
  15291. if (!isEmphasis) {
  15292. if (isBlock) {
  15293. textStyle.insideRollbackOpt = opt;
  15294. applyDefaultTextStyle(textStyle);
  15295. }
  15296. // Set default finally.
  15297. if (textStyle.textFill == null) {
  15298. textStyle.textFill = opt.autoColor;
  15299. }
  15300. }
  15301. // Do not use `getFont` here, because merge should be supported, where
  15302. // part of these properties may be changed in emphasis style, and the
  15303. // others should remain their original value got from normal style.
  15304. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15305. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15306. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15307. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15308. textStyle.textAlign = textStyleModel.getShallow('align');
  15309. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15310. || textStyleModel.getShallow('baseline');
  15311. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15312. textStyle.textWidth = textStyleModel.getShallow('width');
  15313. textStyle.textHeight = textStyleModel.getShallow('height');
  15314. textStyle.textTag = textStyleModel.getShallow('tag');
  15315. if (!isBlock || !opt.disableBox) {
  15316. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15317. textStyle.textPadding = textStyleModel.getShallow('padding');
  15318. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15319. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15320. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15321. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15322. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15323. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15324. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15325. }
  15326. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15327. || globalTextStyle.textShadowColor;
  15328. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15329. || globalTextStyle.textShadowBlur;
  15330. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15331. || globalTextStyle.textShadowOffsetX;
  15332. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15333. || globalTextStyle.textShadowOffsetY;
  15334. }
  15335. function getAutoColor(color, opt) {
  15336. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15337. }
  15338. /**
  15339. * Give some default value to the input `textStyle` object, based on the current settings
  15340. * in this `textStyle` object.
  15341. *
  15342. * The Scenario:
  15343. * when text position is `inside` and `textFill` is not specified, we show
  15344. * text border by default for better view. But it should be considered that text position
  15345. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15346. * restore the style.
  15347. *
  15348. * Usage (& NOTICE):
  15349. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15350. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15351. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15352. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15353. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15354. */
  15355. function applyDefaultTextStyle(textStyle) {
  15356. var textPosition = textStyle.textPosition;
  15357. var opt = textStyle.insideRollbackOpt;
  15358. var insideRollback;
  15359. if (opt && textStyle.textFill == null) {
  15360. var autoColor = opt.autoColor;
  15361. var isRectText = opt.isRectText;
  15362. var useInsideStyle = opt.useInsideStyle;
  15363. var useInsideStyleCache = useInsideStyle !== false
  15364. && (useInsideStyle === true
  15365. || (isRectText
  15366. && textPosition
  15367. // textPosition can be [10, 30]
  15368. && typeof textPosition === 'string'
  15369. && textPosition.indexOf('inside') >= 0
  15370. )
  15371. );
  15372. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15373. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15374. if (useInsideStyleCache || useAutoColorCache) {
  15375. insideRollback = {
  15376. textFill: textStyle.textFill,
  15377. textStroke: textStyle.textStroke,
  15378. textStrokeWidth: textStyle.textStrokeWidth
  15379. };
  15380. }
  15381. if (useInsideStyleCache) {
  15382. textStyle.textFill = '#fff';
  15383. // Consider text with #fff overflow its container.
  15384. if (textStyle.textStroke == null) {
  15385. textStyle.textStroke = autoColor;
  15386. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15387. }
  15388. }
  15389. if (useAutoColorCache) {
  15390. textStyle.textFill = autoColor;
  15391. }
  15392. }
  15393. // Always set `insideRollback`, so that the previous one can be cleared.
  15394. textStyle.insideRollback = insideRollback;
  15395. }
  15396. /**
  15397. * Consider the case: in a scatter,
  15398. * label: {
  15399. * normal: {position: 'inside'},
  15400. * emphasis: {position: 'top'}
  15401. * }
  15402. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15403. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15404. * should be retured to 'autoColor', but not keep '#fff'.
  15405. */
  15406. function rollbackDefaultTextStyle(style) {
  15407. var insideRollback = style.insideRollback;
  15408. if (insideRollback) {
  15409. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15410. style.textFill = insideRollback.textFill;
  15411. style.textStroke = insideRollback.textStroke;
  15412. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15413. style.insideRollback = null;
  15414. }
  15415. }
  15416. function getFont(opt, ecModel) {
  15417. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15418. return trim([
  15419. // FIXME in node-canvas fontWeight is before fontStyle
  15420. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15421. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15422. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15423. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15424. ].join(' '));
  15425. }
  15426. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15427. if (typeof dataIndex === 'function') {
  15428. cb = dataIndex;
  15429. dataIndex = null;
  15430. }
  15431. // Do not check 'animation' property directly here. Consider this case:
  15432. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15433. // but its parent model (`seriesModel`) does.
  15434. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15435. if (animationEnabled) {
  15436. var postfix = isUpdate ? 'Update' : '';
  15437. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15438. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15439. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15440. if (typeof animationDelay === 'function') {
  15441. animationDelay = animationDelay(
  15442. dataIndex,
  15443. animatableModel.getAnimationDelayParams
  15444. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15445. : null
  15446. );
  15447. }
  15448. if (typeof duration === 'function') {
  15449. duration = duration(dataIndex);
  15450. }
  15451. duration > 0
  15452. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15453. : (el.stopAnimation(), el.attr(props), cb && cb());
  15454. }
  15455. else {
  15456. el.stopAnimation();
  15457. el.attr(props);
  15458. cb && cb();
  15459. }
  15460. }
  15461. /**
  15462. * Update graphic element properties with or without animation according to the
  15463. * configuration in series.
  15464. *
  15465. * Caution: this method will stop previous animation.
  15466. * So if do not use this method to one element twice before
  15467. * animation starts, unless you know what you are doing.
  15468. *
  15469. * @param {module:zrender/Element} el
  15470. * @param {Object} props
  15471. * @param {module:echarts/model/Model} [animatableModel]
  15472. * @param {number} [dataIndex]
  15473. * @param {Function} [cb]
  15474. * @example
  15475. * graphic.updateProps(el, {
  15476. * position: [100, 100]
  15477. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15478. * // Or
  15479. * graphic.updateProps(el, {
  15480. * position: [100, 100]
  15481. * }, seriesModel, function () { console.log('Animation done!'); });
  15482. */
  15483. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15484. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15485. }
  15486. /**
  15487. * Init graphic element properties with or without animation according to the
  15488. * configuration in series.
  15489. *
  15490. * Caution: this method will stop previous animation.
  15491. * So if do not use this method to one element twice before
  15492. * animation starts, unless you know what you are doing.
  15493. *
  15494. * @param {module:zrender/Element} el
  15495. * @param {Object} props
  15496. * @param {module:echarts/model/Model} [animatableModel]
  15497. * @param {number} [dataIndex]
  15498. * @param {Function} cb
  15499. */
  15500. function initProps(el, props, animatableModel, dataIndex, cb) {
  15501. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15502. }
  15503. /**
  15504. * Get transform matrix of target (param target),
  15505. * in coordinate of its ancestor (param ancestor)
  15506. *
  15507. * @param {module:zrender/mixin/Transformable} target
  15508. * @param {module:zrender/mixin/Transformable} [ancestor]
  15509. */
  15510. function getTransform(target, ancestor) {
  15511. var mat = identity([]);
  15512. while (target && target !== ancestor) {
  15513. mul$1(mat, target.getLocalTransform(), mat);
  15514. target = target.parent;
  15515. }
  15516. return mat;
  15517. }
  15518. /**
  15519. * Apply transform to an vertex.
  15520. * @param {Array.<number>} target [x, y]
  15521. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15522. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15523. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15524. * @param {boolean=} invert Whether use invert matrix.
  15525. * @return {Array.<number>} [x, y]
  15526. */
  15527. function applyTransform$1(target, transform, invert$$1) {
  15528. if (transform && !isArrayLike(transform)) {
  15529. transform = Transformable.getLocalTransform(transform);
  15530. }
  15531. if (invert$$1) {
  15532. transform = invert([], transform);
  15533. }
  15534. return applyTransform([], target, transform);
  15535. }
  15536. /**
  15537. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15538. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15539. * @param {boolean=} invert Whether use invert matrix.
  15540. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15541. */
  15542. function transformDirection(direction, transform, invert$$1) {
  15543. // Pick a base, ensure that transform result will not be (0, 0).
  15544. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15545. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15546. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15547. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15548. var vertex = [
  15549. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15550. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15551. ];
  15552. vertex = applyTransform$1(vertex, transform, invert$$1);
  15553. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15554. ? (vertex[0] > 0 ? 'right' : 'left')
  15555. : (vertex[1] > 0 ? 'bottom' : 'top');
  15556. }
  15557. /**
  15558. * Apply group transition animation from g1 to g2.
  15559. * If no animatableModel, no animation.
  15560. */
  15561. function groupTransition(g1, g2, animatableModel, cb) {
  15562. if (!g1 || !g2) {
  15563. return;
  15564. }
  15565. function getElMap(g) {
  15566. var elMap = {};
  15567. g.traverse(function (el) {
  15568. if (!el.isGroup && el.anid) {
  15569. elMap[el.anid] = el;
  15570. }
  15571. });
  15572. return elMap;
  15573. }
  15574. function getAnimatableProps(el) {
  15575. var obj = {
  15576. position: clone$1(el.position),
  15577. rotation: el.rotation
  15578. };
  15579. if (el.shape) {
  15580. obj.shape = extend({}, el.shape);
  15581. }
  15582. return obj;
  15583. }
  15584. var elMap1 = getElMap(g1);
  15585. g2.traverse(function (el) {
  15586. if (!el.isGroup && el.anid) {
  15587. var oldEl = elMap1[el.anid];
  15588. if (oldEl) {
  15589. var newProp = getAnimatableProps(el);
  15590. el.attr(getAnimatableProps(oldEl));
  15591. updateProps(el, newProp, animatableModel, el.dataIndex);
  15592. }
  15593. // else {
  15594. // if (el.previousProps) {
  15595. // graphic.updateProps
  15596. // }
  15597. // }
  15598. }
  15599. });
  15600. }
  15601. /**
  15602. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15603. * @param {Object} rect {x, y, width, height}
  15604. * @return {Array.<Array.<number>>} A new clipped points.
  15605. */
  15606. function clipPointsByRect(points, rect) {
  15607. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15608. // and when element have border.
  15609. return map(points, function (point) {
  15610. var x = point[0];
  15611. x = mathMax$1(x, rect.x);
  15612. x = mathMin$1(x, rect.x + rect.width);
  15613. var y = point[1];
  15614. y = mathMax$1(y, rect.y);
  15615. y = mathMin$1(y, rect.y + rect.height);
  15616. return [x, y];
  15617. });
  15618. }
  15619. /**
  15620. * @param {Object} targetRect {x, y, width, height}
  15621. * @param {Object} rect {x, y, width, height}
  15622. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15623. */
  15624. function clipRectByRect(targetRect, rect) {
  15625. var x = mathMax$1(targetRect.x, rect.x);
  15626. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15627. var y = mathMax$1(targetRect.y, rect.y);
  15628. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15629. // If the total rect is cliped, nothing, including the border,
  15630. // should be painted. So return undefined.
  15631. if (x2 >= x && y2 >= y) {
  15632. return {
  15633. x: x,
  15634. y: y,
  15635. width: x2 - x,
  15636. height: y2 - y
  15637. };
  15638. }
  15639. }
  15640. /**
  15641. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15642. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15643. * @param {Object} [rect] {x, y, width, height}
  15644. * @return {module:zrender/Element} Icon path or image element.
  15645. */
  15646. function createIcon(iconStr, opt, rect) {
  15647. opt = extend({rectHover: true}, opt);
  15648. var style = opt.style = {strokeNoScale: true};
  15649. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15650. if (iconStr) {
  15651. return iconStr.indexOf('image://') === 0
  15652. ? (
  15653. style.image = iconStr.slice(8),
  15654. defaults(style, rect),
  15655. new ZImage(opt)
  15656. )
  15657. : (
  15658. makePath(
  15659. iconStr.replace('path://', ''),
  15660. opt,
  15661. rect,
  15662. 'center'
  15663. )
  15664. );
  15665. }
  15666. }
  15667. /**
  15668. * Return `true` if the given line (line `a`) and the given polygon
  15669. * are intersect.
  15670. * Note that we do not count colinear as intersect here because no
  15671. * requirement for that. We could do that if required in future.
  15672. *
  15673. * @param {number} a1x
  15674. * @param {number} a1y
  15675. * @param {number} a2x
  15676. * @param {number} a2y
  15677. * @param {Array.<Array.<number>>} points Points of the polygon.
  15678. * @return {boolean}
  15679. */
  15680. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  15681. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  15682. var p = points[i];
  15683. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  15684. return true;
  15685. }
  15686. p2 = p;
  15687. }
  15688. }
  15689. /**
  15690. * Return `true` if the given two lines (line `a` and line `b`)
  15691. * are intersect.
  15692. * Note that we do not count colinear as intersect here because no
  15693. * requirement for that. We could do that if required in future.
  15694. *
  15695. * @param {number} a1x
  15696. * @param {number} a1y
  15697. * @param {number} a2x
  15698. * @param {number} a2y
  15699. * @param {number} b1x
  15700. * @param {number} b1y
  15701. * @param {number} b2x
  15702. * @param {number} b2y
  15703. * @return {boolean}
  15704. */
  15705. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  15706. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  15707. var mx = a2x - a1x;
  15708. var my = a2y - a1y;
  15709. var nx = b2x - b1x;
  15710. var ny = b2y - b1y;
  15711. // `vec_m` and `vec_n` are parallel iff
  15712. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  15713. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  15714. if (nearZero(nmCrossProduct)) {
  15715. return false;
  15716. }
  15717. // `vec_m` and `vec_n` are intersect iff
  15718. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  15719. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  15720. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  15721. var b1a1x = a1x - b1x;
  15722. var b1a1y = a1y - b1y;
  15723. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  15724. if (q < 0 || q > 1) {
  15725. return false;
  15726. }
  15727. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  15728. if (p < 0 || p > 1) {
  15729. return false;
  15730. }
  15731. return true;
  15732. }
  15733. /**
  15734. * Cross product of 2-dimension vector.
  15735. */
  15736. function crossProduct2d(x1, y1, x2, y2) {
  15737. return x1 * y2 - x2 * y1;
  15738. }
  15739. function nearZero(val) {
  15740. return val <= (1e-6) && val >= -(1e-6);
  15741. }
  15742. // Register built-in shapes. These shapes might be overwirtten
  15743. // by users, although we do not recommend that.
  15744. registerShape('circle', Circle);
  15745. registerShape('sector', Sector);
  15746. registerShape('ring', Ring);
  15747. registerShape('polygon', Polygon);
  15748. registerShape('polyline', Polyline);
  15749. registerShape('rect', Rect);
  15750. registerShape('line', Line);
  15751. registerShape('bezierCurve', BezierCurve);
  15752. registerShape('arc', Arc);
  15753. var graphic = (Object.freeze || Object)({
  15754. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15755. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  15756. extendShape: extendShape,
  15757. extendPath: extendPath,
  15758. registerShape: registerShape,
  15759. getShapeClass: getShapeClass,
  15760. makePath: makePath,
  15761. makeImage: makeImage,
  15762. mergePath: mergePath,
  15763. resizePath: resizePath,
  15764. subPixelOptimizeLine: subPixelOptimizeLine,
  15765. subPixelOptimizeRect: subPixelOptimizeRect,
  15766. subPixelOptimize: subPixelOptimize,
  15767. setElementHoverStyle: setElementHoverStyle,
  15768. setHoverStyle: setHoverStyle,
  15769. setAsHighDownDispatcher: setAsHighDownDispatcher,
  15770. isHighDownDispatcher: isHighDownDispatcher,
  15771. getHighlightDigit: getHighlightDigit,
  15772. setLabelStyle: setLabelStyle,
  15773. modifyLabelStyle: modifyLabelStyle,
  15774. setTextStyle: setTextStyle,
  15775. setText: setText,
  15776. getFont: getFont,
  15777. updateProps: updateProps,
  15778. initProps: initProps,
  15779. getTransform: getTransform,
  15780. applyTransform: applyTransform$1,
  15781. transformDirection: transformDirection,
  15782. groupTransition: groupTransition,
  15783. clipPointsByRect: clipPointsByRect,
  15784. clipRectByRect: clipRectByRect,
  15785. createIcon: createIcon,
  15786. linePolygonIntersect: linePolygonIntersect,
  15787. lineLineIntersect: lineLineIntersect,
  15788. Group: Group,
  15789. Image: ZImage,
  15790. Text: Text,
  15791. Circle: Circle,
  15792. Sector: Sector,
  15793. Ring: Ring,
  15794. Polygon: Polygon,
  15795. Polyline: Polyline,
  15796. Rect: Rect,
  15797. Line: Line,
  15798. BezierCurve: BezierCurve,
  15799. Arc: Arc,
  15800. IncrementalDisplayable: IncrementalDisplayble,
  15801. CompoundPath: CompoundPath,
  15802. LinearGradient: LinearGradient,
  15803. RadialGradient: RadialGradient,
  15804. BoundingRect: BoundingRect
  15805. });
  15806. /*
  15807. * Licensed to the Apache Software Foundation (ASF) under one
  15808. * or more contributor license agreements. See the NOTICE file
  15809. * distributed with this work for additional information
  15810. * regarding copyright ownership. The ASF licenses this file
  15811. * to you under the Apache License, Version 2.0 (the
  15812. * "License"); you may not use this file except in compliance
  15813. * with the License. You may obtain a copy of the License at
  15814. *
  15815. * http://www.apache.org/licenses/LICENSE-2.0
  15816. *
  15817. * Unless required by applicable law or agreed to in writing,
  15818. * software distributed under the License is distributed on an
  15819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15820. * KIND, either express or implied. See the License for the
  15821. * specific language governing permissions and limitations
  15822. * under the License.
  15823. */
  15824. var PATH_COLOR = ['textStyle', 'color'];
  15825. var textStyleMixin = {
  15826. /**
  15827. * Get color property or get color from option.textStyle.color
  15828. * @param {boolean} [isEmphasis]
  15829. * @return {string}
  15830. */
  15831. getTextColor: function (isEmphasis) {
  15832. var ecModel = this.ecModel;
  15833. return this.getShallow('color')
  15834. || (
  15835. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15836. );
  15837. },
  15838. /**
  15839. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15840. * @return {string}
  15841. */
  15842. getFont: function () {
  15843. return getFont({
  15844. fontStyle: this.getShallow('fontStyle'),
  15845. fontWeight: this.getShallow('fontWeight'),
  15846. fontSize: this.getShallow('fontSize'),
  15847. fontFamily: this.getShallow('fontFamily')
  15848. }, this.ecModel);
  15849. },
  15850. getTextRect: function (text) {
  15851. return getBoundingRect(
  15852. text,
  15853. this.getFont(),
  15854. this.getShallow('align'),
  15855. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15856. this.getShallow('padding'),
  15857. this.getShallow('lineHeight'),
  15858. this.getShallow('rich'),
  15859. this.getShallow('truncateText')
  15860. );
  15861. }
  15862. };
  15863. /*
  15864. * Licensed to the Apache Software Foundation (ASF) under one
  15865. * or more contributor license agreements. See the NOTICE file
  15866. * distributed with this work for additional information
  15867. * regarding copyright ownership. The ASF licenses this file
  15868. * to you under the Apache License, Version 2.0 (the
  15869. * "License"); you may not use this file except in compliance
  15870. * with the License. You may obtain a copy of the License at
  15871. *
  15872. * http://www.apache.org/licenses/LICENSE-2.0
  15873. *
  15874. * Unless required by applicable law or agreed to in writing,
  15875. * software distributed under the License is distributed on an
  15876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15877. * KIND, either express or implied. See the License for the
  15878. * specific language governing permissions and limitations
  15879. * under the License.
  15880. */
  15881. var getItemStyle = makeStyleMapper(
  15882. [
  15883. ['fill', 'color'],
  15884. ['stroke', 'borderColor'],
  15885. ['lineWidth', 'borderWidth'],
  15886. ['opacity'],
  15887. ['shadowBlur'],
  15888. ['shadowOffsetX'],
  15889. ['shadowOffsetY'],
  15890. ['shadowColor'],
  15891. ['textPosition'],
  15892. ['textAlign']
  15893. ]
  15894. );
  15895. var itemStyleMixin = {
  15896. getItemStyle: function (excludes, includes) {
  15897. var style = getItemStyle(this, excludes, includes);
  15898. var lineDash = this.getBorderLineDash();
  15899. lineDash && (style.lineDash = lineDash);
  15900. return style;
  15901. },
  15902. getBorderLineDash: function () {
  15903. var lineType = this.get('borderType');
  15904. return (lineType === 'solid' || lineType == null) ? null
  15905. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15906. }
  15907. };
  15908. /*
  15909. * Licensed to the Apache Software Foundation (ASF) under one
  15910. * or more contributor license agreements. See the NOTICE file
  15911. * distributed with this work for additional information
  15912. * regarding copyright ownership. The ASF licenses this file
  15913. * to you under the Apache License, Version 2.0 (the
  15914. * "License"); you may not use this file except in compliance
  15915. * with the License. You may obtain a copy of the License at
  15916. *
  15917. * http://www.apache.org/licenses/LICENSE-2.0
  15918. *
  15919. * Unless required by applicable law or agreed to in writing,
  15920. * software distributed under the License is distributed on an
  15921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15922. * KIND, either express or implied. See the License for the
  15923. * specific language governing permissions and limitations
  15924. * under the License.
  15925. */
  15926. /**
  15927. * @module echarts/model/Model
  15928. */
  15929. var mixin$1 = mixin;
  15930. var inner = makeInner();
  15931. /**
  15932. * @alias module:echarts/model/Model
  15933. * @constructor
  15934. * @param {Object} [option]
  15935. * @param {module:echarts/model/Model} [parentModel]
  15936. * @param {module:echarts/model/Global} [ecModel]
  15937. */
  15938. function Model(option, parentModel, ecModel) {
  15939. /**
  15940. * @type {module:echarts/model/Model}
  15941. * @readOnly
  15942. */
  15943. this.parentModel = parentModel;
  15944. /**
  15945. * @type {module:echarts/model/Global}
  15946. * @readOnly
  15947. */
  15948. this.ecModel = ecModel;
  15949. /**
  15950. * @type {Object}
  15951. * @protected
  15952. */
  15953. this.option = option;
  15954. // Simple optimization
  15955. // if (this.init) {
  15956. // if (arguments.length <= 4) {
  15957. // this.init(option, parentModel, ecModel, extraOpt);
  15958. // }
  15959. // else {
  15960. // this.init.apply(this, arguments);
  15961. // }
  15962. // }
  15963. }
  15964. Model.prototype = {
  15965. constructor: Model,
  15966. /**
  15967. * Model 的初始化函数
  15968. * @param {Object} option
  15969. */
  15970. init: null,
  15971. /**
  15972. * 从新的 Option merge
  15973. */
  15974. mergeOption: function (option) {
  15975. merge(this.option, option, true);
  15976. },
  15977. /**
  15978. * @param {string|Array.<string>} path
  15979. * @param {boolean} [ignoreParent=false]
  15980. * @return {*}
  15981. */
  15982. get: function (path, ignoreParent) {
  15983. if (path == null) {
  15984. return this.option;
  15985. }
  15986. return doGet(
  15987. this.option,
  15988. this.parsePath(path),
  15989. !ignoreParent && getParent(this, path)
  15990. );
  15991. },
  15992. /**
  15993. * @param {string} key
  15994. * @param {boolean} [ignoreParent=false]
  15995. * @return {*}
  15996. */
  15997. getShallow: function (key, ignoreParent) {
  15998. var option = this.option;
  15999. var val = option == null ? option : option[key];
  16000. var parentModel = !ignoreParent && getParent(this, key);
  16001. if (val == null && parentModel) {
  16002. val = parentModel.getShallow(key);
  16003. }
  16004. return val;
  16005. },
  16006. /**
  16007. * @param {string|Array.<string>} [path]
  16008. * @param {module:echarts/model/Model} [parentModel]
  16009. * @return {module:echarts/model/Model}
  16010. */
  16011. getModel: function (path, parentModel) {
  16012. var obj = path == null
  16013. ? this.option
  16014. : doGet(this.option, path = this.parsePath(path));
  16015. var thisParentModel;
  16016. parentModel = parentModel || (
  16017. (thisParentModel = getParent(this, path))
  16018. && thisParentModel.getModel(path)
  16019. );
  16020. return new Model(obj, parentModel, this.ecModel);
  16021. },
  16022. /**
  16023. * If model has option
  16024. */
  16025. isEmpty: function () {
  16026. return this.option == null;
  16027. },
  16028. restoreData: function () {},
  16029. // Pending
  16030. clone: function () {
  16031. var Ctor = this.constructor;
  16032. return new Ctor(clone(this.option));
  16033. },
  16034. setReadOnly: function (properties) {
  16035. // clazzUtil.setReadOnly(this, properties);
  16036. },
  16037. // If path is null/undefined, return null/undefined.
  16038. parsePath: function (path) {
  16039. if (typeof path === 'string') {
  16040. path = path.split('.');
  16041. }
  16042. return path;
  16043. },
  16044. /**
  16045. * @param {Function} getParentMethod
  16046. * param {Array.<string>|string} path
  16047. * return {module:echarts/model/Model}
  16048. */
  16049. customizeGetParent: function (getParentMethod) {
  16050. inner(this).getParent = getParentMethod;
  16051. },
  16052. isAnimationEnabled: function () {
  16053. if (!env$1.node) {
  16054. if (this.option.animation != null) {
  16055. return !!this.option.animation;
  16056. }
  16057. else if (this.parentModel) {
  16058. return this.parentModel.isAnimationEnabled();
  16059. }
  16060. }
  16061. }
  16062. };
  16063. function doGet(obj, pathArr, parentModel) {
  16064. for (var i = 0; i < pathArr.length; i++) {
  16065. // Ignore empty
  16066. if (!pathArr[i]) {
  16067. continue;
  16068. }
  16069. // obj could be number/string/... (like 0)
  16070. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16071. if (obj == null) {
  16072. break;
  16073. }
  16074. }
  16075. if (obj == null && parentModel) {
  16076. obj = parentModel.get(pathArr);
  16077. }
  16078. return obj;
  16079. }
  16080. // `path` can be null/undefined
  16081. function getParent(model, path) {
  16082. var getParentMethod = inner(model).getParent;
  16083. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16084. }
  16085. // Enable Model.extend.
  16086. enableClassExtend(Model);
  16087. enableClassCheck(Model);
  16088. mixin$1(Model, lineStyleMixin);
  16089. mixin$1(Model, areaStyleMixin);
  16090. mixin$1(Model, textStyleMixin);
  16091. mixin$1(Model, itemStyleMixin);
  16092. /*
  16093. * Licensed to the Apache Software Foundation (ASF) under one
  16094. * or more contributor license agreements. See the NOTICE file
  16095. * distributed with this work for additional information
  16096. * regarding copyright ownership. The ASF licenses this file
  16097. * to you under the Apache License, Version 2.0 (the
  16098. * "License"); you may not use this file except in compliance
  16099. * with the License. You may obtain a copy of the License at
  16100. *
  16101. * http://www.apache.org/licenses/LICENSE-2.0
  16102. *
  16103. * Unless required by applicable law or agreed to in writing,
  16104. * software distributed under the License is distributed on an
  16105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16106. * KIND, either express or implied. See the License for the
  16107. * specific language governing permissions and limitations
  16108. * under the License.
  16109. */
  16110. var base = 0;
  16111. /**
  16112. * @public
  16113. * @param {string} type
  16114. * @return {string}
  16115. */
  16116. function getUID(type) {
  16117. // Considering the case of crossing js context,
  16118. // use Math.random to make id as unique as possible.
  16119. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16120. }
  16121. /**
  16122. * @inner
  16123. */
  16124. function enableSubTypeDefaulter(entity) {
  16125. var subTypeDefaulters = {};
  16126. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16127. componentType = parseClassType$1(componentType);
  16128. subTypeDefaulters[componentType.main] = defaulter;
  16129. };
  16130. entity.determineSubType = function (componentType, option) {
  16131. var type = option.type;
  16132. if (!type) {
  16133. var componentTypeMain = parseClassType$1(componentType).main;
  16134. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16135. type = subTypeDefaulters[componentTypeMain](option);
  16136. }
  16137. }
  16138. return type;
  16139. };
  16140. return entity;
  16141. }
  16142. /**
  16143. * Topological travel on Activity Network (Activity On Vertices).
  16144. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16145. *
  16146. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16147. *
  16148. * If there is circle dependencey, Error will be thrown.
  16149. *
  16150. */
  16151. function enableTopologicalTravel(entity, dependencyGetter) {
  16152. /**
  16153. * @public
  16154. * @param {Array.<string>} targetNameList Target Component type list.
  16155. * Can be ['aa', 'bb', 'aa.xx']
  16156. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16157. * @param {Function} callback Params: componentType, dependencies.
  16158. * @param {Object} context Scope of callback.
  16159. */
  16160. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16161. if (!targetNameList.length) {
  16162. return;
  16163. }
  16164. var result = makeDepndencyGraph(fullNameList);
  16165. var graph = result.graph;
  16166. var stack = result.noEntryList;
  16167. var targetNameSet = {};
  16168. each$1(targetNameList, function (name) {
  16169. targetNameSet[name] = true;
  16170. });
  16171. while (stack.length) {
  16172. var currComponentType = stack.pop();
  16173. var currVertex = graph[currComponentType];
  16174. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16175. if (isInTargetNameSet) {
  16176. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16177. delete targetNameSet[currComponentType];
  16178. }
  16179. each$1(
  16180. currVertex.successor,
  16181. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16182. );
  16183. }
  16184. each$1(targetNameSet, function () {
  16185. throw new Error('Circle dependency may exists');
  16186. });
  16187. function removeEdge(succComponentType) {
  16188. graph[succComponentType].entryCount--;
  16189. if (graph[succComponentType].entryCount === 0) {
  16190. stack.push(succComponentType);
  16191. }
  16192. }
  16193. // Consider this case: legend depends on series, and we call
  16194. // chart.setOption({series: [...]}), where only series is in option.
  16195. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16196. // not be called, but only sereis.mergeOption is called. Thus legend
  16197. // have no chance to update its local record about series (like which
  16198. // name of series is available in legend).
  16199. function removeEdgeAndAdd(succComponentType) {
  16200. targetNameSet[succComponentType] = true;
  16201. removeEdge(succComponentType);
  16202. }
  16203. };
  16204. /**
  16205. * DepndencyGraph: {Object}
  16206. * key: conponentType,
  16207. * value: {
  16208. * successor: [conponentTypes...],
  16209. * originalDeps: [conponentTypes...],
  16210. * entryCount: {number}
  16211. * }
  16212. */
  16213. function makeDepndencyGraph(fullNameList) {
  16214. var graph = {};
  16215. var noEntryList = [];
  16216. each$1(fullNameList, function (name) {
  16217. var thisItem = createDependencyGraphItem(graph, name);
  16218. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16219. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16220. thisItem.entryCount = availableDeps.length;
  16221. if (thisItem.entryCount === 0) {
  16222. noEntryList.push(name);
  16223. }
  16224. each$1(availableDeps, function (dependentName) {
  16225. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16226. thisItem.predecessor.push(dependentName);
  16227. }
  16228. var thatItem = createDependencyGraphItem(graph, dependentName);
  16229. if (indexOf(thatItem.successor, dependentName) < 0) {
  16230. thatItem.successor.push(name);
  16231. }
  16232. });
  16233. });
  16234. return {graph: graph, noEntryList: noEntryList};
  16235. }
  16236. function createDependencyGraphItem(graph, name) {
  16237. if (!graph[name]) {
  16238. graph[name] = {predecessor: [], successor: []};
  16239. }
  16240. return graph[name];
  16241. }
  16242. function getAvailableDependencies(originalDeps, fullNameList) {
  16243. var availableDeps = [];
  16244. each$1(originalDeps, function (dep) {
  16245. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16246. });
  16247. return availableDeps;
  16248. }
  16249. }
  16250. /*
  16251. * Licensed to the Apache Software Foundation (ASF) under one
  16252. * or more contributor license agreements. See the NOTICE file
  16253. * distributed with this work for additional information
  16254. * regarding copyright ownership. The ASF licenses this file
  16255. * to you under the Apache License, Version 2.0 (the
  16256. * "License"); you may not use this file except in compliance
  16257. * with the License. You may obtain a copy of the License at
  16258. *
  16259. * http://www.apache.org/licenses/LICENSE-2.0
  16260. *
  16261. * Unless required by applicable law or agreed to in writing,
  16262. * software distributed under the License is distributed on an
  16263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16264. * KIND, either express or implied. See the License for the
  16265. * specific language governing permissions and limitations
  16266. * under the License.
  16267. */
  16268. /*
  16269. * A third-party license is embeded for some of the code in this file:
  16270. * The method "quantile" was copied from "d3.js".
  16271. * (See more details in the comment of the method below.)
  16272. * The use of the source code of this file is also subject to the terms
  16273. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16274. * </licenses/LICENSE-d3>).
  16275. */
  16276. var RADIAN_EPSILON = 1e-4;
  16277. function _trim(str) {
  16278. return str.replace(/^\s+|\s+$/g, '');
  16279. }
  16280. /**
  16281. * Linear mapping a value from domain to range
  16282. * @memberOf module:echarts/util/number
  16283. * @param {(number|Array.<number>)} val
  16284. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16285. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16286. * @param {boolean} clamp
  16287. * @return {(number|Array.<number>}
  16288. */
  16289. function linearMap(val, domain, range, clamp) {
  16290. var subDomain = domain[1] - domain[0];
  16291. var subRange = range[1] - range[0];
  16292. if (subDomain === 0) {
  16293. return subRange === 0
  16294. ? range[0]
  16295. : (range[0] + range[1]) / 2;
  16296. }
  16297. // Avoid accuracy problem in edge, such as
  16298. // 146.39 - 62.83 === 83.55999999999999.
  16299. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16300. // It is a little verbose for efficiency considering this method
  16301. // is a hotspot.
  16302. if (clamp) {
  16303. if (subDomain > 0) {
  16304. if (val <= domain[0]) {
  16305. return range[0];
  16306. }
  16307. else if (val >= domain[1]) {
  16308. return range[1];
  16309. }
  16310. }
  16311. else {
  16312. if (val >= domain[0]) {
  16313. return range[0];
  16314. }
  16315. else if (val <= domain[1]) {
  16316. return range[1];
  16317. }
  16318. }
  16319. }
  16320. else {
  16321. if (val === domain[0]) {
  16322. return range[0];
  16323. }
  16324. if (val === domain[1]) {
  16325. return range[1];
  16326. }
  16327. }
  16328. return (val - domain[0]) / subDomain * subRange + range[0];
  16329. }
  16330. /**
  16331. * Convert a percent string to absolute number.
  16332. * Returns NaN if percent is not a valid string or number
  16333. * @memberOf module:echarts/util/number
  16334. * @param {string|number} percent
  16335. * @param {number} all
  16336. * @return {number}
  16337. */
  16338. function parsePercent$1(percent, all) {
  16339. switch (percent) {
  16340. case 'center':
  16341. case 'middle':
  16342. percent = '50%';
  16343. break;
  16344. case 'left':
  16345. case 'top':
  16346. percent = '0%';
  16347. break;
  16348. case 'right':
  16349. case 'bottom':
  16350. percent = '100%';
  16351. break;
  16352. }
  16353. if (typeof percent === 'string') {
  16354. if (_trim(percent).match(/%$/)) {
  16355. return parseFloat(percent) / 100 * all;
  16356. }
  16357. return parseFloat(percent);
  16358. }
  16359. return percent == null ? NaN : +percent;
  16360. }
  16361. /**
  16362. * (1) Fix rounding error of float numbers.
  16363. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16364. *
  16365. * @param {number} x
  16366. * @param {number} [precision]
  16367. * @param {boolean} [returnStr]
  16368. * @return {number|string}
  16369. */
  16370. function round$1(x, precision, returnStr) {
  16371. if (precision == null) {
  16372. precision = 10;
  16373. }
  16374. // Avoid range error
  16375. precision = Math.min(Math.max(0, precision), 20);
  16376. x = (+x).toFixed(precision);
  16377. return returnStr ? x : +x;
  16378. }
  16379. /**
  16380. * asc sort arr.
  16381. * The input arr will be modified.
  16382. *
  16383. * @param {Array} arr
  16384. * @return {Array} The input arr.
  16385. */
  16386. /**
  16387. * Get precision
  16388. * @param {number} val
  16389. */
  16390. /**
  16391. * @param {string|number} val
  16392. * @return {number}
  16393. */
  16394. function getPrecisionSafe(val) {
  16395. var str = val.toString();
  16396. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16397. var eIndex = str.indexOf('e');
  16398. if (eIndex > 0) {
  16399. var precision = +str.slice(eIndex + 1);
  16400. return precision < 0 ? -precision : 0;
  16401. }
  16402. else {
  16403. var dotIndex = str.indexOf('.');
  16404. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16405. }
  16406. }
  16407. /**
  16408. * Minimal dicernible data precisioin according to a single pixel.
  16409. *
  16410. * @param {Array.<number>} dataExtent
  16411. * @param {Array.<number>} pixelExtent
  16412. * @return {number} precision
  16413. */
  16414. function getPixelPrecision(dataExtent, pixelExtent) {
  16415. var log = Math.log;
  16416. var LN10 = Math.LN10;
  16417. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16418. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16419. // toFixed() digits argument must be between 0 and 20.
  16420. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16421. return !isFinite(precision) ? 20 : precision;
  16422. }
  16423. /**
  16424. * Get a data of given precision, assuring the sum of percentages
  16425. * in valueList is 1.
  16426. * The largest remainer method is used.
  16427. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16428. *
  16429. * @param {Array.<number>} valueList a list of all data
  16430. * @param {number} idx index of the data to be processed in valueList
  16431. * @param {number} precision integer number showing digits of precision
  16432. * @return {number} percent ranging from 0 to 100
  16433. */
  16434. function getPercentWithPrecision(valueList, idx, precision) {
  16435. if (!valueList[idx]) {
  16436. return 0;
  16437. }
  16438. var sum = reduce(valueList, function (acc, val) {
  16439. return acc + (isNaN(val) ? 0 : val);
  16440. }, 0);
  16441. if (sum === 0) {
  16442. return 0;
  16443. }
  16444. var digits = Math.pow(10, precision);
  16445. var votesPerQuota = map(valueList, function (val) {
  16446. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16447. });
  16448. var targetSeats = digits * 100;
  16449. var seats = map(votesPerQuota, function (votes) {
  16450. // Assign automatic seats.
  16451. return Math.floor(votes);
  16452. });
  16453. var currentSum = reduce(seats, function (acc, val) {
  16454. return acc + val;
  16455. }, 0);
  16456. var remainder = map(votesPerQuota, function (votes, idx) {
  16457. return votes - seats[idx];
  16458. });
  16459. // Has remainding votes.
  16460. while (currentSum < targetSeats) {
  16461. // Find next largest remainder.
  16462. var max = Number.NEGATIVE_INFINITY;
  16463. var maxId = null;
  16464. for (var i = 0, len = remainder.length; i < len; ++i) {
  16465. if (remainder[i] > max) {
  16466. max = remainder[i];
  16467. maxId = i;
  16468. }
  16469. }
  16470. // Add a vote to max remainder.
  16471. ++seats[maxId];
  16472. remainder[maxId] = 0;
  16473. ++currentSum;
  16474. }
  16475. return seats[idx] / digits;
  16476. }
  16477. // Number.MAX_SAFE_INTEGER, ie do not support.
  16478. /**
  16479. * To 0 - 2 * PI, considering negative radian.
  16480. * @param {number} radian
  16481. * @return {number}
  16482. */
  16483. function remRadian(radian) {
  16484. var pi2 = Math.PI * 2;
  16485. return (radian % pi2 + pi2) % pi2;
  16486. }
  16487. /**
  16488. * @param {type} radian
  16489. * @return {boolean}
  16490. */
  16491. function isRadianAroundZero(val) {
  16492. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16493. }
  16494. /* eslint-disable */
  16495. 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
  16496. /* eslint-enable */
  16497. /**
  16498. * @param {string|Date|number} value These values can be accepted:
  16499. * + An instance of Date, represent a time in its own time zone.
  16500. * + Or string in a subset of ISO 8601, only including:
  16501. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16502. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16503. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16504. * all of which will be treated as local time if time zone is not specified
  16505. * (see <https://momentjs.com/>).
  16506. * + Or other string format, including (all of which will be treated as loacal time):
  16507. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16508. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16509. * + a timestamp, which represent a time in UTC.
  16510. * @return {Date} date
  16511. */
  16512. function parseDate(value) {
  16513. if (value instanceof Date) {
  16514. return value;
  16515. }
  16516. else if (typeof value === 'string') {
  16517. // Different browsers parse date in different way, so we parse it manually.
  16518. // Some other issues:
  16519. // new Date('1970-01-01') is UTC,
  16520. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16521. // See issue #3623
  16522. var match = TIME_REG.exec(value);
  16523. if (!match) {
  16524. // return Invalid Date.
  16525. return new Date(NaN);
  16526. }
  16527. // Use local time when no timezone offset specifed.
  16528. if (!match[8]) {
  16529. // match[n] can only be string or undefined.
  16530. // But take care of '12' + 1 => '121'.
  16531. return new Date(
  16532. +match[1],
  16533. +(match[2] || 1) - 1,
  16534. +match[3] || 1,
  16535. +match[4] || 0,
  16536. +(match[5] || 0),
  16537. +match[6] || 0,
  16538. +match[7] || 0
  16539. );
  16540. }
  16541. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16542. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16543. // For example, system timezone is set as "Time Zone: America/Toronto",
  16544. // then these code will get different result:
  16545. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16546. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16547. // So we should not use `new Date`, but use `Date.UTC`.
  16548. else {
  16549. var hour = +match[4] || 0;
  16550. if (match[8].toUpperCase() !== 'Z') {
  16551. hour -= match[8].slice(0, 3);
  16552. }
  16553. return new Date(Date.UTC(
  16554. +match[1],
  16555. +(match[2] || 1) - 1,
  16556. +match[3] || 1,
  16557. hour,
  16558. +(match[5] || 0),
  16559. +match[6] || 0,
  16560. +match[7] || 0
  16561. ));
  16562. }
  16563. }
  16564. else if (value == null) {
  16565. return new Date(NaN);
  16566. }
  16567. return new Date(Math.round(value));
  16568. }
  16569. /**
  16570. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16571. *
  16572. * @param {number} val
  16573. * @return {number}
  16574. */
  16575. function quantity(val) {
  16576. return Math.pow(10, quantityExponent(val));
  16577. }
  16578. /**
  16579. * Exponent of the quantity of a number
  16580. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16581. *
  16582. * @param {number} val non-negative value
  16583. * @return {number}
  16584. */
  16585. function quantityExponent(val) {
  16586. if (val === 0) {
  16587. return 0;
  16588. }
  16589. var exp = Math.floor(Math.log(val) / Math.LN10);
  16590. /**
  16591. * exp is expected to be the rounded-down result of the base-10 log of val.
  16592. * But due to the precision loss with Math.log(val), we need to restore it
  16593. * using 10^exp to make sure we can get val back from exp. #11249
  16594. */
  16595. if (val / Math.pow(10, exp) >= 10) {
  16596. exp++;
  16597. }
  16598. return exp;
  16599. }
  16600. /**
  16601. * find a “nice” number approximately equal to x. Round the number if round = true,
  16602. * take ceiling if round = false. The primary observation is that the “nicest”
  16603. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16604. *
  16605. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16606. *
  16607. * @param {number} val Non-negative value.
  16608. * @param {boolean} round
  16609. * @return {number}
  16610. */
  16611. function nice(val, round) {
  16612. var exponent = quantityExponent(val);
  16613. var exp10 = Math.pow(10, exponent);
  16614. var f = val / exp10; // 1 <= f < 10
  16615. var nf;
  16616. if (round) {
  16617. if (f < 1.5) {
  16618. nf = 1;
  16619. }
  16620. else if (f < 2.5) {
  16621. nf = 2;
  16622. }
  16623. else if (f < 4) {
  16624. nf = 3;
  16625. }
  16626. else if (f < 7) {
  16627. nf = 5;
  16628. }
  16629. else {
  16630. nf = 10;
  16631. }
  16632. }
  16633. else {
  16634. if (f < 1) {
  16635. nf = 1;
  16636. }
  16637. else if (f < 2) {
  16638. nf = 2;
  16639. }
  16640. else if (f < 3) {
  16641. nf = 3;
  16642. }
  16643. else if (f < 5) {
  16644. nf = 5;
  16645. }
  16646. else {
  16647. nf = 10;
  16648. }
  16649. }
  16650. val = nf * exp10;
  16651. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16652. // 20 is the uppper bound of toFixed.
  16653. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16654. }
  16655. /**
  16656. * This code was copied from "d3.js"
  16657. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  16658. * See the license statement at the head of this file.
  16659. * @param {Array.<number>} ascArr
  16660. */
  16661. /**
  16662. * Order intervals asc, and split them when overlap.
  16663. * expect(numberUtil.reformIntervals([
  16664. * {interval: [18, 62], close: [1, 1]},
  16665. * {interval: [-Infinity, -70], close: [0, 0]},
  16666. * {interval: [-70, -26], close: [1, 1]},
  16667. * {interval: [-26, 18], close: [1, 1]},
  16668. * {interval: [62, 150], close: [1, 1]},
  16669. * {interval: [106, 150], close: [1, 1]},
  16670. * {interval: [150, Infinity], close: [0, 0]}
  16671. * ])).toEqual([
  16672. * {interval: [-Infinity, -70], close: [0, 0]},
  16673. * {interval: [-70, -26], close: [1, 1]},
  16674. * {interval: [-26, 18], close: [0, 1]},
  16675. * {interval: [18, 62], close: [0, 1]},
  16676. * {interval: [62, 150], close: [0, 1]},
  16677. * {interval: [150, Infinity], close: [0, 0]}
  16678. * ]);
  16679. * @param {Array.<Object>} list, where `close` mean open or close
  16680. * of the interval, and Infinity can be used.
  16681. * @return {Array.<Object>} The origin list, which has been reformed.
  16682. */
  16683. /**
  16684. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16685. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16686. * subtraction forces infinities to NaN
  16687. *
  16688. * @param {*} v
  16689. * @return {boolean}
  16690. */
  16691. /*
  16692. * Licensed to the Apache Software Foundation (ASF) under one
  16693. * or more contributor license agreements. See the NOTICE file
  16694. * distributed with this work for additional information
  16695. * regarding copyright ownership. The ASF licenses this file
  16696. * to you under the Apache License, Version 2.0 (the
  16697. * "License"); you may not use this file except in compliance
  16698. * with the License. You may obtain a copy of the License at
  16699. *
  16700. * http://www.apache.org/licenses/LICENSE-2.0
  16701. *
  16702. * Unless required by applicable law or agreed to in writing,
  16703. * software distributed under the License is distributed on an
  16704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16705. * KIND, either express or implied. See the License for the
  16706. * specific language governing permissions and limitations
  16707. * under the License.
  16708. */
  16709. // import Text from 'zrender/src/graphic/Text';
  16710. /**
  16711. * 每三位默认加,格式化
  16712. * @param {string|number} x
  16713. * @return {string}
  16714. */
  16715. function addCommas(x) {
  16716. if (isNaN(x)) {
  16717. return '-';
  16718. }
  16719. x = (x + '').split('.');
  16720. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16721. + (x.length > 1 ? ('.' + x[1]) : '');
  16722. }
  16723. /**
  16724. * @param {string} str
  16725. * @param {boolean} [upperCaseFirst=false]
  16726. * @return {string} str
  16727. */
  16728. var normalizeCssArray$1 = normalizeCssArray;
  16729. var replaceReg = /([&<>"'])/g;
  16730. var replaceMap = {
  16731. '&': '&amp;',
  16732. '<': '&lt;',
  16733. '>': '&gt;',
  16734. '"': '&quot;',
  16735. '\'': '&#39;'
  16736. };
  16737. function encodeHTML(source) {
  16738. return source == null
  16739. ? ''
  16740. : (source + '').replace(replaceReg, function (str, c) {
  16741. return replaceMap[c];
  16742. });
  16743. }
  16744. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16745. var wrapVar = function (varName, seriesIdx) {
  16746. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16747. };
  16748. /**
  16749. * Template formatter
  16750. * @param {string} tpl
  16751. * @param {Array.<Object>|Object} paramsList
  16752. * @param {boolean} [encode=false]
  16753. * @return {string}
  16754. */
  16755. function formatTpl(tpl, paramsList, encode) {
  16756. if (!isArray(paramsList)) {
  16757. paramsList = [paramsList];
  16758. }
  16759. var seriesLen = paramsList.length;
  16760. if (!seriesLen) {
  16761. return '';
  16762. }
  16763. var $vars = paramsList[0].$vars || [];
  16764. for (var i = 0; i < $vars.length; i++) {
  16765. var alias = TPL_VAR_ALIAS[i];
  16766. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16767. }
  16768. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16769. for (var k = 0; k < $vars.length; k++) {
  16770. var val = paramsList[seriesIdx][$vars[k]];
  16771. tpl = tpl.replace(
  16772. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16773. encode ? encodeHTML(val) : val
  16774. );
  16775. }
  16776. }
  16777. return tpl;
  16778. }
  16779. /**
  16780. * simple Template formatter
  16781. *
  16782. * @param {string} tpl
  16783. * @param {Object} param
  16784. * @param {boolean} [encode=false]
  16785. * @return {string}
  16786. */
  16787. /**
  16788. * @param {Object|string} [opt] If string, means color.
  16789. * @param {string} [opt.color]
  16790. * @param {string} [opt.extraCssText]
  16791. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16792. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16793. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16794. * @return {string}
  16795. */
  16796. function getTooltipMarker(opt, extraCssText) {
  16797. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16798. var color = opt.color;
  16799. var type = opt.type;
  16800. var extraCssText = opt.extraCssText;
  16801. var renderMode = opt.renderMode || 'html';
  16802. var markerId = opt.markerId || 'X';
  16803. if (!color) {
  16804. return '';
  16805. }
  16806. if (renderMode === 'html') {
  16807. return type === 'subItem'
  16808. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16809. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16810. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16811. : '<span style="display:inline-block;margin-right:5px;'
  16812. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16813. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16814. }
  16815. else {
  16816. // Space for rich element marker
  16817. return {
  16818. renderMode: renderMode,
  16819. content: '{marker' + markerId + '|} ',
  16820. style: {
  16821. color: color
  16822. }
  16823. };
  16824. }
  16825. }
  16826. function pad(str, len) {
  16827. str += '';
  16828. return '0000'.substr(0, len - str.length) + str;
  16829. }
  16830. /**
  16831. * ISO Date format
  16832. * @param {string} tpl
  16833. * @param {number} value
  16834. * @param {boolean} [isUTC=false] Default in local time.
  16835. * see `module:echarts/scale/Time`
  16836. * and `module:echarts/util/number#parseDate`.
  16837. * @inner
  16838. */
  16839. function formatTime(tpl, value, isUTC) {
  16840. if (tpl === 'week'
  16841. || tpl === 'month'
  16842. || tpl === 'quarter'
  16843. || tpl === 'half-year'
  16844. || tpl === 'year'
  16845. ) {
  16846. tpl = 'MM-dd\nyyyy';
  16847. }
  16848. var date = parseDate(value);
  16849. var utc = isUTC ? 'UTC' : '';
  16850. var y = date['get' + utc + 'FullYear']();
  16851. var M = date['get' + utc + 'Month']() + 1;
  16852. var d = date['get' + utc + 'Date']();
  16853. var h = date['get' + utc + 'Hours']();
  16854. var m = date['get' + utc + 'Minutes']();
  16855. var s = date['get' + utc + 'Seconds']();
  16856. var S = date['get' + utc + 'Milliseconds']();
  16857. tpl = tpl.replace('MM', pad(M, 2))
  16858. .replace('M', M)
  16859. .replace('yyyy', y)
  16860. .replace('yy', y % 100)
  16861. .replace('dd', pad(d, 2))
  16862. .replace('d', d)
  16863. .replace('hh', pad(h, 2))
  16864. .replace('h', h)
  16865. .replace('mm', pad(m, 2))
  16866. .replace('m', m)
  16867. .replace('ss', pad(s, 2))
  16868. .replace('s', s)
  16869. .replace('SSS', pad(S, 3));
  16870. return tpl;
  16871. }
  16872. /**
  16873. * Capital first
  16874. * @param {string} str
  16875. * @return {string}
  16876. */
  16877. var truncateText$1 = truncateText;
  16878. /**
  16879. * @public
  16880. * @param {Object} opt
  16881. * @param {string} opt.text
  16882. * @param {string} opt.font
  16883. * @param {string} [opt.textAlign='left']
  16884. * @param {string} [opt.textVerticalAlign='top']
  16885. * @param {Array.<number>} [opt.textPadding]
  16886. * @param {number} [opt.textLineHeight]
  16887. * @param {Object} [opt.rich]
  16888. * @param {Object} [opt.truncate]
  16889. * @return {Object} {x, y, width, height, lineHeight}
  16890. */
  16891. /**
  16892. * @deprecated
  16893. * the `textLineHeight` was added later.
  16894. * For backward compatiblility, put it as the last parameter.
  16895. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16896. */
  16897. /*
  16898. * Licensed to the Apache Software Foundation (ASF) under one
  16899. * or more contributor license agreements. See the NOTICE file
  16900. * distributed with this work for additional information
  16901. * regarding copyright ownership. The ASF licenses this file
  16902. * to you under the Apache License, Version 2.0 (the
  16903. * "License"); you may not use this file except in compliance
  16904. * with the License. You may obtain a copy of the License at
  16905. *
  16906. * http://www.apache.org/licenses/LICENSE-2.0
  16907. *
  16908. * Unless required by applicable law or agreed to in writing,
  16909. * software distributed under the License is distributed on an
  16910. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16911. * KIND, either express or implied. See the License for the
  16912. * specific language governing permissions and limitations
  16913. * under the License.
  16914. */
  16915. // Layout helpers for each component positioning
  16916. var each$3 = each$1;
  16917. /**
  16918. * @public
  16919. */
  16920. var LOCATION_PARAMS = [
  16921. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16922. ];
  16923. /**
  16924. * @public
  16925. */
  16926. var HV_NAMES = [
  16927. ['width', 'left', 'right'],
  16928. ['height', 'top', 'bottom']
  16929. ];
  16930. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16931. var x = 0;
  16932. var y = 0;
  16933. if (maxWidth == null) {
  16934. maxWidth = Infinity;
  16935. }
  16936. if (maxHeight == null) {
  16937. maxHeight = Infinity;
  16938. }
  16939. var currentLineMaxSize = 0;
  16940. group.eachChild(function (child, idx) {
  16941. var position = child.position;
  16942. var rect = child.getBoundingRect();
  16943. var nextChild = group.childAt(idx + 1);
  16944. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16945. var nextX;
  16946. var nextY;
  16947. if (orient === 'horizontal') {
  16948. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16949. nextX = x + moveX;
  16950. // Wrap when width exceeds maxWidth or meet a `newline` group
  16951. // FIXME compare before adding gap?
  16952. if (nextX > maxWidth || child.newline) {
  16953. x = 0;
  16954. nextX = moveX;
  16955. y += currentLineMaxSize + gap;
  16956. currentLineMaxSize = rect.height;
  16957. }
  16958. else {
  16959. // FIXME: consider rect.y is not `0`?
  16960. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16961. }
  16962. }
  16963. else {
  16964. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16965. nextY = y + moveY;
  16966. // Wrap when width exceeds maxHeight or meet a `newline` group
  16967. if (nextY > maxHeight || child.newline) {
  16968. x += currentLineMaxSize + gap;
  16969. y = 0;
  16970. nextY = moveY;
  16971. currentLineMaxSize = rect.width;
  16972. }
  16973. else {
  16974. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16975. }
  16976. }
  16977. if (child.newline) {
  16978. return;
  16979. }
  16980. position[0] = x;
  16981. position[1] = y;
  16982. orient === 'horizontal'
  16983. ? (x = nextX + gap)
  16984. : (y = nextY + gap);
  16985. });
  16986. }
  16987. /**
  16988. * VBox or HBox layouting
  16989. * @param {string} orient
  16990. * @param {module:zrender/container/Group} group
  16991. * @param {number} gap
  16992. * @param {number} [width=Infinity]
  16993. * @param {number} [height=Infinity]
  16994. */
  16995. /**
  16996. * VBox layouting
  16997. * @param {module:zrender/container/Group} group
  16998. * @param {number} gap
  16999. * @param {number} [width=Infinity]
  17000. * @param {number} [height=Infinity]
  17001. */
  17002. var vbox = curry(boxLayout, 'vertical');
  17003. /**
  17004. * HBox layouting
  17005. * @param {module:zrender/container/Group} group
  17006. * @param {number} gap
  17007. * @param {number} [width=Infinity]
  17008. * @param {number} [height=Infinity]
  17009. */
  17010. var hbox = curry(boxLayout, 'horizontal');
  17011. /**
  17012. * If x or x2 is not specified or 'center' 'left' 'right',
  17013. * the width would be as long as possible.
  17014. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17015. * the height would be as long as possible.
  17016. *
  17017. * @param {Object} positionInfo
  17018. * @param {number|string} [positionInfo.x]
  17019. * @param {number|string} [positionInfo.y]
  17020. * @param {number|string} [positionInfo.x2]
  17021. * @param {number|string} [positionInfo.y2]
  17022. * @param {Object} containerRect {width, height}
  17023. * @param {string|number} margin
  17024. * @return {Object} {width, height}
  17025. */
  17026. /**
  17027. * Parse position info.
  17028. *
  17029. * @param {Object} positionInfo
  17030. * @param {number|string} [positionInfo.left]
  17031. * @param {number|string} [positionInfo.top]
  17032. * @param {number|string} [positionInfo.right]
  17033. * @param {number|string} [positionInfo.bottom]
  17034. * @param {number|string} [positionInfo.width]
  17035. * @param {number|string} [positionInfo.height]
  17036. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17037. * @param {Object} containerRect
  17038. * @param {string|number} [margin]
  17039. *
  17040. * @return {module:zrender/core/BoundingRect}
  17041. */
  17042. function getLayoutRect(
  17043. positionInfo, containerRect, margin
  17044. ) {
  17045. margin = normalizeCssArray$1(margin || 0);
  17046. var containerWidth = containerRect.width;
  17047. var containerHeight = containerRect.height;
  17048. var left = parsePercent$1(positionInfo.left, containerWidth);
  17049. var top = parsePercent$1(positionInfo.top, containerHeight);
  17050. var right = parsePercent$1(positionInfo.right, containerWidth);
  17051. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17052. var width = parsePercent$1(positionInfo.width, containerWidth);
  17053. var height = parsePercent$1(positionInfo.height, containerHeight);
  17054. var verticalMargin = margin[2] + margin[0];
  17055. var horizontalMargin = margin[1] + margin[3];
  17056. var aspect = positionInfo.aspect;
  17057. // If width is not specified, calculate width from left and right
  17058. if (isNaN(width)) {
  17059. width = containerWidth - right - horizontalMargin - left;
  17060. }
  17061. if (isNaN(height)) {
  17062. height = containerHeight - bottom - verticalMargin - top;
  17063. }
  17064. if (aspect != null) {
  17065. // If width and height are not given
  17066. // 1. Graph should not exceeds the container
  17067. // 2. Aspect must be keeped
  17068. // 3. Graph should take the space as more as possible
  17069. // FIXME
  17070. // Margin is not considered, because there is no case that both
  17071. // using margin and aspect so far.
  17072. if (isNaN(width) && isNaN(height)) {
  17073. if (aspect > containerWidth / containerHeight) {
  17074. width = containerWidth * 0.8;
  17075. }
  17076. else {
  17077. height = containerHeight * 0.8;
  17078. }
  17079. }
  17080. // Calculate width or height with given aspect
  17081. if (isNaN(width)) {
  17082. width = aspect * height;
  17083. }
  17084. if (isNaN(height)) {
  17085. height = width / aspect;
  17086. }
  17087. }
  17088. // If left is not specified, calculate left from right and width
  17089. if (isNaN(left)) {
  17090. left = containerWidth - right - width - horizontalMargin;
  17091. }
  17092. if (isNaN(top)) {
  17093. top = containerHeight - bottom - height - verticalMargin;
  17094. }
  17095. // Align left and top
  17096. switch (positionInfo.left || positionInfo.right) {
  17097. case 'center':
  17098. left = containerWidth / 2 - width / 2 - margin[3];
  17099. break;
  17100. case 'right':
  17101. left = containerWidth - width - horizontalMargin;
  17102. break;
  17103. }
  17104. switch (positionInfo.top || positionInfo.bottom) {
  17105. case 'middle':
  17106. case 'center':
  17107. top = containerHeight / 2 - height / 2 - margin[0];
  17108. break;
  17109. case 'bottom':
  17110. top = containerHeight - height - verticalMargin;
  17111. break;
  17112. }
  17113. // If something is wrong and left, top, width, height are calculated as NaN
  17114. left = left || 0;
  17115. top = top || 0;
  17116. if (isNaN(width)) {
  17117. // Width may be NaN if only one value is given except width
  17118. width = containerWidth - horizontalMargin - left - (right || 0);
  17119. }
  17120. if (isNaN(height)) {
  17121. // Height may be NaN if only one value is given except height
  17122. height = containerHeight - verticalMargin - top - (bottom || 0);
  17123. }
  17124. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17125. rect.margin = margin;
  17126. return rect;
  17127. }
  17128. /**
  17129. * Position a zr element in viewport
  17130. * Group position is specified by either
  17131. * {left, top}, {right, bottom}
  17132. * If all properties exists, right and bottom will be igonred.
  17133. *
  17134. * Logic:
  17135. * 1. Scale (against origin point in parent coord)
  17136. * 2. Rotate (against origin point in parent coord)
  17137. * 3. Traslate (with el.position by this method)
  17138. * So this method only fixes the last step 'Traslate', which does not affect
  17139. * scaling and rotating.
  17140. *
  17141. * If be called repeatly with the same input el, the same result will be gotten.
  17142. *
  17143. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17144. * @param {Object} positionInfo
  17145. * @param {number|string} [positionInfo.left]
  17146. * @param {number|string} [positionInfo.top]
  17147. * @param {number|string} [positionInfo.right]
  17148. * @param {number|string} [positionInfo.bottom]
  17149. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17150. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17151. * @param {Object} containerRect
  17152. * @param {string|number} margin
  17153. * @param {Object} [opt]
  17154. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17155. * @param {Array.<number>} [opt.boundingMode='all']
  17156. * Specify how to calculate boundingRect when locating.
  17157. * 'all': Position the boundingRect that is transformed and uioned
  17158. * both itself and its descendants.
  17159. * This mode simplies confine the elements in the bounding
  17160. * of their container (e.g., using 'right: 0').
  17161. * 'raw': Position the boundingRect that is not transformed and only itself.
  17162. * This mode is useful when you want a element can overflow its
  17163. * container. (Consider a rotated circle needs to be located in a corner.)
  17164. * In this mode positionInfo.width/height can only be number.
  17165. */
  17166. /**
  17167. * @param {Object} option Contains some of the properties in HV_NAMES.
  17168. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17169. */
  17170. /**
  17171. * Consider Case:
  17172. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17173. * through setOption or media query, using normal zrUtil.merge will cause
  17174. * {right: 0} does not take effect.
  17175. *
  17176. * @example
  17177. * ComponentModel.extend({
  17178. * init: function () {
  17179. * ...
  17180. * var inputPositionParams = layout.getLayoutParams(option);
  17181. * this.mergeOption(inputPositionParams);
  17182. * },
  17183. * mergeOption: function (newOption) {
  17184. * newOption && zrUtil.merge(thisOption, newOption, true);
  17185. * layout.mergeLayoutParam(thisOption, newOption);
  17186. * }
  17187. * });
  17188. *
  17189. * @param {Object} targetOption
  17190. * @param {Object} newOption
  17191. * @param {Object|string} [opt]
  17192. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17193. * that width (or height) should not be calculated by left and right (or top and bottom).
  17194. */
  17195. function mergeLayoutParam(targetOption, newOption, opt) {
  17196. !isObject$1(opt) && (opt = {});
  17197. var ignoreSize = opt.ignoreSize;
  17198. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17199. var hResult = merge$$1(HV_NAMES[0], 0);
  17200. var vResult = merge$$1(HV_NAMES[1], 1);
  17201. copy(HV_NAMES[0], targetOption, hResult);
  17202. copy(HV_NAMES[1], targetOption, vResult);
  17203. function merge$$1(names, hvIdx) {
  17204. var newParams = {};
  17205. var newValueCount = 0;
  17206. var merged = {};
  17207. var mergedValueCount = 0;
  17208. var enoughParamNumber = 2;
  17209. each$3(names, function (name) {
  17210. merged[name] = targetOption[name];
  17211. });
  17212. each$3(names, function (name) {
  17213. // Consider case: newOption.width is null, which is
  17214. // set by user for removing width setting.
  17215. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17216. hasValue(newParams, name) && newValueCount++;
  17217. hasValue(merged, name) && mergedValueCount++;
  17218. });
  17219. if (ignoreSize[hvIdx]) {
  17220. // Only one of left/right is premitted to exist.
  17221. if (hasValue(newOption, names[1])) {
  17222. merged[names[2]] = null;
  17223. }
  17224. else if (hasValue(newOption, names[2])) {
  17225. merged[names[1]] = null;
  17226. }
  17227. return merged;
  17228. }
  17229. // Case: newOption: {width: ..., right: ...},
  17230. // or targetOption: {right: ...} and newOption: {width: ...},
  17231. // There is no conflict when merged only has params count
  17232. // little than enoughParamNumber.
  17233. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17234. return merged;
  17235. }
  17236. // Case: newOption: {width: ..., right: ...},
  17237. // Than we can make sure user only want those two, and ignore
  17238. // all origin params in targetOption.
  17239. else if (newValueCount >= enoughParamNumber) {
  17240. return newParams;
  17241. }
  17242. else {
  17243. // Chose another param from targetOption by priority.
  17244. for (var i = 0; i < names.length; i++) {
  17245. var name = names[i];
  17246. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17247. newParams[name] = targetOption[name];
  17248. break;
  17249. }
  17250. }
  17251. return newParams;
  17252. }
  17253. }
  17254. function hasProp(obj, name) {
  17255. return obj.hasOwnProperty(name);
  17256. }
  17257. function hasValue(obj, name) {
  17258. return obj[name] != null && obj[name] !== 'auto';
  17259. }
  17260. function copy(names, target, source) {
  17261. each$3(names, function (name) {
  17262. target[name] = source[name];
  17263. });
  17264. }
  17265. }
  17266. /**
  17267. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17268. * @param {Object} source
  17269. * @return {Object} Result contains those props.
  17270. */
  17271. function getLayoutParams(source) {
  17272. return copyLayoutParams({}, source);
  17273. }
  17274. /**
  17275. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17276. * @param {Object} source
  17277. * @return {Object} Result contains those props.
  17278. */
  17279. function copyLayoutParams(target, source) {
  17280. source && target && each$3(LOCATION_PARAMS, function (name) {
  17281. source.hasOwnProperty(name) && (target[name] = source[name]);
  17282. });
  17283. return target;
  17284. }
  17285. /*
  17286. * Licensed to the Apache Software Foundation (ASF) under one
  17287. * or more contributor license agreements. See the NOTICE file
  17288. * distributed with this work for additional information
  17289. * regarding copyright ownership. The ASF licenses this file
  17290. * to you under the Apache License, Version 2.0 (the
  17291. * "License"); you may not use this file except in compliance
  17292. * with the License. You may obtain a copy of the License at
  17293. *
  17294. * http://www.apache.org/licenses/LICENSE-2.0
  17295. *
  17296. * Unless required by applicable law or agreed to in writing,
  17297. * software distributed under the License is distributed on an
  17298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17299. * KIND, either express or implied. See the License for the
  17300. * specific language governing permissions and limitations
  17301. * under the License.
  17302. */
  17303. var boxLayoutMixin = {
  17304. getBoxLayoutParams: function () {
  17305. return {
  17306. left: this.get('left'),
  17307. top: this.get('top'),
  17308. right: this.get('right'),
  17309. bottom: this.get('bottom'),
  17310. width: this.get('width'),
  17311. height: this.get('height')
  17312. };
  17313. }
  17314. };
  17315. /*
  17316. * Licensed to the Apache Software Foundation (ASF) under one
  17317. * or more contributor license agreements. See the NOTICE file
  17318. * distributed with this work for additional information
  17319. * regarding copyright ownership. The ASF licenses this file
  17320. * to you under the Apache License, Version 2.0 (the
  17321. * "License"); you may not use this file except in compliance
  17322. * with the License. You may obtain a copy of the License at
  17323. *
  17324. * http://www.apache.org/licenses/LICENSE-2.0
  17325. *
  17326. * Unless required by applicable law or agreed to in writing,
  17327. * software distributed under the License is distributed on an
  17328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17329. * KIND, either express or implied. See the License for the
  17330. * specific language governing permissions and limitations
  17331. * under the License.
  17332. */
  17333. /**
  17334. * Component model
  17335. *
  17336. * @module echarts/model/Component
  17337. */
  17338. var inner$1 = makeInner();
  17339. /**
  17340. * @alias module:echarts/model/Component
  17341. * @constructor
  17342. * @param {Object} option
  17343. * @param {module:echarts/model/Model} parentModel
  17344. * @param {module:echarts/model/Model} ecModel
  17345. */
  17346. var ComponentModel = Model.extend({
  17347. type: 'component',
  17348. /**
  17349. * @readOnly
  17350. * @type {string}
  17351. */
  17352. id: '',
  17353. /**
  17354. * Because simplified concept is probably better, series.name (or component.name)
  17355. * has been having too many resposibilities:
  17356. * (1) Generating id (which requires name in option should not be modified).
  17357. * (2) As an index to mapping series when merging option or calling API (a name
  17358. * can refer to more then one components, which is convinient is some case).
  17359. * (3) Display.
  17360. * @readOnly
  17361. */
  17362. name: '',
  17363. /**
  17364. * @readOnly
  17365. * @type {string}
  17366. */
  17367. mainType: '',
  17368. /**
  17369. * @readOnly
  17370. * @type {string}
  17371. */
  17372. subType: '',
  17373. /**
  17374. * @readOnly
  17375. * @type {number}
  17376. */
  17377. componentIndex: 0,
  17378. /**
  17379. * @type {Object}
  17380. * @protected
  17381. */
  17382. defaultOption: null,
  17383. /**
  17384. * @type {module:echarts/model/Global}
  17385. * @readOnly
  17386. */
  17387. ecModel: null,
  17388. /**
  17389. * key: componentType
  17390. * value: Component model list, can not be null.
  17391. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17392. * @readOnly
  17393. */
  17394. dependentModels: [],
  17395. /**
  17396. * @type {string}
  17397. * @readOnly
  17398. */
  17399. uid: null,
  17400. /**
  17401. * Support merge layout params.
  17402. * Only support 'box' now (left/right/top/bottom/width/height).
  17403. * @type {string|Object} Object can be {ignoreSize: true}
  17404. * @readOnly
  17405. */
  17406. layoutMode: null,
  17407. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17408. Model.call(this, option, parentModel, ecModel, extraOpt);
  17409. this.uid = getUID('ec_cpt_model');
  17410. },
  17411. init: function (option, parentModel, ecModel, extraOpt) {
  17412. this.mergeDefaultAndTheme(option, ecModel);
  17413. },
  17414. mergeDefaultAndTheme: function (option, ecModel) {
  17415. var layoutMode = this.layoutMode;
  17416. var inputPositionParams = layoutMode
  17417. ? getLayoutParams(option) : {};
  17418. var themeModel = ecModel.getTheme();
  17419. merge(option, themeModel.get(this.mainType));
  17420. merge(option, this.getDefaultOption());
  17421. if (layoutMode) {
  17422. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17423. }
  17424. },
  17425. mergeOption: function (option, extraOpt) {
  17426. merge(this.option, option, true);
  17427. var layoutMode = this.layoutMode;
  17428. if (layoutMode) {
  17429. mergeLayoutParam(this.option, option, layoutMode);
  17430. }
  17431. },
  17432. // Hooker after init or mergeOption
  17433. optionUpdated: function (newCptOption, isInit) {},
  17434. getDefaultOption: function () {
  17435. var fields = inner$1(this);
  17436. if (!fields.defaultOption) {
  17437. var optList = [];
  17438. var Class = this.constructor;
  17439. while (Class) {
  17440. var opt = Class.prototype.defaultOption;
  17441. opt && optList.push(opt);
  17442. Class = Class.superClass;
  17443. }
  17444. var defaultOption = {};
  17445. for (var i = optList.length - 1; i >= 0; i--) {
  17446. defaultOption = merge(defaultOption, optList[i], true);
  17447. }
  17448. fields.defaultOption = defaultOption;
  17449. }
  17450. return fields.defaultOption;
  17451. },
  17452. getReferringComponents: function (mainType) {
  17453. return this.ecModel.queryComponents({
  17454. mainType: mainType,
  17455. index: this.get(mainType + 'Index', true),
  17456. id: this.get(mainType + 'Id', true)
  17457. });
  17458. }
  17459. });
  17460. // Reset ComponentModel.extend, add preConstruct.
  17461. // clazzUtil.enableClassExtend(
  17462. // ComponentModel,
  17463. // function (option, parentModel, ecModel, extraOpt) {
  17464. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17465. // zrUtil.extend(this, extraOpt);
  17466. // this.uid = componentUtil.getUID('componentModel');
  17467. // // this.setReadOnly([
  17468. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17469. // // 'dependentModels', 'componentIndex'
  17470. // // ]);
  17471. // }
  17472. // );
  17473. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17474. enableClassManagement(
  17475. ComponentModel, {registerWhenExtend: true}
  17476. );
  17477. enableSubTypeDefaulter(ComponentModel);
  17478. // Add capability of ComponentModel.topologicalTravel.
  17479. enableTopologicalTravel(ComponentModel, getDependencies);
  17480. function getDependencies(componentType) {
  17481. var deps = [];
  17482. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17483. deps = deps.concat(Clazz.prototype.dependencies || []);
  17484. });
  17485. // Ensure main type.
  17486. deps = map(deps, function (type) {
  17487. return parseClassType$1(type).main;
  17488. });
  17489. // Hack dataset for convenience.
  17490. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17491. deps.unshift('dataset');
  17492. }
  17493. return deps;
  17494. }
  17495. mixin(ComponentModel, boxLayoutMixin);
  17496. /*
  17497. * Licensed to the Apache Software Foundation (ASF) under one
  17498. * or more contributor license agreements. See the NOTICE file
  17499. * distributed with this work for additional information
  17500. * regarding copyright ownership. The ASF licenses this file
  17501. * to you under the Apache License, Version 2.0 (the
  17502. * "License"); you may not use this file except in compliance
  17503. * with the License. You may obtain a copy of the License at
  17504. *
  17505. * http://www.apache.org/licenses/LICENSE-2.0
  17506. *
  17507. * Unless required by applicable law or agreed to in writing,
  17508. * software distributed under the License is distributed on an
  17509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17510. * KIND, either express or implied. See the License for the
  17511. * specific language governing permissions and limitations
  17512. * under the License.
  17513. */
  17514. var platform = '';
  17515. // Navigator not exists in node
  17516. if (typeof navigator !== 'undefined') {
  17517. platform = navigator.platform || '';
  17518. }
  17519. var globalDefault = {
  17520. // backgroundColor: 'rgba(0,0,0,0)',
  17521. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17522. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17523. // Light colors:
  17524. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17525. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17526. // Dark colors:
  17527. color: [
  17528. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17529. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17530. ],
  17531. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17532. // If xAxis and yAxis declared, grid is created by default.
  17533. // grid: {},
  17534. textStyle: {
  17535. // color: '#000',
  17536. // decoration: 'none',
  17537. // PENDING
  17538. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17539. // fontFamily: 'Arial, Verdana, sans-serif',
  17540. fontSize: 12,
  17541. fontStyle: 'normal',
  17542. fontWeight: 'normal'
  17543. },
  17544. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17545. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17546. // Default is source-over
  17547. blendMode: null,
  17548. animation: 'auto',
  17549. animationDuration: 1000,
  17550. animationDurationUpdate: 300,
  17551. animationEasing: 'exponentialOut',
  17552. animationEasingUpdate: 'cubicOut',
  17553. animationThreshold: 2000,
  17554. // Configuration for progressive/incremental rendering
  17555. progressiveThreshold: 3000,
  17556. progressive: 400,
  17557. // Threshold of if use single hover layer to optimize.
  17558. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17559. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17560. // which is unexpected.
  17561. // see example <echarts/test/heatmap-large.html>.
  17562. hoverLayerThreshold: 3000,
  17563. // See: module:echarts/scale/Time
  17564. useUTC: false
  17565. };
  17566. /*
  17567. * Licensed to the Apache Software Foundation (ASF) under one
  17568. * or more contributor license agreements. See the NOTICE file
  17569. * distributed with this work for additional information
  17570. * regarding copyright ownership. The ASF licenses this file
  17571. * to you under the Apache License, Version 2.0 (the
  17572. * "License"); you may not use this file except in compliance
  17573. * with the License. You may obtain a copy of the License at
  17574. *
  17575. * http://www.apache.org/licenses/LICENSE-2.0
  17576. *
  17577. * Unless required by applicable law or agreed to in writing,
  17578. * software distributed under the License is distributed on an
  17579. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17580. * KIND, either express or implied. See the License for the
  17581. * specific language governing permissions and limitations
  17582. * under the License.
  17583. */
  17584. var inner$2 = makeInner();
  17585. function getNearestColorPalette(colors, requestColorNum) {
  17586. var paletteNum = colors.length;
  17587. // TODO colors must be in order
  17588. for (var i = 0; i < paletteNum; i++) {
  17589. if (colors[i].length > requestColorNum) {
  17590. return colors[i];
  17591. }
  17592. }
  17593. return colors[paletteNum - 1];
  17594. }
  17595. var colorPaletteMixin = {
  17596. clearColorPalette: function () {
  17597. inner$2(this).colorIdx = 0;
  17598. inner$2(this).colorNameMap = {};
  17599. },
  17600. /**
  17601. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17602. * twise with the same parameters will get different result.
  17603. * @param {Object} [scope=this]
  17604. * @param {Object} [requestColorNum]
  17605. * @return {string} color string.
  17606. */
  17607. getColorFromPalette: function (name, scope, requestColorNum) {
  17608. scope = scope || this;
  17609. var scopeFields = inner$2(scope);
  17610. var colorIdx = scopeFields.colorIdx || 0;
  17611. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17612. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17613. if (colorNameMap.hasOwnProperty(name)) {
  17614. return colorNameMap[name];
  17615. }
  17616. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17617. var layeredColorPalette = this.get('colorLayer', true);
  17618. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17619. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17620. // In case can't find in layered color palette.
  17621. colorPalette = colorPalette || defaultColorPalette;
  17622. if (!colorPalette || !colorPalette.length) {
  17623. return;
  17624. }
  17625. var color = colorPalette[colorIdx];
  17626. if (name) {
  17627. colorNameMap[name] = color;
  17628. }
  17629. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17630. return color;
  17631. }
  17632. };
  17633. /*
  17634. * Licensed to the Apache Software Foundation (ASF) under one
  17635. * or more contributor license agreements. See the NOTICE file
  17636. * distributed with this work for additional information
  17637. * regarding copyright ownership. The ASF licenses this file
  17638. * to you under the Apache License, Version 2.0 (the
  17639. * "License"); you may not use this file except in compliance
  17640. * with the License. You may obtain a copy of the License at
  17641. *
  17642. * http://www.apache.org/licenses/LICENSE-2.0
  17643. *
  17644. * Unless required by applicable law or agreed to in writing,
  17645. * software distributed under the License is distributed on an
  17646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17647. * KIND, either express or implied. See the License for the
  17648. * specific language governing permissions and limitations
  17649. * under the License.
  17650. */
  17651. // Avoid typo.
  17652. var SOURCE_FORMAT_ORIGINAL = 'original';
  17653. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17654. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17655. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17656. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17657. // ??? CHANGE A NAME
  17658. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17659. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17660. var SERIES_LAYOUT_BY_ROW = 'row';
  17661. /*
  17662. * Licensed to the Apache Software Foundation (ASF) under one
  17663. * or more contributor license agreements. See the NOTICE file
  17664. * distributed with this work for additional information
  17665. * regarding copyright ownership. The ASF licenses this file
  17666. * to you under the Apache License, Version 2.0 (the
  17667. * "License"); you may not use this file except in compliance
  17668. * with the License. You may obtain a copy of the License at
  17669. *
  17670. * http://www.apache.org/licenses/LICENSE-2.0
  17671. *
  17672. * Unless required by applicable law or agreed to in writing,
  17673. * software distributed under the License is distributed on an
  17674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17675. * KIND, either express or implied. See the License for the
  17676. * specific language governing permissions and limitations
  17677. * under the License.
  17678. */
  17679. /**
  17680. * [sourceFormat]
  17681. *
  17682. * + "original":
  17683. * This format is only used in series.data, where
  17684. * itemStyle can be specified in data item.
  17685. *
  17686. * + "arrayRows":
  17687. * [
  17688. * ['product', 'score', 'amount'],
  17689. * ['Matcha Latte', 89.3, 95.8],
  17690. * ['Milk Tea', 92.1, 89.4],
  17691. * ['Cheese Cocoa', 94.4, 91.2],
  17692. * ['Walnut Brownie', 85.4, 76.9]
  17693. * ]
  17694. *
  17695. * + "objectRows":
  17696. * [
  17697. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17698. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17699. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17700. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17701. * ]
  17702. *
  17703. * + "keyedColumns":
  17704. * {
  17705. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17706. * 'count': [823, 235, 1042, 988],
  17707. * 'score': [95.8, 81.4, 91.2, 76.9]
  17708. * }
  17709. *
  17710. * + "typedArray"
  17711. *
  17712. * + "unknown"
  17713. */
  17714. /**
  17715. * @constructor
  17716. * @param {Object} fields
  17717. * @param {string} fields.sourceFormat
  17718. * @param {Array|Object} fields.fromDataset
  17719. * @param {Array|Object} [fields.data]
  17720. * @param {string} [seriesLayoutBy='column']
  17721. * @param {Array.<Object|string>} [dimensionsDefine]
  17722. * @param {Objet|HashMap} [encodeDefine]
  17723. * @param {number} [startIndex=0]
  17724. * @param {number} [dimensionsDetectCount]
  17725. */
  17726. function Source(fields) {
  17727. /**
  17728. * @type {boolean}
  17729. */
  17730. this.fromDataset = fields.fromDataset;
  17731. /**
  17732. * Not null/undefined.
  17733. * @type {Array|Object}
  17734. */
  17735. this.data = fields.data || (
  17736. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17737. );
  17738. /**
  17739. * See also "detectSourceFormat".
  17740. * Not null/undefined.
  17741. * @type {string}
  17742. */
  17743. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17744. /**
  17745. * 'row' or 'column'
  17746. * Not null/undefined.
  17747. * @type {string} seriesLayoutBy
  17748. */
  17749. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17750. /**
  17751. * dimensions definition in option.
  17752. * can be null/undefined.
  17753. * @type {Array.<Object|string>}
  17754. */
  17755. this.dimensionsDefine = fields.dimensionsDefine;
  17756. /**
  17757. * encode definition in option.
  17758. * can be null/undefined.
  17759. * @type {Objet|HashMap}
  17760. */
  17761. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17762. /**
  17763. * Not null/undefined, uint.
  17764. * @type {number}
  17765. */
  17766. this.startIndex = fields.startIndex || 0;
  17767. /**
  17768. * Can be null/undefined (when unknown), uint.
  17769. * @type {number}
  17770. */
  17771. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17772. }
  17773. /**
  17774. * Wrap original series data for some compatibility cases.
  17775. */
  17776. Source.seriesDataToSource = function (data) {
  17777. return new Source({
  17778. data: data,
  17779. sourceFormat: isTypedArray(data)
  17780. ? SOURCE_FORMAT_TYPED_ARRAY
  17781. : SOURCE_FORMAT_ORIGINAL,
  17782. fromDataset: false
  17783. });
  17784. };
  17785. enableClassCheck(Source);
  17786. /*
  17787. * Licensed to the Apache Software Foundation (ASF) under one
  17788. * or more contributor license agreements. See the NOTICE file
  17789. * distributed with this work for additional information
  17790. * regarding copyright ownership. The ASF licenses this file
  17791. * to you under the Apache License, Version 2.0 (the
  17792. * "License"); you may not use this file except in compliance
  17793. * with the License. You may obtain a copy of the License at
  17794. *
  17795. * http://www.apache.org/licenses/LICENSE-2.0
  17796. *
  17797. * Unless required by applicable law or agreed to in writing,
  17798. * software distributed under the License is distributed on an
  17799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17800. * KIND, either express or implied. See the License for the
  17801. * specific language governing permissions and limitations
  17802. * under the License.
  17803. */
  17804. // The result of `guessOrdinal`.
  17805. var BE_ORDINAL = {
  17806. Must: 1, // Encounter string but not '-' and not number-like.
  17807. Might: 2, // Encounter string but number-like.
  17808. Not: 3 // Other cases
  17809. };
  17810. var inner$3 = makeInner();
  17811. /**
  17812. * @see {module:echarts/data/Source}
  17813. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17814. * @return {string} sourceFormat
  17815. */
  17816. function detectSourceFormat(datasetModel) {
  17817. var data = datasetModel.option.source;
  17818. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17819. if (isTypedArray(data)) {
  17820. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17821. }
  17822. else if (isArray(data)) {
  17823. // FIXME Whether tolerate null in top level array?
  17824. if (data.length === 0) {
  17825. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17826. }
  17827. for (var i = 0, len = data.length; i < len; i++) {
  17828. var item = data[i];
  17829. if (item == null) {
  17830. continue;
  17831. }
  17832. else if (isArray(item)) {
  17833. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17834. break;
  17835. }
  17836. else if (isObject$1(item)) {
  17837. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17838. break;
  17839. }
  17840. }
  17841. }
  17842. else if (isObject$1(data)) {
  17843. for (var key in data) {
  17844. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17845. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17846. break;
  17847. }
  17848. }
  17849. }
  17850. else if (data != null) {
  17851. throw new Error('Invalid data');
  17852. }
  17853. inner$3(datasetModel).sourceFormat = sourceFormat;
  17854. }
  17855. /**
  17856. * [Scenarios]:
  17857. * (1) Provide source data directly:
  17858. * series: {
  17859. * encode: {...},
  17860. * dimensions: [...]
  17861. * seriesLayoutBy: 'row',
  17862. * data: [[...]]
  17863. * }
  17864. * (2) Refer to datasetModel.
  17865. * series: [{
  17866. * encode: {...}
  17867. * // Ignore datasetIndex means `datasetIndex: 0`
  17868. * // and the dimensions defination in dataset is used
  17869. * }, {
  17870. * encode: {...},
  17871. * seriesLayoutBy: 'column',
  17872. * datasetIndex: 1
  17873. * }]
  17874. *
  17875. * Get data from series itself or datset.
  17876. * @return {module:echarts/data/Source} source
  17877. */
  17878. function getSource(seriesModel) {
  17879. return inner$3(seriesModel).source;
  17880. }
  17881. /**
  17882. * MUST be called before mergeOption of all series.
  17883. * @param {module:echarts/model/Global} ecModel
  17884. */
  17885. function resetSourceDefaulter(ecModel) {
  17886. // `datasetMap` is used to make default encode.
  17887. inner$3(ecModel).datasetMap = createHashMap();
  17888. }
  17889. /**
  17890. * [Caution]:
  17891. * MUST be called after series option merged and
  17892. * before "series.getInitailData()" called.
  17893. *
  17894. * [The rule of making default encode]:
  17895. * Category axis (if exists) alway map to the first dimension.
  17896. * Each other axis occupies a subsequent dimension.
  17897. *
  17898. * [Why make default encode]:
  17899. * Simplify the typing of encode in option, avoiding the case like that:
  17900. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17901. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17902. *
  17903. * @param {module:echarts/model/Series} seriesModel
  17904. */
  17905. function prepareSource(seriesModel) {
  17906. var seriesOption = seriesModel.option;
  17907. var data = seriesOption.data;
  17908. var sourceFormat = isTypedArray(data)
  17909. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17910. var fromDataset = false;
  17911. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17912. var sourceHeader = seriesOption.sourceHeader;
  17913. var dimensionsDefine = seriesOption.dimensions;
  17914. var datasetModel = getDatasetModel(seriesModel);
  17915. if (datasetModel) {
  17916. var datasetOption = datasetModel.option;
  17917. data = datasetOption.source;
  17918. sourceFormat = inner$3(datasetModel).sourceFormat;
  17919. fromDataset = true;
  17920. // These settings from series has higher priority.
  17921. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17922. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17923. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17924. }
  17925. var completeResult = completeBySourceData(
  17926. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17927. );
  17928. inner$3(seriesModel).source = new Source({
  17929. data: data,
  17930. fromDataset: fromDataset,
  17931. seriesLayoutBy: seriesLayoutBy,
  17932. sourceFormat: sourceFormat,
  17933. dimensionsDefine: completeResult.dimensionsDefine,
  17934. startIndex: completeResult.startIndex,
  17935. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17936. // Note: dataset option does not have `encode`.
  17937. encodeDefine: seriesOption.encode
  17938. });
  17939. }
  17940. // return {startIndex, dimensionsDefine, dimensionsCount}
  17941. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17942. if (!data) {
  17943. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17944. }
  17945. var dimensionsDetectCount;
  17946. var startIndex;
  17947. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17948. // Rule: Most of the first line are string: it is header.
  17949. // Caution: consider a line with 5 string and 1 number,
  17950. // it still can not be sure it is a head, because the
  17951. // 5 string may be 5 values of category columns.
  17952. if (sourceHeader === 'auto' || sourceHeader == null) {
  17953. arrayRowsTravelFirst(function (val) {
  17954. // '-' is regarded as null/undefined.
  17955. if (val != null && val !== '-') {
  17956. if (isString(val)) {
  17957. startIndex == null && (startIndex = 1);
  17958. }
  17959. else {
  17960. startIndex = 0;
  17961. }
  17962. }
  17963. // 10 is an experience number, avoid long loop.
  17964. }, seriesLayoutBy, data, 10);
  17965. }
  17966. else {
  17967. startIndex = sourceHeader ? 1 : 0;
  17968. }
  17969. if (!dimensionsDefine && startIndex === 1) {
  17970. dimensionsDefine = [];
  17971. arrayRowsTravelFirst(function (val, index) {
  17972. dimensionsDefine[index] = val != null ? val : '';
  17973. }, seriesLayoutBy, data);
  17974. }
  17975. dimensionsDetectCount = dimensionsDefine
  17976. ? dimensionsDefine.length
  17977. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17978. ? data.length
  17979. : data[0]
  17980. ? data[0].length
  17981. : null;
  17982. }
  17983. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17984. if (!dimensionsDefine) {
  17985. dimensionsDefine = objectRowsCollectDimensions(data);
  17986. }
  17987. }
  17988. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17989. if (!dimensionsDefine) {
  17990. dimensionsDefine = [];
  17991. each$1(data, function (colArr, key) {
  17992. dimensionsDefine.push(key);
  17993. });
  17994. }
  17995. }
  17996. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17997. var value0 = getDataItemValue(data[0]);
  17998. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17999. }
  18000. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18001. if (__DEV__) {
  18002. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18003. }
  18004. }
  18005. return {
  18006. startIndex: startIndex,
  18007. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18008. dimensionsDetectCount: dimensionsDetectCount
  18009. };
  18010. }
  18011. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18012. // which is reasonable. But dimension name is duplicated.
  18013. // Returns undefined or an array contains only object without null/undefiend or string.
  18014. function normalizeDimensionsDefine(dimensionsDefine) {
  18015. if (!dimensionsDefine) {
  18016. // The meaning of null/undefined is different from empty array.
  18017. return;
  18018. }
  18019. var nameMap = createHashMap();
  18020. return map(dimensionsDefine, function (item, index) {
  18021. item = extend({}, isObject$1(item) ? item : {name: item});
  18022. // User can set null in dimensions.
  18023. // We dont auto specify name, othewise a given name may
  18024. // cause it be refered unexpectedly.
  18025. if (item.name == null) {
  18026. return item;
  18027. }
  18028. // Also consider number form like 2012.
  18029. item.name += '';
  18030. // User may also specify displayName.
  18031. // displayName will always exists except user not
  18032. // specified or dim name is not specified or detected.
  18033. // (A auto generated dim name will not be used as
  18034. // displayName).
  18035. if (item.displayName == null) {
  18036. item.displayName = item.name;
  18037. }
  18038. var exist = nameMap.get(item.name);
  18039. if (!exist) {
  18040. nameMap.set(item.name, {count: 1});
  18041. }
  18042. else {
  18043. item.name += '-' + exist.count++;
  18044. }
  18045. return item;
  18046. });
  18047. }
  18048. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18049. maxLoop == null && (maxLoop = Infinity);
  18050. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18051. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18052. cb(data[i] ? data[i][0] : null, i);
  18053. }
  18054. }
  18055. else {
  18056. var value0 = data[0] || [];
  18057. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18058. cb(value0[i], i);
  18059. }
  18060. }
  18061. }
  18062. function objectRowsCollectDimensions(data) {
  18063. var firstIndex = 0;
  18064. var obj;
  18065. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18066. if (obj) {
  18067. var dimensions = [];
  18068. each$1(obj, function (value, key) {
  18069. dimensions.push(key);
  18070. });
  18071. return dimensions;
  18072. }
  18073. }
  18074. /**
  18075. * [The strategy of the arrengment of data dimensions for dataset]:
  18076. * "value way": all axes are non-category axes. So series one by one take
  18077. * several (the number is coordSysDims.length) dimensions from dataset.
  18078. * The result of data arrengment of data dimensions like:
  18079. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18080. * "category way": at least one axis is category axis. So the the first data
  18081. * dimension is always mapped to the first category axis and shared by
  18082. * all of the series. The other data dimensions are taken by series like
  18083. * "value way" does.
  18084. * The result of data arrengment of data dimensions like:
  18085. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18086. *
  18087. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18088. * @param {module:model/Series} seriesModel
  18089. * @param {module:data/Source} source
  18090. * @return {Object} encode Never be `null/undefined`.
  18091. */
  18092. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18093. var encode = {};
  18094. var datasetModel = getDatasetModel(seriesModel);
  18095. // Currently only make default when using dataset, util more reqirements occur.
  18096. if (!datasetModel || !coordDimensions) {
  18097. return encode;
  18098. }
  18099. var encodeItemName = [];
  18100. var encodeSeriesName = [];
  18101. var ecModel = seriesModel.ecModel;
  18102. var datasetMap = inner$3(ecModel).datasetMap;
  18103. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18104. var baseCategoryDimIndex;
  18105. var categoryWayValueDimStart;
  18106. coordDimensions = coordDimensions.slice();
  18107. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18108. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18109. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18110. baseCategoryDimIndex = coordDimIdx;
  18111. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18112. }
  18113. encode[coordDimInfo.name] = [];
  18114. });
  18115. var datasetRecord = datasetMap.get(key)
  18116. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18117. // TODO
  18118. // Auto detect first time axis and do arrangement.
  18119. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18120. var coordDimName = coordDimInfo.name;
  18121. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18122. // In value way.
  18123. if (baseCategoryDimIndex == null) {
  18124. var start = datasetRecord.valueWayDim;
  18125. pushDim(encode[coordDimName], start, count);
  18126. pushDim(encodeSeriesName, start, count);
  18127. datasetRecord.valueWayDim += count;
  18128. // ??? TODO give a better default series name rule?
  18129. // especially when encode x y specified.
  18130. // consider: when mutiple series share one dimension
  18131. // category axis, series name should better use
  18132. // the other dimsion name. On the other hand, use
  18133. // both dimensions name.
  18134. }
  18135. // In category way, the first category axis.
  18136. else if (baseCategoryDimIndex === coordDimIdx) {
  18137. pushDim(encode[coordDimName], 0, count);
  18138. pushDim(encodeItemName, 0, count);
  18139. }
  18140. // In category way, the other axis.
  18141. else {
  18142. var start = datasetRecord.categoryWayDim;
  18143. pushDim(encode[coordDimName], start, count);
  18144. pushDim(encodeSeriesName, start, count);
  18145. datasetRecord.categoryWayDim += count;
  18146. }
  18147. });
  18148. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18149. for (var i = 0; i < idxCount; i++) {
  18150. dimIdxArr.push(idxFrom + i);
  18151. }
  18152. }
  18153. function getDataDimCountOnCoordDim(coordDimInfo) {
  18154. var dimsDef = coordDimInfo.dimsDef;
  18155. return dimsDef ? dimsDef.length : 1;
  18156. }
  18157. encodeItemName.length && (encode.itemName = encodeItemName);
  18158. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18159. return encode;
  18160. }
  18161. /**
  18162. * Work for data like [{name: ..., value: ...}, ...].
  18163. *
  18164. * @param {module:model/Series} seriesModel
  18165. * @param {module:data/Source} source
  18166. * @return {Object} encode Never be `null/undefined`.
  18167. */
  18168. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18169. var encode = {};
  18170. var datasetModel = getDatasetModel(seriesModel);
  18171. // Currently only make default when using dataset, util more reqirements occur.
  18172. if (!datasetModel) {
  18173. return encode;
  18174. }
  18175. var sourceFormat = source.sourceFormat;
  18176. var dimensionsDefine = source.dimensionsDefine;
  18177. var potentialNameDimIndex;
  18178. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18179. each$1(dimensionsDefine, function (dim, idx) {
  18180. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18181. potentialNameDimIndex = idx;
  18182. }
  18183. });
  18184. }
  18185. // idxResult: {v, n}.
  18186. var idxResult = (function () {
  18187. var idxRes0 = {};
  18188. var idxRes1 = {};
  18189. var guessRecords = [];
  18190. // 5 is an experience value.
  18191. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18192. var guessResult = doGuessOrdinal(
  18193. source.data, sourceFormat, source.seriesLayoutBy,
  18194. dimensionsDefine, source.startIndex, i
  18195. );
  18196. guessRecords.push(guessResult);
  18197. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18198. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18199. // and then find a name dim with the priority:
  18200. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18201. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18202. idxRes0.v = i;
  18203. }
  18204. if (idxRes0.n == null
  18205. || (idxRes0.n === idxRes0.v)
  18206. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18207. ) {
  18208. idxRes0.n = i;
  18209. }
  18210. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18211. return idxRes0;
  18212. }
  18213. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18214. // find the first BE_ORDINAL.Might as the value dim,
  18215. // and then find a name dim with the priority:
  18216. // "other dim" > "the value dim itself".
  18217. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18218. // treated as number.
  18219. if (!isPureNumber) {
  18220. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18221. idxRes1.v = i;
  18222. }
  18223. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18224. idxRes1.n = i;
  18225. }
  18226. }
  18227. }
  18228. function fulfilled(idxResult) {
  18229. return idxResult.v != null && idxResult.n != null;
  18230. }
  18231. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18232. })();
  18233. if (idxResult) {
  18234. encode.value = idxResult.v;
  18235. // `potentialNameDimIndex` has highest priority.
  18236. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18237. // By default, label use itemName in charts.
  18238. // So we dont set encodeLabel here.
  18239. encode.itemName = [nameDimIndex];
  18240. encode.seriesName = [nameDimIndex];
  18241. }
  18242. return encode;
  18243. }
  18244. /**
  18245. * If return null/undefined, indicate that should not use datasetModel.
  18246. */
  18247. function getDatasetModel(seriesModel) {
  18248. var option = seriesModel.option;
  18249. // Caution: consider the scenario:
  18250. // A dataset is declared and a series is not expected to use the dataset,
  18251. // and at the beginning `setOption({series: { noData })` (just prepare other
  18252. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18253. // the user should set an empty array to avoid that dataset is used by default.
  18254. var thisData = option.data;
  18255. if (!thisData) {
  18256. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18257. }
  18258. }
  18259. /**
  18260. * The rule should not be complex, otherwise user might not
  18261. * be able to known where the data is wrong.
  18262. * The code is ugly, but how to make it neat?
  18263. *
  18264. * @param {module:echars/data/Source} source
  18265. * @param {number} dimIndex
  18266. * @return {BE_ORDINAL} guess result.
  18267. */
  18268. function guessOrdinal(source, dimIndex) {
  18269. return doGuessOrdinal(
  18270. source.data,
  18271. source.sourceFormat,
  18272. source.seriesLayoutBy,
  18273. source.dimensionsDefine,
  18274. source.startIndex,
  18275. dimIndex
  18276. );
  18277. }
  18278. // dimIndex may be overflow source data.
  18279. // return {BE_ORDINAL}
  18280. function doGuessOrdinal(
  18281. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18282. ) {
  18283. var result;
  18284. // Experience value.
  18285. var maxLoop = 5;
  18286. if (isTypedArray(data)) {
  18287. return BE_ORDINAL.Not;
  18288. }
  18289. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18290. // always exists in source.
  18291. var dimName;
  18292. var dimType;
  18293. if (dimensionsDefine) {
  18294. var dimDefItem = dimensionsDefine[dimIndex];
  18295. if (isObject$1(dimDefItem)) {
  18296. dimName = dimDefItem.name;
  18297. dimType = dimDefItem.type;
  18298. }
  18299. else if (isString(dimDefItem)) {
  18300. dimName = dimDefItem;
  18301. }
  18302. }
  18303. if (dimType != null) {
  18304. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18305. }
  18306. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18307. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18308. var sample = data[dimIndex];
  18309. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18310. if ((result = detectValue(sample[startIndex + i])) != null) {
  18311. return result;
  18312. }
  18313. }
  18314. }
  18315. else {
  18316. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18317. var row = data[startIndex + i];
  18318. if (row && (result = detectValue(row[dimIndex])) != null) {
  18319. return result;
  18320. }
  18321. }
  18322. }
  18323. }
  18324. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18325. if (!dimName) {
  18326. return BE_ORDINAL.Not;
  18327. }
  18328. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18329. var item = data[i];
  18330. if (item && (result = detectValue(item[dimName])) != null) {
  18331. return result;
  18332. }
  18333. }
  18334. }
  18335. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18336. if (!dimName) {
  18337. return BE_ORDINAL.Not;
  18338. }
  18339. var sample = data[dimName];
  18340. if (!sample || isTypedArray(sample)) {
  18341. return BE_ORDINAL.Not;
  18342. }
  18343. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18344. if ((result = detectValue(sample[i])) != null) {
  18345. return result;
  18346. }
  18347. }
  18348. }
  18349. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18350. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18351. var item = data[i];
  18352. var val = getDataItemValue(item);
  18353. if (!isArray(val)) {
  18354. return BE_ORDINAL.Not;
  18355. }
  18356. if ((result = detectValue(val[dimIndex])) != null) {
  18357. return result;
  18358. }
  18359. }
  18360. }
  18361. function detectValue(val) {
  18362. var beStr = isString(val);
  18363. // Consider usage convenience, '1', '2' will be treated as "number".
  18364. // `isFinit('')` get `true`.
  18365. if (val != null && isFinite(val) && val !== '') {
  18366. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18367. }
  18368. else if (beStr && val !== '-') {
  18369. return BE_ORDINAL.Must;
  18370. }
  18371. }
  18372. return BE_ORDINAL.Not;
  18373. }
  18374. /*
  18375. * Licensed to the Apache Software Foundation (ASF) under one
  18376. * or more contributor license agreements. See the NOTICE file
  18377. * distributed with this work for additional information
  18378. * regarding copyright ownership. The ASF licenses this file
  18379. * to you under the Apache License, Version 2.0 (the
  18380. * "License"); you may not use this file except in compliance
  18381. * with the License. You may obtain a copy of the License at
  18382. *
  18383. * http://www.apache.org/licenses/LICENSE-2.0
  18384. *
  18385. * Unless required by applicable law or agreed to in writing,
  18386. * software distributed under the License is distributed on an
  18387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18388. * KIND, either express or implied. See the License for the
  18389. * specific language governing permissions and limitations
  18390. * under the License.
  18391. */
  18392. /**
  18393. * ECharts global model
  18394. *
  18395. * @module {echarts/model/Global}
  18396. */
  18397. /**
  18398. * Caution: If the mechanism should be changed some day, these cases
  18399. * should be considered:
  18400. *
  18401. * (1) In `merge option` mode, if using the same option to call `setOption`
  18402. * many times, the result should be the same (try our best to ensure that).
  18403. * (2) In `merge option` mode, if a component has no id/name specified, it
  18404. * will be merged by index, and the result sequence of the components is
  18405. * consistent to the original sequence.
  18406. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18407. * `mergeOption` in module:echarts/model/OptionManager.
  18408. */
  18409. var OPTION_INNER_KEY = '\0_ec_inner';
  18410. /**
  18411. * @alias module:echarts/model/Global
  18412. *
  18413. * @param {Object} option
  18414. * @param {module:echarts/model/Model} parentModel
  18415. * @param {Object} theme
  18416. */
  18417. var GlobalModel = Model.extend({
  18418. init: function (option, parentModel, theme, optionManager) {
  18419. theme = theme || {};
  18420. this.option = null; // Mark as not initialized.
  18421. /**
  18422. * @type {module:echarts/model/Model}
  18423. * @private
  18424. */
  18425. this._theme = new Model(theme);
  18426. /**
  18427. * @type {module:echarts/model/OptionManager}
  18428. */
  18429. this._optionManager = optionManager;
  18430. },
  18431. setOption: function (option, optionPreprocessorFuncs) {
  18432. assert$1(
  18433. !(OPTION_INNER_KEY in option),
  18434. 'please use chart.getOption()'
  18435. );
  18436. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18437. this.resetOption(null);
  18438. },
  18439. /**
  18440. * @param {string} type null/undefined: reset all.
  18441. * 'recreate': force recreate all.
  18442. * 'timeline': only reset timeline option
  18443. * 'media': only reset media query option
  18444. * @return {boolean} Whether option changed.
  18445. */
  18446. resetOption: function (type) {
  18447. var optionChanged = false;
  18448. var optionManager = this._optionManager;
  18449. if (!type || type === 'recreate') {
  18450. var baseOption = optionManager.mountOption(type === 'recreate');
  18451. if (!this.option || type === 'recreate') {
  18452. initBase.call(this, baseOption);
  18453. }
  18454. else {
  18455. this.restoreData();
  18456. this.mergeOption(baseOption);
  18457. }
  18458. optionChanged = true;
  18459. }
  18460. if (type === 'timeline' || type === 'media') {
  18461. this.restoreData();
  18462. }
  18463. if (!type || type === 'recreate' || type === 'timeline') {
  18464. var timelineOption = optionManager.getTimelineOption(this);
  18465. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18466. }
  18467. if (!type || type === 'recreate' || type === 'media') {
  18468. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18469. if (mediaOptions.length) {
  18470. each$1(mediaOptions, function (mediaOption) {
  18471. this.mergeOption(mediaOption, optionChanged = true);
  18472. }, this);
  18473. }
  18474. }
  18475. return optionChanged;
  18476. },
  18477. /**
  18478. * @protected
  18479. */
  18480. mergeOption: function (newOption) {
  18481. var option = this.option;
  18482. var componentsMap = this._componentsMap;
  18483. var newCptTypes = [];
  18484. resetSourceDefaulter(this);
  18485. // If no component class, merge directly.
  18486. // For example: color, animaiton options, etc.
  18487. each$1(newOption, function (componentOption, mainType) {
  18488. if (componentOption == null) {
  18489. return;
  18490. }
  18491. if (!ComponentModel.hasClass(mainType)) {
  18492. // globalSettingTask.dirty();
  18493. option[mainType] = option[mainType] == null
  18494. ? clone(componentOption)
  18495. : merge(option[mainType], componentOption, true);
  18496. }
  18497. else if (mainType) {
  18498. newCptTypes.push(mainType);
  18499. }
  18500. });
  18501. ComponentModel.topologicalTravel(
  18502. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18503. );
  18504. function visitComponent(mainType, dependencies) {
  18505. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18506. var mapResult = mappingToExists(
  18507. componentsMap.get(mainType), newCptOptionList
  18508. );
  18509. makeIdAndName(mapResult);
  18510. // Set mainType and complete subType.
  18511. each$1(mapResult, function (item, index) {
  18512. var opt = item.option;
  18513. if (isObject$1(opt)) {
  18514. item.keyInfo.mainType = mainType;
  18515. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18516. }
  18517. });
  18518. var dependentModels = getComponentsByTypes(
  18519. componentsMap, dependencies
  18520. );
  18521. option[mainType] = [];
  18522. componentsMap.set(mainType, []);
  18523. each$1(mapResult, function (resultItem, index) {
  18524. var componentModel = resultItem.exist;
  18525. var newCptOption = resultItem.option;
  18526. assert$1(
  18527. isObject$1(newCptOption) || componentModel,
  18528. 'Empty component definition'
  18529. );
  18530. // Consider where is no new option and should be merged using {},
  18531. // see removeEdgeAndAdd in topologicalTravel and
  18532. // ComponentModel.getAllClassMainTypes.
  18533. if (!newCptOption) {
  18534. componentModel.mergeOption({}, this);
  18535. componentModel.optionUpdated({}, false);
  18536. }
  18537. else {
  18538. var ComponentModelClass = ComponentModel.getClass(
  18539. mainType, resultItem.keyInfo.subType, true
  18540. );
  18541. if (componentModel && componentModel.constructor === ComponentModelClass) {
  18542. componentModel.name = resultItem.keyInfo.name;
  18543. // componentModel.settingTask && componentModel.settingTask.dirty();
  18544. componentModel.mergeOption(newCptOption, this);
  18545. componentModel.optionUpdated(newCptOption, false);
  18546. }
  18547. else {
  18548. // PENDING Global as parent ?
  18549. var extraOpt = extend(
  18550. {
  18551. dependentModels: dependentModels,
  18552. componentIndex: index
  18553. },
  18554. resultItem.keyInfo
  18555. );
  18556. componentModel = new ComponentModelClass(
  18557. newCptOption, this, this, extraOpt
  18558. );
  18559. extend(componentModel, extraOpt);
  18560. componentModel.init(newCptOption, this, this, extraOpt);
  18561. // Call optionUpdated after init.
  18562. // newCptOption has been used as componentModel.option
  18563. // and may be merged with theme and default, so pass null
  18564. // to avoid confusion.
  18565. componentModel.optionUpdated(null, true);
  18566. }
  18567. }
  18568. componentsMap.get(mainType)[index] = componentModel;
  18569. option[mainType][index] = componentModel.option;
  18570. }, this);
  18571. // Backup series for filtering.
  18572. if (mainType === 'series') {
  18573. createSeriesIndices(this, componentsMap.get('series'));
  18574. }
  18575. }
  18576. this._seriesIndicesMap = createHashMap(
  18577. this._seriesIndices = this._seriesIndices || []
  18578. );
  18579. },
  18580. /**
  18581. * Get option for output (cloned option and inner info removed)
  18582. * @public
  18583. * @return {Object}
  18584. */
  18585. getOption: function () {
  18586. var option = clone(this.option);
  18587. each$1(option, function (opts, mainType) {
  18588. if (ComponentModel.hasClass(mainType)) {
  18589. var opts = normalizeToArray(opts);
  18590. for (var i = opts.length - 1; i >= 0; i--) {
  18591. // Remove options with inner id.
  18592. if (isIdInner(opts[i])) {
  18593. opts.splice(i, 1);
  18594. }
  18595. }
  18596. option[mainType] = opts;
  18597. }
  18598. });
  18599. delete option[OPTION_INNER_KEY];
  18600. return option;
  18601. },
  18602. /**
  18603. * @return {module:echarts/model/Model}
  18604. */
  18605. getTheme: function () {
  18606. return this._theme;
  18607. },
  18608. /**
  18609. * @param {string} mainType
  18610. * @param {number} [idx=0]
  18611. * @return {module:echarts/model/Component}
  18612. */
  18613. getComponent: function (mainType, idx) {
  18614. var list = this._componentsMap.get(mainType);
  18615. if (list) {
  18616. return list[idx || 0];
  18617. }
  18618. },
  18619. /**
  18620. * If none of index and id and name used, return all components with mainType.
  18621. * @param {Object} condition
  18622. * @param {string} condition.mainType
  18623. * @param {string} [condition.subType] If ignore, only query by mainType
  18624. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18625. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18626. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18627. * @return {Array.<module:echarts/model/Component>}
  18628. */
  18629. queryComponents: function (condition) {
  18630. var mainType = condition.mainType;
  18631. if (!mainType) {
  18632. return [];
  18633. }
  18634. var index = condition.index;
  18635. var id = condition.id;
  18636. var name = condition.name;
  18637. var cpts = this._componentsMap.get(mainType);
  18638. if (!cpts || !cpts.length) {
  18639. return [];
  18640. }
  18641. var result;
  18642. if (index != null) {
  18643. if (!isArray(index)) {
  18644. index = [index];
  18645. }
  18646. result = filter(map(index, function (idx) {
  18647. return cpts[idx];
  18648. }), function (val) {
  18649. return !!val;
  18650. });
  18651. }
  18652. else if (id != null) {
  18653. var isIdArray = isArray(id);
  18654. result = filter(cpts, function (cpt) {
  18655. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18656. || (!isIdArray && cpt.id === id);
  18657. });
  18658. }
  18659. else if (name != null) {
  18660. var isNameArray = isArray(name);
  18661. result = filter(cpts, function (cpt) {
  18662. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18663. || (!isNameArray && cpt.name === name);
  18664. });
  18665. }
  18666. else {
  18667. // Return all components with mainType
  18668. result = cpts.slice();
  18669. }
  18670. return filterBySubType(result, condition);
  18671. },
  18672. /**
  18673. * The interface is different from queryComponents,
  18674. * which is convenient for inner usage.
  18675. *
  18676. * @usage
  18677. * var result = findComponents(
  18678. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18679. * );
  18680. * var result = findComponents(
  18681. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18682. * );
  18683. * var result = findComponents(
  18684. * {mainType: 'series',
  18685. * filter: function (model, index) {...}}
  18686. * );
  18687. * // result like [component0, componnet1, ...]
  18688. *
  18689. * @param {Object} condition
  18690. * @param {string} condition.mainType Mandatory.
  18691. * @param {string} [condition.subType] Optional.
  18692. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18693. * where xxx is mainType.
  18694. * If query attribute is null/undefined or has no index/id/name,
  18695. * do not filtering by query conditions, which is convenient for
  18696. * no-payload situations or when target of action is global.
  18697. * @param {Function} [condition.filter] parameter: component, return boolean.
  18698. * @return {Array.<module:echarts/model/Component>}
  18699. */
  18700. findComponents: function (condition) {
  18701. var query = condition.query;
  18702. var mainType = condition.mainType;
  18703. var queryCond = getQueryCond(query);
  18704. var result = queryCond
  18705. ? this.queryComponents(queryCond)
  18706. : this._componentsMap.get(mainType);
  18707. return doFilter(filterBySubType(result, condition));
  18708. function getQueryCond(q) {
  18709. var indexAttr = mainType + 'Index';
  18710. var idAttr = mainType + 'Id';
  18711. var nameAttr = mainType + 'Name';
  18712. return q && (
  18713. q[indexAttr] != null
  18714. || q[idAttr] != null
  18715. || q[nameAttr] != null
  18716. )
  18717. ? {
  18718. mainType: mainType,
  18719. // subType will be filtered finally.
  18720. index: q[indexAttr],
  18721. id: q[idAttr],
  18722. name: q[nameAttr]
  18723. }
  18724. : null;
  18725. }
  18726. function doFilter(res) {
  18727. return condition.filter
  18728. ? filter(res, condition.filter)
  18729. : res;
  18730. }
  18731. },
  18732. /**
  18733. * @usage
  18734. * eachComponent('legend', function (legendModel, index) {
  18735. * ...
  18736. * });
  18737. * eachComponent(function (componentType, model, index) {
  18738. * // componentType does not include subType
  18739. * // (componentType is 'xxx' but not 'xxx.aa')
  18740. * });
  18741. * eachComponent(
  18742. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18743. * function (model, index) {...}
  18744. * );
  18745. * eachComponent(
  18746. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18747. * function (model, index) {...}
  18748. * );
  18749. *
  18750. * @param {string|Object=} mainType When mainType is object, the definition
  18751. * is the same as the method 'findComponents'.
  18752. * @param {Function} cb
  18753. * @param {*} context
  18754. */
  18755. eachComponent: function (mainType, cb, context) {
  18756. var componentsMap = this._componentsMap;
  18757. if (typeof mainType === 'function') {
  18758. context = cb;
  18759. cb = mainType;
  18760. componentsMap.each(function (components, componentType) {
  18761. each$1(components, function (component, index) {
  18762. cb.call(context, componentType, component, index);
  18763. });
  18764. });
  18765. }
  18766. else if (isString(mainType)) {
  18767. each$1(componentsMap.get(mainType), cb, context);
  18768. }
  18769. else if (isObject$1(mainType)) {
  18770. var queryResult = this.findComponents(mainType);
  18771. each$1(queryResult, cb, context);
  18772. }
  18773. },
  18774. /**
  18775. * @param {string} name
  18776. * @return {Array.<module:echarts/model/Series>}
  18777. */
  18778. getSeriesByName: function (name) {
  18779. var series = this._componentsMap.get('series');
  18780. return filter(series, function (oneSeries) {
  18781. return oneSeries.name === name;
  18782. });
  18783. },
  18784. /**
  18785. * @param {number} seriesIndex
  18786. * @return {module:echarts/model/Series}
  18787. */
  18788. getSeriesByIndex: function (seriesIndex) {
  18789. return this._componentsMap.get('series')[seriesIndex];
  18790. },
  18791. /**
  18792. * Get series list before filtered by type.
  18793. * FIXME: rename to getRawSeriesByType?
  18794. *
  18795. * @param {string} subType
  18796. * @return {Array.<module:echarts/model/Series>}
  18797. */
  18798. getSeriesByType: function (subType) {
  18799. var series = this._componentsMap.get('series');
  18800. return filter(series, function (oneSeries) {
  18801. return oneSeries.subType === subType;
  18802. });
  18803. },
  18804. /**
  18805. * @return {Array.<module:echarts/model/Series>}
  18806. */
  18807. getSeries: function () {
  18808. return this._componentsMap.get('series').slice();
  18809. },
  18810. /**
  18811. * @return {number}
  18812. */
  18813. getSeriesCount: function () {
  18814. return this._componentsMap.get('series').length;
  18815. },
  18816. /**
  18817. * After filtering, series may be different
  18818. * frome raw series.
  18819. *
  18820. * @param {Function} cb
  18821. * @param {*} context
  18822. */
  18823. eachSeries: function (cb, context) {
  18824. assertSeriesInitialized(this);
  18825. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18826. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18827. cb.call(context, series, rawSeriesIndex);
  18828. }, this);
  18829. },
  18830. /**
  18831. * Iterate raw series before filtered.
  18832. *
  18833. * @param {Function} cb
  18834. * @param {*} context
  18835. */
  18836. eachRawSeries: function (cb, context) {
  18837. each$1(this._componentsMap.get('series'), cb, context);
  18838. },
  18839. /**
  18840. * After filtering, series may be different.
  18841. * frome raw series.
  18842. *
  18843. * @param {string} subType.
  18844. * @param {Function} cb
  18845. * @param {*} context
  18846. */
  18847. eachSeriesByType: function (subType, cb, context) {
  18848. assertSeriesInitialized(this);
  18849. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18850. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18851. if (series.subType === subType) {
  18852. cb.call(context, series, rawSeriesIndex);
  18853. }
  18854. }, this);
  18855. },
  18856. /**
  18857. * Iterate raw series before filtered of given type.
  18858. *
  18859. * @parma {string} subType
  18860. * @param {Function} cb
  18861. * @param {*} context
  18862. */
  18863. eachRawSeriesByType: function (subType, cb, context) {
  18864. return each$1(this.getSeriesByType(subType), cb, context);
  18865. },
  18866. /**
  18867. * @param {module:echarts/model/Series} seriesModel
  18868. */
  18869. isSeriesFiltered: function (seriesModel) {
  18870. assertSeriesInitialized(this);
  18871. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18872. },
  18873. /**
  18874. * @return {Array.<number>}
  18875. */
  18876. getCurrentSeriesIndices: function () {
  18877. return (this._seriesIndices || []).slice();
  18878. },
  18879. /**
  18880. * @param {Function} cb
  18881. * @param {*} context
  18882. */
  18883. filterSeries: function (cb, context) {
  18884. assertSeriesInitialized(this);
  18885. var filteredSeries = filter(
  18886. this._componentsMap.get('series'), cb, context
  18887. );
  18888. createSeriesIndices(this, filteredSeries);
  18889. },
  18890. restoreData: function (payload) {
  18891. var componentsMap = this._componentsMap;
  18892. createSeriesIndices(this, componentsMap.get('series'));
  18893. var componentTypes = [];
  18894. componentsMap.each(function (components, componentType) {
  18895. componentTypes.push(componentType);
  18896. });
  18897. ComponentModel.topologicalTravel(
  18898. componentTypes,
  18899. ComponentModel.getAllClassMainTypes(),
  18900. function (componentType, dependencies) {
  18901. each$1(componentsMap.get(componentType), function (component) {
  18902. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18903. && component.restoreData();
  18904. });
  18905. }
  18906. );
  18907. }
  18908. });
  18909. function isNotTargetSeries(seriesModel, payload) {
  18910. if (payload) {
  18911. var index = payload.seiresIndex;
  18912. var id = payload.seriesId;
  18913. var name = payload.seriesName;
  18914. return (index != null && seriesModel.componentIndex !== index)
  18915. || (id != null && seriesModel.id !== id)
  18916. || (name != null && seriesModel.name !== name);
  18917. }
  18918. }
  18919. /**
  18920. * @inner
  18921. */
  18922. function mergeTheme(option, theme) {
  18923. // PENDING
  18924. // NOT use `colorLayer` in theme if option has `color`
  18925. var notMergeColorLayer = option.color && !option.colorLayer;
  18926. each$1(theme, function (themeItem, name) {
  18927. if (name === 'colorLayer' && notMergeColorLayer) {
  18928. return;
  18929. }
  18930. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18931. if (!ComponentModel.hasClass(name)) {
  18932. if (typeof themeItem === 'object') {
  18933. option[name] = !option[name]
  18934. ? clone(themeItem)
  18935. : merge(option[name], themeItem, false);
  18936. }
  18937. else {
  18938. if (option[name] == null) {
  18939. option[name] = themeItem;
  18940. }
  18941. }
  18942. }
  18943. });
  18944. }
  18945. function initBase(baseOption) {
  18946. baseOption = baseOption;
  18947. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18948. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18949. this.option = {};
  18950. this.option[OPTION_INNER_KEY] = 1;
  18951. /**
  18952. * Init with series: [], in case of calling findSeries method
  18953. * before series initialized.
  18954. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18955. * @private
  18956. */
  18957. this._componentsMap = createHashMap({series: []});
  18958. /**
  18959. * Mapping between filtered series list and raw series list.
  18960. * key: filtered series indices, value: raw series indices.
  18961. * @type {Array.<nubmer>}
  18962. * @private
  18963. */
  18964. this._seriesIndices;
  18965. this._seriesIndicesMap;
  18966. mergeTheme(baseOption, this._theme.option);
  18967. // TODO Needs clone when merging to the unexisted property
  18968. merge(baseOption, globalDefault, false);
  18969. this.mergeOption(baseOption);
  18970. }
  18971. /**
  18972. * @inner
  18973. * @param {Array.<string>|string} types model types
  18974. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18975. */
  18976. function getComponentsByTypes(componentsMap, types) {
  18977. if (!isArray(types)) {
  18978. types = types ? [types] : [];
  18979. }
  18980. var ret = {};
  18981. each$1(types, function (type) {
  18982. ret[type] = (componentsMap.get(type) || []).slice();
  18983. });
  18984. return ret;
  18985. }
  18986. /**
  18987. * @inner
  18988. */
  18989. function determineSubType(mainType, newCptOption, existComponent) {
  18990. var subType = newCptOption.type
  18991. ? newCptOption.type
  18992. : existComponent
  18993. ? existComponent.subType
  18994. // Use determineSubType only when there is no existComponent.
  18995. : ComponentModel.determineSubType(mainType, newCptOption);
  18996. // tooltip, markline, markpoint may always has no subType
  18997. return subType;
  18998. }
  18999. /**
  19000. * @inner
  19001. */
  19002. function createSeriesIndices(ecModel, seriesModels) {
  19003. ecModel._seriesIndicesMap = createHashMap(
  19004. ecModel._seriesIndices = map(seriesModels, function (series) {
  19005. return series.componentIndex;
  19006. }) || []
  19007. );
  19008. }
  19009. /**
  19010. * @inner
  19011. */
  19012. function filterBySubType(components, condition) {
  19013. // Using hasOwnProperty for restrict. Consider
  19014. // subType is undefined in user payload.
  19015. return condition.hasOwnProperty('subType')
  19016. ? filter(components, function (cpt) {
  19017. return cpt.subType === condition.subType;
  19018. })
  19019. : components;
  19020. }
  19021. /**
  19022. * @inner
  19023. */
  19024. function assertSeriesInitialized(ecModel) {
  19025. // Components that use _seriesIndices should depends on series component,
  19026. // which make sure that their initialization is after series.
  19027. if (__DEV__) {
  19028. if (!ecModel._seriesIndices) {
  19029. throw new Error('Option should contains series.');
  19030. }
  19031. }
  19032. }
  19033. mixin(GlobalModel, colorPaletteMixin);
  19034. /*
  19035. * Licensed to the Apache Software Foundation (ASF) under one
  19036. * or more contributor license agreements. See the NOTICE file
  19037. * distributed with this work for additional information
  19038. * regarding copyright ownership. The ASF licenses this file
  19039. * to you under the Apache License, Version 2.0 (the
  19040. * "License"); you may not use this file except in compliance
  19041. * with the License. You may obtain a copy of the License at
  19042. *
  19043. * http://www.apache.org/licenses/LICENSE-2.0
  19044. *
  19045. * Unless required by applicable law or agreed to in writing,
  19046. * software distributed under the License is distributed on an
  19047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19048. * KIND, either express or implied. See the License for the
  19049. * specific language governing permissions and limitations
  19050. * under the License.
  19051. */
  19052. var echartsAPIList = [
  19053. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19054. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19055. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19056. ];
  19057. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19058. function ExtensionAPI(chartInstance) {
  19059. each$1(echartsAPIList, function (name) {
  19060. this[name] = bind(chartInstance[name], chartInstance);
  19061. }, this);
  19062. }
  19063. /*
  19064. * Licensed to the Apache Software Foundation (ASF) under one
  19065. * or more contributor license agreements. See the NOTICE file
  19066. * distributed with this work for additional information
  19067. * regarding copyright ownership. The ASF licenses this file
  19068. * to you under the Apache License, Version 2.0 (the
  19069. * "License"); you may not use this file except in compliance
  19070. * with the License. You may obtain a copy of the License at
  19071. *
  19072. * http://www.apache.org/licenses/LICENSE-2.0
  19073. *
  19074. * Unless required by applicable law or agreed to in writing,
  19075. * software distributed under the License is distributed on an
  19076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19077. * KIND, either express or implied. See the License for the
  19078. * specific language governing permissions and limitations
  19079. * under the License.
  19080. */
  19081. var coordinateSystemCreators = {};
  19082. function CoordinateSystemManager() {
  19083. this._coordinateSystems = [];
  19084. }
  19085. CoordinateSystemManager.prototype = {
  19086. constructor: CoordinateSystemManager,
  19087. create: function (ecModel, api) {
  19088. var coordinateSystems = [];
  19089. each$1(coordinateSystemCreators, function (creater, type) {
  19090. var list = creater.create(ecModel, api);
  19091. coordinateSystems = coordinateSystems.concat(list || []);
  19092. });
  19093. this._coordinateSystems = coordinateSystems;
  19094. },
  19095. update: function (ecModel, api) {
  19096. each$1(this._coordinateSystems, function (coordSys) {
  19097. coordSys.update && coordSys.update(ecModel, api);
  19098. });
  19099. },
  19100. getCoordinateSystems: function () {
  19101. return this._coordinateSystems.slice();
  19102. }
  19103. };
  19104. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19105. coordinateSystemCreators[type] = coordinateSystemCreator;
  19106. };
  19107. CoordinateSystemManager.get = function (type) {
  19108. return coordinateSystemCreators[type];
  19109. };
  19110. /*
  19111. * Licensed to the Apache Software Foundation (ASF) under one
  19112. * or more contributor license agreements. See the NOTICE file
  19113. * distributed with this work for additional information
  19114. * regarding copyright ownership. The ASF licenses this file
  19115. * to you under the Apache License, Version 2.0 (the
  19116. * "License"); you may not use this file except in compliance
  19117. * with the License. You may obtain a copy of the License at
  19118. *
  19119. * http://www.apache.org/licenses/LICENSE-2.0
  19120. *
  19121. * Unless required by applicable law or agreed to in writing,
  19122. * software distributed under the License is distributed on an
  19123. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19124. * KIND, either express or implied. See the License for the
  19125. * specific language governing permissions and limitations
  19126. * under the License.
  19127. */
  19128. /**
  19129. * ECharts option manager
  19130. *
  19131. * @module {echarts/model/OptionManager}
  19132. */
  19133. var each$4 = each$1;
  19134. var clone$3 = clone;
  19135. var map$1 = map;
  19136. var merge$1 = merge;
  19137. var QUERY_REG = /^(min|max)?(.+)$/;
  19138. /**
  19139. * TERM EXPLANATIONS:
  19140. *
  19141. * [option]:
  19142. *
  19143. * An object that contains definitions of components. For example:
  19144. * var option = {
  19145. * title: {...},
  19146. * legend: {...},
  19147. * visualMap: {...},
  19148. * series: [
  19149. * {data: [...]},
  19150. * {data: [...]},
  19151. * ...
  19152. * ]
  19153. * };
  19154. *
  19155. * [rawOption]:
  19156. *
  19157. * An object input to echarts.setOption. 'rawOption' may be an
  19158. * 'option', or may be an object contains multi-options. For example:
  19159. * var option = {
  19160. * baseOption: {
  19161. * title: {...},
  19162. * legend: {...},
  19163. * series: [
  19164. * {data: [...]},
  19165. * {data: [...]},
  19166. * ...
  19167. * ]
  19168. * },
  19169. * timeline: {...},
  19170. * options: [
  19171. * {title: {...}, series: {data: [...]}},
  19172. * {title: {...}, series: {data: [...]}},
  19173. * ...
  19174. * ],
  19175. * media: [
  19176. * {
  19177. * query: {maxWidth: 320},
  19178. * option: {series: {x: 20}, visualMap: {show: false}}
  19179. * },
  19180. * {
  19181. * query: {minWidth: 320, maxWidth: 720},
  19182. * option: {series: {x: 500}, visualMap: {show: true}}
  19183. * },
  19184. * {
  19185. * option: {series: {x: 1200}, visualMap: {show: true}}
  19186. * }
  19187. * ]
  19188. * };
  19189. *
  19190. * @alias module:echarts/model/OptionManager
  19191. * @param {module:echarts/ExtensionAPI} api
  19192. */
  19193. function OptionManager(api) {
  19194. /**
  19195. * @private
  19196. * @type {module:echarts/ExtensionAPI}
  19197. */
  19198. this._api = api;
  19199. /**
  19200. * @private
  19201. * @type {Array.<number>}
  19202. */
  19203. this._timelineOptions = [];
  19204. /**
  19205. * @private
  19206. * @type {Array.<Object>}
  19207. */
  19208. this._mediaList = [];
  19209. /**
  19210. * @private
  19211. * @type {Object}
  19212. */
  19213. this._mediaDefault;
  19214. /**
  19215. * -1, means default.
  19216. * empty means no media.
  19217. * @private
  19218. * @type {Array.<number>}
  19219. */
  19220. this._currentMediaIndices = [];
  19221. /**
  19222. * @private
  19223. * @type {Object}
  19224. */
  19225. this._optionBackup;
  19226. /**
  19227. * @private
  19228. * @type {Object}
  19229. */
  19230. this._newBaseOption;
  19231. }
  19232. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19233. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19234. // rawOption cloned and backuped when timeline changed, which does no
  19235. // good to performance. What's more, that both timeline and setOption
  19236. // method supply 'notMerge' brings complex and some problems.
  19237. // Consider this case:
  19238. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19239. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19240. OptionManager.prototype = {
  19241. constructor: OptionManager,
  19242. /**
  19243. * @public
  19244. * @param {Object} rawOption Raw option.
  19245. * @param {module:echarts/model/Global} ecModel
  19246. * @param {Array.<Function>} optionPreprocessorFuncs
  19247. * @return {Object} Init option
  19248. */
  19249. setOption: function (rawOption, optionPreprocessorFuncs) {
  19250. if (rawOption) {
  19251. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19252. each$1(normalizeToArray(rawOption.series), function (series) {
  19253. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19254. });
  19255. }
  19256. // Caution: some series modify option data, if do not clone,
  19257. // it should ensure that the repeat modify correctly
  19258. // (create a new object when modify itself).
  19259. rawOption = clone$3(rawOption);
  19260. // FIXME
  19261. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19262. var oldOptionBackup = this._optionBackup;
  19263. var newParsedOption = parseRawOption.call(
  19264. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19265. );
  19266. this._newBaseOption = newParsedOption.baseOption;
  19267. // For setOption at second time (using merge mode);
  19268. if (oldOptionBackup) {
  19269. // Only baseOption can be merged.
  19270. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19271. // For simplicity, timeline options and media options do not support merge,
  19272. // that is, if you `setOption` twice and both has timeline options, the latter
  19273. // timeline opitons will not be merged to the formers, but just substitude them.
  19274. if (newParsedOption.timelineOptions.length) {
  19275. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19276. }
  19277. if (newParsedOption.mediaList.length) {
  19278. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19279. }
  19280. if (newParsedOption.mediaDefault) {
  19281. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19282. }
  19283. }
  19284. else {
  19285. this._optionBackup = newParsedOption;
  19286. }
  19287. },
  19288. /**
  19289. * @param {boolean} isRecreate
  19290. * @return {Object}
  19291. */
  19292. mountOption: function (isRecreate) {
  19293. var optionBackup = this._optionBackup;
  19294. // TODO
  19295. // 如果没有reset功能则不clone。
  19296. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19297. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19298. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19299. this._currentMediaIndices = [];
  19300. return clone$3(isRecreate
  19301. // this._optionBackup.baseOption, which is created at the first `setOption`
  19302. // called, and is merged into every new option by inner method `mergeOption`
  19303. // each time `setOption` called, can be only used in `isRecreate`, because
  19304. // its reliability is under suspicion. In other cases option merge is
  19305. // performed by `model.mergeOption`.
  19306. ? optionBackup.baseOption : this._newBaseOption
  19307. );
  19308. },
  19309. /**
  19310. * @param {module:echarts/model/Global} ecModel
  19311. * @return {Object}
  19312. */
  19313. getTimelineOption: function (ecModel) {
  19314. var option;
  19315. var timelineOptions = this._timelineOptions;
  19316. if (timelineOptions.length) {
  19317. // getTimelineOption can only be called after ecModel inited,
  19318. // so we can get currentIndex from timelineModel.
  19319. var timelineModel = ecModel.getComponent('timeline');
  19320. if (timelineModel) {
  19321. option = clone$3(
  19322. timelineOptions[timelineModel.getCurrentIndex()],
  19323. true
  19324. );
  19325. }
  19326. }
  19327. return option;
  19328. },
  19329. /**
  19330. * @param {module:echarts/model/Global} ecModel
  19331. * @return {Array.<Object>}
  19332. */
  19333. getMediaOption: function (ecModel) {
  19334. var ecWidth = this._api.getWidth();
  19335. var ecHeight = this._api.getHeight();
  19336. var mediaList = this._mediaList;
  19337. var mediaDefault = this._mediaDefault;
  19338. var indices = [];
  19339. var result = [];
  19340. // No media defined.
  19341. if (!mediaList.length && !mediaDefault) {
  19342. return result;
  19343. }
  19344. // Multi media may be applied, the latter defined media has higher priority.
  19345. for (var i = 0, len = mediaList.length; i < len; i++) {
  19346. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19347. indices.push(i);
  19348. }
  19349. }
  19350. // FIXME
  19351. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19352. if (!indices.length && mediaDefault) {
  19353. indices = [-1];
  19354. }
  19355. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19356. result = map$1(indices, function (index) {
  19357. return clone$3(
  19358. index === -1 ? mediaDefault.option : mediaList[index].option
  19359. );
  19360. });
  19361. }
  19362. // Otherwise return nothing.
  19363. this._currentMediaIndices = indices;
  19364. return result;
  19365. }
  19366. };
  19367. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19368. var timelineOptions = [];
  19369. var mediaList = [];
  19370. var mediaDefault;
  19371. var baseOption;
  19372. // Compatible with ec2.
  19373. var timelineOpt = rawOption.timeline;
  19374. if (rawOption.baseOption) {
  19375. baseOption = rawOption.baseOption;
  19376. }
  19377. // For timeline
  19378. if (timelineOpt || rawOption.options) {
  19379. baseOption = baseOption || {};
  19380. timelineOptions = (rawOption.options || []).slice();
  19381. }
  19382. // For media query
  19383. if (rawOption.media) {
  19384. baseOption = baseOption || {};
  19385. var media = rawOption.media;
  19386. each$4(media, function (singleMedia) {
  19387. if (singleMedia && singleMedia.option) {
  19388. if (singleMedia.query) {
  19389. mediaList.push(singleMedia);
  19390. }
  19391. else if (!mediaDefault) {
  19392. // Use the first media default.
  19393. mediaDefault = singleMedia;
  19394. }
  19395. }
  19396. });
  19397. }
  19398. // For normal option
  19399. if (!baseOption) {
  19400. baseOption = rawOption;
  19401. }
  19402. // Set timelineOpt to baseOption in ec3,
  19403. // which is convenient for merge option.
  19404. if (!baseOption.timeline) {
  19405. baseOption.timeline = timelineOpt;
  19406. }
  19407. // Preprocess.
  19408. each$4([baseOption].concat(timelineOptions)
  19409. .concat(map(mediaList, function (media) {
  19410. return media.option;
  19411. })),
  19412. function (option) {
  19413. each$4(optionPreprocessorFuncs, function (preProcess) {
  19414. preProcess(option, isNew);
  19415. });
  19416. }
  19417. );
  19418. return {
  19419. baseOption: baseOption,
  19420. timelineOptions: timelineOptions,
  19421. mediaDefault: mediaDefault,
  19422. mediaList: mediaList
  19423. };
  19424. }
  19425. /**
  19426. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19427. * Support: width, height, aspectRatio
  19428. * Can use max or min as prefix.
  19429. */
  19430. function applyMediaQuery(query, ecWidth, ecHeight) {
  19431. var realMap = {
  19432. width: ecWidth,
  19433. height: ecHeight,
  19434. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19435. };
  19436. var applicatable = true;
  19437. each$1(query, function (value, attr) {
  19438. var matched = attr.match(QUERY_REG);
  19439. if (!matched || !matched[1] || !matched[2]) {
  19440. return;
  19441. }
  19442. var operator = matched[1];
  19443. var realAttr = matched[2].toLowerCase();
  19444. if (!compare(realMap[realAttr], value, operator)) {
  19445. applicatable = false;
  19446. }
  19447. });
  19448. return applicatable;
  19449. }
  19450. function compare(real, expect, operator) {
  19451. if (operator === 'min') {
  19452. return real >= expect;
  19453. }
  19454. else if (operator === 'max') {
  19455. return real <= expect;
  19456. }
  19457. else { // Equals
  19458. return real === expect;
  19459. }
  19460. }
  19461. function indicesEquals(indices1, indices2) {
  19462. // indices is always order by asc and has only finite number.
  19463. return indices1.join(',') === indices2.join(',');
  19464. }
  19465. /**
  19466. * Consider case:
  19467. * `chart.setOption(opt1);`
  19468. * Then user do some interaction like dataZoom, dataView changing.
  19469. * `chart.setOption(opt2);`
  19470. * Then user press 'reset button' in toolbox.
  19471. *
  19472. * After doing that all of the interaction effects should be reset, the
  19473. * chart should be the same as the result of invoke
  19474. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19475. *
  19476. * Although it is not able ensure that
  19477. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19478. * `chart.setOption(merge(opt1, opt2));` exactly,
  19479. * this might be the only simple way to implement that feature.
  19480. *
  19481. * MEMO: We've considered some other approaches:
  19482. * 1. Each model handle its self restoration but not uniform treatment.
  19483. * (Too complex in logic and error-prone)
  19484. * 2. Use a shadow ecModel. (Performace expensive)
  19485. */
  19486. function mergeOption(oldOption, newOption) {
  19487. newOption = newOption || {};
  19488. each$4(newOption, function (newCptOpt, mainType) {
  19489. if (newCptOpt == null) {
  19490. return;
  19491. }
  19492. var oldCptOpt = oldOption[mainType];
  19493. if (!ComponentModel.hasClass(mainType)) {
  19494. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19495. }
  19496. else {
  19497. newCptOpt = normalizeToArray(newCptOpt);
  19498. oldCptOpt = normalizeToArray(oldCptOpt);
  19499. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19500. oldOption[mainType] = map$1(mapResult, function (item) {
  19501. return (item.option && item.exist)
  19502. ? merge$1(item.exist, item.option, true)
  19503. : (item.exist || item.option);
  19504. });
  19505. }
  19506. });
  19507. }
  19508. /*
  19509. * Licensed to the Apache Software Foundation (ASF) under one
  19510. * or more contributor license agreements. See the NOTICE file
  19511. * distributed with this work for additional information
  19512. * regarding copyright ownership. The ASF licenses this file
  19513. * to you under the Apache License, Version 2.0 (the
  19514. * "License"); you may not use this file except in compliance
  19515. * with the License. You may obtain a copy of the License at
  19516. *
  19517. * http://www.apache.org/licenses/LICENSE-2.0
  19518. *
  19519. * Unless required by applicable law or agreed to in writing,
  19520. * software distributed under the License is distributed on an
  19521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19522. * KIND, either express or implied. See the License for the
  19523. * specific language governing permissions and limitations
  19524. * under the License.
  19525. */
  19526. var each$5 = each$1;
  19527. var isObject$3 = isObject$1;
  19528. var POSSIBLE_STYLES = [
  19529. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19530. 'chordStyle', 'label', 'labelLine'
  19531. ];
  19532. function compatEC2ItemStyle(opt) {
  19533. var itemStyleOpt = opt && opt.itemStyle;
  19534. if (!itemStyleOpt) {
  19535. return;
  19536. }
  19537. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19538. var styleName = POSSIBLE_STYLES[i];
  19539. var normalItemStyleOpt = itemStyleOpt.normal;
  19540. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19541. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19542. opt[styleName] = opt[styleName] || {};
  19543. if (!opt[styleName].normal) {
  19544. opt[styleName].normal = normalItemStyleOpt[styleName];
  19545. }
  19546. else {
  19547. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19548. }
  19549. normalItemStyleOpt[styleName] = null;
  19550. }
  19551. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19552. opt[styleName] = opt[styleName] || {};
  19553. if (!opt[styleName].emphasis) {
  19554. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19555. }
  19556. else {
  19557. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19558. }
  19559. emphasisItemStyleOpt[styleName] = null;
  19560. }
  19561. }
  19562. }
  19563. function convertNormalEmphasis(opt, optType, useExtend) {
  19564. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19565. var normalOpt = opt[optType].normal;
  19566. var emphasisOpt = opt[optType].emphasis;
  19567. if (normalOpt) {
  19568. // Timeline controlStyle has other properties besides normal and emphasis
  19569. if (useExtend) {
  19570. opt[optType].normal = opt[optType].emphasis = null;
  19571. defaults(opt[optType], normalOpt);
  19572. }
  19573. else {
  19574. opt[optType] = normalOpt;
  19575. }
  19576. }
  19577. if (emphasisOpt) {
  19578. opt.emphasis = opt.emphasis || {};
  19579. opt.emphasis[optType] = emphasisOpt;
  19580. }
  19581. }
  19582. }
  19583. function removeEC3NormalStatus(opt) {
  19584. convertNormalEmphasis(opt, 'itemStyle');
  19585. convertNormalEmphasis(opt, 'lineStyle');
  19586. convertNormalEmphasis(opt, 'areaStyle');
  19587. convertNormalEmphasis(opt, 'label');
  19588. convertNormalEmphasis(opt, 'labelLine');
  19589. // treemap
  19590. convertNormalEmphasis(opt, 'upperLabel');
  19591. // graph
  19592. convertNormalEmphasis(opt, 'edgeLabel');
  19593. }
  19594. function compatTextStyle(opt, propName) {
  19595. // Check whether is not object (string\null\undefined ...)
  19596. var labelOptSingle = isObject$3(opt) && opt[propName];
  19597. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19598. if (textStyle) {
  19599. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19600. var propName = TEXT_STYLE_OPTIONS[i];
  19601. if (textStyle.hasOwnProperty(propName)) {
  19602. labelOptSingle[propName] = textStyle[propName];
  19603. }
  19604. }
  19605. }
  19606. }
  19607. function compatEC3CommonStyles(opt) {
  19608. if (opt) {
  19609. removeEC3NormalStatus(opt);
  19610. compatTextStyle(opt, 'label');
  19611. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19612. }
  19613. }
  19614. function processSeries(seriesOpt) {
  19615. if (!isObject$3(seriesOpt)) {
  19616. return;
  19617. }
  19618. compatEC2ItemStyle(seriesOpt);
  19619. removeEC3NormalStatus(seriesOpt);
  19620. compatTextStyle(seriesOpt, 'label');
  19621. // treemap
  19622. compatTextStyle(seriesOpt, 'upperLabel');
  19623. // graph
  19624. compatTextStyle(seriesOpt, 'edgeLabel');
  19625. if (seriesOpt.emphasis) {
  19626. compatTextStyle(seriesOpt.emphasis, 'label');
  19627. // treemap
  19628. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19629. // graph
  19630. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19631. }
  19632. var markPoint = seriesOpt.markPoint;
  19633. if (markPoint) {
  19634. compatEC2ItemStyle(markPoint);
  19635. compatEC3CommonStyles(markPoint);
  19636. }
  19637. var markLine = seriesOpt.markLine;
  19638. if (markLine) {
  19639. compatEC2ItemStyle(markLine);
  19640. compatEC3CommonStyles(markLine);
  19641. }
  19642. var markArea = seriesOpt.markArea;
  19643. if (markArea) {
  19644. compatEC3CommonStyles(markArea);
  19645. }
  19646. var data = seriesOpt.data;
  19647. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19648. // then the backward compat based on option type will not be performed.
  19649. if (seriesOpt.type === 'graph') {
  19650. data = data || seriesOpt.nodes;
  19651. var edgeData = seriesOpt.links || seriesOpt.edges;
  19652. if (edgeData && !isTypedArray(edgeData)) {
  19653. for (var i = 0; i < edgeData.length; i++) {
  19654. compatEC3CommonStyles(edgeData[i]);
  19655. }
  19656. }
  19657. each$1(seriesOpt.categories, function (opt) {
  19658. removeEC3NormalStatus(opt);
  19659. });
  19660. }
  19661. if (data && !isTypedArray(data)) {
  19662. for (var i = 0; i < data.length; i++) {
  19663. compatEC3CommonStyles(data[i]);
  19664. }
  19665. }
  19666. // mark point data
  19667. var markPoint = seriesOpt.markPoint;
  19668. if (markPoint && markPoint.data) {
  19669. var mpData = markPoint.data;
  19670. for (var i = 0; i < mpData.length; i++) {
  19671. compatEC3CommonStyles(mpData[i]);
  19672. }
  19673. }
  19674. // mark line data
  19675. var markLine = seriesOpt.markLine;
  19676. if (markLine && markLine.data) {
  19677. var mlData = markLine.data;
  19678. for (var i = 0; i < mlData.length; i++) {
  19679. if (isArray(mlData[i])) {
  19680. compatEC3CommonStyles(mlData[i][0]);
  19681. compatEC3CommonStyles(mlData[i][1]);
  19682. }
  19683. else {
  19684. compatEC3CommonStyles(mlData[i]);
  19685. }
  19686. }
  19687. }
  19688. // Series
  19689. if (seriesOpt.type === 'gauge') {
  19690. compatTextStyle(seriesOpt, 'axisLabel');
  19691. compatTextStyle(seriesOpt, 'title');
  19692. compatTextStyle(seriesOpt, 'detail');
  19693. }
  19694. else if (seriesOpt.type === 'treemap') {
  19695. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19696. each$1(seriesOpt.levels, function (opt) {
  19697. removeEC3NormalStatus(opt);
  19698. });
  19699. }
  19700. else if (seriesOpt.type === 'tree') {
  19701. removeEC3NormalStatus(seriesOpt.leaves);
  19702. }
  19703. // sunburst starts from ec4, so it does not need to compat levels.
  19704. }
  19705. function toArr(o) {
  19706. return isArray(o) ? o : o ? [o] : [];
  19707. }
  19708. function toObj(o) {
  19709. return (isArray(o) ? o[0] : o) || {};
  19710. }
  19711. var compatStyle = function (option, isTheme) {
  19712. each$5(toArr(option.series), function (seriesOpt) {
  19713. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19714. });
  19715. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19716. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19717. each$5(
  19718. axes,
  19719. function (axisName) {
  19720. each$5(toArr(option[axisName]), function (axisOpt) {
  19721. if (axisOpt) {
  19722. compatTextStyle(axisOpt, 'axisLabel');
  19723. compatTextStyle(axisOpt.axisPointer, 'label');
  19724. }
  19725. });
  19726. }
  19727. );
  19728. each$5(toArr(option.parallel), function (parallelOpt) {
  19729. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19730. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19731. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19732. });
  19733. each$5(toArr(option.calendar), function (calendarOpt) {
  19734. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19735. compatTextStyle(calendarOpt, 'dayLabel');
  19736. compatTextStyle(calendarOpt, 'monthLabel');
  19737. compatTextStyle(calendarOpt, 'yearLabel');
  19738. });
  19739. // radar.name.textStyle
  19740. each$5(toArr(option.radar), function (radarOpt) {
  19741. compatTextStyle(radarOpt, 'name');
  19742. });
  19743. each$5(toArr(option.geo), function (geoOpt) {
  19744. if (isObject$3(geoOpt)) {
  19745. compatEC3CommonStyles(geoOpt);
  19746. each$5(toArr(geoOpt.regions), function (regionObj) {
  19747. compatEC3CommonStyles(regionObj);
  19748. });
  19749. }
  19750. });
  19751. each$5(toArr(option.timeline), function (timelineOpt) {
  19752. compatEC3CommonStyles(timelineOpt);
  19753. convertNormalEmphasis(timelineOpt, 'label');
  19754. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19755. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19756. var data = timelineOpt.data;
  19757. isArray(data) && each$1(data, function (item) {
  19758. if (isObject$1(item)) {
  19759. convertNormalEmphasis(item, 'label');
  19760. convertNormalEmphasis(item, 'itemStyle');
  19761. }
  19762. });
  19763. });
  19764. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19765. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19766. each$5(toolboxOpt.feature, function (featureOpt) {
  19767. convertNormalEmphasis(featureOpt, 'iconStyle');
  19768. });
  19769. });
  19770. compatTextStyle(toObj(option.axisPointer), 'label');
  19771. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19772. };
  19773. /*
  19774. * Licensed to the Apache Software Foundation (ASF) under one
  19775. * or more contributor license agreements. See the NOTICE file
  19776. * distributed with this work for additional information
  19777. * regarding copyright ownership. The ASF licenses this file
  19778. * to you under the Apache License, Version 2.0 (the
  19779. * "License"); you may not use this file except in compliance
  19780. * with the License. You may obtain a copy of the License at
  19781. *
  19782. * http://www.apache.org/licenses/LICENSE-2.0
  19783. *
  19784. * Unless required by applicable law or agreed to in writing,
  19785. * software distributed under the License is distributed on an
  19786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19787. * KIND, either express or implied. See the License for the
  19788. * specific language governing permissions and limitations
  19789. * under the License.
  19790. */
  19791. // Compatitable with 2.0
  19792. function get(opt, path) {
  19793. path = path.split(',');
  19794. var obj = opt;
  19795. for (var i = 0; i < path.length; i++) {
  19796. obj = obj && obj[path[i]];
  19797. if (obj == null) {
  19798. break;
  19799. }
  19800. }
  19801. return obj;
  19802. }
  19803. function set$1(opt, path, val, overwrite) {
  19804. path = path.split(',');
  19805. var obj = opt;
  19806. var key;
  19807. for (var i = 0; i < path.length - 1; i++) {
  19808. key = path[i];
  19809. if (obj[key] == null) {
  19810. obj[key] = {};
  19811. }
  19812. obj = obj[key];
  19813. }
  19814. if (overwrite || obj[path[i]] == null) {
  19815. obj[path[i]] = val;
  19816. }
  19817. }
  19818. function compatLayoutProperties(option) {
  19819. each$1(LAYOUT_PROPERTIES, function (prop) {
  19820. if (prop[0] in option && !(prop[1] in option)) {
  19821. option[prop[1]] = option[prop[0]];
  19822. }
  19823. });
  19824. }
  19825. var LAYOUT_PROPERTIES = [
  19826. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19827. ];
  19828. var COMPATITABLE_COMPONENTS = [
  19829. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19830. ];
  19831. var backwardCompat = function (option, isTheme) {
  19832. compatStyle(option, isTheme);
  19833. // Make sure series array for model initialization.
  19834. option.series = normalizeToArray(option.series);
  19835. each$1(option.series, function (seriesOpt) {
  19836. if (!isObject$1(seriesOpt)) {
  19837. return;
  19838. }
  19839. var seriesType = seriesOpt.type;
  19840. if (seriesType === 'line') {
  19841. if (seriesOpt.clipOverflow != null) {
  19842. seriesOpt.clip = seriesOpt.clipOverflow;
  19843. }
  19844. }
  19845. else if (seriesType === 'pie' || seriesType === 'gauge') {
  19846. if (seriesOpt.clockWise != null) {
  19847. seriesOpt.clockwise = seriesOpt.clockWise;
  19848. }
  19849. }
  19850. else if (seriesType === 'gauge') {
  19851. var pointerColor = get(seriesOpt, 'pointer.color');
  19852. pointerColor != null
  19853. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  19854. }
  19855. compatLayoutProperties(seriesOpt);
  19856. });
  19857. // dataRange has changed to visualMap
  19858. if (option.dataRange) {
  19859. option.visualMap = option.dataRange;
  19860. }
  19861. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19862. var options = option[componentName];
  19863. if (options) {
  19864. if (!isArray(options)) {
  19865. options = [options];
  19866. }
  19867. each$1(options, function (option) {
  19868. compatLayoutProperties(option);
  19869. });
  19870. }
  19871. });
  19872. };
  19873. /*
  19874. * Licensed to the Apache Software Foundation (ASF) under one
  19875. * or more contributor license agreements. See the NOTICE file
  19876. * distributed with this work for additional information
  19877. * regarding copyright ownership. The ASF licenses this file
  19878. * to you under the Apache License, Version 2.0 (the
  19879. * "License"); you may not use this file except in compliance
  19880. * with the License. You may obtain a copy of the License at
  19881. *
  19882. * http://www.apache.org/licenses/LICENSE-2.0
  19883. *
  19884. * Unless required by applicable law or agreed to in writing,
  19885. * software distributed under the License is distributed on an
  19886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19887. * KIND, either express or implied. See the License for the
  19888. * specific language governing permissions and limitations
  19889. * under the License.
  19890. */
  19891. // (1) [Caution]: the logic is correct based on the premises:
  19892. // data processing stage is blocked in stream.
  19893. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19894. // (2) Only register once when import repeatly.
  19895. // Should be executed after series filtered and before stack calculation.
  19896. var dataStack = function (ecModel) {
  19897. var stackInfoMap = createHashMap();
  19898. ecModel.eachSeries(function (seriesModel) {
  19899. var stack = seriesModel.get('stack');
  19900. // Compatibal: when `stack` is set as '', do not stack.
  19901. if (stack) {
  19902. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19903. var data = seriesModel.getData();
  19904. var stackInfo = {
  19905. // Used for calculate axis extent automatically.
  19906. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19907. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19908. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19909. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19910. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19911. data: data,
  19912. seriesModel: seriesModel
  19913. };
  19914. // If stacked on axis that do not support data stack.
  19915. if (!stackInfo.stackedDimension
  19916. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19917. ) {
  19918. return;
  19919. }
  19920. stackInfoList.length && data.setCalculationInfo(
  19921. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19922. );
  19923. stackInfoList.push(stackInfo);
  19924. }
  19925. });
  19926. stackInfoMap.each(calculateStack);
  19927. };
  19928. function calculateStack(stackInfoList) {
  19929. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19930. var resultVal = [];
  19931. var resultNaN = [NaN, NaN];
  19932. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19933. var targetData = targetStackInfo.data;
  19934. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19935. // Should not write on raw data, because stack series model list changes
  19936. // depending on legend selection.
  19937. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19938. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19939. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19940. // should also be NaN, to draw a appropriate belt area.
  19941. if (isNaN(sum)) {
  19942. return resultNaN;
  19943. }
  19944. var byValue;
  19945. var stackedDataRawIndex;
  19946. if (isStackedByIndex) {
  19947. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19948. }
  19949. else {
  19950. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19951. }
  19952. // If stackOver is NaN, chart view will render point on value start.
  19953. var stackedOver = NaN;
  19954. for (var j = idxInStack - 1; j >= 0; j--) {
  19955. var stackInfo = stackInfoList[j];
  19956. // Has been optimized by inverted indices on `stackedByDimension`.
  19957. if (!isStackedByIndex) {
  19958. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19959. }
  19960. if (stackedDataRawIndex >= 0) {
  19961. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19962. // Considering positive stack, negative stack and empty data
  19963. if ((sum >= 0 && val > 0) // Positive stack
  19964. || (sum <= 0 && val < 0) // Negative stack
  19965. ) {
  19966. sum += val;
  19967. stackedOver = val;
  19968. break;
  19969. }
  19970. }
  19971. }
  19972. resultVal[0] = sum;
  19973. resultVal[1] = stackedOver;
  19974. return resultVal;
  19975. });
  19976. targetData.hostModel.setData(newData);
  19977. // Update for consequent calculation
  19978. targetStackInfo.data = newData;
  19979. });
  19980. }
  19981. /*
  19982. * Licensed to the Apache Software Foundation (ASF) under one
  19983. * or more contributor license agreements. See the NOTICE file
  19984. * distributed with this work for additional information
  19985. * regarding copyright ownership. The ASF licenses this file
  19986. * to you under the Apache License, Version 2.0 (the
  19987. * "License"); you may not use this file except in compliance
  19988. * with the License. You may obtain a copy of the License at
  19989. *
  19990. * http://www.apache.org/licenses/LICENSE-2.0
  19991. *
  19992. * Unless required by applicable law or agreed to in writing,
  19993. * software distributed under the License is distributed on an
  19994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19995. * KIND, either express or implied. See the License for the
  19996. * specific language governing permissions and limitations
  19997. * under the License.
  19998. */
  19999. // TODO
  20000. // ??? refactor? check the outer usage of data provider.
  20001. // merge with defaultDimValueGetter?
  20002. /**
  20003. * If normal array used, mutable chunk size is supported.
  20004. * If typed array used, chunk size must be fixed.
  20005. */
  20006. function DefaultDataProvider(source, dimSize) {
  20007. if (!Source.isInstance(source)) {
  20008. source = Source.seriesDataToSource(source);
  20009. }
  20010. this._source = source;
  20011. var data = this._data = source.data;
  20012. var sourceFormat = source.sourceFormat;
  20013. // Typed array. TODO IE10+?
  20014. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20015. if (__DEV__) {
  20016. if (dimSize == null) {
  20017. throw new Error('Typed array data must specify dimension size');
  20018. }
  20019. }
  20020. this._offset = 0;
  20021. this._dimSize = dimSize;
  20022. this._data = data;
  20023. }
  20024. var methods = providerMethods[
  20025. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20026. ? sourceFormat + '_' + source.seriesLayoutBy
  20027. : sourceFormat
  20028. ];
  20029. if (__DEV__) {
  20030. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20031. }
  20032. extend(this, methods);
  20033. }
  20034. var providerProto = DefaultDataProvider.prototype;
  20035. // If data is pure without style configuration
  20036. providerProto.pure = false;
  20037. // If data is persistent and will not be released after use.
  20038. providerProto.persistent = true;
  20039. // ???! FIXME legacy data provider do not has method getSource
  20040. providerProto.getSource = function () {
  20041. return this._source;
  20042. };
  20043. var providerMethods = {
  20044. 'arrayRows_column': {
  20045. pure: true,
  20046. count: function () {
  20047. return Math.max(0, this._data.length - this._source.startIndex);
  20048. },
  20049. getItem: function (idx) {
  20050. return this._data[idx + this._source.startIndex];
  20051. },
  20052. appendData: appendDataSimply
  20053. },
  20054. 'arrayRows_row': {
  20055. pure: true,
  20056. count: function () {
  20057. var row = this._data[0];
  20058. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20059. },
  20060. getItem: function (idx) {
  20061. idx += this._source.startIndex;
  20062. var item = [];
  20063. var data = this._data;
  20064. for (var i = 0; i < data.length; i++) {
  20065. var row = data[i];
  20066. item.push(row ? row[idx] : null);
  20067. }
  20068. return item;
  20069. },
  20070. appendData: function () {
  20071. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20072. }
  20073. },
  20074. 'objectRows': {
  20075. pure: true,
  20076. count: countSimply,
  20077. getItem: getItemSimply,
  20078. appendData: appendDataSimply
  20079. },
  20080. 'keyedColumns': {
  20081. pure: true,
  20082. count: function () {
  20083. var dimName = this._source.dimensionsDefine[0].name;
  20084. var col = this._data[dimName];
  20085. return col ? col.length : 0;
  20086. },
  20087. getItem: function (idx) {
  20088. var item = [];
  20089. var dims = this._source.dimensionsDefine;
  20090. for (var i = 0; i < dims.length; i++) {
  20091. var col = this._data[dims[i].name];
  20092. item.push(col ? col[idx] : null);
  20093. }
  20094. return item;
  20095. },
  20096. appendData: function (newData) {
  20097. var data = this._data;
  20098. each$1(newData, function (newCol, key) {
  20099. var oldCol = data[key] || (data[key] = []);
  20100. for (var i = 0; i < (newCol || []).length; i++) {
  20101. oldCol.push(newCol[i]);
  20102. }
  20103. });
  20104. }
  20105. },
  20106. 'original': {
  20107. count: countSimply,
  20108. getItem: getItemSimply,
  20109. appendData: appendDataSimply
  20110. },
  20111. 'typedArray': {
  20112. persistent: false,
  20113. pure: true,
  20114. count: function () {
  20115. return this._data ? (this._data.length / this._dimSize) : 0;
  20116. },
  20117. getItem: function (idx, out) {
  20118. idx = idx - this._offset;
  20119. out = out || [];
  20120. var offset = this._dimSize * idx;
  20121. for (var i = 0; i < this._dimSize; i++) {
  20122. out[i] = this._data[offset + i];
  20123. }
  20124. return out;
  20125. },
  20126. appendData: function (newData) {
  20127. if (__DEV__) {
  20128. assert$1(
  20129. isTypedArray(newData),
  20130. 'Added data must be TypedArray if data in initialization is TypedArray'
  20131. );
  20132. }
  20133. this._data = newData;
  20134. },
  20135. // Clean self if data is already used.
  20136. clean: function () {
  20137. // PENDING
  20138. this._offset += this.count();
  20139. this._data = null;
  20140. }
  20141. }
  20142. };
  20143. function countSimply() {
  20144. return this._data.length;
  20145. }
  20146. function getItemSimply(idx) {
  20147. return this._data[idx];
  20148. }
  20149. function appendDataSimply(newData) {
  20150. for (var i = 0; i < newData.length; i++) {
  20151. this._data.push(newData[i]);
  20152. }
  20153. }
  20154. var rawValueGetters = {
  20155. arrayRows: getRawValueSimply,
  20156. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20157. return dimIndex != null ? dataItem[dimName] : dataItem;
  20158. },
  20159. keyedColumns: getRawValueSimply,
  20160. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20161. // FIXME
  20162. // In some case (markpoint in geo (geo-map.html)), dataItem
  20163. // is {coord: [...]}
  20164. var value = getDataItemValue(dataItem);
  20165. return (dimIndex == null || !(value instanceof Array))
  20166. ? value
  20167. : value[dimIndex];
  20168. },
  20169. typedArray: getRawValueSimply
  20170. };
  20171. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20172. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20173. }
  20174. var defaultDimValueGetters = {
  20175. arrayRows: getDimValueSimply,
  20176. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20177. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20178. },
  20179. keyedColumns: getDimValueSimply,
  20180. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20181. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20182. // If dataItem is an plain object with no value field, the var `value`
  20183. // will be assigned with the object, but it will be tread correctly
  20184. // in the `convertDataValue`.
  20185. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20186. // If any dataItem is like { value: 10 }
  20187. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20188. this.hasItemOption = true;
  20189. }
  20190. return converDataValue(
  20191. (value instanceof Array)
  20192. ? value[dimIndex]
  20193. // If value is a single number or something else not array.
  20194. : value,
  20195. this._dimensionInfos[dimName]
  20196. );
  20197. },
  20198. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20199. return dataItem[dimIndex];
  20200. }
  20201. };
  20202. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20203. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20204. }
  20205. /**
  20206. * This helper method convert value in data.
  20207. * @param {string|number|Date} value
  20208. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20209. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20210. */
  20211. function converDataValue(value, dimInfo) {
  20212. // Performance sensitive.
  20213. var dimType = dimInfo && dimInfo.type;
  20214. if (dimType === 'ordinal') {
  20215. // If given value is a category string
  20216. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20217. return ordinalMeta
  20218. ? ordinalMeta.parseAndCollect(value)
  20219. : value;
  20220. }
  20221. if (dimType === 'time'
  20222. // spead up when using timestamp
  20223. && typeof value !== 'number'
  20224. && value != null
  20225. && value !== '-'
  20226. ) {
  20227. value = +parseDate(value);
  20228. }
  20229. // dimType defaults 'number'.
  20230. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20231. // parse to NaN.
  20232. return (value == null || value === '')
  20233. ? NaN
  20234. // If string (like '-'), using '+' parse to NaN
  20235. // If object, also parse to NaN
  20236. : +value;
  20237. }
  20238. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20239. // Consider persistent.
  20240. // Caution: why use raw value to display on label or tooltip?
  20241. // A reason is to avoid format. For example time value we do not know
  20242. // how to format is expected. More over, if stack is used, calculated
  20243. // value may be 0.91000000001, which have brings trouble to display.
  20244. // TODO: consider how to treat null/undefined/NaN when display?
  20245. /**
  20246. * @param {module:echarts/data/List} data
  20247. * @param {number} dataIndex
  20248. * @param {string|number} [dim] dimName or dimIndex
  20249. * @return {Array.<number>|string|number} can be null/undefined.
  20250. */
  20251. function retrieveRawValue(data, dataIndex, dim) {
  20252. if (!data) {
  20253. return;
  20254. }
  20255. // Consider data may be not persistent.
  20256. var dataItem = data.getRawDataItem(dataIndex);
  20257. if (dataItem == null) {
  20258. return;
  20259. }
  20260. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20261. var dimName;
  20262. var dimIndex;
  20263. var dimInfo = data.getDimensionInfo(dim);
  20264. if (dimInfo) {
  20265. dimName = dimInfo.name;
  20266. dimIndex = dimInfo.index;
  20267. }
  20268. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20269. }
  20270. /**
  20271. * Compatible with some cases (in pie, map) like:
  20272. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20273. * where only sourceFormat is 'original' and 'objectRows' supported.
  20274. *
  20275. * ??? TODO
  20276. * Supported detail options in data item when using 'arrayRows'.
  20277. *
  20278. * @param {module:echarts/data/List} data
  20279. * @param {number} dataIndex
  20280. * @param {string} attr like 'selected'
  20281. */
  20282. function retrieveRawAttr(data, dataIndex, attr) {
  20283. if (!data) {
  20284. return;
  20285. }
  20286. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20287. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20288. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20289. ) {
  20290. return;
  20291. }
  20292. var dataItem = data.getRawDataItem(dataIndex);
  20293. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20294. dataItem = null;
  20295. }
  20296. if (dataItem) {
  20297. return dataItem[attr];
  20298. }
  20299. }
  20300. /*
  20301. * Licensed to the Apache Software Foundation (ASF) under one
  20302. * or more contributor license agreements. See the NOTICE file
  20303. * distributed with this work for additional information
  20304. * regarding copyright ownership. The ASF licenses this file
  20305. * to you under the Apache License, Version 2.0 (the
  20306. * "License"); you may not use this file except in compliance
  20307. * with the License. You may obtain a copy of the License at
  20308. *
  20309. * http://www.apache.org/licenses/LICENSE-2.0
  20310. *
  20311. * Unless required by applicable law or agreed to in writing,
  20312. * software distributed under the License is distributed on an
  20313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20314. * KIND, either express or implied. See the License for the
  20315. * specific language governing permissions and limitations
  20316. * under the License.
  20317. */
  20318. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20319. // PENDING A little ugly
  20320. var dataFormatMixin = {
  20321. /**
  20322. * Get params for formatter
  20323. * @param {number} dataIndex
  20324. * @param {string} [dataType]
  20325. * @return {Object}
  20326. */
  20327. getDataParams: function (dataIndex, dataType) {
  20328. var data = this.getData(dataType);
  20329. var rawValue = this.getRawValue(dataIndex, dataType);
  20330. var rawDataIndex = data.getRawIndex(dataIndex);
  20331. var name = data.getName(dataIndex);
  20332. var itemOpt = data.getRawDataItem(dataIndex);
  20333. var color = data.getItemVisual(dataIndex, 'color');
  20334. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20335. var tooltipModel = this.ecModel.getComponent('tooltip');
  20336. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20337. var renderMode = getTooltipRenderMode(renderModeOption);
  20338. var mainType = this.mainType;
  20339. var isSeries = mainType === 'series';
  20340. var userOutput = data.userOutput;
  20341. return {
  20342. componentType: mainType,
  20343. componentSubType: this.subType,
  20344. componentIndex: this.componentIndex,
  20345. seriesType: isSeries ? this.subType : null,
  20346. seriesIndex: this.seriesIndex,
  20347. seriesId: isSeries ? this.id : null,
  20348. seriesName: isSeries ? this.name : null,
  20349. name: name,
  20350. dataIndex: rawDataIndex,
  20351. data: itemOpt,
  20352. dataType: dataType,
  20353. value: rawValue,
  20354. color: color,
  20355. borderColor: borderColor,
  20356. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20357. encode: userOutput ? userOutput.encode : null,
  20358. marker: getTooltipMarker({
  20359. color: color,
  20360. renderMode: renderMode
  20361. }),
  20362. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20363. $vars: ['seriesName', 'name', 'value']
  20364. };
  20365. },
  20366. /**
  20367. * Format label
  20368. * @param {number} dataIndex
  20369. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20370. * @param {string} [dataType]
  20371. * @param {number} [dimIndex] Only used in some chart that
  20372. * use formatter in different dimensions, like radar.
  20373. * @param {string} [labelProp='label']
  20374. * @return {string} If not formatter, return null/undefined
  20375. */
  20376. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20377. status = status || 'normal';
  20378. var data = this.getData(dataType);
  20379. var itemModel = data.getItemModel(dataIndex);
  20380. var params = this.getDataParams(dataIndex, dataType);
  20381. if (dimIndex != null && (params.value instanceof Array)) {
  20382. params.value = params.value[dimIndex];
  20383. }
  20384. var formatter = itemModel.get(
  20385. status === 'normal'
  20386. ? [labelProp || 'label', 'formatter']
  20387. : [status, labelProp || 'label', 'formatter']
  20388. );
  20389. if (typeof formatter === 'function') {
  20390. params.status = status;
  20391. params.dimensionIndex = dimIndex;
  20392. return formatter(params);
  20393. }
  20394. else if (typeof formatter === 'string') {
  20395. var str = formatTpl(formatter, params);
  20396. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20397. // Do not support '}' in dim name util have to.
  20398. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20399. var len = dim.length;
  20400. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20401. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20402. }
  20403. return retrieveRawValue(data, dataIndex, dim);
  20404. });
  20405. }
  20406. },
  20407. /**
  20408. * Get raw value in option
  20409. * @param {number} idx
  20410. * @param {string} [dataType]
  20411. * @return {Array|number|string}
  20412. */
  20413. getRawValue: function (idx, dataType) {
  20414. return retrieveRawValue(this.getData(dataType), idx);
  20415. },
  20416. /**
  20417. * Should be implemented.
  20418. * @param {number} dataIndex
  20419. * @param {boolean} [multipleSeries=false]
  20420. * @param {number} [dataType]
  20421. * @return {string} tooltip string
  20422. */
  20423. formatTooltip: function () {
  20424. // Empty function
  20425. }
  20426. };
  20427. /*
  20428. * Licensed to the Apache Software Foundation (ASF) under one
  20429. * or more contributor license agreements. See the NOTICE file
  20430. * distributed with this work for additional information
  20431. * regarding copyright ownership. The ASF licenses this file
  20432. * to you under the Apache License, Version 2.0 (the
  20433. * "License"); you may not use this file except in compliance
  20434. * with the License. You may obtain a copy of the License at
  20435. *
  20436. * http://www.apache.org/licenses/LICENSE-2.0
  20437. *
  20438. * Unless required by applicable law or agreed to in writing,
  20439. * software distributed under the License is distributed on an
  20440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20441. * KIND, either express or implied. See the License for the
  20442. * specific language governing permissions and limitations
  20443. * under the License.
  20444. */
  20445. /**
  20446. * @param {Object} define
  20447. * @return See the return of `createTask`.
  20448. */
  20449. function createTask(define) {
  20450. return new Task(define);
  20451. }
  20452. /**
  20453. * @constructor
  20454. * @param {Object} define
  20455. * @param {Function} define.reset Custom reset
  20456. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20457. * @param {Function} [define.count] count is used to determin data task.
  20458. * @param {Function} [define.onDirty] count is used to determin data task.
  20459. */
  20460. function Task(define) {
  20461. define = define || {};
  20462. this._reset = define.reset;
  20463. this._plan = define.plan;
  20464. this._count = define.count;
  20465. this._onDirty = define.onDirty;
  20466. this._dirty = true;
  20467. // Context must be specified implicitly, to
  20468. // avoid miss update context when model changed.
  20469. this.context;
  20470. }
  20471. var taskProto = Task.prototype;
  20472. /**
  20473. * @param {Object} performArgs
  20474. * @param {number} [performArgs.step] Specified step.
  20475. * @param {number} [performArgs.skip] Skip customer perform call.
  20476. * @param {number} [performArgs.modBy] Sampling window size.
  20477. * @param {number} [performArgs.modDataCount] Sampling count.
  20478. */
  20479. taskProto.perform = function (performArgs) {
  20480. var upTask = this._upstream;
  20481. var skip = performArgs && performArgs.skip;
  20482. // TODO some refactor.
  20483. // Pull data. Must pull data each time, because context.data
  20484. // may be updated by Series.setData.
  20485. if (this._dirty && upTask) {
  20486. var context = this.context;
  20487. context.data = context.outputData = upTask.context.outputData;
  20488. }
  20489. if (this.__pipeline) {
  20490. this.__pipeline.currentTask = this;
  20491. }
  20492. var planResult;
  20493. if (this._plan && !skip) {
  20494. planResult = this._plan(this.context);
  20495. }
  20496. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20497. // elements uniformed distributed when progress, especially when moving or zooming.
  20498. var lastModBy = normalizeModBy(this._modBy);
  20499. var lastModDataCount = this._modDataCount || 0;
  20500. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20501. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20502. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20503. planResult = 'reset';
  20504. }
  20505. function normalizeModBy(val) {
  20506. !(val >= 1) && (val = 1); // jshint ignore:line
  20507. return val;
  20508. }
  20509. var forceFirstProgress;
  20510. if (this._dirty || planResult === 'reset') {
  20511. this._dirty = false;
  20512. forceFirstProgress = reset(this, skip);
  20513. }
  20514. this._modBy = modBy;
  20515. this._modDataCount = modDataCount;
  20516. var step = performArgs && performArgs.step;
  20517. if (upTask) {
  20518. if (__DEV__) {
  20519. assert$1(upTask._outputDueEnd != null);
  20520. }
  20521. this._dueEnd = upTask._outputDueEnd;
  20522. }
  20523. // DataTask or overallTask
  20524. else {
  20525. if (__DEV__) {
  20526. assert$1(!this._progress || this._count);
  20527. }
  20528. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20529. }
  20530. // Note: Stubs, that its host overall task let it has progress, has progress.
  20531. // If no progress, pass index from upstream to downstream each time plan called.
  20532. if (this._progress) {
  20533. var start = this._dueIndex;
  20534. var end = Math.min(
  20535. step != null ? this._dueIndex + step : Infinity,
  20536. this._dueEnd
  20537. );
  20538. if (!skip && (forceFirstProgress || start < end)) {
  20539. var progress = this._progress;
  20540. if (isArray(progress)) {
  20541. for (var i = 0; i < progress.length; i++) {
  20542. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20543. }
  20544. }
  20545. else {
  20546. doProgress(this, progress, start, end, modBy, modDataCount);
  20547. }
  20548. }
  20549. this._dueIndex = end;
  20550. // If no `outputDueEnd`, assume that output data and
  20551. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20552. var outputDueEnd = this._settedOutputEnd != null
  20553. ? this._settedOutputEnd : end;
  20554. if (__DEV__) {
  20555. // ??? Can not rollback.
  20556. assert$1(outputDueEnd >= this._outputDueEnd);
  20557. }
  20558. this._outputDueEnd = outputDueEnd;
  20559. }
  20560. else {
  20561. // (1) Some overall task has no progress.
  20562. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20563. // This should always be performed so it can be passed to downstream.
  20564. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20565. ? this._settedOutputEnd : this._dueEnd;
  20566. }
  20567. return this.unfinished();
  20568. };
  20569. var iterator = (function () {
  20570. var end;
  20571. var current;
  20572. var modBy;
  20573. var modDataCount;
  20574. var winCount;
  20575. var it = {
  20576. reset: function (s, e, sStep, sCount) {
  20577. current = s;
  20578. end = e;
  20579. modBy = sStep;
  20580. modDataCount = sCount;
  20581. winCount = Math.ceil(modDataCount / modBy);
  20582. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20583. }
  20584. };
  20585. return it;
  20586. function sequentialNext() {
  20587. return current < end ? current++ : null;
  20588. }
  20589. function modNext() {
  20590. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20591. var result = current >= end
  20592. ? null
  20593. : dataIndex < modDataCount
  20594. ? dataIndex
  20595. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20596. // Use normal linear rendering mode.
  20597. : current;
  20598. current++;
  20599. return result;
  20600. }
  20601. })();
  20602. taskProto.dirty = function () {
  20603. this._dirty = true;
  20604. this._onDirty && this._onDirty(this.context);
  20605. };
  20606. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20607. iterator.reset(start, end, modBy, modDataCount);
  20608. taskIns._callingProgress = progress;
  20609. taskIns._callingProgress({
  20610. start: start, end: end, count: end - start, next: iterator.next
  20611. }, taskIns.context);
  20612. }
  20613. function reset(taskIns, skip) {
  20614. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20615. taskIns._settedOutputEnd = null;
  20616. var progress;
  20617. var forceFirstProgress;
  20618. if (!skip && taskIns._reset) {
  20619. progress = taskIns._reset(taskIns.context);
  20620. if (progress && progress.progress) {
  20621. forceFirstProgress = progress.forceFirstProgress;
  20622. progress = progress.progress;
  20623. }
  20624. // To simplify no progress checking, array must has item.
  20625. if (isArray(progress) && !progress.length) {
  20626. progress = null;
  20627. }
  20628. }
  20629. taskIns._progress = progress;
  20630. taskIns._modBy = taskIns._modDataCount = null;
  20631. var downstream = taskIns._downstream;
  20632. downstream && downstream.dirty();
  20633. return forceFirstProgress;
  20634. }
  20635. /**
  20636. * @return {boolean}
  20637. */
  20638. taskProto.unfinished = function () {
  20639. return this._progress && this._dueIndex < this._dueEnd;
  20640. };
  20641. /**
  20642. * @param {Object} downTask The downstream task.
  20643. * @return {Object} The downstream task.
  20644. */
  20645. taskProto.pipe = function (downTask) {
  20646. if (__DEV__) {
  20647. assert$1(downTask && !downTask._disposed && downTask !== this);
  20648. }
  20649. // If already downstream, do not dirty downTask.
  20650. if (this._downstream !== downTask || this._dirty) {
  20651. this._downstream = downTask;
  20652. downTask._upstream = this;
  20653. downTask.dirty();
  20654. }
  20655. };
  20656. taskProto.dispose = function () {
  20657. if (this._disposed) {
  20658. return;
  20659. }
  20660. this._upstream && (this._upstream._downstream = null);
  20661. this._downstream && (this._downstream._upstream = null);
  20662. this._dirty = false;
  20663. this._disposed = true;
  20664. };
  20665. taskProto.getUpstream = function () {
  20666. return this._upstream;
  20667. };
  20668. taskProto.getDownstream = function () {
  20669. return this._downstream;
  20670. };
  20671. taskProto.setOutputEnd = function (end) {
  20672. // This only happend in dataTask, dataZoom, map, currently.
  20673. // where dataZoom do not set end each time, but only set
  20674. // when reset. So we should record the setted end, in case
  20675. // that the stub of dataZoom perform again and earse the
  20676. // setted end by upstream.
  20677. this._outputDueEnd = this._settedOutputEnd = end;
  20678. };
  20679. ///////////////////////////////////////////////////////////
  20680. // For stream debug (Should be commented out after used!)
  20681. // Usage: printTask(this, 'begin');
  20682. // Usage: printTask(this, null, {someExtraProp});
  20683. // function printTask(task, prefix, extra) {
  20684. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20685. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20686. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20687. // var props = [];
  20688. // if (task.__pipeline) {
  20689. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20690. // props.push({text: 'idx', value: val});
  20691. // } else {
  20692. // var stubCount = 0;
  20693. // task.agentStubMap.each(() => stubCount++);
  20694. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20695. // }
  20696. // props.push({text: 'uid', value: task.uidDebug});
  20697. // if (task.__pipeline) {
  20698. // props.push({text: 'pid', value: task.__pipeline.id});
  20699. // task.agent && props.push(
  20700. // {text: 'stubFor', value: task.agent.uidDebug}
  20701. // );
  20702. // }
  20703. // props.push(
  20704. // {text: 'dirty', value: task._dirty},
  20705. // {text: 'dueIndex', value: task._dueIndex},
  20706. // {text: 'dueEnd', value: task._dueEnd},
  20707. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20708. // );
  20709. // if (extra) {
  20710. // Object.keys(extra).forEach(key => {
  20711. // props.push({text: key, value: extra[key]});
  20712. // });
  20713. // }
  20714. // var args = ['color: blue'];
  20715. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20716. // args.push('color: black', 'color: red'),
  20717. // `${item.text}: %c${item.value}`
  20718. // )).join('%c, ');
  20719. // console.log.apply(console, [msg].concat(args));
  20720. // // console.log(this);
  20721. // }
  20722. /*
  20723. * Licensed to the Apache Software Foundation (ASF) under one
  20724. * or more contributor license agreements. See the NOTICE file
  20725. * distributed with this work for additional information
  20726. * regarding copyright ownership. The ASF licenses this file
  20727. * to you under the Apache License, Version 2.0 (the
  20728. * "License"); you may not use this file except in compliance
  20729. * with the License. You may obtain a copy of the License at
  20730. *
  20731. * http://www.apache.org/licenses/LICENSE-2.0
  20732. *
  20733. * Unless required by applicable law or agreed to in writing,
  20734. * software distributed under the License is distributed on an
  20735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20736. * KIND, either express or implied. See the License for the
  20737. * specific language governing permissions and limitations
  20738. * under the License.
  20739. */
  20740. var inner$4 = makeInner();
  20741. var SeriesModel = ComponentModel.extend({
  20742. type: 'series.__base__',
  20743. /**
  20744. * @readOnly
  20745. */
  20746. seriesIndex: 0,
  20747. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20748. coordinateSystem: null,
  20749. /**
  20750. * @type {Object}
  20751. * @protected
  20752. */
  20753. defaultOption: null,
  20754. /**
  20755. * legend visual provider to the legend component
  20756. * @type {Object}
  20757. */
  20758. // PENDING
  20759. legendVisualProvider: null,
  20760. /**
  20761. * Access path of color for visual
  20762. */
  20763. visualColorAccessPath: 'itemStyle.color',
  20764. /**
  20765. * Access path of borderColor for visual
  20766. */
  20767. visualBorderColorAccessPath: 'itemStyle.borderColor',
  20768. /**
  20769. * Support merge layout params.
  20770. * Only support 'box' now (left/right/top/bottom/width/height).
  20771. * @type {string|Object} Object can be {ignoreSize: true}
  20772. * @readOnly
  20773. */
  20774. layoutMode: null,
  20775. init: function (option, parentModel, ecModel, extraOpt) {
  20776. /**
  20777. * @type {number}
  20778. * @readOnly
  20779. */
  20780. this.seriesIndex = this.componentIndex;
  20781. this.dataTask = createTask({
  20782. count: dataTaskCount,
  20783. reset: dataTaskReset
  20784. });
  20785. this.dataTask.context = {model: this};
  20786. this.mergeDefaultAndTheme(option, ecModel);
  20787. prepareSource(this);
  20788. var data = this.getInitialData(option, ecModel);
  20789. wrapData(data, this);
  20790. this.dataTask.context.data = data;
  20791. if (__DEV__) {
  20792. assert$1(data, 'getInitialData returned invalid data.');
  20793. }
  20794. /**
  20795. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20796. * @private
  20797. */
  20798. inner$4(this).dataBeforeProcessed = data;
  20799. // If we reverse the order (make data firstly, and then make
  20800. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20801. // cause data.graph.data !== data when using
  20802. // module:echarts/data/Graph or module:echarts/data/Tree.
  20803. // See module:echarts/data/helper/linkList
  20804. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20805. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20806. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20807. // Call `seriesModel.getRawData()` instead.
  20808. // this.restoreData();
  20809. autoSeriesName(this);
  20810. },
  20811. /**
  20812. * Util for merge default and theme to option
  20813. * @param {Object} option
  20814. * @param {module:echarts/model/Global} ecModel
  20815. */
  20816. mergeDefaultAndTheme: function (option, ecModel) {
  20817. var layoutMode = this.layoutMode;
  20818. var inputPositionParams = layoutMode
  20819. ? getLayoutParams(option) : {};
  20820. // Backward compat: using subType on theme.
  20821. // But if name duplicate between series subType
  20822. // (for example: parallel) add component mainType,
  20823. // add suffix 'Series'.
  20824. var themeSubType = this.subType;
  20825. if (ComponentModel.hasClass(themeSubType)) {
  20826. themeSubType += 'Series';
  20827. }
  20828. merge(
  20829. option,
  20830. ecModel.getTheme().get(this.subType)
  20831. );
  20832. merge(option, this.getDefaultOption());
  20833. // Default label emphasis `show`
  20834. defaultEmphasis(option, 'label', ['show']);
  20835. this.fillDataTextStyle(option.data);
  20836. if (layoutMode) {
  20837. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20838. }
  20839. },
  20840. mergeOption: function (newSeriesOption, ecModel) {
  20841. // this.settingTask.dirty();
  20842. newSeriesOption = merge(this.option, newSeriesOption, true);
  20843. this.fillDataTextStyle(newSeriesOption.data);
  20844. var layoutMode = this.layoutMode;
  20845. if (layoutMode) {
  20846. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20847. }
  20848. prepareSource(this);
  20849. var data = this.getInitialData(newSeriesOption, ecModel);
  20850. wrapData(data, this);
  20851. this.dataTask.dirty();
  20852. this.dataTask.context.data = data;
  20853. inner$4(this).dataBeforeProcessed = data;
  20854. autoSeriesName(this);
  20855. },
  20856. fillDataTextStyle: function (data) {
  20857. // Default data label emphasis `show`
  20858. // FIXME Tree structure data ?
  20859. // FIXME Performance ?
  20860. if (data && !isTypedArray(data)) {
  20861. var props = ['show'];
  20862. for (var i = 0; i < data.length; i++) {
  20863. if (data[i] && data[i].label) {
  20864. defaultEmphasis(data[i], 'label', props);
  20865. }
  20866. }
  20867. }
  20868. },
  20869. /**
  20870. * Init a data structure from data related option in series
  20871. * Must be overwritten
  20872. */
  20873. getInitialData: function () {},
  20874. /**
  20875. * Append data to list
  20876. * @param {Object} params
  20877. * @param {Array|TypedArray} params.data
  20878. */
  20879. appendData: function (params) {
  20880. // FIXME ???
  20881. // (1) If data from dataset, forbidden append.
  20882. // (2) support append data of dataset.
  20883. var data = this.getRawData();
  20884. data.appendData(params.data);
  20885. },
  20886. /**
  20887. * Consider some method like `filter`, `map` need make new data,
  20888. * We should make sure that `seriesModel.getData()` get correct
  20889. * data in the stream procedure. So we fetch data from upstream
  20890. * each time `task.perform` called.
  20891. * @param {string} [dataType]
  20892. * @return {module:echarts/data/List}
  20893. */
  20894. getData: function (dataType) {
  20895. var task = getCurrentTask(this);
  20896. if (task) {
  20897. var data = task.context.data;
  20898. return dataType == null ? data : data.getLinkedData(dataType);
  20899. }
  20900. else {
  20901. // When series is not alive (that may happen when click toolbox
  20902. // restore or setOption with not merge mode), series data may
  20903. // be still need to judge animation or something when graphic
  20904. // elements want to know whether fade out.
  20905. return inner$4(this).data;
  20906. }
  20907. },
  20908. /**
  20909. * @param {module:echarts/data/List} data
  20910. */
  20911. setData: function (data) {
  20912. var task = getCurrentTask(this);
  20913. if (task) {
  20914. var context = task.context;
  20915. // Consider case: filter, data sample.
  20916. if (context.data !== data && task.modifyOutputEnd) {
  20917. task.setOutputEnd(data.count());
  20918. }
  20919. context.outputData = data;
  20920. // Caution: setData should update context.data,
  20921. // Because getData may be called multiply in a
  20922. // single stage and expect to get the data just
  20923. // set. (For example, AxisProxy, x y both call
  20924. // getData and setDate sequentially).
  20925. // So the context.data should be fetched from
  20926. // upstream each time when a stage starts to be
  20927. // performed.
  20928. if (task !== this.dataTask) {
  20929. context.data = data;
  20930. }
  20931. }
  20932. inner$4(this).data = data;
  20933. },
  20934. /**
  20935. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20936. * @return {module:echarts/data/Source} source
  20937. */
  20938. getSource: function () {
  20939. return getSource(this);
  20940. },
  20941. /**
  20942. * Get data before processed
  20943. * @return {module:echarts/data/List}
  20944. */
  20945. getRawData: function () {
  20946. return inner$4(this).dataBeforeProcessed;
  20947. },
  20948. /**
  20949. * Get base axis if has coordinate system and has axis.
  20950. * By default use coordSys.getBaseAxis();
  20951. * Can be overrided for some chart.
  20952. * @return {type} description
  20953. */
  20954. getBaseAxis: function () {
  20955. var coordSys = this.coordinateSystem;
  20956. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20957. },
  20958. // FIXME
  20959. /**
  20960. * Default tooltip formatter
  20961. *
  20962. * @param {number} dataIndex
  20963. * @param {boolean} [multipleSeries=false]
  20964. * @param {number} [dataType]
  20965. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20966. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20967. * string is used as DOM HTML content.
  20968. * 'richText' is used for rendering tooltip in rich text form, for those where
  20969. * DOM operation is not supported.
  20970. * @return {Object} formatted tooltip with `html` and `markers`
  20971. */
  20972. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20973. var series = this;
  20974. renderMode = renderMode || 'html';
  20975. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20976. var isRichText = renderMode === 'richText';
  20977. var markers = {};
  20978. var markerId = 0;
  20979. function formatArrayValue(value) {
  20980. // ??? TODO refactor these logic.
  20981. // check: category-no-encode-has-axis-data in dataset.html
  20982. var vertially = reduce(value, function (vertially, val, idx) {
  20983. var dimItem = data.getDimensionInfo(idx);
  20984. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20985. }, 0);
  20986. var result = [];
  20987. tooltipDims.length
  20988. ? each$1(tooltipDims, function (dim) {
  20989. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20990. })
  20991. // By default, all dims is used on tooltip.
  20992. : each$1(value, setEachItem);
  20993. function setEachItem(val, dim) {
  20994. var dimInfo = data.getDimensionInfo(dim);
  20995. // If `dimInfo.tooltip` is not set, show tooltip.
  20996. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20997. return;
  20998. }
  20999. var dimType = dimInfo.type;
  21000. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21001. var dimHead = getTooltipMarker({
  21002. color: color,
  21003. type: 'subItem',
  21004. renderMode: renderMode,
  21005. markerId: markName
  21006. });
  21007. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21008. var valStr = (vertially
  21009. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21010. : ''
  21011. )
  21012. // FIXME should not format time for raw data?
  21013. + encodeHTML(dimType === 'ordinal'
  21014. ? val + ''
  21015. : dimType === 'time'
  21016. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21017. : addCommas(val)
  21018. );
  21019. valStr && result.push(valStr);
  21020. if (isRichText) {
  21021. markers[markName] = color;
  21022. ++markerId;
  21023. }
  21024. }
  21025. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21026. var content = newLine + result.join(newLine || ', ');
  21027. return {
  21028. renderMode: renderMode,
  21029. content: content,
  21030. style: markers
  21031. };
  21032. }
  21033. function formatSingleValue(val) {
  21034. // return encodeHTML(addCommas(val));
  21035. return {
  21036. renderMode: renderMode,
  21037. content: encodeHTML(addCommas(val)),
  21038. style: markers
  21039. };
  21040. }
  21041. var data = this.getData();
  21042. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21043. var tooltipDimLen = tooltipDims.length;
  21044. var value = this.getRawValue(dataIndex);
  21045. var isValueArr = isArray(value);
  21046. var color = data.getItemVisual(dataIndex, 'color');
  21047. if (isObject$1(color) && color.colorStops) {
  21048. color = (color.colorStops[0] || {}).color;
  21049. }
  21050. color = color || 'transparent';
  21051. // Complicated rule for pretty tooltip.
  21052. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21053. ? formatArrayValue(value)
  21054. : tooltipDimLen
  21055. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21056. : formatSingleValue(isValueArr ? value[0] : value);
  21057. var content = formattedValue.content;
  21058. var markName = series.seriesIndex + 'at' + markerId;
  21059. var colorEl = getTooltipMarker({
  21060. color: color,
  21061. type: 'item',
  21062. renderMode: renderMode,
  21063. markerId: markName
  21064. });
  21065. markers[markName] = color;
  21066. ++markerId;
  21067. var name = data.getName(dataIndex);
  21068. var seriesName = this.name;
  21069. if (!isNameSpecified(this)) {
  21070. seriesName = '';
  21071. }
  21072. seriesName = seriesName
  21073. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21074. : '';
  21075. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21076. var html = !multipleSeries
  21077. ? seriesName + colorStr
  21078. + (name
  21079. ? encodeHTML(name) + ': ' + content
  21080. : content
  21081. )
  21082. : colorStr + seriesName + content;
  21083. return {
  21084. html: html,
  21085. markers: markers
  21086. };
  21087. },
  21088. /**
  21089. * @return {boolean}
  21090. */
  21091. isAnimationEnabled: function () {
  21092. if (env$1.node) {
  21093. return false;
  21094. }
  21095. var animationEnabled = this.getShallow('animation');
  21096. if (animationEnabled) {
  21097. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21098. animationEnabled = false;
  21099. }
  21100. }
  21101. return animationEnabled;
  21102. },
  21103. restoreData: function () {
  21104. this.dataTask.dirty();
  21105. },
  21106. getColorFromPalette: function (name, scope, requestColorNum) {
  21107. var ecModel = this.ecModel;
  21108. // PENDING
  21109. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21110. if (!color) {
  21111. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21112. }
  21113. return color;
  21114. },
  21115. /**
  21116. * Use `data.mapDimension(coordDim, true)` instead.
  21117. * @deprecated
  21118. */
  21119. coordDimToDataDim: function (coordDim) {
  21120. return this.getRawData().mapDimension(coordDim, true);
  21121. },
  21122. /**
  21123. * Get progressive rendering count each step
  21124. * @return {number}
  21125. */
  21126. getProgressive: function () {
  21127. return this.get('progressive');
  21128. },
  21129. /**
  21130. * Get progressive rendering count each step
  21131. * @return {number}
  21132. */
  21133. getProgressiveThreshold: function () {
  21134. return this.get('progressiveThreshold');
  21135. },
  21136. /**
  21137. * Get data indices for show tooltip content. See tooltip.
  21138. * @abstract
  21139. * @param {Array.<string>|string} dim
  21140. * @param {Array.<number>} value
  21141. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21142. * @return {Object} {dataIndices, nestestValue}.
  21143. */
  21144. getAxisTooltipData: null,
  21145. /**
  21146. * See tooltip.
  21147. * @abstract
  21148. * @param {number} dataIndex
  21149. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21150. */
  21151. getTooltipPosition: null,
  21152. /**
  21153. * @see {module:echarts/stream/Scheduler}
  21154. */
  21155. pipeTask: null,
  21156. /**
  21157. * Convinient for override in extended class.
  21158. * @protected
  21159. * @type {Function}
  21160. */
  21161. preventIncremental: null,
  21162. /**
  21163. * @public
  21164. * @readOnly
  21165. * @type {Object}
  21166. */
  21167. pipelineContext: null
  21168. });
  21169. mixin(SeriesModel, dataFormatMixin);
  21170. mixin(SeriesModel, colorPaletteMixin);
  21171. /**
  21172. * MUST be called after `prepareSource` called
  21173. * Here we need to make auto series, especially for auto legend. But we
  21174. * do not modify series.name in option to avoid side effects.
  21175. */
  21176. function autoSeriesName(seriesModel) {
  21177. // User specified name has higher priority, otherwise it may cause
  21178. // series can not be queried unexpectedly.
  21179. var name = seriesModel.name;
  21180. if (!isNameSpecified(seriesModel)) {
  21181. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21182. }
  21183. }
  21184. function getSeriesAutoName(seriesModel) {
  21185. var data = seriesModel.getRawData();
  21186. var dataDims = data.mapDimension('seriesName', true);
  21187. var nameArr = [];
  21188. each$1(dataDims, function (dataDim) {
  21189. var dimInfo = data.getDimensionInfo(dataDim);
  21190. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21191. });
  21192. return nameArr.join(' ');
  21193. }
  21194. function dataTaskCount(context) {
  21195. return context.model.getRawData().count();
  21196. }
  21197. function dataTaskReset(context) {
  21198. var seriesModel = context.model;
  21199. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21200. return dataTaskProgress;
  21201. }
  21202. function dataTaskProgress(param, context) {
  21203. // Avoid repead cloneShallow when data just created in reset.
  21204. if (param.end > context.outputData.count()) {
  21205. context.model.getRawData().cloneShallow(context.outputData);
  21206. }
  21207. }
  21208. // TODO refactor
  21209. function wrapData(data, seriesModel) {
  21210. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21211. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21212. });
  21213. }
  21214. function onDataSelfChange(seriesModel) {
  21215. var task = getCurrentTask(seriesModel);
  21216. if (task) {
  21217. // Consider case: filter, selectRange
  21218. task.setOutputEnd(this.count());
  21219. }
  21220. }
  21221. function getCurrentTask(seriesModel) {
  21222. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21223. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21224. if (pipeline) {
  21225. // When pipline finished, the currrentTask keep the last
  21226. // task (renderTask).
  21227. var task = pipeline.currentTask;
  21228. if (task) {
  21229. var agentStubMap = task.agentStubMap;
  21230. if (agentStubMap) {
  21231. task = agentStubMap.get(seriesModel.uid);
  21232. }
  21233. }
  21234. return task;
  21235. }
  21236. }
  21237. /*
  21238. * Licensed to the Apache Software Foundation (ASF) under one
  21239. * or more contributor license agreements. See the NOTICE file
  21240. * distributed with this work for additional information
  21241. * regarding copyright ownership. The ASF licenses this file
  21242. * to you under the Apache License, Version 2.0 (the
  21243. * "License"); you may not use this file except in compliance
  21244. * with the License. You may obtain a copy of the License at
  21245. *
  21246. * http://www.apache.org/licenses/LICENSE-2.0
  21247. *
  21248. * Unless required by applicable law or agreed to in writing,
  21249. * software distributed under the License is distributed on an
  21250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21251. * KIND, either express or implied. See the License for the
  21252. * specific language governing permissions and limitations
  21253. * under the License.
  21254. */
  21255. var Component = function () {
  21256. /**
  21257. * @type {module:zrender/container/Group}
  21258. * @readOnly
  21259. */
  21260. this.group = new Group();
  21261. /**
  21262. * @type {string}
  21263. * @readOnly
  21264. */
  21265. this.uid = getUID('viewComponent');
  21266. };
  21267. Component.prototype = {
  21268. constructor: Component,
  21269. init: function (ecModel, api) {},
  21270. render: function (componentModel, ecModel, api, payload) {},
  21271. dispose: function () {},
  21272. /**
  21273. * @param {string} eventType
  21274. * @param {Object} query
  21275. * @param {module:zrender/Element} targetEl
  21276. * @param {Object} packedEvent
  21277. * @return {boolen} Pass only when return `true`.
  21278. */
  21279. filterForExposedEvent: null
  21280. };
  21281. var componentProto = Component.prototype;
  21282. componentProto.updateView =
  21283. componentProto.updateLayout =
  21284. componentProto.updateVisual =
  21285. function (seriesModel, ecModel, api, payload) {
  21286. // Do nothing;
  21287. };
  21288. // Enable Component.extend.
  21289. enableClassExtend(Component);
  21290. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21291. enableClassManagement(Component, {registerWhenExtend: true});
  21292. /*
  21293. * Licensed to the Apache Software Foundation (ASF) under one
  21294. * or more contributor license agreements. See the NOTICE file
  21295. * distributed with this work for additional information
  21296. * regarding copyright ownership. The ASF licenses this file
  21297. * to you under the Apache License, Version 2.0 (the
  21298. * "License"); you may not use this file except in compliance
  21299. * with the License. You may obtain a copy of the License at
  21300. *
  21301. * http://www.apache.org/licenses/LICENSE-2.0
  21302. *
  21303. * Unless required by applicable law or agreed to in writing,
  21304. * software distributed under the License is distributed on an
  21305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21306. * KIND, either express or implied. See the License for the
  21307. * specific language governing permissions and limitations
  21308. * under the License.
  21309. */
  21310. /**
  21311. * @return {string} If large mode changed, return string 'reset';
  21312. */
  21313. var createRenderPlanner = function () {
  21314. var inner = makeInner();
  21315. return function (seriesModel) {
  21316. var fields = inner(seriesModel);
  21317. var pipelineContext = seriesModel.pipelineContext;
  21318. var originalLarge = fields.large;
  21319. var originalProgressive = fields.progressiveRender;
  21320. var large = fields.large = pipelineContext.large;
  21321. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21322. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21323. };
  21324. };
  21325. /*
  21326. * Licensed to the Apache Software Foundation (ASF) under one
  21327. * or more contributor license agreements. See the NOTICE file
  21328. * distributed with this work for additional information
  21329. * regarding copyright ownership. The ASF licenses this file
  21330. * to you under the Apache License, Version 2.0 (the
  21331. * "License"); you may not use this file except in compliance
  21332. * with the License. You may obtain a copy of the License at
  21333. *
  21334. * http://www.apache.org/licenses/LICENSE-2.0
  21335. *
  21336. * Unless required by applicable law or agreed to in writing,
  21337. * software distributed under the License is distributed on an
  21338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21339. * KIND, either express or implied. See the License for the
  21340. * specific language governing permissions and limitations
  21341. * under the License.
  21342. */
  21343. var inner$5 = makeInner();
  21344. var renderPlanner = createRenderPlanner();
  21345. function Chart() {
  21346. /**
  21347. * @type {module:zrender/container/Group}
  21348. * @readOnly
  21349. */
  21350. this.group = new Group();
  21351. /**
  21352. * @type {string}
  21353. * @readOnly
  21354. */
  21355. this.uid = getUID('viewChart');
  21356. this.renderTask = createTask({
  21357. plan: renderTaskPlan,
  21358. reset: renderTaskReset
  21359. });
  21360. this.renderTask.context = {view: this};
  21361. }
  21362. Chart.prototype = {
  21363. type: 'chart',
  21364. /**
  21365. * Init the chart.
  21366. * @param {module:echarts/model/Global} ecModel
  21367. * @param {module:echarts/ExtensionAPI} api
  21368. */
  21369. init: function (ecModel, api) {},
  21370. /**
  21371. * Render the chart.
  21372. * @param {module:echarts/model/Series} seriesModel
  21373. * @param {module:echarts/model/Global} ecModel
  21374. * @param {module:echarts/ExtensionAPI} api
  21375. * @param {Object} payload
  21376. */
  21377. render: function (seriesModel, ecModel, api, payload) {},
  21378. /**
  21379. * Highlight series or specified data item.
  21380. * @param {module:echarts/model/Series} seriesModel
  21381. * @param {module:echarts/model/Global} ecModel
  21382. * @param {module:echarts/ExtensionAPI} api
  21383. * @param {Object} payload
  21384. */
  21385. highlight: function (seriesModel, ecModel, api, payload) {
  21386. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21387. },
  21388. /**
  21389. * Downplay series or specified data item.
  21390. * @param {module:echarts/model/Series} seriesModel
  21391. * @param {module:echarts/model/Global} ecModel
  21392. * @param {module:echarts/ExtensionAPI} api
  21393. * @param {Object} payload
  21394. */
  21395. downplay: function (seriesModel, ecModel, api, payload) {
  21396. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21397. },
  21398. /**
  21399. * Remove self.
  21400. * @param {module:echarts/model/Global} ecModel
  21401. * @param {module:echarts/ExtensionAPI} api
  21402. */
  21403. remove: function (ecModel, api) {
  21404. this.group.removeAll();
  21405. },
  21406. /**
  21407. * Dispose self.
  21408. * @param {module:echarts/model/Global} ecModel
  21409. * @param {module:echarts/ExtensionAPI} api
  21410. */
  21411. dispose: function () {},
  21412. /**
  21413. * Rendering preparation in progressive mode.
  21414. * @param {module:echarts/model/Series} seriesModel
  21415. * @param {module:echarts/model/Global} ecModel
  21416. * @param {module:echarts/ExtensionAPI} api
  21417. * @param {Object} payload
  21418. */
  21419. incrementalPrepareRender: null,
  21420. /**
  21421. * Render in progressive mode.
  21422. * @param {Object} params See taskParams in `stream/task.js`
  21423. * @param {module:echarts/model/Series} seriesModel
  21424. * @param {module:echarts/model/Global} ecModel
  21425. * @param {module:echarts/ExtensionAPI} api
  21426. * @param {Object} payload
  21427. */
  21428. incrementalRender: null,
  21429. /**
  21430. * Update transform directly.
  21431. * @param {module:echarts/model/Series} seriesModel
  21432. * @param {module:echarts/model/Global} ecModel
  21433. * @param {module:echarts/ExtensionAPI} api
  21434. * @param {Object} payload
  21435. * @return {Object} {update: true}
  21436. */
  21437. updateTransform: null,
  21438. /**
  21439. * The view contains the given point.
  21440. * @interface
  21441. * @param {Array.<number>} point
  21442. * @return {boolean}
  21443. */
  21444. // containPoint: function () {}
  21445. /**
  21446. * @param {string} eventType
  21447. * @param {Object} query
  21448. * @param {module:zrender/Element} targetEl
  21449. * @param {Object} packedEvent
  21450. * @return {boolen} Pass only when return `true`.
  21451. */
  21452. filterForExposedEvent: null
  21453. };
  21454. var chartProto = Chart.prototype;
  21455. chartProto.updateView =
  21456. chartProto.updateLayout =
  21457. chartProto.updateVisual =
  21458. function (seriesModel, ecModel, api, payload) {
  21459. this.render(seriesModel, ecModel, api, payload);
  21460. };
  21461. /**
  21462. * Set state of single element
  21463. * @param {module:zrender/Element} el
  21464. * @param {string} state 'normal'|'emphasis'
  21465. * @param {number} highlightDigit
  21466. */
  21467. function elSetState(el, state, highlightDigit) {
  21468. if (el) {
  21469. el.trigger(state, highlightDigit);
  21470. if (el.isGroup
  21471. // Simple optimize.
  21472. && !isHighDownDispatcher(el)
  21473. ) {
  21474. for (var i = 0, len = el.childCount(); i < len; i++) {
  21475. elSetState(el.childAt(i), state, highlightDigit);
  21476. }
  21477. }
  21478. }
  21479. }
  21480. /**
  21481. * @param {module:echarts/data/List} data
  21482. * @param {Object} payload
  21483. * @param {string} state 'normal'|'emphasis'
  21484. */
  21485. function toggleHighlight(data, payload, state) {
  21486. var dataIndex = queryDataIndex(data, payload);
  21487. var highlightDigit = (payload && payload.highlightKey != null)
  21488. ? getHighlightDigit(payload.highlightKey)
  21489. : null;
  21490. if (dataIndex != null) {
  21491. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21492. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  21493. });
  21494. }
  21495. else {
  21496. data.eachItemGraphicEl(function (el) {
  21497. elSetState(el, state, highlightDigit);
  21498. });
  21499. }
  21500. }
  21501. // Enable Chart.extend.
  21502. enableClassExtend(Chart, ['dispose']);
  21503. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21504. enableClassManagement(Chart, {registerWhenExtend: true});
  21505. Chart.markUpdateMethod = function (payload, methodName) {
  21506. inner$5(payload).updateMethod = methodName;
  21507. };
  21508. function renderTaskPlan(context) {
  21509. return renderPlanner(context.model);
  21510. }
  21511. function renderTaskReset(context) {
  21512. var seriesModel = context.model;
  21513. var ecModel = context.ecModel;
  21514. var api = context.api;
  21515. var payload = context.payload;
  21516. // ???! remove updateView updateVisual
  21517. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21518. var view = context.view;
  21519. var updateMethod = payload && inner$5(payload).updateMethod;
  21520. var methodName = progressiveRender
  21521. ? 'incrementalPrepareRender'
  21522. : (updateMethod && view[updateMethod])
  21523. ? updateMethod
  21524. // `appendData` is also supported when data amount
  21525. // is less than progressive threshold.
  21526. : 'render';
  21527. if (methodName !== 'render') {
  21528. view[methodName](seriesModel, ecModel, api, payload);
  21529. }
  21530. return progressMethodMap[methodName];
  21531. }
  21532. var progressMethodMap = {
  21533. incrementalPrepareRender: {
  21534. progress: function (params, context) {
  21535. context.view.incrementalRender(
  21536. params, context.model, context.ecModel, context.api, context.payload
  21537. );
  21538. }
  21539. },
  21540. render: {
  21541. // Put view.render in `progress` to support appendData. But in this case
  21542. // view.render should not be called in reset, otherwise it will be called
  21543. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21544. // in any cases.
  21545. forceFirstProgress: true,
  21546. progress: function (params, context) {
  21547. context.view.render(
  21548. context.model, context.ecModel, context.api, context.payload
  21549. );
  21550. }
  21551. }
  21552. };
  21553. /*
  21554. * Licensed to the Apache Software Foundation (ASF) under one
  21555. * or more contributor license agreements. See the NOTICE file
  21556. * distributed with this work for additional information
  21557. * regarding copyright ownership. The ASF licenses this file
  21558. * to you under the Apache License, Version 2.0 (the
  21559. * "License"); you may not use this file except in compliance
  21560. * with the License. You may obtain a copy of the License at
  21561. *
  21562. * http://www.apache.org/licenses/LICENSE-2.0
  21563. *
  21564. * Unless required by applicable law or agreed to in writing,
  21565. * software distributed under the License is distributed on an
  21566. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21567. * KIND, either express or implied. See the License for the
  21568. * specific language governing permissions and limitations
  21569. * under the License.
  21570. */
  21571. /**
  21572. * @public
  21573. * @param {(Function)} fn
  21574. * @param {number} [delay=0] Unit: ms.
  21575. * @param {boolean} [debounce=false]
  21576. * true: If call interval less than `delay`, only the last call works.
  21577. * false: If call interval less than `delay, call works on fixed rate.
  21578. * @return {(Function)} throttled fn.
  21579. */
  21580. function throttle(fn, delay, debounce) {
  21581. var currCall;
  21582. var lastCall = 0;
  21583. var lastExec = 0;
  21584. var timer = null;
  21585. var diff;
  21586. var scope;
  21587. var args;
  21588. var debounceNextCall;
  21589. delay = delay || 0;
  21590. function exec() {
  21591. lastExec = (new Date()).getTime();
  21592. timer = null;
  21593. fn.apply(scope, args || []);
  21594. }
  21595. var cb = function () {
  21596. currCall = (new Date()).getTime();
  21597. scope = this;
  21598. args = arguments;
  21599. var thisDelay = debounceNextCall || delay;
  21600. var thisDebounce = debounceNextCall || debounce;
  21601. debounceNextCall = null;
  21602. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21603. clearTimeout(timer);
  21604. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21605. // than a new call of `cb`, that is, preserving the command order. Consider
  21606. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21607. // happens, either the `exec` is called dierectly, or the call is delayed.
  21608. // But the delayed call should never be later than next call of `cb`. Under
  21609. // this assurance, we can simply update view state each time `dispatchAction`
  21610. // triggered by user roaming, but not need to add extra code to avoid the
  21611. // state being "rolled-back".
  21612. if (thisDebounce) {
  21613. timer = setTimeout(exec, thisDelay);
  21614. }
  21615. else {
  21616. if (diff >= 0) {
  21617. exec();
  21618. }
  21619. else {
  21620. timer = setTimeout(exec, -diff);
  21621. }
  21622. }
  21623. lastCall = currCall;
  21624. };
  21625. /**
  21626. * Clear throttle.
  21627. * @public
  21628. */
  21629. cb.clear = function () {
  21630. if (timer) {
  21631. clearTimeout(timer);
  21632. timer = null;
  21633. }
  21634. };
  21635. /**
  21636. * Enable debounce once.
  21637. */
  21638. cb.debounceNextCall = function (debounceDelay) {
  21639. debounceNextCall = debounceDelay;
  21640. };
  21641. return cb;
  21642. }
  21643. /**
  21644. * Create throttle method or update throttle rate.
  21645. *
  21646. * @example
  21647. * ComponentView.prototype.render = function () {
  21648. * ...
  21649. * throttle.createOrUpdate(
  21650. * this,
  21651. * '_dispatchAction',
  21652. * this.model.get('throttle'),
  21653. * 'fixRate'
  21654. * );
  21655. * };
  21656. * ComponentView.prototype.remove = function () {
  21657. * throttle.clear(this, '_dispatchAction');
  21658. * };
  21659. * ComponentView.prototype.dispose = function () {
  21660. * throttle.clear(this, '_dispatchAction');
  21661. * };
  21662. *
  21663. * @public
  21664. * @param {Object} obj
  21665. * @param {string} fnAttr
  21666. * @param {number} [rate]
  21667. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21668. * @return {Function} throttled function.
  21669. */
  21670. /**
  21671. * Clear throttle. Example see throttle.createOrUpdate.
  21672. *
  21673. * @public
  21674. * @param {Object} obj
  21675. * @param {string} fnAttr
  21676. */
  21677. /*
  21678. * Licensed to the Apache Software Foundation (ASF) under one
  21679. * or more contributor license agreements. See the NOTICE file
  21680. * distributed with this work for additional information
  21681. * regarding copyright ownership. The ASF licenses this file
  21682. * to you under the Apache License, Version 2.0 (the
  21683. * "License"); you may not use this file except in compliance
  21684. * with the License. You may obtain a copy of the License at
  21685. *
  21686. * http://www.apache.org/licenses/LICENSE-2.0
  21687. *
  21688. * Unless required by applicable law or agreed to in writing,
  21689. * software distributed under the License is distributed on an
  21690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21691. * KIND, either express or implied. See the License for the
  21692. * specific language governing permissions and limitations
  21693. * under the License.
  21694. */
  21695. var seriesColor = {
  21696. createOnAllSeries: true,
  21697. performRawSeries: true,
  21698. reset: function (seriesModel, ecModel) {
  21699. var data = seriesModel.getData();
  21700. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21701. // Set in itemStyle
  21702. var color = seriesModel.get(colorAccessPath);
  21703. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  21704. ? color : null;
  21705. // Default color
  21706. if (!color || colorCallback) {
  21707. color = seriesModel.getColorFromPalette(
  21708. // TODO series count changed.
  21709. seriesModel.name, null, ecModel.getSeriesCount()
  21710. );
  21711. }
  21712. data.setVisual('color', color);
  21713. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  21714. var borderColor = seriesModel.get(borderColorAccessPath);
  21715. data.setVisual('borderColor', borderColor);
  21716. // Only visible series has each data be visual encoded
  21717. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21718. if (colorCallback) {
  21719. data.each(function (idx) {
  21720. data.setItemVisual(
  21721. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  21722. );
  21723. });
  21724. }
  21725. // itemStyle in each data item
  21726. var dataEach = function (data, idx) {
  21727. var itemModel = data.getItemModel(idx);
  21728. var color = itemModel.get(colorAccessPath, true);
  21729. var borderColor = itemModel.get(borderColorAccessPath, true);
  21730. if (color != null) {
  21731. data.setItemVisual(idx, 'color', color);
  21732. }
  21733. if (borderColor != null) {
  21734. data.setItemVisual(idx, 'borderColor', borderColor);
  21735. }
  21736. };
  21737. return { dataEach: data.hasItemOption ? dataEach : null };
  21738. }
  21739. }
  21740. };
  21741. /*
  21742. * Licensed to the Apache Software Foundation (ASF) under one
  21743. * or more contributor license agreements. See the NOTICE file
  21744. * distributed with this work for additional information
  21745. * regarding copyright ownership. The ASF licenses this file
  21746. * to you under the Apache License, Version 2.0 (the
  21747. * "License"); you may not use this file except in compliance
  21748. * with the License. You may obtain a copy of the License at
  21749. *
  21750. * http://www.apache.org/licenses/LICENSE-2.0
  21751. *
  21752. * Unless required by applicable law or agreed to in writing,
  21753. * software distributed under the License is distributed on an
  21754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21755. * KIND, either express or implied. See the License for the
  21756. * specific language governing permissions and limitations
  21757. * under the License.
  21758. */
  21759. /**
  21760. * Language: (Simplified) Chinese.
  21761. */
  21762. var lang = {
  21763. legend: {
  21764. selector: {
  21765. all: '全选',
  21766. inverse: '反选'
  21767. }
  21768. },
  21769. toolbox: {
  21770. brush: {
  21771. title: {
  21772. rect: '矩形选择',
  21773. polygon: '圈选',
  21774. lineX: '横向选择',
  21775. lineY: '纵向选择',
  21776. keep: '保持选择',
  21777. clear: '清除选择'
  21778. }
  21779. },
  21780. dataView: {
  21781. title: '数据视图',
  21782. lang: ['数据视图', '关闭', '刷新']
  21783. },
  21784. dataZoom: {
  21785. title: {
  21786. zoom: '区域缩放',
  21787. back: '区域缩放还原'
  21788. }
  21789. },
  21790. magicType: {
  21791. title: {
  21792. line: '切换为折线图',
  21793. bar: '切换为柱状图',
  21794. stack: '切换为堆叠',
  21795. tiled: '切换为平铺'
  21796. }
  21797. },
  21798. restore: {
  21799. title: '还原'
  21800. },
  21801. saveAsImage: {
  21802. title: '保存为图片',
  21803. lang: ['右键另存为图片']
  21804. }
  21805. },
  21806. series: {
  21807. typeNames: {
  21808. pie: '饼图',
  21809. bar: '柱状图',
  21810. line: '折线图',
  21811. scatter: '散点图',
  21812. effectScatter: '涟漪散点图',
  21813. radar: '雷达图',
  21814. tree: '树图',
  21815. treemap: '矩形树图',
  21816. boxplot: '箱型图',
  21817. candlestick: 'K线图',
  21818. k: 'K线图',
  21819. heatmap: '热力图',
  21820. map: '地图',
  21821. parallel: '平行坐标图',
  21822. lines: '线图',
  21823. graph: '关系图',
  21824. sankey: '桑基图',
  21825. funnel: '漏斗图',
  21826. gauge: '仪表盘图',
  21827. pictorialBar: '象形柱图',
  21828. themeRiver: '主题河流图',
  21829. sunburst: '旭日图'
  21830. }
  21831. },
  21832. aria: {
  21833. general: {
  21834. withTitle: '这是一个关于“{title}”的图表。',
  21835. withoutTitle: '这是一个图表,'
  21836. },
  21837. series: {
  21838. single: {
  21839. prefix: '',
  21840. withName: '图表类型是{seriesType},表示{seriesName}。',
  21841. withoutName: '图表类型是{seriesType}。'
  21842. },
  21843. multiple: {
  21844. prefix: '它由{seriesCount}个图表系列组成。',
  21845. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21846. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21847. separator: {
  21848. middle: ';',
  21849. end: '。'
  21850. }
  21851. }
  21852. },
  21853. data: {
  21854. allData: '其数据是——',
  21855. partialData: '其中,前{displayCnt}项是——',
  21856. withName: '{name}的数据是{value}',
  21857. withoutName: '{value}',
  21858. separator: {
  21859. middle: ',',
  21860. end: ''
  21861. }
  21862. }
  21863. }
  21864. };
  21865. /*
  21866. * Licensed to the Apache Software Foundation (ASF) under one
  21867. * or more contributor license agreements. See the NOTICE file
  21868. * distributed with this work for additional information
  21869. * regarding copyright ownership. The ASF licenses this file
  21870. * to you under the Apache License, Version 2.0 (the
  21871. * "License"); you may not use this file except in compliance
  21872. * with the License. You may obtain a copy of the License at
  21873. *
  21874. * http://www.apache.org/licenses/LICENSE-2.0
  21875. *
  21876. * Unless required by applicable law or agreed to in writing,
  21877. * software distributed under the License is distributed on an
  21878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21879. * KIND, either express or implied. See the License for the
  21880. * specific language governing permissions and limitations
  21881. * under the License.
  21882. */
  21883. var aria = function (dom, ecModel) {
  21884. var ariaModel = ecModel.getModel('aria');
  21885. if (!ariaModel.get('show')) {
  21886. return;
  21887. }
  21888. else if (ariaModel.get('description')) {
  21889. dom.setAttribute('aria-label', ariaModel.get('description'));
  21890. return;
  21891. }
  21892. var seriesCnt = 0;
  21893. ecModel.eachSeries(function (seriesModel, idx) {
  21894. ++seriesCnt;
  21895. }, this);
  21896. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21897. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21898. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21899. var ariaLabel;
  21900. if (seriesCnt < 1) {
  21901. // No series, no aria label
  21902. return;
  21903. }
  21904. else {
  21905. var title = getTitle();
  21906. if (title) {
  21907. ariaLabel = replace(getConfig('general.withTitle'), {
  21908. title: title
  21909. });
  21910. }
  21911. else {
  21912. ariaLabel = getConfig('general.withoutTitle');
  21913. }
  21914. var seriesLabels = [];
  21915. var prefix = seriesCnt > 1
  21916. ? 'series.multiple.prefix'
  21917. : 'series.single.prefix';
  21918. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21919. ecModel.eachSeries(function (seriesModel, idx) {
  21920. if (idx < displaySeriesCnt) {
  21921. var seriesLabel;
  21922. var seriesName = seriesModel.get('name');
  21923. var seriesTpl = 'series.'
  21924. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21925. seriesLabel = getConfig(seriesName
  21926. ? seriesTpl + 'withName'
  21927. : seriesTpl + 'withoutName');
  21928. seriesLabel = replace(seriesLabel, {
  21929. seriesId: seriesModel.seriesIndex,
  21930. seriesName: seriesModel.get('name'),
  21931. seriesType: getSeriesTypeName(seriesModel.subType)
  21932. });
  21933. var data = seriesModel.getData();
  21934. window.data = data;
  21935. if (data.count() > maxDataCnt) {
  21936. // Show part of data
  21937. seriesLabel += replace(getConfig('data.partialData'), {
  21938. displayCnt: maxDataCnt
  21939. });
  21940. }
  21941. else {
  21942. seriesLabel += getConfig('data.allData');
  21943. }
  21944. var dataLabels = [];
  21945. for (var i = 0; i < data.count(); i++) {
  21946. if (i < maxDataCnt) {
  21947. var name = data.getName(i);
  21948. var value = retrieveRawValue(data, i);
  21949. dataLabels.push(
  21950. replace(
  21951. name
  21952. ? getConfig('data.withName')
  21953. : getConfig('data.withoutName'),
  21954. {
  21955. name: name,
  21956. value: value
  21957. }
  21958. )
  21959. );
  21960. }
  21961. }
  21962. seriesLabel += dataLabels
  21963. .join(getConfig('data.separator.middle'))
  21964. + getConfig('data.separator.end');
  21965. seriesLabels.push(seriesLabel);
  21966. }
  21967. });
  21968. ariaLabel += seriesLabels
  21969. .join(getConfig('series.multiple.separator.middle'))
  21970. + getConfig('series.multiple.separator.end');
  21971. dom.setAttribute('aria-label', ariaLabel);
  21972. }
  21973. function replace(str, keyValues) {
  21974. if (typeof str !== 'string') {
  21975. return str;
  21976. }
  21977. var result = str;
  21978. each$1(keyValues, function (value, key) {
  21979. result = result.replace(
  21980. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21981. value
  21982. );
  21983. });
  21984. return result;
  21985. }
  21986. function getConfig(path) {
  21987. var userConfig = ariaModel.get(path);
  21988. if (userConfig == null) {
  21989. var pathArr = path.split('.');
  21990. var result = lang.aria;
  21991. for (var i = 0; i < pathArr.length; ++i) {
  21992. result = result[pathArr[i]];
  21993. }
  21994. return result;
  21995. }
  21996. else {
  21997. return userConfig;
  21998. }
  21999. }
  22000. function getTitle() {
  22001. var title = ecModel.getModel('title').option;
  22002. if (title && title.length) {
  22003. title = title[0];
  22004. }
  22005. return title && title.text;
  22006. }
  22007. function getSeriesTypeName(type) {
  22008. return lang.series.typeNames[type] || '自定义图';
  22009. }
  22010. };
  22011. /*
  22012. * Licensed to the Apache Software Foundation (ASF) under one
  22013. * or more contributor license agreements. See the NOTICE file
  22014. * distributed with this work for additional information
  22015. * regarding copyright ownership. The ASF licenses this file
  22016. * to you under the Apache License, Version 2.0 (the
  22017. * "License"); you may not use this file except in compliance
  22018. * with the License. You may obtain a copy of the License at
  22019. *
  22020. * http://www.apache.org/licenses/LICENSE-2.0
  22021. *
  22022. * Unless required by applicable law or agreed to in writing,
  22023. * software distributed under the License is distributed on an
  22024. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22025. * KIND, either express or implied. See the License for the
  22026. * specific language governing permissions and limitations
  22027. * under the License.
  22028. */
  22029. var PI$1 = Math.PI;
  22030. /**
  22031. * @param {module:echarts/ExtensionAPI} api
  22032. * @param {Object} [opts]
  22033. * @param {string} [opts.text]
  22034. * @param {string} [opts.color]
  22035. * @param {string} [opts.textColor]
  22036. * @return {module:zrender/Element}
  22037. */
  22038. var loadingDefault = function (api, opts) {
  22039. opts = opts || {};
  22040. defaults(opts, {
  22041. text: 'loading',
  22042. color: '#c23531',
  22043. textColor: '#000',
  22044. maskColor: 'rgba(255, 255, 255, 0.8)',
  22045. zlevel: 0
  22046. });
  22047. var mask = new Rect({
  22048. style: {
  22049. fill: opts.maskColor
  22050. },
  22051. zlevel: opts.zlevel,
  22052. z: 10000
  22053. });
  22054. var arc = new Arc({
  22055. shape: {
  22056. startAngle: -PI$1 / 2,
  22057. endAngle: -PI$1 / 2 + 0.1,
  22058. r: 10
  22059. },
  22060. style: {
  22061. stroke: opts.color,
  22062. lineCap: 'round',
  22063. lineWidth: 5
  22064. },
  22065. zlevel: opts.zlevel,
  22066. z: 10001
  22067. });
  22068. var labelRect = new Rect({
  22069. style: {
  22070. fill: 'none',
  22071. text: opts.text,
  22072. textPosition: 'right',
  22073. textDistance: 10,
  22074. textFill: opts.textColor
  22075. },
  22076. zlevel: opts.zlevel,
  22077. z: 10001
  22078. });
  22079. arc.animateShape(true)
  22080. .when(1000, {
  22081. endAngle: PI$1 * 3 / 2
  22082. })
  22083. .start('circularInOut');
  22084. arc.animateShape(true)
  22085. .when(1000, {
  22086. startAngle: PI$1 * 3 / 2
  22087. })
  22088. .delay(300)
  22089. .start('circularInOut');
  22090. var group = new Group();
  22091. group.add(arc);
  22092. group.add(labelRect);
  22093. group.add(mask);
  22094. // Inject resize
  22095. group.resize = function () {
  22096. var cx = api.getWidth() / 2;
  22097. var cy = api.getHeight() / 2;
  22098. arc.setShape({
  22099. cx: cx,
  22100. cy: cy
  22101. });
  22102. var r = arc.shape.r;
  22103. labelRect.setShape({
  22104. x: cx - r,
  22105. y: cy - r,
  22106. width: r * 2,
  22107. height: r * 2
  22108. });
  22109. mask.setShape({
  22110. x: 0,
  22111. y: 0,
  22112. width: api.getWidth(),
  22113. height: api.getHeight()
  22114. });
  22115. };
  22116. group.resize();
  22117. return group;
  22118. };
  22119. /*
  22120. * Licensed to the Apache Software Foundation (ASF) under one
  22121. * or more contributor license agreements. See the NOTICE file
  22122. * distributed with this work for additional information
  22123. * regarding copyright ownership. The ASF licenses this file
  22124. * to you under the Apache License, Version 2.0 (the
  22125. * "License"); you may not use this file except in compliance
  22126. * with the License. You may obtain a copy of the License at
  22127. *
  22128. * http://www.apache.org/licenses/LICENSE-2.0
  22129. *
  22130. * Unless required by applicable law or agreed to in writing,
  22131. * software distributed under the License is distributed on an
  22132. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22133. * KIND, either express or implied. See the License for the
  22134. * specific language governing permissions and limitations
  22135. * under the License.
  22136. */
  22137. /**
  22138. * @module echarts/stream/Scheduler
  22139. */
  22140. /**
  22141. * @constructor
  22142. */
  22143. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22144. this.ecInstance = ecInstance;
  22145. this.api = api;
  22146. this.unfinished;
  22147. // Fix current processors in case that in some rear cases that
  22148. // processors might be registered after echarts instance created.
  22149. // Register processors incrementally for a echarts instance is
  22150. // not supported by this stream architecture.
  22151. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22152. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22153. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22154. /**
  22155. * @private
  22156. * @type {
  22157. * [handlerUID: string]: {
  22158. * seriesTaskMap?: {
  22159. * [seriesUID: string]: Task
  22160. * },
  22161. * overallTask?: Task
  22162. * }
  22163. * }
  22164. */
  22165. this._stageTaskMap = createHashMap();
  22166. }
  22167. var proto = Scheduler.prototype;
  22168. /**
  22169. * @param {module:echarts/model/Global} ecModel
  22170. * @param {Object} payload
  22171. */
  22172. proto.restoreData = function (ecModel, payload) {
  22173. // TODO: Only restroe needed series and components, but not all components.
  22174. // Currently `restoreData` of all of the series and component will be called.
  22175. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22176. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22177. // and some components like coordinate system, axes, dataZoom, visualMap only
  22178. // need their target series refresh.
  22179. // (1) If we are implementing this feature some day, we should consider these cases:
  22180. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22181. // on the settings of `dataZoom`), it should be re-performed if the component
  22182. // is modified by `setOption`.
  22183. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22184. // it should be re-performed when the result array of `getTargetSeries` changed.
  22185. // We use `dependencies` to cover these issues.
  22186. // (3) How to update target series when coordinate system related components modified.
  22187. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22188. // and this case all of the tasks will be set as dirty.
  22189. ecModel.restoreData(payload);
  22190. // Theoretically an overall task not only depends on each of its target series, but also
  22191. // depends on all of the series.
  22192. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22193. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22194. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22195. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22196. // probably cause state chaos (consider `dataZoomProcessor`).
  22197. this._stageTaskMap.each(function (taskRecord) {
  22198. var overallTask = taskRecord.overallTask;
  22199. overallTask && overallTask.dirty();
  22200. });
  22201. };
  22202. // If seriesModel provided, incremental threshold is check by series data.
  22203. proto.getPerformArgs = function (task, isBlock) {
  22204. // For overall task
  22205. if (!task.__pipeline) {
  22206. return;
  22207. }
  22208. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22209. var pCtx = pipeline.context;
  22210. var incremental = !isBlock
  22211. && pipeline.progressiveEnabled
  22212. && (!pCtx || pCtx.progressiveRender)
  22213. && task.__idxInPipeline > pipeline.blockIndex;
  22214. var step = incremental ? pipeline.step : null;
  22215. var modDataCount = pCtx && pCtx.modDataCount;
  22216. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22217. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22218. };
  22219. proto.getPipeline = function (pipelineId) {
  22220. return this._pipelineMap.get(pipelineId);
  22221. };
  22222. /**
  22223. * Current, progressive rendering starts from visual and layout.
  22224. * Always detect render mode in the same stage, avoiding that incorrect
  22225. * detection caused by data filtering.
  22226. * Caution:
  22227. * `updateStreamModes` use `seriesModel.getData()`.
  22228. */
  22229. proto.updateStreamModes = function (seriesModel, view) {
  22230. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22231. var data = seriesModel.getData();
  22232. var dataLen = data.count();
  22233. // `progressiveRender` means that can render progressively in each
  22234. // animation frame. Note that some types of series do not provide
  22235. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22236. // use the term `incremental` but not `progressive` to describe the
  22237. // case that `chart.appendData`.
  22238. var progressiveRender = pipeline.progressiveEnabled
  22239. && view.incrementalPrepareRender
  22240. && dataLen >= pipeline.threshold;
  22241. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22242. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22243. // see `test/candlestick-large3.html`
  22244. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22245. seriesModel.pipelineContext = pipeline.context = {
  22246. progressiveRender: progressiveRender,
  22247. modDataCount: modDataCount,
  22248. large: large
  22249. };
  22250. };
  22251. proto.restorePipelines = function (ecModel) {
  22252. var scheduler = this;
  22253. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22254. ecModel.eachSeries(function (seriesModel) {
  22255. var progressive = seriesModel.getProgressive();
  22256. var pipelineId = seriesModel.uid;
  22257. pipelineMap.set(pipelineId, {
  22258. id: pipelineId,
  22259. head: null,
  22260. tail: null,
  22261. threshold: seriesModel.getProgressiveThreshold(),
  22262. progressiveEnabled: progressive
  22263. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22264. blockIndex: -1,
  22265. step: Math.round(progressive || 700),
  22266. count: 0
  22267. });
  22268. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22269. });
  22270. };
  22271. proto.prepareStageTasks = function () {
  22272. var stageTaskMap = this._stageTaskMap;
  22273. var ecModel = this.ecInstance.getModel();
  22274. var api = this.api;
  22275. each$1(this._allHandlers, function (handler) {
  22276. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22277. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22278. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22279. }, this);
  22280. };
  22281. proto.prepareView = function (view, model, ecModel, api) {
  22282. var renderTask = view.renderTask;
  22283. var context = renderTask.context;
  22284. context.model = model;
  22285. context.ecModel = ecModel;
  22286. context.api = api;
  22287. renderTask.__block = !view.incrementalPrepareRender;
  22288. pipe(this, model, renderTask);
  22289. };
  22290. proto.performDataProcessorTasks = function (ecModel, payload) {
  22291. // If we do not use `block` here, it should be considered when to update modes.
  22292. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22293. };
  22294. // opt
  22295. // opt.visualType: 'visual' or 'layout'
  22296. // opt.setDirty
  22297. proto.performVisualTasks = function (ecModel, payload, opt) {
  22298. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22299. };
  22300. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22301. opt = opt || {};
  22302. var unfinished;
  22303. each$1(stageHandlers, function (stageHandler, idx) {
  22304. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22305. return;
  22306. }
  22307. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22308. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22309. var overallTask = stageHandlerRecord.overallTask;
  22310. if (overallTask) {
  22311. var overallNeedDirty;
  22312. var agentStubMap = overallTask.agentStubMap;
  22313. agentStubMap.each(function (stub) {
  22314. if (needSetDirty(opt, stub)) {
  22315. stub.dirty();
  22316. overallNeedDirty = true;
  22317. }
  22318. });
  22319. overallNeedDirty && overallTask.dirty();
  22320. updatePayload(overallTask, payload);
  22321. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22322. // Execute stubs firstly, which may set the overall task dirty,
  22323. // then execute the overall task. And stub will call seriesModel.setData,
  22324. // which ensures that in the overallTask seriesModel.getData() will not
  22325. // return incorrect data.
  22326. agentStubMap.each(function (stub) {
  22327. stub.perform(performArgs);
  22328. });
  22329. unfinished |= overallTask.perform(performArgs);
  22330. }
  22331. else if (seriesTaskMap) {
  22332. seriesTaskMap.each(function (task, pipelineId) {
  22333. if (needSetDirty(opt, task)) {
  22334. task.dirty();
  22335. }
  22336. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22337. performArgs.skip = !stageHandler.performRawSeries
  22338. && ecModel.isSeriesFiltered(task.context.model);
  22339. updatePayload(task, payload);
  22340. unfinished |= task.perform(performArgs);
  22341. });
  22342. }
  22343. });
  22344. function needSetDirty(opt, task) {
  22345. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22346. }
  22347. scheduler.unfinished |= unfinished;
  22348. }
  22349. proto.performSeriesTasks = function (ecModel) {
  22350. var unfinished;
  22351. ecModel.eachSeries(function (seriesModel) {
  22352. // Progress to the end for dataInit and dataRestore.
  22353. unfinished |= seriesModel.dataTask.perform();
  22354. });
  22355. this.unfinished |= unfinished;
  22356. };
  22357. proto.plan = function () {
  22358. // Travel pipelines, check block.
  22359. this._pipelineMap.each(function (pipeline) {
  22360. var task = pipeline.tail;
  22361. do {
  22362. if (task.__block) {
  22363. pipeline.blockIndex = task.__idxInPipeline;
  22364. break;
  22365. }
  22366. task = task.getUpstream();
  22367. }
  22368. while (task);
  22369. });
  22370. };
  22371. var updatePayload = proto.updatePayload = function (task, payload) {
  22372. payload !== 'remain' && (task.context.payload = payload);
  22373. };
  22374. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22375. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22376. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22377. var seriesType = stageHandler.seriesType;
  22378. var getTargetSeries = stageHandler.getTargetSeries;
  22379. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22380. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22381. // it works but it may cause other irrelevant charts blocked.
  22382. if (stageHandler.createOnAllSeries) {
  22383. ecModel.eachRawSeries(create);
  22384. }
  22385. else if (seriesType) {
  22386. ecModel.eachRawSeriesByType(seriesType, create);
  22387. }
  22388. else if (getTargetSeries) {
  22389. getTargetSeries(ecModel, api).each(create);
  22390. }
  22391. function create(seriesModel) {
  22392. var pipelineId = seriesModel.uid;
  22393. // Init tasks for each seriesModel only once.
  22394. // Reuse original task instance.
  22395. var task = seriesTaskMap.get(pipelineId)
  22396. || seriesTaskMap.set(pipelineId, createTask({
  22397. plan: seriesTaskPlan,
  22398. reset: seriesTaskReset,
  22399. count: seriesTaskCount
  22400. }));
  22401. task.context = {
  22402. model: seriesModel,
  22403. ecModel: ecModel,
  22404. api: api,
  22405. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22406. plan: stageHandler.plan,
  22407. reset: stageHandler.reset,
  22408. scheduler: scheduler
  22409. };
  22410. pipe(scheduler, seriesModel, task);
  22411. }
  22412. // Clear unused series tasks.
  22413. var pipelineMap = scheduler._pipelineMap;
  22414. seriesTaskMap.each(function (task, pipelineId) {
  22415. if (!pipelineMap.get(pipelineId)) {
  22416. task.dispose();
  22417. seriesTaskMap.removeKey(pipelineId);
  22418. }
  22419. });
  22420. }
  22421. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22422. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22423. // For overall task, the function only be called on reset stage.
  22424. || createTask({reset: overallTaskReset});
  22425. overallTask.context = {
  22426. ecModel: ecModel,
  22427. api: api,
  22428. overallReset: stageHandler.overallReset,
  22429. scheduler: scheduler
  22430. };
  22431. // Reuse orignal stubs.
  22432. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22433. var seriesType = stageHandler.seriesType;
  22434. var getTargetSeries = stageHandler.getTargetSeries;
  22435. var overallProgress = true;
  22436. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22437. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22438. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22439. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22440. // we set the pipeline block.
  22441. if (seriesType) {
  22442. ecModel.eachRawSeriesByType(seriesType, createStub);
  22443. }
  22444. else if (getTargetSeries) {
  22445. getTargetSeries(ecModel, api).each(createStub);
  22446. }
  22447. // Otherwise, (usually it is legancy case), the overall task will only be
  22448. // executed when upstream dirty. Otherwise the progressive rendering of all
  22449. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22450. // dirty info from upsteam.
  22451. else {
  22452. overallProgress = false;
  22453. each$1(ecModel.getSeries(), createStub);
  22454. }
  22455. function createStub(seriesModel) {
  22456. var pipelineId = seriesModel.uid;
  22457. var stub = agentStubMap.get(pipelineId);
  22458. if (!stub) {
  22459. stub = agentStubMap.set(pipelineId, createTask(
  22460. {reset: stubReset, onDirty: stubOnDirty}
  22461. ));
  22462. // When the result of `getTargetSeries` changed, the overallTask
  22463. // should be set as dirty and re-performed.
  22464. overallTask.dirty();
  22465. }
  22466. stub.context = {
  22467. model: seriesModel,
  22468. overallProgress: overallProgress,
  22469. modifyOutputEnd: modifyOutputEnd
  22470. };
  22471. stub.agent = overallTask;
  22472. stub.__block = overallProgress;
  22473. pipe(scheduler, seriesModel, stub);
  22474. }
  22475. // Clear unused stubs.
  22476. var pipelineMap = scheduler._pipelineMap;
  22477. agentStubMap.each(function (stub, pipelineId) {
  22478. if (!pipelineMap.get(pipelineId)) {
  22479. stub.dispose();
  22480. // When the result of `getTargetSeries` changed, the overallTask
  22481. // should be set as dirty and re-performed.
  22482. overallTask.dirty();
  22483. agentStubMap.removeKey(pipelineId);
  22484. }
  22485. });
  22486. }
  22487. function overallTaskReset(context) {
  22488. context.overallReset(
  22489. context.ecModel, context.api, context.payload
  22490. );
  22491. }
  22492. function stubReset(context, upstreamContext) {
  22493. return context.overallProgress && stubProgress;
  22494. }
  22495. function stubProgress() {
  22496. this.agent.dirty();
  22497. this.getDownstream().dirty();
  22498. }
  22499. function stubOnDirty() {
  22500. this.agent && this.agent.dirty();
  22501. }
  22502. function seriesTaskPlan(context) {
  22503. return context.plan && context.plan(
  22504. context.model, context.ecModel, context.api, context.payload
  22505. );
  22506. }
  22507. function seriesTaskReset(context) {
  22508. if (context.useClearVisual) {
  22509. context.data.clearAllVisual();
  22510. }
  22511. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22512. context.model, context.ecModel, context.api, context.payload
  22513. ));
  22514. return resetDefines.length > 1
  22515. ? map(resetDefines, function (v, idx) {
  22516. return makeSeriesTaskProgress(idx);
  22517. })
  22518. : singleSeriesTaskProgress;
  22519. }
  22520. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22521. function makeSeriesTaskProgress(resetDefineIdx) {
  22522. return function (params, context) {
  22523. var data = context.data;
  22524. var resetDefine = context.resetDefines[resetDefineIdx];
  22525. if (resetDefine && resetDefine.dataEach) {
  22526. for (var i = params.start; i < params.end; i++) {
  22527. resetDefine.dataEach(data, i);
  22528. }
  22529. }
  22530. else if (resetDefine && resetDefine.progress) {
  22531. resetDefine.progress(params, data);
  22532. }
  22533. };
  22534. }
  22535. function seriesTaskCount(context) {
  22536. return context.data.count();
  22537. }
  22538. function pipe(scheduler, seriesModel, task) {
  22539. var pipelineId = seriesModel.uid;
  22540. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22541. !pipeline.head && (pipeline.head = task);
  22542. pipeline.tail && pipeline.tail.pipe(task);
  22543. pipeline.tail = task;
  22544. task.__idxInPipeline = pipeline.count++;
  22545. task.__pipeline = pipeline;
  22546. }
  22547. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22548. if (isFunction$1(stageHandler)) {
  22549. stageHandler = {
  22550. overallReset: stageHandler,
  22551. seriesType: detectSeriseType(stageHandler)
  22552. };
  22553. }
  22554. stageHandler.uid = getUID('stageHandler');
  22555. visualType && (stageHandler.visualType = visualType);
  22556. return stageHandler;
  22557. };
  22558. /**
  22559. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22560. * To ensure that they can work normally, they should work in block mode, that is,
  22561. * they should not be started util the previous tasks finished. So they cause the
  22562. * progressive rendering disabled. We try to detect the series type, to narrow down
  22563. * the block range to only the series type they concern, but not all series.
  22564. */
  22565. function detectSeriseType(legacyFunc) {
  22566. seriesType = null;
  22567. try {
  22568. // Assume there is no async when calling `eachSeriesByType`.
  22569. legacyFunc(ecModelMock, apiMock);
  22570. }
  22571. catch (e) {
  22572. }
  22573. return seriesType;
  22574. }
  22575. var ecModelMock = {};
  22576. var apiMock = {};
  22577. var seriesType;
  22578. mockMethods(ecModelMock, GlobalModel);
  22579. mockMethods(apiMock, ExtensionAPI);
  22580. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22581. seriesType = type;
  22582. };
  22583. ecModelMock.eachComponent = function (cond) {
  22584. if (cond.mainType === 'series' && cond.subType) {
  22585. seriesType = cond.subType;
  22586. }
  22587. };
  22588. function mockMethods(target, Clz) {
  22589. /* eslint-disable */
  22590. for (var name in Clz.prototype) {
  22591. // Do not use hasOwnProperty
  22592. target[name] = noop;
  22593. }
  22594. /* eslint-enable */
  22595. }
  22596. /*
  22597. * Licensed to the Apache Software Foundation (ASF) under one
  22598. * or more contributor license agreements. See the NOTICE file
  22599. * distributed with this work for additional information
  22600. * regarding copyright ownership. The ASF licenses this file
  22601. * to you under the Apache License, Version 2.0 (the
  22602. * "License"); you may not use this file except in compliance
  22603. * with the License. You may obtain a copy of the License at
  22604. *
  22605. * http://www.apache.org/licenses/LICENSE-2.0
  22606. *
  22607. * Unless required by applicable law or agreed to in writing,
  22608. * software distributed under the License is distributed on an
  22609. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22610. * KIND, either express or implied. See the License for the
  22611. * specific language governing permissions and limitations
  22612. * under the License.
  22613. */
  22614. var colorAll = [
  22615. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22616. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22617. ];
  22618. var lightTheme = {
  22619. color: colorAll,
  22620. colorLayer: [
  22621. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22622. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22623. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22624. colorAll
  22625. ]
  22626. };
  22627. /*
  22628. * Licensed to the Apache Software Foundation (ASF) under one
  22629. * or more contributor license agreements. See the NOTICE file
  22630. * distributed with this work for additional information
  22631. * regarding copyright ownership. The ASF licenses this file
  22632. * to you under the Apache License, Version 2.0 (the
  22633. * "License"); you may not use this file except in compliance
  22634. * with the License. You may obtain a copy of the License at
  22635. *
  22636. * http://www.apache.org/licenses/LICENSE-2.0
  22637. *
  22638. * Unless required by applicable law or agreed to in writing,
  22639. * software distributed under the License is distributed on an
  22640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22641. * KIND, either express or implied. See the License for the
  22642. * specific language governing permissions and limitations
  22643. * under the License.
  22644. */
  22645. var contrastColor = '#eee';
  22646. var axisCommon = function () {
  22647. return {
  22648. axisLine: {
  22649. lineStyle: {
  22650. color: contrastColor
  22651. }
  22652. },
  22653. axisTick: {
  22654. lineStyle: {
  22655. color: contrastColor
  22656. }
  22657. },
  22658. axisLabel: {
  22659. textStyle: {
  22660. color: contrastColor
  22661. }
  22662. },
  22663. splitLine: {
  22664. lineStyle: {
  22665. type: 'dashed',
  22666. color: '#aaa'
  22667. }
  22668. },
  22669. splitArea: {
  22670. areaStyle: {
  22671. color: contrastColor
  22672. }
  22673. }
  22674. };
  22675. };
  22676. var colorPalette = [
  22677. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22678. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22679. ];
  22680. var theme = {
  22681. color: colorPalette,
  22682. backgroundColor: '#333',
  22683. tooltip: {
  22684. axisPointer: {
  22685. lineStyle: {
  22686. color: contrastColor
  22687. },
  22688. crossStyle: {
  22689. color: contrastColor
  22690. },
  22691. label: {
  22692. color: '#000'
  22693. }
  22694. }
  22695. },
  22696. legend: {
  22697. textStyle: {
  22698. color: contrastColor
  22699. }
  22700. },
  22701. textStyle: {
  22702. color: contrastColor
  22703. },
  22704. title: {
  22705. textStyle: {
  22706. color: contrastColor
  22707. }
  22708. },
  22709. toolbox: {
  22710. iconStyle: {
  22711. normal: {
  22712. borderColor: contrastColor
  22713. }
  22714. }
  22715. },
  22716. dataZoom: {
  22717. textStyle: {
  22718. color: contrastColor
  22719. }
  22720. },
  22721. visualMap: {
  22722. textStyle: {
  22723. color: contrastColor
  22724. }
  22725. },
  22726. timeline: {
  22727. lineStyle: {
  22728. color: contrastColor
  22729. },
  22730. itemStyle: {
  22731. normal: {
  22732. color: colorPalette[1]
  22733. }
  22734. },
  22735. label: {
  22736. normal: {
  22737. textStyle: {
  22738. color: contrastColor
  22739. }
  22740. }
  22741. },
  22742. controlStyle: {
  22743. normal: {
  22744. color: contrastColor,
  22745. borderColor: contrastColor
  22746. }
  22747. }
  22748. },
  22749. timeAxis: axisCommon(),
  22750. logAxis: axisCommon(),
  22751. valueAxis: axisCommon(),
  22752. categoryAxis: axisCommon(),
  22753. line: {
  22754. symbol: 'circle'
  22755. },
  22756. graph: {
  22757. color: colorPalette
  22758. },
  22759. gauge: {
  22760. title: {
  22761. textStyle: {
  22762. color: contrastColor
  22763. }
  22764. }
  22765. },
  22766. candlestick: {
  22767. itemStyle: {
  22768. normal: {
  22769. color: '#FD1050',
  22770. color0: '#0CF49B',
  22771. borderColor: '#FD1050',
  22772. borderColor0: '#0CF49B'
  22773. }
  22774. }
  22775. }
  22776. };
  22777. theme.categoryAxis.splitLine.show = false;
  22778. /*
  22779. * Licensed to the Apache Software Foundation (ASF) under one
  22780. * or more contributor license agreements. See the NOTICE file
  22781. * distributed with this work for additional information
  22782. * regarding copyright ownership. The ASF licenses this file
  22783. * to you under the Apache License, Version 2.0 (the
  22784. * "License"); you may not use this file except in compliance
  22785. * with the License. You may obtain a copy of the License at
  22786. *
  22787. * http://www.apache.org/licenses/LICENSE-2.0
  22788. *
  22789. * Unless required by applicable law or agreed to in writing,
  22790. * software distributed under the License is distributed on an
  22791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22792. * KIND, either express or implied. See the License for the
  22793. * specific language governing permissions and limitations
  22794. * under the License.
  22795. */
  22796. /**
  22797. * This module is imported by echarts directly.
  22798. *
  22799. * Notice:
  22800. * Always keep this file exists for backward compatibility.
  22801. * Because before 4.1.0, dataset is an optional component,
  22802. * some users may import this module manually.
  22803. */
  22804. ComponentModel.extend({
  22805. type: 'dataset',
  22806. /**
  22807. * @protected
  22808. */
  22809. defaultOption: {
  22810. // 'row', 'column'
  22811. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22812. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22813. sourceHeader: null,
  22814. dimensions: null,
  22815. source: null
  22816. },
  22817. optionUpdated: function () {
  22818. detectSourceFormat(this);
  22819. }
  22820. });
  22821. Component.extend({
  22822. type: 'dataset'
  22823. });
  22824. /**
  22825. * 椭圆形状
  22826. * @module zrender/graphic/shape/Ellipse
  22827. */
  22828. var Ellipse = Path.extend({
  22829. type: 'ellipse',
  22830. shape: {
  22831. cx: 0, cy: 0,
  22832. rx: 0, ry: 0
  22833. },
  22834. buildPath: function (ctx, shape) {
  22835. var k = 0.5522848;
  22836. var x = shape.cx;
  22837. var y = shape.cy;
  22838. var a = shape.rx;
  22839. var b = shape.ry;
  22840. var ox = a * k; // 水平控制点偏移量
  22841. var oy = b * k; // 垂直控制点偏移量
  22842. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22843. ctx.moveTo(x - a, y);
  22844. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22845. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22846. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22847. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22848. ctx.closePath();
  22849. }
  22850. });
  22851. // import RadialGradient from '../graphic/RadialGradient';
  22852. // import Pattern from '../graphic/Pattern';
  22853. // import * as vector from '../core/vector';
  22854. // Most of the values can be separated by comma and/or white space.
  22855. var DILIMITER_REG = /[\s,]+/;
  22856. /**
  22857. * For big svg string, this method might be time consuming.
  22858. *
  22859. * @param {string} svg xml string
  22860. * @return {Object} xml root.
  22861. */
  22862. function parseXML(svg) {
  22863. if (isString(svg)) {
  22864. var parser = new DOMParser();
  22865. svg = parser.parseFromString(svg, 'text/xml');
  22866. }
  22867. // Document node. If using $.get, doc node may be input.
  22868. if (svg.nodeType === 9) {
  22869. svg = svg.firstChild;
  22870. }
  22871. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22872. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22873. svg = svg.nextSibling;
  22874. }
  22875. return svg;
  22876. }
  22877. function SVGParser() {
  22878. this._defs = {};
  22879. this._root = null;
  22880. this._isDefine = false;
  22881. this._isText = false;
  22882. }
  22883. SVGParser.prototype.parse = function (xml, opt) {
  22884. opt = opt || {};
  22885. var svg = parseXML(xml);
  22886. if (!svg) {
  22887. throw new Error('Illegal svg');
  22888. }
  22889. var root = new Group();
  22890. this._root = root;
  22891. // parse view port
  22892. var viewBox = svg.getAttribute('viewBox') || '';
  22893. // If width/height not specified, means "100%" of `opt.width/height`.
  22894. // TODO: Other percent value not supported yet.
  22895. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22896. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22897. // If width/height not specified, set as null for output.
  22898. isNaN(width) && (width = null);
  22899. isNaN(height) && (height = null);
  22900. // Apply inline style on svg element.
  22901. parseAttributes(svg, root, null, true);
  22902. var child = svg.firstChild;
  22903. while (child) {
  22904. this._parseNode(child, root);
  22905. child = child.nextSibling;
  22906. }
  22907. var viewBoxRect;
  22908. var viewBoxTransform;
  22909. if (viewBox) {
  22910. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22911. // Some invalid case like viewBox: 'none'.
  22912. if (viewBoxArr.length >= 4) {
  22913. viewBoxRect = {
  22914. x: parseFloat(viewBoxArr[0] || 0),
  22915. y: parseFloat(viewBoxArr[1] || 0),
  22916. width: parseFloat(viewBoxArr[2]),
  22917. height: parseFloat(viewBoxArr[3])
  22918. };
  22919. }
  22920. }
  22921. if (viewBoxRect && width != null && height != null) {
  22922. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22923. if (!opt.ignoreViewBox) {
  22924. // If set transform on the output group, it probably bring trouble when
  22925. // some users only intend to show the clipped content inside the viewBox,
  22926. // but not intend to transform the output group. So we keep the output
  22927. // group no transform. If the user intend to use the viewBox as a
  22928. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22929. // manually according to the viewBox info in the output of this method.
  22930. var elRoot = root;
  22931. root = new Group();
  22932. root.add(elRoot);
  22933. elRoot.scale = viewBoxTransform.scale.slice();
  22934. elRoot.position = viewBoxTransform.position.slice();
  22935. }
  22936. }
  22937. // Some shapes might be overflow the viewport, which should be
  22938. // clipped despite whether the viewBox is used, as the SVG does.
  22939. if (!opt.ignoreRootClip && width != null && height != null) {
  22940. root.setClipPath(new Rect({
  22941. shape: {x: 0, y: 0, width: width, height: height}
  22942. }));
  22943. }
  22944. // Set width/height on group just for output the viewport size.
  22945. return {
  22946. root: root,
  22947. width: width,
  22948. height: height,
  22949. viewBoxRect: viewBoxRect,
  22950. viewBoxTransform: viewBoxTransform
  22951. };
  22952. };
  22953. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22954. var nodeName = xmlNode.nodeName.toLowerCase();
  22955. // TODO
  22956. // support <style>...</style> in svg, where nodeName is 'style',
  22957. // CSS classes is defined globally wherever the style tags are declared.
  22958. if (nodeName === 'defs') {
  22959. // define flag
  22960. this._isDefine = true;
  22961. }
  22962. else if (nodeName === 'text') {
  22963. this._isText = true;
  22964. }
  22965. var el;
  22966. if (this._isDefine) {
  22967. var parser = defineParsers[nodeName];
  22968. if (parser) {
  22969. var def = parser.call(this, xmlNode);
  22970. var id = xmlNode.getAttribute('id');
  22971. if (id) {
  22972. this._defs[id] = def;
  22973. }
  22974. }
  22975. }
  22976. else {
  22977. var parser = nodeParsers[nodeName];
  22978. if (parser) {
  22979. el = parser.call(this, xmlNode, parentGroup);
  22980. parentGroup.add(el);
  22981. }
  22982. }
  22983. var child = xmlNode.firstChild;
  22984. while (child) {
  22985. if (child.nodeType === 1) {
  22986. this._parseNode(child, el);
  22987. }
  22988. // Is text
  22989. if (child.nodeType === 3 && this._isText) {
  22990. this._parseText(child, el);
  22991. }
  22992. child = child.nextSibling;
  22993. }
  22994. // Quit define
  22995. if (nodeName === 'defs') {
  22996. this._isDefine = false;
  22997. }
  22998. else if (nodeName === 'text') {
  22999. this._isText = false;
  23000. }
  23001. };
  23002. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23003. if (xmlNode.nodeType === 1) {
  23004. var dx = xmlNode.getAttribute('dx') || 0;
  23005. var dy = xmlNode.getAttribute('dy') || 0;
  23006. this._textX += parseFloat(dx);
  23007. this._textY += parseFloat(dy);
  23008. }
  23009. var text = new Text({
  23010. style: {
  23011. text: xmlNode.textContent,
  23012. transformText: true
  23013. },
  23014. position: [this._textX || 0, this._textY || 0]
  23015. });
  23016. inheritStyle(parentGroup, text);
  23017. parseAttributes(xmlNode, text, this._defs);
  23018. var fontSize = text.style.fontSize;
  23019. if (fontSize && fontSize < 9) {
  23020. // PENDING
  23021. text.style.fontSize = 9;
  23022. text.scale = text.scale || [1, 1];
  23023. text.scale[0] *= fontSize / 9;
  23024. text.scale[1] *= fontSize / 9;
  23025. }
  23026. var rect = text.getBoundingRect();
  23027. this._textX += rect.width;
  23028. parentGroup.add(text);
  23029. return text;
  23030. };
  23031. var nodeParsers = {
  23032. 'g': function (xmlNode, parentGroup) {
  23033. var g = new Group();
  23034. inheritStyle(parentGroup, g);
  23035. parseAttributes(xmlNode, g, this._defs);
  23036. return g;
  23037. },
  23038. 'rect': function (xmlNode, parentGroup) {
  23039. var rect = new Rect();
  23040. inheritStyle(parentGroup, rect);
  23041. parseAttributes(xmlNode, rect, this._defs);
  23042. rect.setShape({
  23043. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23044. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23045. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23046. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23047. });
  23048. // console.log(xmlNode.getAttribute('transform'));
  23049. // console.log(rect.transform);
  23050. return rect;
  23051. },
  23052. 'circle': function (xmlNode, parentGroup) {
  23053. var circle = new Circle();
  23054. inheritStyle(parentGroup, circle);
  23055. parseAttributes(xmlNode, circle, this._defs);
  23056. circle.setShape({
  23057. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23058. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23059. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23060. });
  23061. return circle;
  23062. },
  23063. 'line': function (xmlNode, parentGroup) {
  23064. var line = new Line();
  23065. inheritStyle(parentGroup, line);
  23066. parseAttributes(xmlNode, line, this._defs);
  23067. line.setShape({
  23068. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23069. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23070. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23071. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23072. });
  23073. return line;
  23074. },
  23075. 'ellipse': function (xmlNode, parentGroup) {
  23076. var ellipse = new Ellipse();
  23077. inheritStyle(parentGroup, ellipse);
  23078. parseAttributes(xmlNode, ellipse, this._defs);
  23079. ellipse.setShape({
  23080. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23081. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23082. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23083. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23084. });
  23085. return ellipse;
  23086. },
  23087. 'polygon': function (xmlNode, parentGroup) {
  23088. var points = xmlNode.getAttribute('points');
  23089. if (points) {
  23090. points = parsePoints(points);
  23091. }
  23092. var polygon = new Polygon({
  23093. shape: {
  23094. points: points || []
  23095. }
  23096. });
  23097. inheritStyle(parentGroup, polygon);
  23098. parseAttributes(xmlNode, polygon, this._defs);
  23099. return polygon;
  23100. },
  23101. 'polyline': function (xmlNode, parentGroup) {
  23102. var path = new Path();
  23103. inheritStyle(parentGroup, path);
  23104. parseAttributes(xmlNode, path, this._defs);
  23105. var points = xmlNode.getAttribute('points');
  23106. if (points) {
  23107. points = parsePoints(points);
  23108. }
  23109. var polyline = new Polyline({
  23110. shape: {
  23111. points: points || []
  23112. }
  23113. });
  23114. return polyline;
  23115. },
  23116. 'image': function (xmlNode, parentGroup) {
  23117. var img = new ZImage();
  23118. inheritStyle(parentGroup, img);
  23119. parseAttributes(xmlNode, img, this._defs);
  23120. img.setStyle({
  23121. image: xmlNode.getAttribute('xlink:href'),
  23122. x: xmlNode.getAttribute('x'),
  23123. y: xmlNode.getAttribute('y'),
  23124. width: xmlNode.getAttribute('width'),
  23125. height: xmlNode.getAttribute('height')
  23126. });
  23127. return img;
  23128. },
  23129. 'text': function (xmlNode, parentGroup) {
  23130. var x = xmlNode.getAttribute('x') || 0;
  23131. var y = xmlNode.getAttribute('y') || 0;
  23132. var dx = xmlNode.getAttribute('dx') || 0;
  23133. var dy = xmlNode.getAttribute('dy') || 0;
  23134. this._textX = parseFloat(x) + parseFloat(dx);
  23135. this._textY = parseFloat(y) + parseFloat(dy);
  23136. var g = new Group();
  23137. inheritStyle(parentGroup, g);
  23138. parseAttributes(xmlNode, g, this._defs);
  23139. return g;
  23140. },
  23141. 'tspan': function (xmlNode, parentGroup) {
  23142. var x = xmlNode.getAttribute('x');
  23143. var y = xmlNode.getAttribute('y');
  23144. if (x != null) {
  23145. // new offset x
  23146. this._textX = parseFloat(x);
  23147. }
  23148. if (y != null) {
  23149. // new offset y
  23150. this._textY = parseFloat(y);
  23151. }
  23152. var dx = xmlNode.getAttribute('dx') || 0;
  23153. var dy = xmlNode.getAttribute('dy') || 0;
  23154. var g = new Group();
  23155. inheritStyle(parentGroup, g);
  23156. parseAttributes(xmlNode, g, this._defs);
  23157. this._textX += dx;
  23158. this._textY += dy;
  23159. return g;
  23160. },
  23161. 'path': function (xmlNode, parentGroup) {
  23162. // TODO svg fill rule
  23163. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23164. // path.style.globalCompositeOperation = 'xor';
  23165. var d = xmlNode.getAttribute('d') || '';
  23166. // Performance sensitive.
  23167. var path = createFromString(d);
  23168. inheritStyle(parentGroup, path);
  23169. parseAttributes(xmlNode, path, this._defs);
  23170. return path;
  23171. }
  23172. };
  23173. var defineParsers = {
  23174. 'lineargradient': function (xmlNode) {
  23175. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23176. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23177. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23178. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23179. var gradient = new LinearGradient(x1, y1, x2, y2);
  23180. _parseGradientColorStops(xmlNode, gradient);
  23181. return gradient;
  23182. },
  23183. 'radialgradient': function (xmlNode) {
  23184. }
  23185. };
  23186. function _parseGradientColorStops(xmlNode, gradient) {
  23187. var stop = xmlNode.firstChild;
  23188. while (stop) {
  23189. if (stop.nodeType === 1) {
  23190. var offset = stop.getAttribute('offset');
  23191. if (offset.indexOf('%') > 0) { // percentage
  23192. offset = parseInt(offset, 10) / 100;
  23193. }
  23194. else if (offset) { // number from 0 to 1
  23195. offset = parseFloat(offset);
  23196. }
  23197. else {
  23198. offset = 0;
  23199. }
  23200. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23201. gradient.addColorStop(offset, stopColor);
  23202. }
  23203. stop = stop.nextSibling;
  23204. }
  23205. }
  23206. function inheritStyle(parent, child) {
  23207. if (parent && parent.__inheritedStyle) {
  23208. if (!child.__inheritedStyle) {
  23209. child.__inheritedStyle = {};
  23210. }
  23211. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23212. }
  23213. }
  23214. function parsePoints(pointsString) {
  23215. var list = trim(pointsString).split(DILIMITER_REG);
  23216. var points = [];
  23217. for (var i = 0; i < list.length; i += 2) {
  23218. var x = parseFloat(list[i]);
  23219. var y = parseFloat(list[i + 1]);
  23220. points.push([x, y]);
  23221. }
  23222. return points;
  23223. }
  23224. var attributesMap = {
  23225. 'fill': 'fill',
  23226. 'stroke': 'stroke',
  23227. 'stroke-width': 'lineWidth',
  23228. 'opacity': 'opacity',
  23229. 'fill-opacity': 'fillOpacity',
  23230. 'stroke-opacity': 'strokeOpacity',
  23231. 'stroke-dasharray': 'lineDash',
  23232. 'stroke-dashoffset': 'lineDashOffset',
  23233. 'stroke-linecap': 'lineCap',
  23234. 'stroke-linejoin': 'lineJoin',
  23235. 'stroke-miterlimit': 'miterLimit',
  23236. 'font-family': 'fontFamily',
  23237. 'font-size': 'fontSize',
  23238. 'font-style': 'fontStyle',
  23239. 'font-weight': 'fontWeight',
  23240. 'text-align': 'textAlign',
  23241. 'alignment-baseline': 'textBaseline'
  23242. };
  23243. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23244. var zrStyle = el.__inheritedStyle || {};
  23245. var isTextEl = el.type === 'text';
  23246. // TODO Shadow
  23247. if (xmlNode.nodeType === 1) {
  23248. parseTransformAttribute(xmlNode, el);
  23249. extend(zrStyle, parseStyleAttribute(xmlNode));
  23250. if (!onlyInlineStyle) {
  23251. for (var svgAttrName in attributesMap) {
  23252. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23253. var attrValue = xmlNode.getAttribute(svgAttrName);
  23254. if (attrValue != null) {
  23255. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23256. }
  23257. }
  23258. }
  23259. }
  23260. }
  23261. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23262. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23263. el.style = el.style || new Style();
  23264. var elStyle = el.style;
  23265. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23266. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23267. each$1([
  23268. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23269. ], function (propName) {
  23270. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23271. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23272. });
  23273. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23274. zrStyle.textBaseline = 'alphabetic';
  23275. }
  23276. if (zrStyle.textBaseline === 'alphabetic') {
  23277. zrStyle.textBaseline = 'bottom';
  23278. }
  23279. if (zrStyle.textAlign === 'start') {
  23280. zrStyle.textAlign = 'left';
  23281. }
  23282. if (zrStyle.textAlign === 'end') {
  23283. zrStyle.textAlign = 'right';
  23284. }
  23285. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23286. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23287. ], function (propName) {
  23288. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23289. });
  23290. if (zrStyle.lineDash) {
  23291. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23292. }
  23293. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23294. // enable stroke
  23295. el[elStrokeProp] = true;
  23296. }
  23297. el.__inheritedStyle = zrStyle;
  23298. }
  23299. var urlRegex = /url\(\s*#(.*?)\)/;
  23300. function getPaint(str, defs) {
  23301. // if (str === 'none') {
  23302. // return;
  23303. // }
  23304. var urlMatch = defs && str && str.match(urlRegex);
  23305. if (urlMatch) {
  23306. var url = trim(urlMatch[1]);
  23307. var def = defs[url];
  23308. return def;
  23309. }
  23310. return str;
  23311. }
  23312. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23313. function parseTransformAttribute(xmlNode, node) {
  23314. var transform = xmlNode.getAttribute('transform');
  23315. if (transform) {
  23316. transform = transform.replace(/,/g, ' ');
  23317. var m = null;
  23318. var transformOps = [];
  23319. transform.replace(transformRegex, function (str, type, value) {
  23320. transformOps.push(type, value);
  23321. });
  23322. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23323. var value = transformOps[i];
  23324. var type = transformOps[i - 1];
  23325. m = m || create$1();
  23326. switch (type) {
  23327. case 'translate':
  23328. value = trim(value).split(DILIMITER_REG);
  23329. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23330. break;
  23331. case 'scale':
  23332. value = trim(value).split(DILIMITER_REG);
  23333. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23334. break;
  23335. case 'rotate':
  23336. value = trim(value).split(DILIMITER_REG);
  23337. rotate(m, m, parseFloat(value[0]));
  23338. break;
  23339. case 'skew':
  23340. value = trim(value).split(DILIMITER_REG);
  23341. console.warn('Skew transform is not supported yet');
  23342. break;
  23343. case 'matrix':
  23344. var value = trim(value).split(DILIMITER_REG);
  23345. m[0] = parseFloat(value[0]);
  23346. m[1] = parseFloat(value[1]);
  23347. m[2] = parseFloat(value[2]);
  23348. m[3] = parseFloat(value[3]);
  23349. m[4] = parseFloat(value[4]);
  23350. m[5] = parseFloat(value[5]);
  23351. break;
  23352. }
  23353. }
  23354. node.setLocalTransform(m);
  23355. }
  23356. }
  23357. // Value may contain space.
  23358. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23359. function parseStyleAttribute(xmlNode) {
  23360. var style = xmlNode.getAttribute('style');
  23361. var result = {};
  23362. if (!style) {
  23363. return result;
  23364. }
  23365. var styleList = {};
  23366. styleRegex.lastIndex = 0;
  23367. var styleRegResult;
  23368. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23369. styleList[styleRegResult[1]] = styleRegResult[2];
  23370. }
  23371. for (var svgAttrName in attributesMap) {
  23372. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23373. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23374. }
  23375. }
  23376. return result;
  23377. }
  23378. /**
  23379. * @param {Array.<number>} viewBoxRect
  23380. * @param {number} width
  23381. * @param {number} height
  23382. * @return {Object} {scale, position}
  23383. */
  23384. function makeViewBoxTransform(viewBoxRect, width, height) {
  23385. var scaleX = width / viewBoxRect.width;
  23386. var scaleY = height / viewBoxRect.height;
  23387. var scale = Math.min(scaleX, scaleY);
  23388. // preserveAspectRatio 'xMidYMid'
  23389. var viewBoxScale = [scale, scale];
  23390. var viewBoxPosition = [
  23391. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23392. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23393. ];
  23394. return {
  23395. scale: viewBoxScale,
  23396. position: viewBoxPosition
  23397. };
  23398. }
  23399. /**
  23400. * @param {string|XMLElement} xml
  23401. * @param {Object} [opt]
  23402. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23403. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23404. * @param {boolean} [opt.ignoreViewBox]
  23405. * @param {boolean} [opt.ignoreRootClip]
  23406. * @return {Object} result:
  23407. * {
  23408. * root: Group, The root of the the result tree of zrender shapes,
  23409. * width: number, the viewport width of the SVG,
  23410. * height: number, the viewport height of the SVG,
  23411. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23412. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23413. * }
  23414. */
  23415. /*
  23416. * Licensed to the Apache Software Foundation (ASF) under one
  23417. * or more contributor license agreements. See the NOTICE file
  23418. * distributed with this work for additional information
  23419. * regarding copyright ownership. The ASF licenses this file
  23420. * to you under the Apache License, Version 2.0 (the
  23421. * "License"); you may not use this file except in compliance
  23422. * with the License. You may obtain a copy of the License at
  23423. *
  23424. * http://www.apache.org/licenses/LICENSE-2.0
  23425. *
  23426. * Unless required by applicable law or agreed to in writing,
  23427. * software distributed under the License is distributed on an
  23428. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23429. * KIND, either express or implied. See the License for the
  23430. * specific language governing permissions and limitations
  23431. * under the License.
  23432. */
  23433. var storage = createHashMap();
  23434. // For minimize the code size of common echarts package,
  23435. // do not put too much logic in this module.
  23436. var mapDataStorage = {
  23437. // The format of record: see `echarts.registerMap`.
  23438. // Compatible with previous `echarts.registerMap`.
  23439. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23440. var records;
  23441. if (isArray(rawGeoJson)) {
  23442. records = rawGeoJson;
  23443. }
  23444. else if (rawGeoJson.svg) {
  23445. records = [{
  23446. type: 'svg',
  23447. source: rawGeoJson.svg,
  23448. specialAreas: rawGeoJson.specialAreas
  23449. }];
  23450. }
  23451. else {
  23452. // Backward compatibility.
  23453. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23454. rawSpecialAreas = rawGeoJson.specialAreas;
  23455. rawGeoJson = rawGeoJson.geoJson;
  23456. }
  23457. records = [{
  23458. type: 'geoJSON',
  23459. source: rawGeoJson,
  23460. specialAreas: rawSpecialAreas
  23461. }];
  23462. }
  23463. each$1(records, function (record) {
  23464. var type = record.type;
  23465. type === 'geoJson' && (type = record.type = 'geoJSON');
  23466. var parse = parsers[type];
  23467. if (__DEV__) {
  23468. assert$1(parse, 'Illegal map type: ' + type);
  23469. }
  23470. parse(record);
  23471. });
  23472. return storage.set(mapName, records);
  23473. },
  23474. retrieveMap: function (mapName) {
  23475. return storage.get(mapName);
  23476. }
  23477. };
  23478. var parsers = {
  23479. geoJSON: function (record) {
  23480. var source = record.source;
  23481. record.geoJSON = !isString(source)
  23482. ? source
  23483. : (typeof JSON !== 'undefined' && JSON.parse)
  23484. ? JSON.parse(source)
  23485. : (new Function('return (' + source + ');'))();
  23486. },
  23487. // Only perform parse to XML object here, which might be time
  23488. // consiming for large SVG.
  23489. // Although convert XML to zrender element is also time consiming,
  23490. // if we do it here, the clone of zrender elements has to be
  23491. // required. So we do it once for each geo instance, util real
  23492. // performance issues call for optimizing it.
  23493. svg: function (record) {
  23494. record.svgXML = parseXML(record.source);
  23495. }
  23496. };
  23497. /*
  23498. * Licensed to the Apache Software Foundation (ASF) under one
  23499. * or more contributor license agreements. See the NOTICE file
  23500. * distributed with this work for additional information
  23501. * regarding copyright ownership. The ASF licenses this file
  23502. * to you under the Apache License, Version 2.0 (the
  23503. * "License"); you may not use this file except in compliance
  23504. * with the License. You may obtain a copy of the License at
  23505. *
  23506. * http://www.apache.org/licenses/LICENSE-2.0
  23507. *
  23508. * Unless required by applicable law or agreed to in writing,
  23509. * software distributed under the License is distributed on an
  23510. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23511. * KIND, either express or implied. See the License for the
  23512. * specific language governing permissions and limitations
  23513. * under the License.
  23514. */
  23515. var assert = assert$1;
  23516. var each = each$1;
  23517. var isFunction = isFunction$1;
  23518. var isObject = isObject$1;
  23519. var parseClassType = ComponentModel.parseClassType;
  23520. var version = '4.6.0';
  23521. var dependencies = {
  23522. zrender: '4.2.0'
  23523. };
  23524. var TEST_FRAME_REMAIN_TIME = 1;
  23525. var PRIORITY_PROCESSOR_FILTER = 1000;
  23526. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  23527. var PRIORITY_PROCESSOR_DATASTACK = 900;
  23528. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23529. var PRIORITY_VISUAL_LAYOUT = 1000;
  23530. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  23531. var PRIORITY_VISUAL_GLOBAL = 2000;
  23532. var PRIORITY_VISUAL_CHART = 3000;
  23533. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  23534. var PRIORITY_VISUAL_COMPONENT = 4000;
  23535. // FIXME
  23536. // necessary?
  23537. var PRIORITY_VISUAL_BRUSH = 5000;
  23538. var PRIORITY = {
  23539. PROCESSOR: {
  23540. FILTER: PRIORITY_PROCESSOR_FILTER,
  23541. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  23542. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23543. },
  23544. VISUAL: {
  23545. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23546. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  23547. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23548. CHART: PRIORITY_VISUAL_CHART,
  23549. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  23550. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23551. BRUSH: PRIORITY_VISUAL_BRUSH
  23552. }
  23553. };
  23554. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23555. // where they must not be invoked nestedly, except the only case: invoke
  23556. // dispatchAction with updateMethod "none" in main process.
  23557. // This flag is used to carry out this rule.
  23558. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23559. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23560. var OPTION_UPDATED = '__optionUpdated';
  23561. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23562. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  23563. return function (eventName, handler, context) {
  23564. if (!ignoreDisposed && this._disposed) {
  23565. disposedWarning(this.id);
  23566. return;
  23567. }
  23568. // Event name is all lowercase
  23569. eventName = eventName && eventName.toLowerCase();
  23570. Eventful.prototype[method].call(this, eventName, handler, context);
  23571. };
  23572. }
  23573. /**
  23574. * @module echarts~MessageCenter
  23575. */
  23576. function MessageCenter() {
  23577. Eventful.call(this);
  23578. }
  23579. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  23580. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  23581. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  23582. mixin(MessageCenter, Eventful);
  23583. /**
  23584. * @module echarts~ECharts
  23585. */
  23586. function ECharts(dom, theme$$1, opts) {
  23587. opts = opts || {};
  23588. // Get theme by name
  23589. if (typeof theme$$1 === 'string') {
  23590. theme$$1 = themeStorage[theme$$1];
  23591. }
  23592. /**
  23593. * @type {string}
  23594. */
  23595. this.id;
  23596. /**
  23597. * Group id
  23598. * @type {string}
  23599. */
  23600. this.group;
  23601. /**
  23602. * @type {HTMLElement}
  23603. * @private
  23604. */
  23605. this._dom = dom;
  23606. var defaultRenderer = 'canvas';
  23607. if (__DEV__) {
  23608. defaultRenderer = (
  23609. typeof window === 'undefined' ? global : window
  23610. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23611. }
  23612. /**
  23613. * @type {module:zrender/ZRender}
  23614. * @private
  23615. */
  23616. var zr = this._zr = init$1(dom, {
  23617. renderer: opts.renderer || defaultRenderer,
  23618. devicePixelRatio: opts.devicePixelRatio,
  23619. width: opts.width,
  23620. height: opts.height
  23621. });
  23622. /**
  23623. * Expect 60 fps.
  23624. * @type {Function}
  23625. * @private
  23626. */
  23627. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23628. var theme$$1 = clone(theme$$1);
  23629. theme$$1 && backwardCompat(theme$$1, true);
  23630. /**
  23631. * @type {Object}
  23632. * @private
  23633. */
  23634. this._theme = theme$$1;
  23635. /**
  23636. * @type {Array.<module:echarts/view/Chart>}
  23637. * @private
  23638. */
  23639. this._chartsViews = [];
  23640. /**
  23641. * @type {Object.<string, module:echarts/view/Chart>}
  23642. * @private
  23643. */
  23644. this._chartsMap = {};
  23645. /**
  23646. * @type {Array.<module:echarts/view/Component>}
  23647. * @private
  23648. */
  23649. this._componentsViews = [];
  23650. /**
  23651. * @type {Object.<string, module:echarts/view/Component>}
  23652. * @private
  23653. */
  23654. this._componentsMap = {};
  23655. /**
  23656. * @type {module:echarts/CoordinateSystem}
  23657. * @private
  23658. */
  23659. this._coordSysMgr = new CoordinateSystemManager();
  23660. /**
  23661. * @type {module:echarts/ExtensionAPI}
  23662. * @private
  23663. */
  23664. var api = this._api = createExtensionAPI(this);
  23665. // Sort on demand
  23666. function prioritySortFunc(a, b) {
  23667. return a.__prio - b.__prio;
  23668. }
  23669. sort(visualFuncs, prioritySortFunc);
  23670. sort(dataProcessorFuncs, prioritySortFunc);
  23671. /**
  23672. * @type {module:echarts/stream/Scheduler}
  23673. */
  23674. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23675. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23676. /**
  23677. * @type {module:echarts~MessageCenter}
  23678. * @private
  23679. */
  23680. this._messageCenter = new MessageCenter();
  23681. // Init mouse events
  23682. this._initEvents();
  23683. // In case some people write `window.onresize = chart.resize`
  23684. this.resize = bind(this.resize, this);
  23685. // Can't dispatch action during rendering procedure
  23686. this._pendingActions = [];
  23687. zr.animation.on('frame', this._onframe, this);
  23688. bindRenderedEvent(zr, this);
  23689. // ECharts instance can be used as value.
  23690. setAsPrimitive(this);
  23691. }
  23692. var echartsProto = ECharts.prototype;
  23693. echartsProto._onframe = function () {
  23694. if (this._disposed) {
  23695. return;
  23696. }
  23697. var scheduler = this._scheduler;
  23698. // Lazy update
  23699. if (this[OPTION_UPDATED]) {
  23700. var silent = this[OPTION_UPDATED].silent;
  23701. this[IN_MAIN_PROCESS] = true;
  23702. prepare(this);
  23703. updateMethods.update.call(this);
  23704. this[IN_MAIN_PROCESS] = false;
  23705. this[OPTION_UPDATED] = false;
  23706. flushPendingActions.call(this, silent);
  23707. triggerUpdatedEvent.call(this, silent);
  23708. }
  23709. // Avoid do both lazy update and progress in one frame.
  23710. else if (scheduler.unfinished) {
  23711. // Stream progress.
  23712. var remainTime = TEST_FRAME_REMAIN_TIME;
  23713. var ecModel = this._model;
  23714. var api = this._api;
  23715. scheduler.unfinished = false;
  23716. do {
  23717. var startTime = +new Date();
  23718. scheduler.performSeriesTasks(ecModel);
  23719. // Currently dataProcessorFuncs do not check threshold.
  23720. scheduler.performDataProcessorTasks(ecModel);
  23721. updateStreamModes(this, ecModel);
  23722. // Do not update coordinate system here. Because that coord system update in
  23723. // each frame is not a good user experience. So we follow the rule that
  23724. // the extent of the coordinate system is determin in the first frame (the
  23725. // frame is executed immedietely after task reset.
  23726. // this._coordSysMgr.update(ecModel, api);
  23727. // console.log('--- ec frame visual ---', remainTime);
  23728. scheduler.performVisualTasks(ecModel);
  23729. renderSeries(this, this._model, api, 'remain');
  23730. remainTime -= (+new Date() - startTime);
  23731. }
  23732. while (remainTime > 0 && scheduler.unfinished);
  23733. // Call flush explicitly for trigger finished event.
  23734. if (!scheduler.unfinished) {
  23735. this._zr.flush();
  23736. }
  23737. // Else, zr flushing be ensue within the same frame,
  23738. // because zr flushing is after onframe event.
  23739. }
  23740. };
  23741. /**
  23742. * @return {HTMLElement}
  23743. */
  23744. echartsProto.getDom = function () {
  23745. return this._dom;
  23746. };
  23747. /**
  23748. * @return {module:zrender~ZRender}
  23749. */
  23750. echartsProto.getZr = function () {
  23751. return this._zr;
  23752. };
  23753. /**
  23754. * Usage:
  23755. * chart.setOption(option, notMerge, lazyUpdate);
  23756. * chart.setOption(option, {
  23757. * notMerge: ...,
  23758. * lazyUpdate: ...,
  23759. * silent: ...
  23760. * });
  23761. *
  23762. * @param {Object} option
  23763. * @param {Object|boolean} [opts] opts or notMerge.
  23764. * @param {boolean} [opts.notMerge=false]
  23765. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23766. */
  23767. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23768. if (__DEV__) {
  23769. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23770. }
  23771. if (this._disposed) {
  23772. disposedWarning(this.id);
  23773. return;
  23774. }
  23775. var silent;
  23776. if (isObject(notMerge)) {
  23777. lazyUpdate = notMerge.lazyUpdate;
  23778. silent = notMerge.silent;
  23779. notMerge = notMerge.notMerge;
  23780. }
  23781. this[IN_MAIN_PROCESS] = true;
  23782. if (!this._model || notMerge) {
  23783. var optionManager = new OptionManager(this._api);
  23784. var theme$$1 = this._theme;
  23785. var ecModel = this._model = new GlobalModel();
  23786. ecModel.scheduler = this._scheduler;
  23787. ecModel.init(null, null, theme$$1, optionManager);
  23788. }
  23789. this._model.setOption(option, optionPreprocessorFuncs);
  23790. if (lazyUpdate) {
  23791. this[OPTION_UPDATED] = {silent: silent};
  23792. this[IN_MAIN_PROCESS] = false;
  23793. }
  23794. else {
  23795. prepare(this);
  23796. updateMethods.update.call(this);
  23797. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23798. // fetched after `setOption`.
  23799. this._zr.flush();
  23800. this[OPTION_UPDATED] = false;
  23801. this[IN_MAIN_PROCESS] = false;
  23802. flushPendingActions.call(this, silent);
  23803. triggerUpdatedEvent.call(this, silent);
  23804. }
  23805. };
  23806. /**
  23807. * @DEPRECATED
  23808. */
  23809. echartsProto.setTheme = function () {
  23810. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23811. };
  23812. /**
  23813. * @return {module:echarts/model/Global}
  23814. */
  23815. echartsProto.getModel = function () {
  23816. return this._model;
  23817. };
  23818. /**
  23819. * @return {Object}
  23820. */
  23821. echartsProto.getOption = function () {
  23822. return this._model && this._model.getOption();
  23823. };
  23824. /**
  23825. * @return {number}
  23826. */
  23827. echartsProto.getWidth = function () {
  23828. return this._zr.getWidth();
  23829. };
  23830. /**
  23831. * @return {number}
  23832. */
  23833. echartsProto.getHeight = function () {
  23834. return this._zr.getHeight();
  23835. };
  23836. /**
  23837. * @return {number}
  23838. */
  23839. echartsProto.getDevicePixelRatio = function () {
  23840. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23841. };
  23842. /**
  23843. * Get canvas which has all thing rendered
  23844. * @param {Object} opts
  23845. * @param {string} [opts.backgroundColor]
  23846. * @return {string}
  23847. */
  23848. echartsProto.getRenderedCanvas = function (opts) {
  23849. if (!env$1.canvasSupported) {
  23850. return;
  23851. }
  23852. opts = opts || {};
  23853. opts.pixelRatio = opts.pixelRatio || 1;
  23854. opts.backgroundColor = opts.backgroundColor
  23855. || this._model.get('backgroundColor');
  23856. var zr = this._zr;
  23857. // var list = zr.storage.getDisplayList();
  23858. // Stop animations
  23859. // Never works before in init animation, so remove it.
  23860. // zrUtil.each(list, function (el) {
  23861. // el.stopAnimation(true);
  23862. // });
  23863. return zr.painter.getRenderedCanvas(opts);
  23864. };
  23865. /**
  23866. * Get svg data url
  23867. * @return {string}
  23868. */
  23869. echartsProto.getSvgDataUrl = function () {
  23870. if (!env$1.svgSupported) {
  23871. return;
  23872. }
  23873. var zr = this._zr;
  23874. var list = zr.storage.getDisplayList();
  23875. // Stop animations
  23876. each$1(list, function (el) {
  23877. el.stopAnimation(true);
  23878. });
  23879. return zr.painter.pathToDataUrl();
  23880. };
  23881. /**
  23882. * @return {string}
  23883. * @param {Object} opts
  23884. * @param {string} [opts.type='png']
  23885. * @param {string} [opts.pixelRatio=1]
  23886. * @param {string} [opts.backgroundColor]
  23887. * @param {string} [opts.excludeComponents]
  23888. */
  23889. echartsProto.getDataURL = function (opts) {
  23890. if (this._disposed) {
  23891. disposedWarning(this.id);
  23892. return;
  23893. }
  23894. opts = opts || {};
  23895. var excludeComponents = opts.excludeComponents;
  23896. var ecModel = this._model;
  23897. var excludesComponentViews = [];
  23898. var self = this;
  23899. each(excludeComponents, function (componentType) {
  23900. ecModel.eachComponent({
  23901. mainType: componentType
  23902. }, function (component) {
  23903. var view = self._componentsMap[component.__viewId];
  23904. if (!view.group.ignore) {
  23905. excludesComponentViews.push(view);
  23906. view.group.ignore = true;
  23907. }
  23908. });
  23909. });
  23910. var url = this._zr.painter.getType() === 'svg'
  23911. ? this.getSvgDataUrl()
  23912. : this.getRenderedCanvas(opts).toDataURL(
  23913. 'image/' + (opts && opts.type || 'png')
  23914. );
  23915. each(excludesComponentViews, function (view) {
  23916. view.group.ignore = false;
  23917. });
  23918. return url;
  23919. };
  23920. /**
  23921. * @return {string}
  23922. * @param {Object} opts
  23923. * @param {string} [opts.type='png']
  23924. * @param {string} [opts.pixelRatio=1]
  23925. * @param {string} [opts.backgroundColor]
  23926. */
  23927. echartsProto.getConnectedDataURL = function (opts) {
  23928. if (this._disposed) {
  23929. disposedWarning(this.id);
  23930. return;
  23931. }
  23932. if (!env$1.canvasSupported) {
  23933. return;
  23934. }
  23935. var groupId = this.group;
  23936. var mathMin = Math.min;
  23937. var mathMax = Math.max;
  23938. var MAX_NUMBER = Infinity;
  23939. if (connectedGroups[groupId]) {
  23940. var left = MAX_NUMBER;
  23941. var top = MAX_NUMBER;
  23942. var right = -MAX_NUMBER;
  23943. var bottom = -MAX_NUMBER;
  23944. var canvasList = [];
  23945. var dpr = (opts && opts.pixelRatio) || 1;
  23946. each$1(instances, function (chart, id) {
  23947. if (chart.group === groupId) {
  23948. var canvas = chart.getRenderedCanvas(
  23949. clone(opts)
  23950. );
  23951. var boundingRect = chart.getDom().getBoundingClientRect();
  23952. left = mathMin(boundingRect.left, left);
  23953. top = mathMin(boundingRect.top, top);
  23954. right = mathMax(boundingRect.right, right);
  23955. bottom = mathMax(boundingRect.bottom, bottom);
  23956. canvasList.push({
  23957. dom: canvas,
  23958. left: boundingRect.left,
  23959. top: boundingRect.top
  23960. });
  23961. }
  23962. });
  23963. left *= dpr;
  23964. top *= dpr;
  23965. right *= dpr;
  23966. bottom *= dpr;
  23967. var width = right - left;
  23968. var height = bottom - top;
  23969. var targetCanvas = createCanvas();
  23970. targetCanvas.width = width;
  23971. targetCanvas.height = height;
  23972. var zr = init$1(targetCanvas);
  23973. // Background between the charts
  23974. if (opts.connectedBackgroundColor) {
  23975. zr.add(new Rect({
  23976. shape: {
  23977. x: 0,
  23978. y: 0,
  23979. width: width,
  23980. height: height
  23981. },
  23982. style: {
  23983. fill: opts.connectedBackgroundColor
  23984. }
  23985. }));
  23986. }
  23987. each(canvasList, function (item) {
  23988. var img = new ZImage({
  23989. style: {
  23990. x: item.left * dpr - left,
  23991. y: item.top * dpr - top,
  23992. image: item.dom
  23993. }
  23994. });
  23995. zr.add(img);
  23996. });
  23997. zr.refreshImmediately();
  23998. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23999. }
  24000. else {
  24001. return this.getDataURL(opts);
  24002. }
  24003. };
  24004. /**
  24005. * Convert from logical coordinate system to pixel coordinate system.
  24006. * See CoordinateSystem#convertToPixel.
  24007. * @param {string|Object} finder
  24008. * If string, e.g., 'geo', means {geoIndex: 0}.
  24009. * If Object, could contain some of these properties below:
  24010. * {
  24011. * seriesIndex / seriesId / seriesName,
  24012. * geoIndex / geoId, geoName,
  24013. * bmapIndex / bmapId / bmapName,
  24014. * xAxisIndex / xAxisId / xAxisName,
  24015. * yAxisIndex / yAxisId / yAxisName,
  24016. * gridIndex / gridId / gridName,
  24017. * ... (can be extended)
  24018. * }
  24019. * @param {Array|number} value
  24020. * @return {Array|number} result
  24021. */
  24022. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24023. /**
  24024. * Convert from pixel coordinate system to logical coordinate system.
  24025. * See CoordinateSystem#convertFromPixel.
  24026. * @param {string|Object} finder
  24027. * If string, e.g., 'geo', means {geoIndex: 0}.
  24028. * If Object, could contain some of these properties below:
  24029. * {
  24030. * seriesIndex / seriesId / seriesName,
  24031. * geoIndex / geoId / geoName,
  24032. * bmapIndex / bmapId / bmapName,
  24033. * xAxisIndex / xAxisId / xAxisName,
  24034. * yAxisIndex / yAxisId / yAxisName
  24035. * gridIndex / gridId / gridName,
  24036. * ... (can be extended)
  24037. * }
  24038. * @param {Array|number} value
  24039. * @return {Array|number} result
  24040. */
  24041. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24042. function doConvertPixel(methodName, finder, value) {
  24043. if (this._disposed) {
  24044. disposedWarning(this.id);
  24045. return;
  24046. }
  24047. var ecModel = this._model;
  24048. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24049. var result;
  24050. finder = parseFinder(ecModel, finder);
  24051. for (var i = 0; i < coordSysList.length; i++) {
  24052. var coordSys = coordSysList[i];
  24053. if (coordSys[methodName]
  24054. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24055. ) {
  24056. return result;
  24057. }
  24058. }
  24059. if (__DEV__) {
  24060. console.warn(
  24061. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24062. );
  24063. }
  24064. }
  24065. /**
  24066. * Is the specified coordinate systems or components contain the given pixel point.
  24067. * @param {string|Object} finder
  24068. * If string, e.g., 'geo', means {geoIndex: 0}.
  24069. * If Object, could contain some of these properties below:
  24070. * {
  24071. * seriesIndex / seriesId / seriesName,
  24072. * geoIndex / geoId / geoName,
  24073. * bmapIndex / bmapId / bmapName,
  24074. * xAxisIndex / xAxisId / xAxisName,
  24075. * yAxisIndex / yAxisId / yAxisName,
  24076. * gridIndex / gridId / gridName,
  24077. * ... (can be extended)
  24078. * }
  24079. * @param {Array|number} value
  24080. * @return {boolean} result
  24081. */
  24082. echartsProto.containPixel = function (finder, value) {
  24083. if (this._disposed) {
  24084. disposedWarning(this.id);
  24085. return;
  24086. }
  24087. var ecModel = this._model;
  24088. var result;
  24089. finder = parseFinder(ecModel, finder);
  24090. each$1(finder, function (models, key) {
  24091. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24092. var coordSys = model.coordinateSystem;
  24093. if (coordSys && coordSys.containPoint) {
  24094. result |= !!coordSys.containPoint(value);
  24095. }
  24096. else if (key === 'seriesModels') {
  24097. var view = this._chartsMap[model.__viewId];
  24098. if (view && view.containPoint) {
  24099. result |= view.containPoint(value, model);
  24100. }
  24101. else {
  24102. if (__DEV__) {
  24103. console.warn(key + ': ' + (view
  24104. ? 'The found component do not support containPoint.'
  24105. : 'No view mapping to the found component.'
  24106. ));
  24107. }
  24108. }
  24109. }
  24110. else {
  24111. if (__DEV__) {
  24112. console.warn(key + ': containPoint is not supported');
  24113. }
  24114. }
  24115. }, this);
  24116. }, this);
  24117. return !!result;
  24118. };
  24119. /**
  24120. * Get visual from series or data.
  24121. * @param {string|Object} finder
  24122. * If string, e.g., 'series', means {seriesIndex: 0}.
  24123. * If Object, could contain some of these properties below:
  24124. * {
  24125. * seriesIndex / seriesId / seriesName,
  24126. * dataIndex / dataIndexInside
  24127. * }
  24128. * If dataIndex is not specified, series visual will be fetched,
  24129. * but not data item visual.
  24130. * If all of seriesIndex, seriesId, seriesName are not specified,
  24131. * visual will be fetched from first series.
  24132. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24133. */
  24134. echartsProto.getVisual = function (finder, visualType) {
  24135. var ecModel = this._model;
  24136. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24137. var seriesModel = finder.seriesModel;
  24138. if (__DEV__) {
  24139. if (!seriesModel) {
  24140. console.warn('There is no specified seires model');
  24141. }
  24142. }
  24143. var data = seriesModel.getData();
  24144. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24145. ? finder.dataIndexInside
  24146. : finder.hasOwnProperty('dataIndex')
  24147. ? data.indexOfRawIndex(finder.dataIndex)
  24148. : null;
  24149. return dataIndexInside != null
  24150. ? data.getItemVisual(dataIndexInside, visualType)
  24151. : data.getVisual(visualType);
  24152. };
  24153. /**
  24154. * Get view of corresponding component model
  24155. * @param {module:echarts/model/Component} componentModel
  24156. * @return {module:echarts/view/Component}
  24157. */
  24158. echartsProto.getViewOfComponentModel = function (componentModel) {
  24159. return this._componentsMap[componentModel.__viewId];
  24160. };
  24161. /**
  24162. * Get view of corresponding series model
  24163. * @param {module:echarts/model/Series} seriesModel
  24164. * @return {module:echarts/view/Chart}
  24165. */
  24166. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24167. return this._chartsMap[seriesModel.__viewId];
  24168. };
  24169. var updateMethods = {
  24170. prepareAndUpdate: function (payload) {
  24171. prepare(this);
  24172. updateMethods.update.call(this, payload);
  24173. },
  24174. /**
  24175. * @param {Object} payload
  24176. * @private
  24177. */
  24178. update: function (payload) {
  24179. // console.profile && console.profile('update');
  24180. var ecModel = this._model;
  24181. var api = this._api;
  24182. var zr = this._zr;
  24183. var coordSysMgr = this._coordSysMgr;
  24184. var scheduler = this._scheduler;
  24185. // update before setOption
  24186. if (!ecModel) {
  24187. return;
  24188. }
  24189. scheduler.restoreData(ecModel, payload);
  24190. scheduler.performSeriesTasks(ecModel);
  24191. // TODO
  24192. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24193. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24194. // Create new coordinate system each update
  24195. // In LineView may save the old coordinate system and use it to get the orignal point
  24196. coordSysMgr.create(ecModel, api);
  24197. scheduler.performDataProcessorTasks(ecModel, payload);
  24198. // Current stream render is not supported in data process. So we can update
  24199. // stream modes after data processing, where the filtered data is used to
  24200. // deteming whether use progressive rendering.
  24201. updateStreamModes(this, ecModel);
  24202. // We update stream modes before coordinate system updated, then the modes info
  24203. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24204. // the drawback is the full coord info can not be fetched. Fortunately this full
  24205. // coord is not requied in stream mode updater currently.
  24206. coordSysMgr.update(ecModel, api);
  24207. clearColorPalette(ecModel);
  24208. scheduler.performVisualTasks(ecModel, payload);
  24209. render(this, ecModel, api, payload);
  24210. // Set background
  24211. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24212. // In IE8
  24213. if (!env$1.canvasSupported) {
  24214. var colorArr = parse(backgroundColor);
  24215. backgroundColor = stringify(colorArr, 'rgb');
  24216. if (colorArr[3] === 0) {
  24217. backgroundColor = 'transparent';
  24218. }
  24219. }
  24220. else {
  24221. zr.setBackgroundColor(backgroundColor);
  24222. }
  24223. performPostUpdateFuncs(ecModel, api);
  24224. // console.profile && console.profileEnd('update');
  24225. },
  24226. /**
  24227. * @param {Object} payload
  24228. * @private
  24229. */
  24230. updateTransform: function (payload) {
  24231. var ecModel = this._model;
  24232. var ecIns = this;
  24233. var api = this._api;
  24234. // update before setOption
  24235. if (!ecModel) {
  24236. return;
  24237. }
  24238. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24239. var componentDirtyList = [];
  24240. ecModel.eachComponent(function (componentType, componentModel) {
  24241. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24242. if (componentView && componentView.__alive) {
  24243. if (componentView.updateTransform) {
  24244. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24245. result && result.update && componentDirtyList.push(componentView);
  24246. }
  24247. else {
  24248. componentDirtyList.push(componentView);
  24249. }
  24250. }
  24251. });
  24252. var seriesDirtyMap = createHashMap();
  24253. ecModel.eachSeries(function (seriesModel) {
  24254. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24255. if (chartView.updateTransform) {
  24256. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24257. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24258. }
  24259. else {
  24260. seriesDirtyMap.set(seriesModel.uid, 1);
  24261. }
  24262. });
  24263. clearColorPalette(ecModel);
  24264. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24265. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24266. this._scheduler.performVisualTasks(
  24267. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24268. );
  24269. // Currently, not call render of components. Geo render cost a lot.
  24270. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24271. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24272. performPostUpdateFuncs(ecModel, this._api);
  24273. },
  24274. /**
  24275. * @param {Object} payload
  24276. * @private
  24277. */
  24278. updateView: function (payload) {
  24279. var ecModel = this._model;
  24280. // update before setOption
  24281. if (!ecModel) {
  24282. return;
  24283. }
  24284. Chart.markUpdateMethod(payload, 'updateView');
  24285. clearColorPalette(ecModel);
  24286. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24287. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24288. render(this, this._model, this._api, payload);
  24289. performPostUpdateFuncs(ecModel, this._api);
  24290. },
  24291. /**
  24292. * @param {Object} payload
  24293. * @private
  24294. */
  24295. updateVisual: function (payload) {
  24296. updateMethods.update.call(this, payload);
  24297. // var ecModel = this._model;
  24298. // // update before setOption
  24299. // if (!ecModel) {
  24300. // return;
  24301. // }
  24302. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24303. // clearColorPalette(ecModel);
  24304. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24305. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24306. // render(this, this._model, this._api, payload);
  24307. // performPostUpdateFuncs(ecModel, this._api);
  24308. },
  24309. /**
  24310. * @param {Object} payload
  24311. * @private
  24312. */
  24313. updateLayout: function (payload) {
  24314. updateMethods.update.call(this, payload);
  24315. // var ecModel = this._model;
  24316. // // update before setOption
  24317. // if (!ecModel) {
  24318. // return;
  24319. // }
  24320. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24321. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24322. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24323. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24324. // render(this, this._model, this._api, payload);
  24325. // performPostUpdateFuncs(ecModel, this._api);
  24326. }
  24327. };
  24328. function prepare(ecIns) {
  24329. var ecModel = ecIns._model;
  24330. var scheduler = ecIns._scheduler;
  24331. scheduler.restorePipelines(ecModel);
  24332. scheduler.prepareStageTasks();
  24333. prepareView(ecIns, 'component', ecModel, scheduler);
  24334. prepareView(ecIns, 'chart', ecModel, scheduler);
  24335. scheduler.plan();
  24336. }
  24337. /**
  24338. * @private
  24339. */
  24340. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24341. var ecModel = ecIns._model;
  24342. // broadcast
  24343. if (!mainType) {
  24344. // FIXME
  24345. // Chart will not be update directly here, except set dirty.
  24346. // But there is no such scenario now.
  24347. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24348. return;
  24349. }
  24350. var query = {};
  24351. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24352. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24353. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24354. var condition = {mainType: mainType, query: query};
  24355. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24356. var excludeSeriesId = payload.excludeSeriesId;
  24357. if (excludeSeriesId != null) {
  24358. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24359. }
  24360. // If dispatchAction before setOption, do nothing.
  24361. ecModel && ecModel.eachComponent(condition, function (model) {
  24362. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24363. callView(ecIns[
  24364. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24365. ][model.__viewId]);
  24366. }
  24367. }, ecIns);
  24368. function callView(view) {
  24369. view && view.__alive && view[method] && view[method](
  24370. view.__model, ecModel, ecIns._api, payload
  24371. );
  24372. }
  24373. }
  24374. /**
  24375. * Resize the chart
  24376. * @param {Object} opts
  24377. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24378. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24379. * @param {boolean} [opts.silent=false]
  24380. */
  24381. echartsProto.resize = function (opts) {
  24382. if (__DEV__) {
  24383. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24384. }
  24385. if (this._disposed) {
  24386. disposedWarning(this.id);
  24387. return;
  24388. }
  24389. this._zr.resize(opts);
  24390. var ecModel = this._model;
  24391. // Resize loading effect
  24392. this._loadingFX && this._loadingFX.resize();
  24393. if (!ecModel) {
  24394. return;
  24395. }
  24396. var optionChanged = ecModel.resetOption('media');
  24397. var silent = opts && opts.silent;
  24398. this[IN_MAIN_PROCESS] = true;
  24399. optionChanged && prepare(this);
  24400. updateMethods.update.call(this);
  24401. this[IN_MAIN_PROCESS] = false;
  24402. flushPendingActions.call(this, silent);
  24403. triggerUpdatedEvent.call(this, silent);
  24404. };
  24405. function updateStreamModes(ecIns, ecModel) {
  24406. var chartsMap = ecIns._chartsMap;
  24407. var scheduler = ecIns._scheduler;
  24408. ecModel.eachSeries(function (seriesModel) {
  24409. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24410. });
  24411. }
  24412. /**
  24413. * Show loading effect
  24414. * @param {string} [name='default']
  24415. * @param {Object} [cfg]
  24416. */
  24417. echartsProto.showLoading = function (name, cfg) {
  24418. if (this._disposed) {
  24419. disposedWarning(this.id);
  24420. return;
  24421. }
  24422. if (isObject(name)) {
  24423. cfg = name;
  24424. name = '';
  24425. }
  24426. name = name || 'default';
  24427. this.hideLoading();
  24428. if (!loadingEffects[name]) {
  24429. if (__DEV__) {
  24430. console.warn('Loading effects ' + name + ' not exists.');
  24431. }
  24432. return;
  24433. }
  24434. var el = loadingEffects[name](this._api, cfg);
  24435. var zr = this._zr;
  24436. this._loadingFX = el;
  24437. zr.add(el);
  24438. };
  24439. /**
  24440. * Hide loading effect
  24441. */
  24442. echartsProto.hideLoading = function () {
  24443. if (this._disposed) {
  24444. disposedWarning(this.id);
  24445. return;
  24446. }
  24447. this._loadingFX && this._zr.remove(this._loadingFX);
  24448. this._loadingFX = null;
  24449. };
  24450. /**
  24451. * @param {Object} eventObj
  24452. * @return {Object}
  24453. */
  24454. echartsProto.makeActionFromEvent = function (eventObj) {
  24455. var payload = extend({}, eventObj);
  24456. payload.type = eventActionMap[eventObj.type];
  24457. return payload;
  24458. };
  24459. /**
  24460. * @pubilc
  24461. * @param {Object} payload
  24462. * @param {string} [payload.type] Action type
  24463. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24464. * @param {boolean} [opt.silent=false] Whether trigger events.
  24465. * @param {boolean} [opt.flush=undefined]
  24466. * true: Flush immediately, and then pixel in canvas can be fetched
  24467. * immediately. Caution: it might affect performance.
  24468. * false: Not flush.
  24469. * undefined: Auto decide whether perform flush.
  24470. */
  24471. echartsProto.dispatchAction = function (payload, opt) {
  24472. if (this._disposed) {
  24473. disposedWarning(this.id);
  24474. return;
  24475. }
  24476. if (!isObject(opt)) {
  24477. opt = {silent: !!opt};
  24478. }
  24479. if (!actions[payload.type]) {
  24480. return;
  24481. }
  24482. // Avoid dispatch action before setOption. Especially in `connect`.
  24483. if (!this._model) {
  24484. return;
  24485. }
  24486. // May dispatchAction in rendering procedure
  24487. if (this[IN_MAIN_PROCESS]) {
  24488. this._pendingActions.push(payload);
  24489. return;
  24490. }
  24491. doDispatchAction.call(this, payload, opt.silent);
  24492. if (opt.flush) {
  24493. this._zr.flush(true);
  24494. }
  24495. else if (opt.flush !== false && env$1.browser.weChat) {
  24496. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24497. // hang when sliding page (on touch event), which cause that zr does not
  24498. // refresh util user interaction finished, which is not expected.
  24499. // But `dispatchAction` may be called too frequently when pan on touch
  24500. // screen, which impacts performance if do not throttle them.
  24501. this._throttledZrFlush();
  24502. }
  24503. flushPendingActions.call(this, opt.silent);
  24504. triggerUpdatedEvent.call(this, opt.silent);
  24505. };
  24506. function doDispatchAction(payload, silent) {
  24507. var payloadType = payload.type;
  24508. var escapeConnect = payload.escapeConnect;
  24509. var actionWrap = actions[payloadType];
  24510. var actionInfo = actionWrap.actionInfo;
  24511. var cptType = (actionInfo.update || 'update').split(':');
  24512. var updateMethod = cptType.pop();
  24513. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24514. this[IN_MAIN_PROCESS] = true;
  24515. var payloads = [payload];
  24516. var batched = false;
  24517. // Batch action
  24518. if (payload.batch) {
  24519. batched = true;
  24520. payloads = map(payload.batch, function (item) {
  24521. item = defaults(extend({}, item), payload);
  24522. item.batch = null;
  24523. return item;
  24524. });
  24525. }
  24526. var eventObjBatch = [];
  24527. var eventObj;
  24528. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24529. each(payloads, function (batchItem) {
  24530. // Action can specify the event by return it.
  24531. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24532. // Emit event outside
  24533. eventObj = eventObj || extend({}, batchItem);
  24534. // Convert type to eventType
  24535. eventObj.type = actionInfo.event || eventObj.type;
  24536. eventObjBatch.push(eventObj);
  24537. // light update does not perform data process, layout and visual.
  24538. if (isHighDown) {
  24539. // method, payload, mainType, subType
  24540. updateDirectly(this, updateMethod, batchItem, 'series');
  24541. }
  24542. else if (cptType) {
  24543. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24544. }
  24545. }, this);
  24546. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24547. // Still dirty
  24548. if (this[OPTION_UPDATED]) {
  24549. // FIXME Pass payload ?
  24550. prepare(this);
  24551. updateMethods.update.call(this, payload);
  24552. this[OPTION_UPDATED] = false;
  24553. }
  24554. else {
  24555. updateMethods[updateMethod].call(this, payload);
  24556. }
  24557. }
  24558. // Follow the rule of action batch
  24559. if (batched) {
  24560. eventObj = {
  24561. type: actionInfo.event || payloadType,
  24562. escapeConnect: escapeConnect,
  24563. batch: eventObjBatch
  24564. };
  24565. }
  24566. else {
  24567. eventObj = eventObjBatch[0];
  24568. }
  24569. this[IN_MAIN_PROCESS] = false;
  24570. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24571. }
  24572. function flushPendingActions(silent) {
  24573. var pendingActions = this._pendingActions;
  24574. while (pendingActions.length) {
  24575. var payload = pendingActions.shift();
  24576. doDispatchAction.call(this, payload, silent);
  24577. }
  24578. }
  24579. function triggerUpdatedEvent(silent) {
  24580. !silent && this.trigger('updated');
  24581. }
  24582. /**
  24583. * Event `rendered` is triggered when zr
  24584. * rendered. It is useful for realtime
  24585. * snapshot (reflect animation).
  24586. *
  24587. * Event `finished` is triggered when:
  24588. * (1) zrender rendering finished.
  24589. * (2) initial animation finished.
  24590. * (3) progressive rendering finished.
  24591. * (4) no pending action.
  24592. * (5) no delayed setOption needs to be processed.
  24593. */
  24594. function bindRenderedEvent(zr, ecIns) {
  24595. zr.on('rendered', function () {
  24596. ecIns.trigger('rendered');
  24597. // The `finished` event should not be triggered repeatly,
  24598. // so it should only be triggered when rendering indeed happend
  24599. // in zrender. (Consider the case that dipatchAction is keep
  24600. // triggering when mouse move).
  24601. if (
  24602. // Although zr is dirty if initial animation is not finished
  24603. // and this checking is called on frame, we also check
  24604. // animation finished for robustness.
  24605. zr.animation.isFinished()
  24606. && !ecIns[OPTION_UPDATED]
  24607. && !ecIns._scheduler.unfinished
  24608. && !ecIns._pendingActions.length
  24609. ) {
  24610. ecIns.trigger('finished');
  24611. }
  24612. });
  24613. }
  24614. /**
  24615. * @param {Object} params
  24616. * @param {number} params.seriesIndex
  24617. * @param {Array|TypedArray} params.data
  24618. */
  24619. echartsProto.appendData = function (params) {
  24620. if (this._disposed) {
  24621. disposedWarning(this.id);
  24622. return;
  24623. }
  24624. var seriesIndex = params.seriesIndex;
  24625. var ecModel = this.getModel();
  24626. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24627. if (__DEV__) {
  24628. assert(params.data && seriesModel);
  24629. }
  24630. seriesModel.appendData(params);
  24631. // Note: `appendData` does not support that update extent of coordinate
  24632. // system, util some scenario require that. In the expected usage of
  24633. // `appendData`, the initial extent of coordinate system should better
  24634. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24635. // the extent changed while `appendData`, the location of the painted
  24636. // graphic elements have to be changed, which make the usage of
  24637. // `appendData` meaningless.
  24638. this._scheduler.unfinished = true;
  24639. };
  24640. /**
  24641. * Register event
  24642. * @method
  24643. */
  24644. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  24645. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  24646. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  24647. /**
  24648. * Prepare view instances of charts and components
  24649. * @param {module:echarts/model/Global} ecModel
  24650. * @private
  24651. */
  24652. function prepareView(ecIns, type, ecModel, scheduler) {
  24653. var isComponent = type === 'component';
  24654. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24655. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24656. var zr = ecIns._zr;
  24657. var api = ecIns._api;
  24658. for (var i = 0; i < viewList.length; i++) {
  24659. viewList[i].__alive = false;
  24660. }
  24661. isComponent
  24662. ? ecModel.eachComponent(function (componentType, model) {
  24663. componentType !== 'series' && doPrepare(model);
  24664. })
  24665. : ecModel.eachSeries(doPrepare);
  24666. function doPrepare(model) {
  24667. // Consider: id same and type changed.
  24668. var viewId = '_ec_' + model.id + '_' + model.type;
  24669. var view = viewMap[viewId];
  24670. if (!view) {
  24671. var classType = parseClassType(model.type);
  24672. var Clazz = isComponent
  24673. ? Component.getClass(classType.main, classType.sub)
  24674. : Chart.getClass(classType.sub);
  24675. if (__DEV__) {
  24676. assert(Clazz, classType.sub + ' does not exist.');
  24677. }
  24678. view = new Clazz();
  24679. view.init(ecModel, api);
  24680. viewMap[viewId] = view;
  24681. viewList.push(view);
  24682. zr.add(view.group);
  24683. }
  24684. model.__viewId = view.__id = viewId;
  24685. view.__alive = true;
  24686. view.__model = model;
  24687. view.group.__ecComponentInfo = {
  24688. mainType: model.mainType,
  24689. index: model.componentIndex
  24690. };
  24691. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24692. }
  24693. for (var i = 0; i < viewList.length;) {
  24694. var view = viewList[i];
  24695. if (!view.__alive) {
  24696. !isComponent && view.renderTask.dispose();
  24697. zr.remove(view.group);
  24698. view.dispose(ecModel, api);
  24699. viewList.splice(i, 1);
  24700. delete viewMap[view.__id];
  24701. view.__id = view.group.__ecComponentInfo = null;
  24702. }
  24703. else {
  24704. i++;
  24705. }
  24706. }
  24707. }
  24708. // /**
  24709. // * Encode visual infomation from data after data processing
  24710. // *
  24711. // * @param {module:echarts/model/Global} ecModel
  24712. // * @param {object} layout
  24713. // * @param {boolean} [layoutFilter] `true`: only layout,
  24714. // * `false`: only not layout,
  24715. // * `null`/`undefined`: all.
  24716. // * @param {string} taskBaseTag
  24717. // * @private
  24718. // */
  24719. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24720. // each(visualFuncs, function (visual, index) {
  24721. // var isLayout = visual.isLayout;
  24722. // if (layoutFilter == null
  24723. // || (layoutFilter === false && !isLayout)
  24724. // || (layoutFilter === true && isLayout)
  24725. // ) {
  24726. // visual.func(ecModel, api, payload);
  24727. // }
  24728. // });
  24729. // }
  24730. function clearColorPalette(ecModel) {
  24731. ecModel.clearColorPalette();
  24732. ecModel.eachSeries(function (seriesModel) {
  24733. seriesModel.clearColorPalette();
  24734. });
  24735. }
  24736. function render(ecIns, ecModel, api, payload) {
  24737. renderComponents(ecIns, ecModel, api, payload);
  24738. each(ecIns._chartsViews, function (chart) {
  24739. chart.__alive = false;
  24740. });
  24741. renderSeries(ecIns, ecModel, api, payload);
  24742. // Remove groups of unrendered charts
  24743. each(ecIns._chartsViews, function (chart) {
  24744. if (!chart.__alive) {
  24745. chart.remove(ecModel, api);
  24746. }
  24747. });
  24748. }
  24749. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24750. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24751. var componentModel = componentView.__model;
  24752. componentView.render(componentModel, ecModel, api, payload);
  24753. updateZ(componentModel, componentView);
  24754. });
  24755. }
  24756. /**
  24757. * Render each chart and component
  24758. * @private
  24759. */
  24760. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24761. // Render all charts
  24762. var scheduler = ecIns._scheduler;
  24763. var unfinished;
  24764. ecModel.eachSeries(function (seriesModel) {
  24765. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24766. chartView.__alive = true;
  24767. var renderTask = chartView.renderTask;
  24768. scheduler.updatePayload(renderTask, payload);
  24769. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24770. renderTask.dirty();
  24771. }
  24772. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24773. chartView.group.silent = !!seriesModel.get('silent');
  24774. updateZ(seriesModel, chartView);
  24775. updateBlend(seriesModel, chartView);
  24776. });
  24777. scheduler.unfinished |= unfinished;
  24778. // If use hover layer
  24779. updateHoverLayerStatus(ecIns, ecModel);
  24780. // Add aria
  24781. aria(ecIns._zr.dom, ecModel);
  24782. }
  24783. function performPostUpdateFuncs(ecModel, api) {
  24784. each(postUpdateFuncs, function (func) {
  24785. func(ecModel, api);
  24786. });
  24787. }
  24788. var MOUSE_EVENT_NAMES = [
  24789. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24790. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24791. ];
  24792. /**
  24793. * @private
  24794. */
  24795. echartsProto._initEvents = function () {
  24796. each(MOUSE_EVENT_NAMES, function (eveName) {
  24797. var handler = function (e) {
  24798. var ecModel = this.getModel();
  24799. var el = e.target;
  24800. var params;
  24801. var isGlobalOut = eveName === 'globalout';
  24802. // no e.target when 'globalout'.
  24803. if (isGlobalOut) {
  24804. params = {};
  24805. }
  24806. else if (el && el.dataIndex != null) {
  24807. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24808. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24809. }
  24810. // If element has custom eventData of components
  24811. else if (el && el.eventData) {
  24812. params = extend({}, el.eventData);
  24813. }
  24814. // Contract: if params prepared in mouse event,
  24815. // these properties must be specified:
  24816. // {
  24817. // componentType: string (component main type)
  24818. // componentIndex: number
  24819. // }
  24820. // Otherwise event query can not work.
  24821. if (params) {
  24822. var componentType = params.componentType;
  24823. var componentIndex = params.componentIndex;
  24824. // Special handling for historic reason: when trigger by
  24825. // markLine/markPoint/markArea, the componentType is
  24826. // 'markLine'/'markPoint'/'markArea', but we should better
  24827. // enable them to be queried by seriesIndex, since their
  24828. // option is set in each series.
  24829. if (componentType === 'markLine'
  24830. || componentType === 'markPoint'
  24831. || componentType === 'markArea'
  24832. ) {
  24833. componentType = 'series';
  24834. componentIndex = params.seriesIndex;
  24835. }
  24836. var model = componentType && componentIndex != null
  24837. && ecModel.getComponent(componentType, componentIndex);
  24838. var view = model && this[
  24839. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24840. ][model.__viewId];
  24841. if (__DEV__) {
  24842. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24843. // be missed, otherwise there is no way to distinguish source component.
  24844. // See `dataFormat.getDataParams`.
  24845. if (!isGlobalOut && !(model && view)) {
  24846. console.warn('model or view can not be found by params');
  24847. }
  24848. }
  24849. params.event = e;
  24850. params.type = eveName;
  24851. this._ecEventProcessor.eventInfo = {
  24852. targetEl: el,
  24853. packedEvent: params,
  24854. model: model,
  24855. view: view
  24856. };
  24857. this.trigger(eveName, params);
  24858. }
  24859. };
  24860. // Consider that some component (like tooltip, brush, ...)
  24861. // register zr event handler, but user event handler might
  24862. // do anything, such as call `setOption` or `dispatchAction`,
  24863. // which probably update any of the content and probably
  24864. // cause problem if it is called previous other inner handlers.
  24865. handler.zrEventfulCallAtLast = true;
  24866. this._zr.on(eveName, handler, this);
  24867. }, this);
  24868. each(eventActionMap, function (actionType, eventType) {
  24869. this._messageCenter.on(eventType, function (event) {
  24870. this.trigger(eventType, event);
  24871. }, this);
  24872. }, this);
  24873. };
  24874. /**
  24875. * @return {boolean}
  24876. */
  24877. echartsProto.isDisposed = function () {
  24878. return this._disposed;
  24879. };
  24880. /**
  24881. * Clear
  24882. */
  24883. echartsProto.clear = function () {
  24884. if (this._disposed) {
  24885. disposedWarning(this.id);
  24886. return;
  24887. }
  24888. this.setOption({ series: [] }, true);
  24889. };
  24890. /**
  24891. * Dispose instance
  24892. */
  24893. echartsProto.dispose = function () {
  24894. if (this._disposed) {
  24895. disposedWarning(this.id);
  24896. return;
  24897. }
  24898. this._disposed = true;
  24899. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24900. var api = this._api;
  24901. var ecModel = this._model;
  24902. each(this._componentsViews, function (component) {
  24903. component.dispose(ecModel, api);
  24904. });
  24905. each(this._chartsViews, function (chart) {
  24906. chart.dispose(ecModel, api);
  24907. });
  24908. // Dispose after all views disposed
  24909. this._zr.dispose();
  24910. delete instances[this.id];
  24911. };
  24912. mixin(ECharts, Eventful);
  24913. function disposedWarning(id) {
  24914. if (__DEV__) {
  24915. console.warn('Instance ' + id + ' has been disposed');
  24916. }
  24917. }
  24918. function updateHoverLayerStatus(ecIns, ecModel) {
  24919. var zr = ecIns._zr;
  24920. var storage = zr.storage;
  24921. var elCount = 0;
  24922. storage.traverse(function (el) {
  24923. elCount++;
  24924. });
  24925. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24926. ecModel.eachSeries(function (seriesModel) {
  24927. if (seriesModel.preventUsingHoverLayer) {
  24928. return;
  24929. }
  24930. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24931. if (chartView.__alive) {
  24932. chartView.group.traverse(function (el) {
  24933. // Don't switch back.
  24934. el.useHoverLayer = true;
  24935. });
  24936. }
  24937. });
  24938. }
  24939. }
  24940. /**
  24941. * Update chart progressive and blend.
  24942. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24943. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24944. */
  24945. function updateBlend(seriesModel, chartView) {
  24946. var blendMode = seriesModel.get('blendMode') || null;
  24947. if (__DEV__) {
  24948. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24949. console.warn('Only canvas support blendMode');
  24950. }
  24951. }
  24952. chartView.group.traverse(function (el) {
  24953. // FIXME marker and other components
  24954. if (!el.isGroup) {
  24955. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24956. if (el.style.blend !== blendMode) {
  24957. el.setStyle('blend', blendMode);
  24958. }
  24959. }
  24960. if (el.eachPendingDisplayable) {
  24961. el.eachPendingDisplayable(function (displayable) {
  24962. displayable.setStyle('blend', blendMode);
  24963. });
  24964. }
  24965. });
  24966. }
  24967. /**
  24968. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24969. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24970. */
  24971. function updateZ(model, view) {
  24972. var z = model.get('z');
  24973. var zlevel = model.get('zlevel');
  24974. // Set z and zlevel
  24975. view.group.traverse(function (el) {
  24976. if (el.type !== 'group') {
  24977. z != null && (el.z = z);
  24978. zlevel != null && (el.zlevel = zlevel);
  24979. }
  24980. });
  24981. }
  24982. function createExtensionAPI(ecInstance) {
  24983. var coordSysMgr = ecInstance._coordSysMgr;
  24984. return extend(new ExtensionAPI(ecInstance), {
  24985. // Inject methods
  24986. getCoordinateSystems: bind(
  24987. coordSysMgr.getCoordinateSystems, coordSysMgr
  24988. ),
  24989. getComponentByElement: function (el) {
  24990. while (el) {
  24991. var modelInfo = el.__ecComponentInfo;
  24992. if (modelInfo != null) {
  24993. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24994. }
  24995. el = el.parent;
  24996. }
  24997. }
  24998. });
  24999. }
  25000. /**
  25001. * @class
  25002. * Usage of query:
  25003. * `chart.on('click', query, handler);`
  25004. * The `query` can be:
  25005. * + The component type query string, only `mainType` or `mainType.subType`,
  25006. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25007. * + The component query object, like:
  25008. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25009. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25010. * + The data query object, like:
  25011. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25012. * + The other query object (cmponent customized query), like:
  25013. * `{element: 'some'}` (only available in custom series).
  25014. *
  25015. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25016. * same as there is no such prop in the `query` object.
  25017. */
  25018. function EventProcessor() {
  25019. // These info required: targetEl, packedEvent, model, view
  25020. this.eventInfo;
  25021. }
  25022. EventProcessor.prototype = {
  25023. constructor: EventProcessor,
  25024. normalizeQuery: function (query) {
  25025. var cptQuery = {};
  25026. var dataQuery = {};
  25027. var otherQuery = {};
  25028. // `query` is `mainType` or `mainType.subType` of component.
  25029. if (isString(query)) {
  25030. var condCptType = parseClassType(query);
  25031. // `.main` and `.sub` may be ''.
  25032. cptQuery.mainType = condCptType.main || null;
  25033. cptQuery.subType = condCptType.sub || null;
  25034. }
  25035. // `query` is an object, convert to {mainType, index, name, id}.
  25036. else {
  25037. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25038. // can not be used in `compomentModel.filterForExposedEvent`.
  25039. var suffixes = ['Index', 'Name', 'Id'];
  25040. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25041. each$1(query, function (val, key) {
  25042. var reserved = false;
  25043. for (var i = 0; i < suffixes.length; i++) {
  25044. var propSuffix = suffixes[i];
  25045. var suffixPos = key.lastIndexOf(propSuffix);
  25046. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25047. var mainType = key.slice(0, suffixPos);
  25048. // Consider `dataIndex`.
  25049. if (mainType !== 'data') {
  25050. cptQuery.mainType = mainType;
  25051. cptQuery[propSuffix.toLowerCase()] = val;
  25052. reserved = true;
  25053. }
  25054. }
  25055. }
  25056. if (dataKeys.hasOwnProperty(key)) {
  25057. dataQuery[key] = val;
  25058. reserved = true;
  25059. }
  25060. if (!reserved) {
  25061. otherQuery[key] = val;
  25062. }
  25063. });
  25064. }
  25065. return {
  25066. cptQuery: cptQuery,
  25067. dataQuery: dataQuery,
  25068. otherQuery: otherQuery
  25069. };
  25070. },
  25071. filter: function (eventType, query, args) {
  25072. // They should be assigned before each trigger call.
  25073. var eventInfo = this.eventInfo;
  25074. if (!eventInfo) {
  25075. return true;
  25076. }
  25077. var targetEl = eventInfo.targetEl;
  25078. var packedEvent = eventInfo.packedEvent;
  25079. var model = eventInfo.model;
  25080. var view = eventInfo.view;
  25081. // For event like 'globalout'.
  25082. if (!model || !view) {
  25083. return true;
  25084. }
  25085. var cptQuery = query.cptQuery;
  25086. var dataQuery = query.dataQuery;
  25087. return check(cptQuery, model, 'mainType')
  25088. && check(cptQuery, model, 'subType')
  25089. && check(cptQuery, model, 'index', 'componentIndex')
  25090. && check(cptQuery, model, 'name')
  25091. && check(cptQuery, model, 'id')
  25092. && check(dataQuery, packedEvent, 'name')
  25093. && check(dataQuery, packedEvent, 'dataIndex')
  25094. && check(dataQuery, packedEvent, 'dataType')
  25095. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25096. eventType, query.otherQuery, targetEl, packedEvent
  25097. ));
  25098. function check(query, host, prop, propOnHost) {
  25099. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25100. }
  25101. },
  25102. afterTrigger: function () {
  25103. // Make sure the eventInfo wont be used in next trigger.
  25104. this.eventInfo = null;
  25105. }
  25106. };
  25107. /**
  25108. * @type {Object} key: actionType.
  25109. * @inner
  25110. */
  25111. var actions = {};
  25112. /**
  25113. * Map eventType to actionType
  25114. * @type {Object}
  25115. */
  25116. var eventActionMap = {};
  25117. /**
  25118. * Data processor functions of each stage
  25119. * @type {Array.<Object.<string, Function>>}
  25120. * @inner
  25121. */
  25122. var dataProcessorFuncs = [];
  25123. /**
  25124. * @type {Array.<Function>}
  25125. * @inner
  25126. */
  25127. var optionPreprocessorFuncs = [];
  25128. /**
  25129. * @type {Array.<Function>}
  25130. * @inner
  25131. */
  25132. var postUpdateFuncs = [];
  25133. /**
  25134. * Visual encoding functions of each stage
  25135. * @type {Array.<Object.<string, Function>>}
  25136. */
  25137. var visualFuncs = [];
  25138. /**
  25139. * Theme storage
  25140. * @type {Object.<key, Object>}
  25141. */
  25142. var themeStorage = {};
  25143. /**
  25144. * Loading effects
  25145. */
  25146. var loadingEffects = {};
  25147. var instances = {};
  25148. var connectedGroups = {};
  25149. var idBase = new Date() - 0;
  25150. var groupIdBase = new Date() - 0;
  25151. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25152. function enableConnect(chart) {
  25153. var STATUS_PENDING = 0;
  25154. var STATUS_UPDATING = 1;
  25155. var STATUS_UPDATED = 2;
  25156. var STATUS_KEY = '__connectUpdateStatus';
  25157. function updateConnectedChartsStatus(charts, status) {
  25158. for (var i = 0; i < charts.length; i++) {
  25159. var otherChart = charts[i];
  25160. otherChart[STATUS_KEY] = status;
  25161. }
  25162. }
  25163. each(eventActionMap, function (actionType, eventType) {
  25164. chart._messageCenter.on(eventType, function (event) {
  25165. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25166. if (event && event.escapeConnect) {
  25167. return;
  25168. }
  25169. var action = chart.makeActionFromEvent(event);
  25170. var otherCharts = [];
  25171. each(instances, function (otherChart) {
  25172. if (otherChart !== chart && otherChart.group === chart.group) {
  25173. otherCharts.push(otherChart);
  25174. }
  25175. });
  25176. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25177. each(otherCharts, function (otherChart) {
  25178. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25179. otherChart.dispatchAction(action);
  25180. }
  25181. });
  25182. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25183. }
  25184. });
  25185. });
  25186. }
  25187. /**
  25188. * @param {HTMLElement} dom
  25189. * @param {Object} [theme]
  25190. * @param {Object} opts
  25191. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25192. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25193. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25194. * Can be 'auto' (the same as null/undefined)
  25195. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25196. * Can be 'auto' (the same as null/undefined)
  25197. */
  25198. function init(dom, theme$$1, opts) {
  25199. if (__DEV__) {
  25200. // Check version
  25201. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25202. throw new Error(
  25203. 'zrender/src ' + version$1
  25204. + ' is too old for ECharts ' + version
  25205. + '. Current version need ZRender '
  25206. + dependencies.zrender + '+'
  25207. );
  25208. }
  25209. if (!dom) {
  25210. throw new Error('Initialize failed: invalid dom.');
  25211. }
  25212. }
  25213. var existInstance = getInstanceByDom(dom);
  25214. if (existInstance) {
  25215. if (__DEV__) {
  25216. console.warn('There is a chart instance already initialized on the dom.');
  25217. }
  25218. return existInstance;
  25219. }
  25220. if (__DEV__) {
  25221. if (isDom(dom)
  25222. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25223. && (
  25224. (!dom.clientWidth && (!opts || opts.width == null))
  25225. || (!dom.clientHeight && (!opts || opts.height == null))
  25226. )
  25227. ) {
  25228. console.warn('Can\'t get DOM width or height. Please check '
  25229. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25230. + 'For example, you may need to call this in the callback '
  25231. + 'of window.onload.');
  25232. }
  25233. }
  25234. var chart = new ECharts(dom, theme$$1, opts);
  25235. chart.id = 'ec_' + idBase++;
  25236. instances[chart.id] = chart;
  25237. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25238. enableConnect(chart);
  25239. return chart;
  25240. }
  25241. /**
  25242. * @return {string|Array.<module:echarts~ECharts>} groupId
  25243. */
  25244. function connect(groupId) {
  25245. // Is array of charts
  25246. if (isArray(groupId)) {
  25247. var charts = groupId;
  25248. groupId = null;
  25249. // If any chart has group
  25250. each(charts, function (chart) {
  25251. if (chart.group != null) {
  25252. groupId = chart.group;
  25253. }
  25254. });
  25255. groupId = groupId || ('g_' + groupIdBase++);
  25256. each(charts, function (chart) {
  25257. chart.group = groupId;
  25258. });
  25259. }
  25260. connectedGroups[groupId] = true;
  25261. return groupId;
  25262. }
  25263. /**
  25264. * @DEPRECATED
  25265. * @return {string} groupId
  25266. */
  25267. function disConnect(groupId) {
  25268. connectedGroups[groupId] = false;
  25269. }
  25270. /**
  25271. * @return {string} groupId
  25272. */
  25273. var disconnect = disConnect;
  25274. /**
  25275. * Dispose a chart instance
  25276. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25277. */
  25278. function dispose(chart) {
  25279. if (typeof chart === 'string') {
  25280. chart = instances[chart];
  25281. }
  25282. else if (!(chart instanceof ECharts)) {
  25283. // Try to treat as dom
  25284. chart = getInstanceByDom(chart);
  25285. }
  25286. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25287. chart.dispose();
  25288. }
  25289. }
  25290. /**
  25291. * @param {HTMLElement} dom
  25292. * @return {echarts~ECharts}
  25293. */
  25294. function getInstanceByDom(dom) {
  25295. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25296. }
  25297. /**
  25298. * @param {string} key
  25299. * @return {echarts~ECharts}
  25300. */
  25301. function getInstanceById(key) {
  25302. return instances[key];
  25303. }
  25304. /**
  25305. * Register theme
  25306. */
  25307. function registerTheme(name, theme$$1) {
  25308. themeStorage[name] = theme$$1;
  25309. }
  25310. /**
  25311. * Register option preprocessor
  25312. * @param {Function} preprocessorFunc
  25313. */
  25314. function registerPreprocessor(preprocessorFunc) {
  25315. optionPreprocessorFuncs.push(preprocessorFunc);
  25316. }
  25317. /**
  25318. * @param {number} [priority=1000]
  25319. * @param {Object|Function} processor
  25320. */
  25321. function registerProcessor(priority, processor) {
  25322. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25323. }
  25324. /**
  25325. * Register postUpdater
  25326. * @param {Function} postUpdateFunc
  25327. */
  25328. function registerPostUpdate(postUpdateFunc) {
  25329. postUpdateFuncs.push(postUpdateFunc);
  25330. }
  25331. /**
  25332. * Usage:
  25333. * registerAction('someAction', 'someEvent', function () { ... });
  25334. * registerAction('someAction', function () { ... });
  25335. * registerAction(
  25336. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25337. * function () { ... }
  25338. * );
  25339. *
  25340. * @param {(string|Object)} actionInfo
  25341. * @param {string} actionInfo.type
  25342. * @param {string} [actionInfo.event]
  25343. * @param {string} [actionInfo.update]
  25344. * @param {string} [eventName]
  25345. * @param {Function} action
  25346. */
  25347. function registerAction(actionInfo, eventName, action) {
  25348. if (typeof eventName === 'function') {
  25349. action = eventName;
  25350. eventName = '';
  25351. }
  25352. var actionType = isObject(actionInfo)
  25353. ? actionInfo.type
  25354. : ([actionInfo, actionInfo = {
  25355. event: eventName
  25356. }][0]);
  25357. // Event name is all lowercase
  25358. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25359. eventName = actionInfo.event;
  25360. // Validate action type and event name.
  25361. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25362. if (!actions[actionType]) {
  25363. actions[actionType] = {action: action, actionInfo: actionInfo};
  25364. }
  25365. eventActionMap[eventName] = actionType;
  25366. }
  25367. /**
  25368. * @param {string} type
  25369. * @param {*} CoordinateSystem
  25370. */
  25371. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25372. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25373. }
  25374. /**
  25375. * Get dimensions of specified coordinate system.
  25376. * @param {string} type
  25377. * @return {Array.<string|Object>}
  25378. */
  25379. function getCoordinateSystemDimensions(type) {
  25380. var coordSysCreator = CoordinateSystemManager.get(type);
  25381. if (coordSysCreator) {
  25382. return coordSysCreator.getDimensionsInfo
  25383. ? coordSysCreator.getDimensionsInfo()
  25384. : coordSysCreator.dimensions.slice();
  25385. }
  25386. }
  25387. /**
  25388. * Layout is a special stage of visual encoding
  25389. * Most visual encoding like color are common for different chart
  25390. * But each chart has it's own layout algorithm
  25391. *
  25392. * @param {number} [priority=1000]
  25393. * @param {Function} layoutTask
  25394. */
  25395. function registerLayout(priority, layoutTask) {
  25396. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25397. }
  25398. /**
  25399. * @param {number} [priority=3000]
  25400. * @param {module:echarts/stream/Task} visualTask
  25401. */
  25402. function registerVisual(priority, visualTask) {
  25403. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25404. }
  25405. /**
  25406. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25407. */
  25408. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25409. if (isFunction(priority) || isObject(priority)) {
  25410. fn = priority;
  25411. priority = defaultPriority;
  25412. }
  25413. if (__DEV__) {
  25414. if (isNaN(priority) || priority == null) {
  25415. throw new Error('Illegal priority');
  25416. }
  25417. // Check duplicate
  25418. each(targetList, function (wrap) {
  25419. assert(wrap.__raw !== fn);
  25420. });
  25421. }
  25422. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25423. stageHandler.__prio = priority;
  25424. stageHandler.__raw = fn;
  25425. targetList.push(stageHandler);
  25426. return stageHandler;
  25427. }
  25428. /**
  25429. * @param {string} name
  25430. */
  25431. function registerLoading(name, loadingFx) {
  25432. loadingEffects[name] = loadingFx;
  25433. }
  25434. /**
  25435. * @param {Object} opts
  25436. * @param {string} [superClass]
  25437. */
  25438. function extendComponentModel(opts/*, superClass*/) {
  25439. // var Clazz = ComponentModel;
  25440. // if (superClass) {
  25441. // var classType = parseClassType(superClass);
  25442. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25443. // }
  25444. return ComponentModel.extend(opts);
  25445. }
  25446. /**
  25447. * @param {Object} opts
  25448. * @param {string} [superClass]
  25449. */
  25450. function extendComponentView(opts/*, superClass*/) {
  25451. // var Clazz = ComponentView;
  25452. // if (superClass) {
  25453. // var classType = parseClassType(superClass);
  25454. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25455. // }
  25456. return Component.extend(opts);
  25457. }
  25458. /**
  25459. * @param {Object} opts
  25460. * @param {string} [superClass]
  25461. */
  25462. function extendSeriesModel(opts/*, superClass*/) {
  25463. // var Clazz = SeriesModel;
  25464. // if (superClass) {
  25465. // superClass = 'series.' + superClass.replace('series.', '');
  25466. // var classType = parseClassType(superClass);
  25467. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25468. // }
  25469. return SeriesModel.extend(opts);
  25470. }
  25471. /**
  25472. * @param {Object} opts
  25473. * @param {string} [superClass]
  25474. */
  25475. function extendChartView(opts/*, superClass*/) {
  25476. // var Clazz = ChartView;
  25477. // if (superClass) {
  25478. // superClass = superClass.replace('series.', '');
  25479. // var classType = parseClassType(superClass);
  25480. // Clazz = ChartView.getClass(classType.main, true);
  25481. // }
  25482. return Chart.extend(opts);
  25483. }
  25484. /**
  25485. * ZRender need a canvas context to do measureText.
  25486. * But in node environment canvas may be created by node-canvas.
  25487. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25488. *
  25489. * Be careful of using it in the browser.
  25490. *
  25491. * @param {Function} creator
  25492. * @example
  25493. * var Canvas = require('canvas');
  25494. * var echarts = require('echarts');
  25495. * echarts.setCanvasCreator(function () {
  25496. * // Small size is enough.
  25497. * return new Canvas(32, 32);
  25498. * });
  25499. */
  25500. function setCanvasCreator(creator) {
  25501. $override('createCanvas', creator);
  25502. }
  25503. /**
  25504. * @param {string} mapName
  25505. * @param {Array.<Object>|Object|string} geoJson
  25506. * @param {Object} [specialAreas]
  25507. *
  25508. * @example GeoJSON
  25509. * $.get('USA.json', function (geoJson) {
  25510. * echarts.registerMap('USA', geoJson);
  25511. * // Or
  25512. * echarts.registerMap('USA', {
  25513. * geoJson: geoJson,
  25514. * specialAreas: {}
  25515. * })
  25516. * });
  25517. *
  25518. * $.get('airport.svg', function (svg) {
  25519. * echarts.registerMap('airport', {
  25520. * svg: svg
  25521. * }
  25522. * });
  25523. *
  25524. * echarts.registerMap('eu', [
  25525. * {svg: eu-topographic.svg},
  25526. * {geoJSON: eu.json}
  25527. * ])
  25528. */
  25529. function registerMap(mapName, geoJson, specialAreas) {
  25530. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25531. }
  25532. /**
  25533. * @param {string} mapName
  25534. * @return {Object}
  25535. */
  25536. function getMap(mapName) {
  25537. // For backward compatibility, only return the first one.
  25538. var records = mapDataStorage.retrieveMap(mapName);
  25539. return records && records[0] && {
  25540. geoJson: records[0].geoJSON,
  25541. specialAreas: records[0].specialAreas
  25542. };
  25543. }
  25544. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25545. registerPreprocessor(backwardCompat);
  25546. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  25547. registerLoading('default', loadingDefault);
  25548. // Default actions
  25549. registerAction({
  25550. type: 'highlight',
  25551. event: 'highlight',
  25552. update: 'highlight'
  25553. }, noop);
  25554. registerAction({
  25555. type: 'downplay',
  25556. event: 'downplay',
  25557. update: 'downplay'
  25558. }, noop);
  25559. // Default theme
  25560. registerTheme('light', lightTheme);
  25561. registerTheme('dark', theme);
  25562. // For backward compatibility, where the namespace `dataTool` will
  25563. // be mounted on `echarts` is the extension `dataTool` is imported.
  25564. var dataTool = {};
  25565. /*
  25566. * Licensed to the Apache Software Foundation (ASF) under one
  25567. * or more contributor license agreements. See the NOTICE file
  25568. * distributed with this work for additional information
  25569. * regarding copyright ownership. The ASF licenses this file
  25570. * to you under the Apache License, Version 2.0 (the
  25571. * "License"); you may not use this file except in compliance
  25572. * with the License. You may obtain a copy of the License at
  25573. *
  25574. * http://www.apache.org/licenses/LICENSE-2.0
  25575. *
  25576. * Unless required by applicable law or agreed to in writing,
  25577. * software distributed under the License is distributed on an
  25578. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25579. * KIND, either express or implied. See the License for the
  25580. * specific language governing permissions and limitations
  25581. * under the License.
  25582. */
  25583. function defaultKeyGetter(item) {
  25584. return item;
  25585. }
  25586. /**
  25587. * @param {Array} oldArr
  25588. * @param {Array} newArr
  25589. * @param {Function} oldKeyGetter
  25590. * @param {Function} newKeyGetter
  25591. * @param {Object} [context] Can be visited by this.context in callback.
  25592. */
  25593. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25594. this._old = oldArr;
  25595. this._new = newArr;
  25596. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25597. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25598. this.context = context;
  25599. }
  25600. DataDiffer.prototype = {
  25601. constructor: DataDiffer,
  25602. /**
  25603. * Callback function when add a data
  25604. */
  25605. add: function (func) {
  25606. this._add = func;
  25607. return this;
  25608. },
  25609. /**
  25610. * Callback function when update a data
  25611. */
  25612. update: function (func) {
  25613. this._update = func;
  25614. return this;
  25615. },
  25616. /**
  25617. * Callback function when remove a data
  25618. */
  25619. remove: function (func) {
  25620. this._remove = func;
  25621. return this;
  25622. },
  25623. execute: function () {
  25624. var oldArr = this._old;
  25625. var newArr = this._new;
  25626. var oldDataIndexMap = {};
  25627. var newDataIndexMap = {};
  25628. var oldDataKeyArr = [];
  25629. var newDataKeyArr = [];
  25630. var i;
  25631. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25632. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25633. for (i = 0; i < oldArr.length; i++) {
  25634. var key = oldDataKeyArr[i];
  25635. var idx = newDataIndexMap[key];
  25636. // idx can never be empty array here. see 'set null' logic below.
  25637. if (idx != null) {
  25638. // Consider there is duplicate key (for example, use dataItem.name as key).
  25639. // We should make sure every item in newArr and oldArr can be visited.
  25640. var len = idx.length;
  25641. if (len) {
  25642. len === 1 && (newDataIndexMap[key] = null);
  25643. idx = idx.shift();
  25644. }
  25645. else {
  25646. newDataIndexMap[key] = null;
  25647. }
  25648. this._update && this._update(idx, i);
  25649. }
  25650. else {
  25651. this._remove && this._remove(i);
  25652. }
  25653. }
  25654. for (var i = 0; i < newDataKeyArr.length; i++) {
  25655. var key = newDataKeyArr[i];
  25656. if (newDataIndexMap.hasOwnProperty(key)) {
  25657. var idx = newDataIndexMap[key];
  25658. if (idx == null) {
  25659. continue;
  25660. }
  25661. // idx can never be empty array here. see 'set null' logic above.
  25662. if (!idx.length) {
  25663. this._add && this._add(idx);
  25664. }
  25665. else {
  25666. for (var j = 0, len = idx.length; j < len; j++) {
  25667. this._add && this._add(idx[j]);
  25668. }
  25669. }
  25670. }
  25671. }
  25672. }
  25673. };
  25674. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25675. for (var i = 0; i < arr.length; i++) {
  25676. // Add prefix to avoid conflict with Object.prototype.
  25677. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25678. var existence = map[key];
  25679. if (existence == null) {
  25680. keyArr.push(key);
  25681. map[key] = i;
  25682. }
  25683. else {
  25684. if (!existence.length) {
  25685. map[key] = existence = [existence];
  25686. }
  25687. existence.push(i);
  25688. }
  25689. }
  25690. }
  25691. /*
  25692. * Licensed to the Apache Software Foundation (ASF) under one
  25693. * or more contributor license agreements. See the NOTICE file
  25694. * distributed with this work for additional information
  25695. * regarding copyright ownership. The ASF licenses this file
  25696. * to you under the Apache License, Version 2.0 (the
  25697. * "License"); you may not use this file except in compliance
  25698. * with the License. You may obtain a copy of the License at
  25699. *
  25700. * http://www.apache.org/licenses/LICENSE-2.0
  25701. *
  25702. * Unless required by applicable law or agreed to in writing,
  25703. * software distributed under the License is distributed on an
  25704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25705. * KIND, either express or implied. See the License for the
  25706. * specific language governing permissions and limitations
  25707. * under the License.
  25708. */
  25709. var OTHER_DIMENSIONS = createHashMap([
  25710. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25711. ]);
  25712. function summarizeDimensions(data) {
  25713. var summary = {};
  25714. var encode = summary.encode = {};
  25715. var notExtraCoordDimMap = createHashMap();
  25716. var defaultedLabel = [];
  25717. var defaultedTooltip = [];
  25718. // See the comment of `List.js#userOutput`.
  25719. var userOutput = summary.userOutput = {
  25720. dimensionNames: data.dimensions.slice(),
  25721. encode: {}
  25722. };
  25723. each$1(data.dimensions, function (dimName) {
  25724. var dimItem = data.getDimensionInfo(dimName);
  25725. var coordDim = dimItem.coordDim;
  25726. if (coordDim) {
  25727. if (__DEV__) {
  25728. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25729. }
  25730. var coordDimIndex = dimItem.coordDimIndex;
  25731. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  25732. if (!dimItem.isExtraCoord) {
  25733. notExtraCoordDimMap.set(coordDim, 1);
  25734. // Use the last coord dim (and label friendly) as default label,
  25735. // because when dataset is used, it is hard to guess which dimension
  25736. // can be value dimension. If both show x, y on label is not look good,
  25737. // and conventionally y axis is focused more.
  25738. if (mayLabelDimType(dimItem.type)) {
  25739. defaultedLabel[0] = dimName;
  25740. }
  25741. // User output encode do not contain generated coords.
  25742. // And it only has index. User can use index to retrieve value from the raw item array.
  25743. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  25744. }
  25745. if (dimItem.defaultTooltip) {
  25746. defaultedTooltip.push(dimName);
  25747. }
  25748. }
  25749. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25750. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  25751. var dimIndex = dimItem.otherDims[otherDim];
  25752. if (dimIndex != null && dimIndex !== false) {
  25753. encodeArr[dimIndex] = dimItem.name;
  25754. }
  25755. });
  25756. });
  25757. var dataDimsOnCoord = [];
  25758. var encodeFirstDimNotExtra = {};
  25759. notExtraCoordDimMap.each(function (v, coordDim) {
  25760. var dimArr = encode[coordDim];
  25761. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25762. // But should fix the case that radar axes: simplify the logic
  25763. // of `completeDimension`, remove `extraPrefix`.
  25764. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25765. // Not necessary to remove duplicate, because a data
  25766. // dim canot on more than one coordDim.
  25767. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25768. });
  25769. summary.dataDimsOnCoord = dataDimsOnCoord;
  25770. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25771. var encodeLabel = encode.label;
  25772. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25773. // in this way. Use label.formatter instead. May be remove this approach someday.
  25774. if (encodeLabel && encodeLabel.length) {
  25775. defaultedLabel = encodeLabel.slice();
  25776. }
  25777. var encodeTooltip = encode.tooltip;
  25778. if (encodeTooltip && encodeTooltip.length) {
  25779. defaultedTooltip = encodeTooltip.slice();
  25780. }
  25781. else if (!defaultedTooltip.length) {
  25782. defaultedTooltip = defaultedLabel.slice();
  25783. }
  25784. encode.defaultedLabel = defaultedLabel;
  25785. encode.defaultedTooltip = defaultedTooltip;
  25786. return summary;
  25787. }
  25788. function getOrCreateEncodeArr(encode, dim) {
  25789. if (!encode.hasOwnProperty(dim)) {
  25790. encode[dim] = [];
  25791. }
  25792. return encode[dim];
  25793. }
  25794. function getDimensionTypeByAxis(axisType) {
  25795. return axisType === 'category'
  25796. ? 'ordinal'
  25797. : axisType === 'time'
  25798. ? 'time'
  25799. : 'float';
  25800. }
  25801. function mayLabelDimType(dimType) {
  25802. // In most cases, ordinal and time do not suitable for label.
  25803. // Ordinal info can be displayed on axis. Time is too long.
  25804. return !(dimType === 'ordinal' || dimType === 'time');
  25805. }
  25806. // function findTheLastDimMayLabel(data) {
  25807. // // Get last value dim
  25808. // var dimensions = data.dimensions.slice();
  25809. // var valueType;
  25810. // var valueDim;
  25811. // while (dimensions.length && (
  25812. // valueDim = dimensions.pop(),
  25813. // valueType = data.getDimensionInfo(valueDim).type,
  25814. // valueType === 'ordinal' || valueType === 'time'
  25815. // )) {} // jshint ignore:line
  25816. // return valueDim;
  25817. // }
  25818. /*
  25819. * Licensed to the Apache Software Foundation (ASF) under one
  25820. * or more contributor license agreements. See the NOTICE file
  25821. * distributed with this work for additional information
  25822. * regarding copyright ownership. The ASF licenses this file
  25823. * to you under the Apache License, Version 2.0 (the
  25824. * "License"); you may not use this file except in compliance
  25825. * with the License. You may obtain a copy of the License at
  25826. *
  25827. * http://www.apache.org/licenses/LICENSE-2.0
  25828. *
  25829. * Unless required by applicable law or agreed to in writing,
  25830. * software distributed under the License is distributed on an
  25831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25832. * KIND, either express or implied. See the License for the
  25833. * specific language governing permissions and limitations
  25834. * under the License.
  25835. */
  25836. /**
  25837. * @class
  25838. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  25839. */
  25840. function DataDimensionInfo(opt) {
  25841. if (opt != null) {
  25842. extend(this, opt);
  25843. }
  25844. /**
  25845. * Dimension name.
  25846. * Mandatory.
  25847. * @type {string}
  25848. */
  25849. // this.name;
  25850. /**
  25851. * The origin name in dimsDef, see source helper.
  25852. * If displayName given, the tooltip will displayed vertically.
  25853. * Optional.
  25854. * @type {string}
  25855. */
  25856. // this.displayName;
  25857. /**
  25858. * Which coordSys dimension this dimension mapped to.
  25859. * A `coordDim` can be a "coordSysDim" that the coordSys required
  25860. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  25861. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  25862. * (That is determined by whether `isExtraCoord` is `true`).
  25863. * Mandatory.
  25864. * @type {string}
  25865. */
  25866. // this.coordDim;
  25867. /**
  25868. * The index of this dimension in `series.encode[coordDim]`.
  25869. * Mandatory.
  25870. * @type {number}
  25871. */
  25872. // this.coordDimIndex;
  25873. /**
  25874. * Dimension type. The enumerable values are the key of
  25875. * `dataCtors` of `data/List`.
  25876. * Optional.
  25877. * @type {string}
  25878. */
  25879. // this.type;
  25880. /**
  25881. * This index of this dimension info in `data/List#_dimensionInfos`.
  25882. * Mandatory after added to `data/List`.
  25883. * @type {number}
  25884. */
  25885. // this.index;
  25886. /**
  25887. * The format of `otherDims` is:
  25888. * ```js
  25889. * {
  25890. * tooltip: number optional,
  25891. * label: number optional,
  25892. * itemName: number optional,
  25893. * seriesName: number optional,
  25894. * }
  25895. * ```
  25896. *
  25897. * A `series.encode` can specified these fields:
  25898. * ```js
  25899. * encode: {
  25900. * // "3, 1, 5" is the index of data dimension.
  25901. * tooltip: [3, 1, 5],
  25902. * label: [0, 3],
  25903. * ...
  25904. * }
  25905. * ```
  25906. * `otherDims` is the parse result of the `series.encode` above, like:
  25907. * ```js
  25908. * // Suppose the index of this data dimension is `3`.
  25909. * this.otherDims = {
  25910. * // `3` is at the index `0` of the `encode.tooltip`
  25911. * tooltip: 0,
  25912. * // `3` is at the index `1` of the `encode.tooltip`
  25913. * label: 1
  25914. * };
  25915. * ```
  25916. *
  25917. * This prop should never be `null`/`undefined` after initialized.
  25918. * @type {Object}
  25919. */
  25920. this.otherDims = {};
  25921. /**
  25922. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  25923. * "coordSys" required.
  25924. * Mandatory.
  25925. * @type {boolean}
  25926. */
  25927. // this.isExtraCoord;
  25928. /**
  25929. * @type {module:data/OrdinalMeta}
  25930. */
  25931. // this.ordinalMeta;
  25932. /**
  25933. * Whether to create inverted indices.
  25934. * @type {boolean}
  25935. */
  25936. // this.createInvertedIndices;
  25937. }
  25938. /*
  25939. * Licensed to the Apache Software Foundation (ASF) under one
  25940. * or more contributor license agreements. See the NOTICE file
  25941. * distributed with this work for additional information
  25942. * regarding copyright ownership. The ASF licenses this file
  25943. * to you under the Apache License, Version 2.0 (the
  25944. * "License"); you may not use this file except in compliance
  25945. * with the License. You may obtain a copy of the License at
  25946. *
  25947. * http://www.apache.org/licenses/LICENSE-2.0
  25948. *
  25949. * Unless required by applicable law or agreed to in writing,
  25950. * software distributed under the License is distributed on an
  25951. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25952. * KIND, either express or implied. See the License for the
  25953. * specific language governing permissions and limitations
  25954. * under the License.
  25955. */
  25956. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25957. /**
  25958. * List for data storage
  25959. * @module echarts/data/List
  25960. */
  25961. var isObject$4 = isObject$1;
  25962. var UNDEFINED = 'undefined';
  25963. var INDEX_NOT_FOUND = -1;
  25964. // Use prefix to avoid index to be the same as otherIdList[idx],
  25965. // which will cause weird udpate animation.
  25966. var ID_PREFIX = 'e\0\0';
  25967. var dataCtors = {
  25968. 'float': typeof Float64Array === UNDEFINED
  25969. ? Array : Float64Array,
  25970. 'int': typeof Int32Array === UNDEFINED
  25971. ? Array : Int32Array,
  25972. // Ordinal data type can be string or int
  25973. 'ordinal': Array,
  25974. 'number': Array,
  25975. 'time': Array
  25976. };
  25977. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25978. // different from the Ctor of typed array.
  25979. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25980. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25981. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25982. function getIndicesCtor(list) {
  25983. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25984. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25985. }
  25986. function cloneChunk(originalChunk) {
  25987. var Ctor = originalChunk.constructor;
  25988. // Only shallow clone is enough when Array.
  25989. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25990. }
  25991. var TRANSFERABLE_PROPERTIES = [
  25992. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25993. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25994. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25995. ];
  25996. var CLONE_PROPERTIES = [
  25997. '_extent', '_approximateExtent', '_rawExtent'
  25998. ];
  25999. function transferProperties(target, source) {
  26000. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26001. if (source.hasOwnProperty(propName)) {
  26002. target[propName] = source[propName];
  26003. }
  26004. });
  26005. target.__wrappedMethods = source.__wrappedMethods;
  26006. each$1(CLONE_PROPERTIES, function (propName) {
  26007. target[propName] = clone(source[propName]);
  26008. });
  26009. target._calculationInfo = extend(source._calculationInfo);
  26010. }
  26011. /**
  26012. * @constructor
  26013. * @alias module:echarts/data/List
  26014. *
  26015. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26016. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26017. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26018. * @param {module:echarts/model/Model} hostModel
  26019. */
  26020. var List = function (dimensions, hostModel) {
  26021. dimensions = dimensions || ['x', 'y'];
  26022. var dimensionInfos = {};
  26023. var dimensionNames = [];
  26024. var invertedIndicesMap = {};
  26025. for (var i = 0; i < dimensions.length; i++) {
  26026. // Use the original dimensions[i], where other flag props may exists.
  26027. var dimensionInfo = dimensions[i];
  26028. if (isString(dimensionInfo)) {
  26029. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26030. }
  26031. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26032. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26033. }
  26034. var dimensionName = dimensionInfo.name;
  26035. dimensionInfo.type = dimensionInfo.type || 'float';
  26036. if (!dimensionInfo.coordDim) {
  26037. dimensionInfo.coordDim = dimensionName;
  26038. dimensionInfo.coordDimIndex = 0;
  26039. }
  26040. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26041. dimensionNames.push(dimensionName);
  26042. dimensionInfos[dimensionName] = dimensionInfo;
  26043. dimensionInfo.index = i;
  26044. if (dimensionInfo.createInvertedIndices) {
  26045. invertedIndicesMap[dimensionName] = [];
  26046. }
  26047. }
  26048. /**
  26049. * @readOnly
  26050. * @type {Array.<string>}
  26051. */
  26052. this.dimensions = dimensionNames;
  26053. /**
  26054. * Infomation of each data dimension, like data type.
  26055. * @type {Object}
  26056. */
  26057. this._dimensionInfos = dimensionInfos;
  26058. /**
  26059. * @type {module:echarts/model/Model}
  26060. */
  26061. this.hostModel = hostModel;
  26062. /**
  26063. * @type {module:echarts/model/Model}
  26064. */
  26065. this.dataType;
  26066. /**
  26067. * Indices stores the indices of data subset after filtered.
  26068. * This data subset will be used in chart.
  26069. * @type {Array.<number>}
  26070. * @readOnly
  26071. */
  26072. this._indices = null;
  26073. this._count = 0;
  26074. this._rawCount = 0;
  26075. /**
  26076. * Data storage
  26077. * @type {Object.<key, Array.<TypedArray|Array>>}
  26078. * @private
  26079. */
  26080. this._storage = {};
  26081. /**
  26082. * @type {Array.<string>}
  26083. */
  26084. this._nameList = [];
  26085. /**
  26086. * @type {Array.<string>}
  26087. */
  26088. this._idList = [];
  26089. /**
  26090. * Models of data option is stored sparse for optimizing memory cost
  26091. * @type {Array.<module:echarts/model/Model>}
  26092. * @private
  26093. */
  26094. this._optionModels = [];
  26095. /**
  26096. * Global visual properties after visual coding
  26097. * @type {Object}
  26098. * @private
  26099. */
  26100. this._visual = {};
  26101. /**
  26102. * Globel layout properties.
  26103. * @type {Object}
  26104. * @private
  26105. */
  26106. this._layout = {};
  26107. /**
  26108. * Item visual properties after visual coding
  26109. * @type {Array.<Object>}
  26110. * @private
  26111. */
  26112. this._itemVisuals = [];
  26113. /**
  26114. * Key: visual type, Value: boolean
  26115. * @type {Object}
  26116. * @readOnly
  26117. */
  26118. this.hasItemVisual = {};
  26119. /**
  26120. * Item layout properties after layout
  26121. * @type {Array.<Object>}
  26122. * @private
  26123. */
  26124. this._itemLayouts = [];
  26125. /**
  26126. * Graphic elemnents
  26127. * @type {Array.<module:zrender/Element>}
  26128. * @private
  26129. */
  26130. this._graphicEls = [];
  26131. /**
  26132. * Max size of each chunk.
  26133. * @type {number}
  26134. * @private
  26135. */
  26136. this._chunkSize = 1e5;
  26137. /**
  26138. * @type {number}
  26139. * @private
  26140. */
  26141. this._chunkCount = 0;
  26142. /**
  26143. * @type {Array.<Array|Object>}
  26144. * @private
  26145. */
  26146. this._rawData;
  26147. /**
  26148. * Raw extent will not be cloned, but only transfered.
  26149. * It will not be calculated util needed.
  26150. * key: dim,
  26151. * value: {end: number, extent: Array.<number>}
  26152. * @type {Object}
  26153. * @private
  26154. */
  26155. this._rawExtent = {};
  26156. /**
  26157. * @type {Object}
  26158. * @private
  26159. */
  26160. this._extent = {};
  26161. /**
  26162. * key: dim
  26163. * value: extent
  26164. * @type {Object}
  26165. * @private
  26166. */
  26167. this._approximateExtent = {};
  26168. /**
  26169. * Cache summary info for fast visit. See "dimensionHelper".
  26170. * @type {Object}
  26171. * @private
  26172. */
  26173. this._dimensionsSummary = summarizeDimensions(this);
  26174. /**
  26175. * @type {Object.<Array|TypedArray>}
  26176. * @private
  26177. */
  26178. this._invertedIndicesMap = invertedIndicesMap;
  26179. /**
  26180. * @type {Object}
  26181. * @private
  26182. */
  26183. this._calculationInfo = {};
  26184. /**
  26185. * User output info of this data.
  26186. * DO NOT use it in other places!
  26187. *
  26188. * When preparing user params for user callbacks, we have
  26189. * to clone these inner data structures to prevent users
  26190. * from modifying them to effect built-in logic. And for
  26191. * performance consideration we make this `userOutput` to
  26192. * avoid clone them too many times.
  26193. *
  26194. * @type {Object}
  26195. * @readOnly
  26196. */
  26197. this.userOutput = this._dimensionsSummary.userOutput;
  26198. };
  26199. var listProto = List.prototype;
  26200. listProto.type = 'list';
  26201. /**
  26202. * If each data item has it's own option
  26203. * @type {boolean}
  26204. */
  26205. listProto.hasItemOption = true;
  26206. /**
  26207. * The meanings of the input parameter `dim`:
  26208. *
  26209. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26210. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26211. * + If dim is a number-like string (e.g., `"1"`):
  26212. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26213. * + If not, it will be converted to a number, which means the index of the dimension.
  26214. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26215. * dimension setting, although now it seems that it is not a good idea.)
  26216. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26217. * if no dimension name is defined as `"1"`.
  26218. * + If dim is a not-number-like string, it means the concrete dim name.
  26219. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26220. * or customized in `dimensions` property of option like `"age"`.
  26221. *
  26222. * Get dimension name
  26223. * @param {string|number} dim See above.
  26224. * @return {string} Concrete dim name.
  26225. */
  26226. listProto.getDimension = function (dim) {
  26227. if (typeof dim === 'number'
  26228. // If being a number-like string but not being defined a dimension name.
  26229. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26230. ) {
  26231. dim = this.dimensions[dim];
  26232. }
  26233. return dim;
  26234. };
  26235. /**
  26236. * Get type and calculation info of particular dimension
  26237. * @param {string|number} dim
  26238. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26239. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26240. */
  26241. listProto.getDimensionInfo = function (dim) {
  26242. // Do not clone, because there may be categories in dimInfo.
  26243. return this._dimensionInfos[this.getDimension(dim)];
  26244. };
  26245. /**
  26246. * @return {Array.<string>} concrete dimension name list on coord.
  26247. */
  26248. listProto.getDimensionsOnCoord = function () {
  26249. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26250. };
  26251. /**
  26252. * @param {string} coordDim
  26253. * @param {number} [idx] A coordDim may map to more than one data dim.
  26254. * If idx is `true`, return a array of all mapped dims.
  26255. * If idx is not specified, return the first dim not extra.
  26256. * @return {string|Array.<string>} concrete data dim.
  26257. * If idx is number, and not found, return null/undefined.
  26258. * If idx is `true`, and not found, return empty array (always return array).
  26259. */
  26260. listProto.mapDimension = function (coordDim, idx) {
  26261. var dimensionsSummary = this._dimensionsSummary;
  26262. if (idx == null) {
  26263. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26264. }
  26265. var dims = dimensionsSummary.encode[coordDim];
  26266. return idx === true
  26267. // always return array if idx is `true`
  26268. ? (dims || []).slice()
  26269. : (dims && dims[idx]);
  26270. };
  26271. /**
  26272. * Initialize from data
  26273. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26274. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26275. * defualt label/tooltip.
  26276. * A name can be specified in encode.itemName,
  26277. * or dataItem.name (only for series option data),
  26278. * or provided in nameList from outside.
  26279. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26280. */
  26281. listProto.initData = function (data, nameList, dimValueGetter) {
  26282. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26283. if (notProvider) {
  26284. data = new DefaultDataProvider(data, this.dimensions.length);
  26285. }
  26286. if (__DEV__) {
  26287. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26288. throw new Error('Inavlid data provider.');
  26289. }
  26290. }
  26291. this._rawData = data;
  26292. // Clear
  26293. this._storage = {};
  26294. this._indices = null;
  26295. this._nameList = nameList || [];
  26296. this._idList = [];
  26297. this._nameRepeatCount = {};
  26298. if (!dimValueGetter) {
  26299. this.hasItemOption = false;
  26300. }
  26301. /**
  26302. * @readOnly
  26303. */
  26304. this.defaultDimValueGetter = defaultDimValueGetters[
  26305. this._rawData.getSource().sourceFormat
  26306. ];
  26307. // Default dim value getter
  26308. this._dimValueGetter = dimValueGetter = dimValueGetter
  26309. || this.defaultDimValueGetter;
  26310. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26311. // Reset raw extent.
  26312. this._rawExtent = {};
  26313. this._initDataFromProvider(0, data.count());
  26314. // If data has no item option.
  26315. if (data.pure) {
  26316. this.hasItemOption = false;
  26317. }
  26318. };
  26319. listProto.getProvider = function () {
  26320. return this._rawData;
  26321. };
  26322. /**
  26323. * Caution: Can be only called on raw data (before `this._indices` created).
  26324. */
  26325. listProto.appendData = function (data) {
  26326. if (__DEV__) {
  26327. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26328. }
  26329. var rawData = this._rawData;
  26330. var start = this.count();
  26331. rawData.appendData(data);
  26332. var end = rawData.count();
  26333. if (!rawData.persistent) {
  26334. end += start;
  26335. }
  26336. this._initDataFromProvider(start, end);
  26337. };
  26338. /**
  26339. * Caution: Can be only called on raw data (before `this._indices` created).
  26340. * This method does not modify `rawData` (`dataProvider`), but only
  26341. * add values to storage.
  26342. *
  26343. * The final count will be increased by `Math.max(values.length, names.length)`.
  26344. *
  26345. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26346. * [
  26347. * [12, 33, 44],
  26348. * [NaN, 43, 1],
  26349. * ['-', 'asdf', 0]
  26350. * ]
  26351. * Each item is exaclty cooresponding to a dimension.
  26352. * @param {Array.<string>} [names]
  26353. */
  26354. listProto.appendValues = function (values, names) {
  26355. var chunkSize = this._chunkSize;
  26356. var storage = this._storage;
  26357. var dimensions = this.dimensions;
  26358. var dimLen = dimensions.length;
  26359. var rawExtent = this._rawExtent;
  26360. var start = this.count();
  26361. var end = start + Math.max(values.length, names ? names.length : 0);
  26362. var originalChunkCount = this._chunkCount;
  26363. for (var i = 0; i < dimLen; i++) {
  26364. var dim = dimensions[i];
  26365. if (!rawExtent[dim]) {
  26366. rawExtent[dim] = getInitialExtent();
  26367. }
  26368. if (!storage[dim]) {
  26369. storage[dim] = [];
  26370. }
  26371. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26372. this._chunkCount = storage[dim].length;
  26373. }
  26374. var emptyDataItem = new Array(dimLen);
  26375. for (var idx = start; idx < end; idx++) {
  26376. var sourceIdx = idx - start;
  26377. var chunkIndex = Math.floor(idx / chunkSize);
  26378. var chunkOffset = idx % chunkSize;
  26379. // Store the data by dimensions
  26380. for (var k = 0; k < dimLen; k++) {
  26381. var dim = dimensions[k];
  26382. var val = this._dimValueGetterArrayRows(
  26383. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26384. );
  26385. storage[dim][chunkIndex][chunkOffset] = val;
  26386. var dimRawExtent = rawExtent[dim];
  26387. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26388. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26389. }
  26390. if (names) {
  26391. this._nameList[idx] = names[sourceIdx];
  26392. }
  26393. }
  26394. this._rawCount = this._count = end;
  26395. // Reset data extent
  26396. this._extent = {};
  26397. prepareInvertedIndex(this);
  26398. };
  26399. listProto._initDataFromProvider = function (start, end) {
  26400. // Optimize.
  26401. if (start >= end) {
  26402. return;
  26403. }
  26404. var chunkSize = this._chunkSize;
  26405. var rawData = this._rawData;
  26406. var storage = this._storage;
  26407. var dimensions = this.dimensions;
  26408. var dimLen = dimensions.length;
  26409. var dimensionInfoMap = this._dimensionInfos;
  26410. var nameList = this._nameList;
  26411. var idList = this._idList;
  26412. var rawExtent = this._rawExtent;
  26413. var nameRepeatCount = this._nameRepeatCount = {};
  26414. var nameDimIdx;
  26415. var originalChunkCount = this._chunkCount;
  26416. for (var i = 0; i < dimLen; i++) {
  26417. var dim = dimensions[i];
  26418. if (!rawExtent[dim]) {
  26419. rawExtent[dim] = getInitialExtent();
  26420. }
  26421. var dimInfo = dimensionInfoMap[dim];
  26422. if (dimInfo.otherDims.itemName === 0) {
  26423. nameDimIdx = this._nameDimIdx = i;
  26424. }
  26425. if (dimInfo.otherDims.itemId === 0) {
  26426. this._idDimIdx = i;
  26427. }
  26428. if (!storage[dim]) {
  26429. storage[dim] = [];
  26430. }
  26431. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26432. this._chunkCount = storage[dim].length;
  26433. }
  26434. var dataItem = new Array(dimLen);
  26435. for (var idx = start; idx < end; idx++) {
  26436. // NOTICE: Try not to write things into dataItem
  26437. dataItem = rawData.getItem(idx, dataItem);
  26438. // Each data item is value
  26439. // [1, 2]
  26440. // 2
  26441. // Bar chart, line chart which uses category axis
  26442. // only gives the 'y' value. 'x' value is the indices of category
  26443. // Use a tempValue to normalize the value to be a (x, y) value
  26444. var chunkIndex = Math.floor(idx / chunkSize);
  26445. var chunkOffset = idx % chunkSize;
  26446. // Store the data by dimensions
  26447. for (var k = 0; k < dimLen; k++) {
  26448. var dim = dimensions[k];
  26449. var dimStorage = storage[dim][chunkIndex];
  26450. // PENDING NULL is empty or zero
  26451. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26452. dimStorage[chunkOffset] = val;
  26453. var dimRawExtent = rawExtent[dim];
  26454. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26455. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26456. }
  26457. // ??? FIXME not check by pure but sourceFormat?
  26458. // TODO refactor these logic.
  26459. if (!rawData.pure) {
  26460. var name = nameList[idx];
  26461. if (dataItem && name == null) {
  26462. // If dataItem is {name: ...}, it has highest priority.
  26463. // That is appropriate for many common cases.
  26464. if (dataItem.name != null) {
  26465. // There is no other place to persistent dataItem.name,
  26466. // so save it to nameList.
  26467. nameList[idx] = name = dataItem.name;
  26468. }
  26469. else if (nameDimIdx != null) {
  26470. var nameDim = dimensions[nameDimIdx];
  26471. var nameDimChunk = storage[nameDim][chunkIndex];
  26472. if (nameDimChunk) {
  26473. name = nameDimChunk[chunkOffset];
  26474. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26475. if (ordinalMeta && ordinalMeta.categories.length) {
  26476. name = ordinalMeta.categories[name];
  26477. }
  26478. }
  26479. }
  26480. }
  26481. // Try using the id in option
  26482. // id or name is used on dynamical data, mapping old and new items.
  26483. var id = dataItem == null ? null : dataItem.id;
  26484. if (id == null && name != null) {
  26485. // Use name as id and add counter to avoid same name
  26486. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26487. id = name;
  26488. if (nameRepeatCount[name] > 0) {
  26489. id += '__ec__' + nameRepeatCount[name];
  26490. }
  26491. nameRepeatCount[name]++;
  26492. }
  26493. id != null && (idList[idx] = id);
  26494. }
  26495. }
  26496. if (!rawData.persistent && rawData.clean) {
  26497. // Clean unused data if data source is typed array.
  26498. rawData.clean();
  26499. }
  26500. this._rawCount = this._count = end;
  26501. // Reset data extent
  26502. this._extent = {};
  26503. prepareInvertedIndex(this);
  26504. };
  26505. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26506. var DataCtor = dataCtors[dimInfo.type];
  26507. var lastChunkIndex = chunkCount - 1;
  26508. var dim = dimInfo.name;
  26509. var resizeChunkArray = storage[dim][lastChunkIndex];
  26510. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26511. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26512. // The cost of the copy is probably inconsiderable
  26513. // within the initial chunkSize.
  26514. for (var j = 0; j < resizeChunkArray.length; j++) {
  26515. newStore[j] = resizeChunkArray[j];
  26516. }
  26517. storage[dim][lastChunkIndex] = newStore;
  26518. }
  26519. // Create new chunks.
  26520. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26521. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26522. }
  26523. }
  26524. function prepareInvertedIndex(list) {
  26525. var invertedIndicesMap = list._invertedIndicesMap;
  26526. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26527. var dimInfo = list._dimensionInfos[dim];
  26528. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26529. var ordinalMeta = dimInfo.ordinalMeta;
  26530. if (ordinalMeta) {
  26531. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26532. ordinalMeta.categories.length
  26533. );
  26534. // The default value of TypedArray is 0. To avoid miss
  26535. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26536. for (var i = 0; i < invertedIndices.length; i++) {
  26537. invertedIndices[i] = INDEX_NOT_FOUND;
  26538. }
  26539. for (var i = 0; i < list._count; i++) {
  26540. // Only support the case that all values are distinct.
  26541. invertedIndices[list.get(dim, i)] = i;
  26542. }
  26543. }
  26544. });
  26545. }
  26546. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26547. var val;
  26548. if (dimIndex != null) {
  26549. var chunkSize = list._chunkSize;
  26550. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26551. var chunkOffset = rawIndex % chunkSize;
  26552. var dim = list.dimensions[dimIndex];
  26553. var chunk = list._storage[dim][chunkIndex];
  26554. if (chunk) {
  26555. val = chunk[chunkOffset];
  26556. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26557. if (ordinalMeta && ordinalMeta.categories.length) {
  26558. val = ordinalMeta.categories[val];
  26559. }
  26560. }
  26561. }
  26562. return val;
  26563. }
  26564. /**
  26565. * @return {number}
  26566. */
  26567. listProto.count = function () {
  26568. return this._count;
  26569. };
  26570. listProto.getIndices = function () {
  26571. var newIndices;
  26572. var indices = this._indices;
  26573. if (indices) {
  26574. var Ctor = indices.constructor;
  26575. var thisCount = this._count;
  26576. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26577. if (Ctor === Array) {
  26578. newIndices = new Ctor(thisCount);
  26579. for (var i = 0; i < thisCount; i++) {
  26580. newIndices[i] = indices[i];
  26581. }
  26582. }
  26583. else {
  26584. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26585. }
  26586. }
  26587. else {
  26588. var Ctor = getIndicesCtor(this);
  26589. var newIndices = new Ctor(this.count());
  26590. for (var i = 0; i < newIndices.length; i++) {
  26591. newIndices[i] = i;
  26592. }
  26593. }
  26594. return newIndices;
  26595. };
  26596. /**
  26597. * Get value. Return NaN if idx is out of range.
  26598. * @param {string} dim Dim must be concrete name.
  26599. * @param {number} idx
  26600. * @param {boolean} stack
  26601. * @return {number}
  26602. */
  26603. listProto.get = function (dim, idx /*, stack */) {
  26604. if (!(idx >= 0 && idx < this._count)) {
  26605. return NaN;
  26606. }
  26607. var storage = this._storage;
  26608. if (!storage[dim]) {
  26609. // TODO Warn ?
  26610. return NaN;
  26611. }
  26612. idx = this.getRawIndex(idx);
  26613. var chunkIndex = Math.floor(idx / this._chunkSize);
  26614. var chunkOffset = idx % this._chunkSize;
  26615. var chunkStore = storage[dim][chunkIndex];
  26616. var value = chunkStore[chunkOffset];
  26617. // FIXME ordinal data type is not stackable
  26618. // if (stack) {
  26619. // var dimensionInfo = this._dimensionInfos[dim];
  26620. // if (dimensionInfo && dimensionInfo.stackable) {
  26621. // var stackedOn = this.stackedOn;
  26622. // while (stackedOn) {
  26623. // // Get no stacked data of stacked on
  26624. // var stackedValue = stackedOn.get(dim, idx);
  26625. // // Considering positive stack, negative stack and empty data
  26626. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26627. // || (value <= 0 && stackedValue < 0) // Negative stack
  26628. // ) {
  26629. // value += stackedValue;
  26630. // }
  26631. // stackedOn = stackedOn.stackedOn;
  26632. // }
  26633. // }
  26634. // }
  26635. return value;
  26636. };
  26637. /**
  26638. * @param {string} dim concrete dim
  26639. * @param {number} rawIndex
  26640. * @return {number|string}
  26641. */
  26642. listProto.getByRawIndex = function (dim, rawIdx) {
  26643. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26644. return NaN;
  26645. }
  26646. var dimStore = this._storage[dim];
  26647. if (!dimStore) {
  26648. // TODO Warn ?
  26649. return NaN;
  26650. }
  26651. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26652. var chunkOffset = rawIdx % this._chunkSize;
  26653. var chunkStore = dimStore[chunkIndex];
  26654. return chunkStore[chunkOffset];
  26655. };
  26656. /**
  26657. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26658. * Hack a much simpler _getFast
  26659. * @private
  26660. */
  26661. listProto._getFast = function (dim, rawIdx) {
  26662. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26663. var chunkOffset = rawIdx % this._chunkSize;
  26664. var chunkStore = this._storage[dim][chunkIndex];
  26665. return chunkStore[chunkOffset];
  26666. };
  26667. /**
  26668. * Get value for multi dimensions.
  26669. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26670. * @param {number} idx
  26671. * @return {number}
  26672. */
  26673. listProto.getValues = function (dimensions, idx /*, stack */) {
  26674. var values = [];
  26675. if (!isArray(dimensions)) {
  26676. // stack = idx;
  26677. idx = dimensions;
  26678. dimensions = this.dimensions;
  26679. }
  26680. for (var i = 0, len = dimensions.length; i < len; i++) {
  26681. values.push(this.get(dimensions[i], idx /*, stack */));
  26682. }
  26683. return values;
  26684. };
  26685. /**
  26686. * If value is NaN. Inlcuding '-'
  26687. * Only check the coord dimensions.
  26688. * @param {string} dim
  26689. * @param {number} idx
  26690. * @return {number}
  26691. */
  26692. listProto.hasValue = function (idx) {
  26693. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26694. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26695. // Ordinal type originally can be string or number.
  26696. // But when an ordinal type is used on coord, it can
  26697. // not be string but only number. So we can also use isNaN.
  26698. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  26699. return false;
  26700. }
  26701. }
  26702. return true;
  26703. };
  26704. /**
  26705. * Get extent of data in one dimension
  26706. * @param {string} dim
  26707. * @param {boolean} stack
  26708. */
  26709. listProto.getDataExtent = function (dim /*, stack */) {
  26710. // Make sure use concrete dim as cache name.
  26711. dim = this.getDimension(dim);
  26712. var dimData = this._storage[dim];
  26713. var initialExtent = getInitialExtent();
  26714. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26715. if (!dimData) {
  26716. return initialExtent;
  26717. }
  26718. // Make more strict checkings to ensure hitting cache.
  26719. var currEnd = this.count();
  26720. // var cacheName = [dim, !!stack].join('_');
  26721. // var cacheName = dim;
  26722. // Consider the most cases when using data zoom, `getDataExtent`
  26723. // happened before filtering. We cache raw extent, which is not
  26724. // necessary to be cleared and recalculated when restore data.
  26725. var useRaw = !this._indices; // && !stack;
  26726. var dimExtent;
  26727. if (useRaw) {
  26728. return this._rawExtent[dim].slice();
  26729. }
  26730. dimExtent = this._extent[dim];
  26731. if (dimExtent) {
  26732. return dimExtent.slice();
  26733. }
  26734. dimExtent = initialExtent;
  26735. var min = dimExtent[0];
  26736. var max = dimExtent[1];
  26737. for (var i = 0; i < currEnd; i++) {
  26738. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26739. var value = this._getFast(dim, this.getRawIndex(i));
  26740. value < min && (min = value);
  26741. value > max && (max = value);
  26742. }
  26743. dimExtent = [min, max];
  26744. this._extent[dim] = dimExtent;
  26745. return dimExtent;
  26746. };
  26747. /**
  26748. * Optimize for the scenario that data is filtered by a given extent.
  26749. * Consider that if data amount is more than hundreds of thousand,
  26750. * extent calculation will cost more than 10ms and the cache will
  26751. * be erased because of the filtering.
  26752. */
  26753. listProto.getApproximateExtent = function (dim /*, stack */) {
  26754. dim = this.getDimension(dim);
  26755. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26756. };
  26757. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26758. dim = this.getDimension(dim);
  26759. this._approximateExtent[dim] = extent.slice();
  26760. };
  26761. /**
  26762. * @param {string} key
  26763. * @return {*}
  26764. */
  26765. listProto.getCalculationInfo = function (key) {
  26766. return this._calculationInfo[key];
  26767. };
  26768. /**
  26769. * @param {string|Object} key or k-v object
  26770. * @param {*} [value]
  26771. */
  26772. listProto.setCalculationInfo = function (key, value) {
  26773. isObject$4(key)
  26774. ? extend(this._calculationInfo, key)
  26775. : (this._calculationInfo[key] = value);
  26776. };
  26777. /**
  26778. * Get sum of data in one dimension
  26779. * @param {string} dim
  26780. */
  26781. listProto.getSum = function (dim /*, stack */) {
  26782. var dimData = this._storage[dim];
  26783. var sum = 0;
  26784. if (dimData) {
  26785. for (var i = 0, len = this.count(); i < len; i++) {
  26786. var value = this.get(dim, i /*, stack */);
  26787. if (!isNaN(value)) {
  26788. sum += value;
  26789. }
  26790. }
  26791. }
  26792. return sum;
  26793. };
  26794. /**
  26795. * Get median of data in one dimension
  26796. * @param {string} dim
  26797. */
  26798. listProto.getMedian = function (dim /*, stack */) {
  26799. var dimDataArray = [];
  26800. // map all data of one dimension
  26801. this.each(dim, function (val, idx) {
  26802. if (!isNaN(val)) {
  26803. dimDataArray.push(val);
  26804. }
  26805. });
  26806. // TODO
  26807. // Use quick select?
  26808. // immutability & sort
  26809. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26810. return a - b;
  26811. });
  26812. var len = this.count();
  26813. // calculate median
  26814. return len === 0
  26815. ? 0
  26816. : len % 2 === 1
  26817. ? sortedDimDataArray[(len - 1) / 2]
  26818. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26819. };
  26820. // /**
  26821. // * Retreive the index with given value
  26822. // * @param {string} dim Concrete dimension.
  26823. // * @param {number} value
  26824. // * @return {number}
  26825. // */
  26826. // Currently incorrect: should return dataIndex but not rawIndex.
  26827. // Do not fix it until this method is to be used somewhere.
  26828. // FIXME Precision of float value
  26829. // listProto.indexOf = function (dim, value) {
  26830. // var storage = this._storage;
  26831. // var dimData = storage[dim];
  26832. // var chunkSize = this._chunkSize;
  26833. // if (dimData) {
  26834. // for (var i = 0, len = this.count(); i < len; i++) {
  26835. // var chunkIndex = Math.floor(i / chunkSize);
  26836. // var chunkOffset = i % chunkSize;
  26837. // if (dimData[chunkIndex][chunkOffset] === value) {
  26838. // return i;
  26839. // }
  26840. // }
  26841. // }
  26842. // return -1;
  26843. // };
  26844. /**
  26845. * Only support the dimension which inverted index created.
  26846. * Do not support other cases until required.
  26847. * @param {string} concrete dim
  26848. * @param {number|string} value
  26849. * @return {number} rawIndex
  26850. */
  26851. listProto.rawIndexOf = function (dim, value) {
  26852. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26853. if (__DEV__) {
  26854. if (!invertedIndices) {
  26855. throw new Error('Do not supported yet');
  26856. }
  26857. }
  26858. var rawIndex = invertedIndices[value];
  26859. if (rawIndex == null || isNaN(rawIndex)) {
  26860. return INDEX_NOT_FOUND;
  26861. }
  26862. return rawIndex;
  26863. };
  26864. /**
  26865. * Retreive the index with given name
  26866. * @param {number} idx
  26867. * @param {number} name
  26868. * @return {number}
  26869. */
  26870. listProto.indexOfName = function (name) {
  26871. for (var i = 0, len = this.count(); i < len; i++) {
  26872. if (this.getName(i) === name) {
  26873. return i;
  26874. }
  26875. }
  26876. return -1;
  26877. };
  26878. /**
  26879. * Retreive the index with given raw data index
  26880. * @param {number} idx
  26881. * @param {number} name
  26882. * @return {number}
  26883. */
  26884. listProto.indexOfRawIndex = function (rawIndex) {
  26885. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26886. return -1;
  26887. }
  26888. if (!this._indices) {
  26889. return rawIndex;
  26890. }
  26891. // Indices are ascending
  26892. var indices = this._indices;
  26893. // If rawIndex === dataIndex
  26894. var rawDataIndex = indices[rawIndex];
  26895. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26896. return rawIndex;
  26897. }
  26898. var left = 0;
  26899. var right = this._count - 1;
  26900. while (left <= right) {
  26901. var mid = (left + right) / 2 | 0;
  26902. if (indices[mid] < rawIndex) {
  26903. left = mid + 1;
  26904. }
  26905. else if (indices[mid] > rawIndex) {
  26906. right = mid - 1;
  26907. }
  26908. else {
  26909. return mid;
  26910. }
  26911. }
  26912. return -1;
  26913. };
  26914. /**
  26915. * Retreive the index of nearest value
  26916. * @param {string} dim
  26917. * @param {number} value
  26918. * @param {number} [maxDistance=Infinity]
  26919. * @return {Array.<number>} If and only if multiple indices has
  26920. * the same value, they are put to the result.
  26921. */
  26922. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26923. var storage = this._storage;
  26924. var dimData = storage[dim];
  26925. var nearestIndices = [];
  26926. if (!dimData) {
  26927. return nearestIndices;
  26928. }
  26929. if (maxDistance == null) {
  26930. maxDistance = Infinity;
  26931. }
  26932. var minDist = Infinity;
  26933. var minDiff = -1;
  26934. var nearestIndicesLen = 0;
  26935. // Check the test case of `test/ut/spec/data/List.js`.
  26936. for (var i = 0, len = this.count(); i < len; i++) {
  26937. var diff = value - this.get(dim, i);
  26938. var dist = Math.abs(diff);
  26939. if (dist <= maxDistance) {
  26940. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  26941. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  26942. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  26943. // So we chose the one that `diff >= 0` in this csae.
  26944. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  26945. // should be push to `nearestIndices`.
  26946. if (dist < minDist
  26947. || (dist === minDist && diff >= 0 && minDiff < 0)
  26948. ) {
  26949. minDist = dist;
  26950. minDiff = diff;
  26951. nearestIndicesLen = 0;
  26952. }
  26953. if (diff === minDiff) {
  26954. nearestIndices[nearestIndicesLen++] = i;
  26955. }
  26956. }
  26957. }
  26958. nearestIndices.length = nearestIndicesLen;
  26959. return nearestIndices;
  26960. };
  26961. /**
  26962. * Get raw data index
  26963. * @param {number} idx
  26964. * @return {number}
  26965. */
  26966. listProto.getRawIndex = getRawIndexWithoutIndices;
  26967. function getRawIndexWithoutIndices(idx) {
  26968. return idx;
  26969. }
  26970. function getRawIndexWithIndices(idx) {
  26971. if (idx < this._count && idx >= 0) {
  26972. return this._indices[idx];
  26973. }
  26974. return -1;
  26975. }
  26976. /**
  26977. * Get raw data item
  26978. * @param {number} idx
  26979. * @return {number}
  26980. */
  26981. listProto.getRawDataItem = function (idx) {
  26982. if (!this._rawData.persistent) {
  26983. var val = [];
  26984. for (var i = 0; i < this.dimensions.length; i++) {
  26985. var dim = this.dimensions[i];
  26986. val.push(this.get(dim, idx));
  26987. }
  26988. return val;
  26989. }
  26990. else {
  26991. return this._rawData.getItem(this.getRawIndex(idx));
  26992. }
  26993. };
  26994. /**
  26995. * @param {number} idx
  26996. * @param {boolean} [notDefaultIdx=false]
  26997. * @return {string}
  26998. */
  26999. listProto.getName = function (idx) {
  27000. var rawIndex = this.getRawIndex(idx);
  27001. return this._nameList[rawIndex]
  27002. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27003. || '';
  27004. };
  27005. /**
  27006. * @param {number} idx
  27007. * @param {boolean} [notDefaultIdx=false]
  27008. * @return {string}
  27009. */
  27010. listProto.getId = function (idx) {
  27011. return getId(this, this.getRawIndex(idx));
  27012. };
  27013. function getId(list, rawIndex) {
  27014. var id = list._idList[rawIndex];
  27015. if (id == null) {
  27016. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27017. }
  27018. if (id == null) {
  27019. // FIXME Check the usage in graph, should not use prefix.
  27020. id = ID_PREFIX + rawIndex;
  27021. }
  27022. return id;
  27023. }
  27024. function normalizeDimensions(dimensions) {
  27025. if (!isArray(dimensions)) {
  27026. dimensions = [dimensions];
  27027. }
  27028. return dimensions;
  27029. }
  27030. function validateDimensions(list, dims) {
  27031. for (var i = 0; i < dims.length; i++) {
  27032. // stroage may be empty when no data, so use
  27033. // dimensionInfos to check.
  27034. if (!list._dimensionInfos[dims[i]]) {
  27035. console.error('Unkown dimension ' + dims[i]);
  27036. }
  27037. }
  27038. }
  27039. /**
  27040. * Data iteration
  27041. * @param {string|Array.<string>}
  27042. * @param {Function} cb
  27043. * @param {*} [context=this]
  27044. *
  27045. * @example
  27046. * list.each('x', function (x, idx) {});
  27047. * list.each(['x', 'y'], function (x, y, idx) {});
  27048. * list.each(function (idx) {})
  27049. */
  27050. listProto.each = function (dims, cb, context, contextCompat) {
  27051. 'use strict';
  27052. if (!this._count) {
  27053. return;
  27054. }
  27055. if (typeof dims === 'function') {
  27056. contextCompat = context;
  27057. context = cb;
  27058. cb = dims;
  27059. dims = [];
  27060. }
  27061. // contextCompat just for compat echarts3
  27062. context = context || contextCompat || this;
  27063. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27064. if (__DEV__) {
  27065. validateDimensions(this, dims);
  27066. }
  27067. var dimSize = dims.length;
  27068. for (var i = 0; i < this.count(); i++) {
  27069. // Simple optimization
  27070. switch (dimSize) {
  27071. case 0:
  27072. cb.call(context, i);
  27073. break;
  27074. case 1:
  27075. cb.call(context, this.get(dims[0], i), i);
  27076. break;
  27077. case 2:
  27078. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27079. break;
  27080. default:
  27081. var k = 0;
  27082. var value = [];
  27083. for (; k < dimSize; k++) {
  27084. value[k] = this.get(dims[k], i);
  27085. }
  27086. // Index
  27087. value[k] = i;
  27088. cb.apply(context, value);
  27089. }
  27090. }
  27091. };
  27092. /**
  27093. * Data filter
  27094. * @param {string|Array.<string>}
  27095. * @param {Function} cb
  27096. * @param {*} [context=this]
  27097. */
  27098. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27099. 'use strict';
  27100. if (!this._count) {
  27101. return;
  27102. }
  27103. if (typeof dimensions === 'function') {
  27104. contextCompat = context;
  27105. context = cb;
  27106. cb = dimensions;
  27107. dimensions = [];
  27108. }
  27109. // contextCompat just for compat echarts3
  27110. context = context || contextCompat || this;
  27111. dimensions = map(
  27112. normalizeDimensions(dimensions), this.getDimension, this
  27113. );
  27114. if (__DEV__) {
  27115. validateDimensions(this, dimensions);
  27116. }
  27117. var count = this.count();
  27118. var Ctor = getIndicesCtor(this);
  27119. var newIndices = new Ctor(count);
  27120. var value = [];
  27121. var dimSize = dimensions.length;
  27122. var offset = 0;
  27123. var dim0 = dimensions[0];
  27124. for (var i = 0; i < count; i++) {
  27125. var keep;
  27126. var rawIdx = this.getRawIndex(i);
  27127. // Simple optimization
  27128. if (dimSize === 0) {
  27129. keep = cb.call(context, i);
  27130. }
  27131. else if (dimSize === 1) {
  27132. var val = this._getFast(dim0, rawIdx);
  27133. keep = cb.call(context, val, i);
  27134. }
  27135. else {
  27136. for (var k = 0; k < dimSize; k++) {
  27137. value[k] = this._getFast(dim0, rawIdx);
  27138. }
  27139. value[k] = i;
  27140. keep = cb.apply(context, value);
  27141. }
  27142. if (keep) {
  27143. newIndices[offset++] = rawIdx;
  27144. }
  27145. }
  27146. // Set indices after filtered.
  27147. if (offset < count) {
  27148. this._indices = newIndices;
  27149. }
  27150. this._count = offset;
  27151. // Reset data extent
  27152. this._extent = {};
  27153. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27154. return this;
  27155. };
  27156. /**
  27157. * Select data in range. (For optimization of filter)
  27158. * (Manually inline code, support 5 million data filtering in data zoom.)
  27159. */
  27160. listProto.selectRange = function (range) {
  27161. 'use strict';
  27162. if (!this._count) {
  27163. return;
  27164. }
  27165. var dimensions = [];
  27166. for (var dim in range) {
  27167. if (range.hasOwnProperty(dim)) {
  27168. dimensions.push(dim);
  27169. }
  27170. }
  27171. if (__DEV__) {
  27172. validateDimensions(this, dimensions);
  27173. }
  27174. var dimSize = dimensions.length;
  27175. if (!dimSize) {
  27176. return;
  27177. }
  27178. var originalCount = this.count();
  27179. var Ctor = getIndicesCtor(this);
  27180. var newIndices = new Ctor(originalCount);
  27181. var offset = 0;
  27182. var dim0 = dimensions[0];
  27183. var min = range[dim0][0];
  27184. var max = range[dim0][1];
  27185. var quickFinished = false;
  27186. if (!this._indices) {
  27187. // Extreme optimization for common case. About 2x faster in chrome.
  27188. var idx = 0;
  27189. if (dimSize === 1) {
  27190. var dimStorage = this._storage[dimensions[0]];
  27191. for (var k = 0; k < this._chunkCount; k++) {
  27192. var chunkStorage = dimStorage[k];
  27193. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27194. for (var i = 0; i < len; i++) {
  27195. var val = chunkStorage[i];
  27196. // NaN will not be filtered. Consider the case, in line chart, empty
  27197. // value indicates the line should be broken. But for the case like
  27198. // scatter plot, a data item with empty value will not be rendered,
  27199. // but the axis extent may be effected if some other dim of the data
  27200. // item has value. Fortunately it is not a significant negative effect.
  27201. if (
  27202. (val >= min && val <= max) || isNaN(val)
  27203. ) {
  27204. newIndices[offset++] = idx;
  27205. }
  27206. idx++;
  27207. }
  27208. }
  27209. quickFinished = true;
  27210. }
  27211. else if (dimSize === 2) {
  27212. var dimStorage = this._storage[dim0];
  27213. var dimStorage2 = this._storage[dimensions[1]];
  27214. var min2 = range[dimensions[1]][0];
  27215. var max2 = range[dimensions[1]][1];
  27216. for (var k = 0; k < this._chunkCount; k++) {
  27217. var chunkStorage = dimStorage[k];
  27218. var chunkStorage2 = dimStorage2[k];
  27219. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27220. for (var i = 0; i < len; i++) {
  27221. var val = chunkStorage[i];
  27222. var val2 = chunkStorage2[i];
  27223. // Do not filter NaN, see comment above.
  27224. if ((
  27225. (val >= min && val <= max) || isNaN(val)
  27226. )
  27227. && (
  27228. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27229. )
  27230. ) {
  27231. newIndices[offset++] = idx;
  27232. }
  27233. idx++;
  27234. }
  27235. }
  27236. quickFinished = true;
  27237. }
  27238. }
  27239. if (!quickFinished) {
  27240. if (dimSize === 1) {
  27241. for (var i = 0; i < originalCount; i++) {
  27242. var rawIndex = this.getRawIndex(i);
  27243. var val = this._getFast(dim0, rawIndex);
  27244. // Do not filter NaN, see comment above.
  27245. if (
  27246. (val >= min && val <= max) || isNaN(val)
  27247. ) {
  27248. newIndices[offset++] = rawIndex;
  27249. }
  27250. }
  27251. }
  27252. else {
  27253. for (var i = 0; i < originalCount; i++) {
  27254. var keep = true;
  27255. var rawIndex = this.getRawIndex(i);
  27256. for (var k = 0; k < dimSize; k++) {
  27257. var dimk = dimensions[k];
  27258. var val = this._getFast(dim, rawIndex);
  27259. // Do not filter NaN, see comment above.
  27260. if (val < range[dimk][0] || val > range[dimk][1]) {
  27261. keep = false;
  27262. }
  27263. }
  27264. if (keep) {
  27265. newIndices[offset++] = this.getRawIndex(i);
  27266. }
  27267. }
  27268. }
  27269. }
  27270. // Set indices after filtered.
  27271. if (offset < originalCount) {
  27272. this._indices = newIndices;
  27273. }
  27274. this._count = offset;
  27275. // Reset data extent
  27276. this._extent = {};
  27277. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27278. return this;
  27279. };
  27280. /**
  27281. * Data mapping to a plain array
  27282. * @param {string|Array.<string>} [dimensions]
  27283. * @param {Function} cb
  27284. * @param {*} [context=this]
  27285. * @return {Array}
  27286. */
  27287. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27288. 'use strict';
  27289. if (typeof dimensions === 'function') {
  27290. contextCompat = context;
  27291. context = cb;
  27292. cb = dimensions;
  27293. dimensions = [];
  27294. }
  27295. // contextCompat just for compat echarts3
  27296. context = context || contextCompat || this;
  27297. var result = [];
  27298. this.each(dimensions, function () {
  27299. result.push(cb && cb.apply(this, arguments));
  27300. }, context);
  27301. return result;
  27302. };
  27303. // Data in excludeDimensions is copied, otherwise transfered.
  27304. function cloneListForMapAndSample(original, excludeDimensions) {
  27305. var allDimensions = original.dimensions;
  27306. var list = new List(
  27307. map(allDimensions, original.getDimensionInfo, original),
  27308. original.hostModel
  27309. );
  27310. // FIXME If needs stackedOn, value may already been stacked
  27311. transferProperties(list, original);
  27312. var storage = list._storage = {};
  27313. var originalStorage = original._storage;
  27314. // Init storage
  27315. for (var i = 0; i < allDimensions.length; i++) {
  27316. var dim = allDimensions[i];
  27317. if (originalStorage[dim]) {
  27318. // Notice that we do not reset invertedIndicesMap here, becuase
  27319. // there is no scenario of mapping or sampling ordinal dimension.
  27320. if (indexOf(excludeDimensions, dim) >= 0) {
  27321. storage[dim] = cloneDimStore(originalStorage[dim]);
  27322. list._rawExtent[dim] = getInitialExtent();
  27323. list._extent[dim] = null;
  27324. }
  27325. else {
  27326. // Direct reference for other dimensions
  27327. storage[dim] = originalStorage[dim];
  27328. }
  27329. }
  27330. }
  27331. return list;
  27332. }
  27333. function cloneDimStore(originalDimStore) {
  27334. var newDimStore = new Array(originalDimStore.length);
  27335. for (var j = 0; j < originalDimStore.length; j++) {
  27336. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27337. }
  27338. return newDimStore;
  27339. }
  27340. function getInitialExtent() {
  27341. return [Infinity, -Infinity];
  27342. }
  27343. /**
  27344. * Data mapping to a new List with given dimensions
  27345. * @param {string|Array.<string>} dimensions
  27346. * @param {Function} cb
  27347. * @param {*} [context=this]
  27348. * @return {Array}
  27349. */
  27350. listProto.map = function (dimensions, cb, context, contextCompat) {
  27351. 'use strict';
  27352. // contextCompat just for compat echarts3
  27353. context = context || contextCompat || this;
  27354. dimensions = map(
  27355. normalizeDimensions(dimensions), this.getDimension, this
  27356. );
  27357. if (__DEV__) {
  27358. validateDimensions(this, dimensions);
  27359. }
  27360. var list = cloneListForMapAndSample(this, dimensions);
  27361. // Following properties are all immutable.
  27362. // So we can reference to the same value
  27363. list._indices = this._indices;
  27364. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27365. var storage = list._storage;
  27366. var tmpRetValue = [];
  27367. var chunkSize = this._chunkSize;
  27368. var dimSize = dimensions.length;
  27369. var dataCount = this.count();
  27370. var values = [];
  27371. var rawExtent = list._rawExtent;
  27372. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27373. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27374. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27375. }
  27376. values[dimSize] = dataIndex;
  27377. var retValue = cb && cb.apply(context, values);
  27378. if (retValue != null) {
  27379. // a number or string (in oridinal dimension)?
  27380. if (typeof retValue !== 'object') {
  27381. tmpRetValue[0] = retValue;
  27382. retValue = tmpRetValue;
  27383. }
  27384. var rawIndex = this.getRawIndex(dataIndex);
  27385. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27386. var chunkOffset = rawIndex % chunkSize;
  27387. for (var i = 0; i < retValue.length; i++) {
  27388. var dim = dimensions[i];
  27389. var val = retValue[i];
  27390. var rawExtentOnDim = rawExtent[dim];
  27391. var dimStore = storage[dim];
  27392. if (dimStore) {
  27393. dimStore[chunkIndex][chunkOffset] = val;
  27394. }
  27395. if (val < rawExtentOnDim[0]) {
  27396. rawExtentOnDim[0] = val;
  27397. }
  27398. if (val > rawExtentOnDim[1]) {
  27399. rawExtentOnDim[1] = val;
  27400. }
  27401. }
  27402. }
  27403. }
  27404. return list;
  27405. };
  27406. /**
  27407. * Large data down sampling on given dimension
  27408. * @param {string} dimension
  27409. * @param {number} rate
  27410. * @param {Function} sampleValue
  27411. * @param {Function} sampleIndex Sample index for name and id
  27412. */
  27413. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27414. var list = cloneListForMapAndSample(this, [dimension]);
  27415. var targetStorage = list._storage;
  27416. var frameValues = [];
  27417. var frameSize = Math.floor(1 / rate);
  27418. var dimStore = targetStorage[dimension];
  27419. var len = this.count();
  27420. var chunkSize = this._chunkSize;
  27421. var rawExtentOnDim = list._rawExtent[dimension];
  27422. var newIndices = new (getIndicesCtor(this))(len);
  27423. var offset = 0;
  27424. for (var i = 0; i < len; i += frameSize) {
  27425. // Last frame
  27426. if (frameSize > len - i) {
  27427. frameSize = len - i;
  27428. frameValues.length = frameSize;
  27429. }
  27430. for (var k = 0; k < frameSize; k++) {
  27431. var dataIdx = this.getRawIndex(i + k);
  27432. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27433. var originalChunkOffset = dataIdx % chunkSize;
  27434. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27435. }
  27436. var value = sampleValue(frameValues);
  27437. var sampleFrameIdx = this.getRawIndex(
  27438. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27439. );
  27440. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27441. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27442. // Only write value on the filtered data
  27443. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27444. if (value < rawExtentOnDim[0]) {
  27445. rawExtentOnDim[0] = value;
  27446. }
  27447. if (value > rawExtentOnDim[1]) {
  27448. rawExtentOnDim[1] = value;
  27449. }
  27450. newIndices[offset++] = sampleFrameIdx;
  27451. }
  27452. list._count = offset;
  27453. list._indices = newIndices;
  27454. list.getRawIndex = getRawIndexWithIndices;
  27455. return list;
  27456. };
  27457. /**
  27458. * Get model of one data item.
  27459. *
  27460. * @param {number} idx
  27461. */
  27462. // FIXME Model proxy ?
  27463. listProto.getItemModel = function (idx) {
  27464. var hostModel = this.hostModel;
  27465. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27466. };
  27467. /**
  27468. * Create a data differ
  27469. * @param {module:echarts/data/List} otherList
  27470. * @return {module:echarts/data/DataDiffer}
  27471. */
  27472. listProto.diff = function (otherList) {
  27473. var thisList = this;
  27474. return new DataDiffer(
  27475. otherList ? otherList.getIndices() : [],
  27476. this.getIndices(),
  27477. function (idx) {
  27478. return getId(otherList, idx);
  27479. },
  27480. function (idx) {
  27481. return getId(thisList, idx);
  27482. }
  27483. );
  27484. };
  27485. /**
  27486. * Get visual property.
  27487. * @param {string} key
  27488. */
  27489. listProto.getVisual = function (key) {
  27490. var visual = this._visual;
  27491. return visual && visual[key];
  27492. };
  27493. /**
  27494. * Set visual property
  27495. * @param {string|Object} key
  27496. * @param {*} [value]
  27497. *
  27498. * @example
  27499. * setVisual('color', color);
  27500. * setVisual({
  27501. * 'color': color
  27502. * });
  27503. */
  27504. listProto.setVisual = function (key, val) {
  27505. if (isObject$4(key)) {
  27506. for (var name in key) {
  27507. if (key.hasOwnProperty(name)) {
  27508. this.setVisual(name, key[name]);
  27509. }
  27510. }
  27511. return;
  27512. }
  27513. this._visual = this._visual || {};
  27514. this._visual[key] = val;
  27515. };
  27516. /**
  27517. * Set layout property.
  27518. * @param {string|Object} key
  27519. * @param {*} [val]
  27520. */
  27521. listProto.setLayout = function (key, val) {
  27522. if (isObject$4(key)) {
  27523. for (var name in key) {
  27524. if (key.hasOwnProperty(name)) {
  27525. this.setLayout(name, key[name]);
  27526. }
  27527. }
  27528. return;
  27529. }
  27530. this._layout[key] = val;
  27531. };
  27532. /**
  27533. * Get layout property.
  27534. * @param {string} key.
  27535. * @return {*}
  27536. */
  27537. listProto.getLayout = function (key) {
  27538. return this._layout[key];
  27539. };
  27540. /**
  27541. * Get layout of single data item
  27542. * @param {number} idx
  27543. */
  27544. listProto.getItemLayout = function (idx) {
  27545. return this._itemLayouts[idx];
  27546. };
  27547. /**
  27548. * Set layout of single data item
  27549. * @param {number} idx
  27550. * @param {Object} layout
  27551. * @param {boolean=} [merge=false]
  27552. */
  27553. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27554. this._itemLayouts[idx] = merge$$1
  27555. ? extend(this._itemLayouts[idx] || {}, layout)
  27556. : layout;
  27557. };
  27558. /**
  27559. * Clear all layout of single data item
  27560. */
  27561. listProto.clearItemLayouts = function () {
  27562. this._itemLayouts.length = 0;
  27563. };
  27564. /**
  27565. * Get visual property of single data item
  27566. * @param {number} idx
  27567. * @param {string} key
  27568. * @param {boolean} [ignoreParent=false]
  27569. */
  27570. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27571. var itemVisual = this._itemVisuals[idx];
  27572. var val = itemVisual && itemVisual[key];
  27573. if (val == null && !ignoreParent) {
  27574. // Use global visual property
  27575. return this.getVisual(key);
  27576. }
  27577. return val;
  27578. };
  27579. /**
  27580. * Set visual property of single data item
  27581. *
  27582. * @param {number} idx
  27583. * @param {string|Object} key
  27584. * @param {*} [value]
  27585. *
  27586. * @example
  27587. * setItemVisual(0, 'color', color);
  27588. * setItemVisual(0, {
  27589. * 'color': color
  27590. * });
  27591. */
  27592. listProto.setItemVisual = function (idx, key, value) {
  27593. var itemVisual = this._itemVisuals[idx] || {};
  27594. var hasItemVisual = this.hasItemVisual;
  27595. this._itemVisuals[idx] = itemVisual;
  27596. if (isObject$4(key)) {
  27597. for (var name in key) {
  27598. if (key.hasOwnProperty(name)) {
  27599. itemVisual[name] = key[name];
  27600. hasItemVisual[name] = true;
  27601. }
  27602. }
  27603. return;
  27604. }
  27605. itemVisual[key] = value;
  27606. hasItemVisual[key] = true;
  27607. };
  27608. /**
  27609. * Clear itemVisuals and list visual.
  27610. */
  27611. listProto.clearAllVisual = function () {
  27612. this._visual = {};
  27613. this._itemVisuals = [];
  27614. this.hasItemVisual = {};
  27615. };
  27616. var setItemDataAndSeriesIndex = function (child) {
  27617. child.seriesIndex = this.seriesIndex;
  27618. child.dataIndex = this.dataIndex;
  27619. child.dataType = this.dataType;
  27620. };
  27621. /**
  27622. * Set graphic element relative to data. It can be set as null
  27623. * @param {number} idx
  27624. * @param {module:zrender/Element} [el]
  27625. */
  27626. listProto.setItemGraphicEl = function (idx, el) {
  27627. var hostModel = this.hostModel;
  27628. if (el) {
  27629. // Add data index and series index for indexing the data by element
  27630. // Useful in tooltip
  27631. el.dataIndex = idx;
  27632. el.dataType = this.dataType;
  27633. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27634. if (el.type === 'group') {
  27635. el.traverse(setItemDataAndSeriesIndex, el);
  27636. }
  27637. }
  27638. this._graphicEls[idx] = el;
  27639. };
  27640. /**
  27641. * @param {number} idx
  27642. * @return {module:zrender/Element}
  27643. */
  27644. listProto.getItemGraphicEl = function (idx) {
  27645. return this._graphicEls[idx];
  27646. };
  27647. /**
  27648. * @param {Function} cb
  27649. * @param {*} context
  27650. */
  27651. listProto.eachItemGraphicEl = function (cb, context) {
  27652. each$1(this._graphicEls, function (el, idx) {
  27653. if (el) {
  27654. cb && cb.call(context, el, idx);
  27655. }
  27656. });
  27657. };
  27658. /**
  27659. * Shallow clone a new list except visual and layout properties, and graph elements.
  27660. * New list only change the indices.
  27661. */
  27662. listProto.cloneShallow = function (list) {
  27663. if (!list) {
  27664. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27665. list = new List(dimensionInfoList, this.hostModel);
  27666. }
  27667. // FIXME
  27668. list._storage = this._storage;
  27669. transferProperties(list, this);
  27670. // Clone will not change the data extent and indices
  27671. if (this._indices) {
  27672. var Ctor = this._indices.constructor;
  27673. list._indices = new Ctor(this._indices);
  27674. }
  27675. else {
  27676. list._indices = null;
  27677. }
  27678. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27679. return list;
  27680. };
  27681. /**
  27682. * Wrap some method to add more feature
  27683. * @param {string} methodName
  27684. * @param {Function} injectFunction
  27685. */
  27686. listProto.wrapMethod = function (methodName, injectFunction) {
  27687. var originalMethod = this[methodName];
  27688. if (typeof originalMethod !== 'function') {
  27689. return;
  27690. }
  27691. this.__wrappedMethods = this.__wrappedMethods || [];
  27692. this.__wrappedMethods.push(methodName);
  27693. this[methodName] = function () {
  27694. var res = originalMethod.apply(this, arguments);
  27695. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27696. };
  27697. };
  27698. // Methods that create a new list based on this list should be listed here.
  27699. // Notice that those method should `RETURN` the new list.
  27700. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27701. // Methods that change indices of this list should be listed here.
  27702. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27703. /*
  27704. * Licensed to the Apache Software Foundation (ASF) under one
  27705. * or more contributor license agreements. See the NOTICE file
  27706. * distributed with this work for additional information
  27707. * regarding copyright ownership. The ASF licenses this file
  27708. * to you under the Apache License, Version 2.0 (the
  27709. * "License"); you may not use this file except in compliance
  27710. * with the License. You may obtain a copy of the License at
  27711. *
  27712. * http://www.apache.org/licenses/LICENSE-2.0
  27713. *
  27714. * Unless required by applicable law or agreed to in writing,
  27715. * software distributed under the License is distributed on an
  27716. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27717. * KIND, either express or implied. See the License for the
  27718. * specific language governing permissions and limitations
  27719. * under the License.
  27720. */
  27721. /**
  27722. * @deprecated
  27723. * Use `echarts/data/helper/createDimensions` instead.
  27724. */
  27725. /**
  27726. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27727. *
  27728. * This method builds the relationship between:
  27729. * + "what the coord sys or series requires (see `sysDims`)",
  27730. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  27731. * + "what the data source provids (see `source`)".
  27732. *
  27733. * Some guess strategy will be adapted if user does not define something.
  27734. * If no 'value' dimension specified, the first no-named dimension will be
  27735. * named as 'value'.
  27736. *
  27737. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27738. * provides not only dim template, but also default order.
  27739. * properties: 'name', 'type', 'displayName'.
  27740. * `name` of each item provides default coord name.
  27741. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27742. * provide dims count that the sysDim required.
  27743. * [{ordinalMeta}] can be specified.
  27744. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27745. * @param {Object} [opt]
  27746. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27747. * For example: ['asdf', {name, type}, ...].
  27748. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27749. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  27750. * If not specified, auto find the next available data dim.
  27751. * param source {module:data/Source}
  27752. * param dimCount {number}
  27753. * return {Object} encode Never be `null/undefined`.
  27754. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27755. * If not specified, extra dim names will be:
  27756. * 'value', 'value0', 'value1', ...
  27757. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27758. * If `generateCoordCount` specified, the generated dim names will be:
  27759. * `generateCoord` + 0, `generateCoord` + 1, ...
  27760. * can be Infinity, indicate that use all of the remain columns.
  27761. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27762. * @return {Array.<module:data/DataDimensionInfo>}
  27763. */
  27764. function completeDimensions(sysDims, source, opt) {
  27765. if (!Source.isInstance(source)) {
  27766. source = Source.seriesDataToSource(source);
  27767. }
  27768. opt = opt || {};
  27769. sysDims = (sysDims || []).slice();
  27770. var dimsDef = (opt.dimsDef || []).slice();
  27771. var dataDimNameMap = createHashMap();
  27772. var coordDimNameMap = createHashMap();
  27773. // var valueCandidate;
  27774. var result = [];
  27775. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27776. // Apply user defined dims (`name` and `type`) and init result.
  27777. for (var i = 0; i < dimCount; i++) {
  27778. var dimDefItem = dimsDef[i] = extend(
  27779. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27780. );
  27781. var userDimName = dimDefItem.name;
  27782. var resultItem = result[i] = new DataDimensionInfo();
  27783. // Name will be applied later for avoiding duplication.
  27784. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27785. // Only if `series.dimensions` is defined in option
  27786. // displayName, will be set, and dimension will be diplayed vertically in
  27787. // tooltip by default.
  27788. resultItem.name = resultItem.displayName = userDimName;
  27789. dataDimNameMap.set(userDimName, i);
  27790. }
  27791. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27792. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27793. }
  27794. var encodeDef = opt.encodeDef;
  27795. if (!encodeDef && opt.encodeDefaulter) {
  27796. encodeDef = opt.encodeDefaulter(source, dimCount);
  27797. }
  27798. encodeDef = createHashMap(encodeDef);
  27799. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27800. encodeDef.each(function (dataDims, coordDim) {
  27801. dataDims = normalizeToArray(dataDims).slice();
  27802. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27803. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27804. // this case.
  27805. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  27806. encodeDef.set(coordDim, false);
  27807. return;
  27808. }
  27809. var validDataDims = encodeDef.set(coordDim, []);
  27810. each$1(dataDims, function (resultDimIdx, idx) {
  27811. // The input resultDimIdx can be dim name or index.
  27812. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27813. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27814. validDataDims[idx] = resultDimIdx;
  27815. applyDim(result[resultDimIdx], coordDim, idx);
  27816. }
  27817. });
  27818. });
  27819. // Apply templetes and default order from `sysDims`.
  27820. var availDimIdx = 0;
  27821. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27822. var coordDim;
  27823. var sysDimItem;
  27824. var sysDimItemDimsDef;
  27825. var sysDimItemOtherDims;
  27826. if (isString(sysDimItem)) {
  27827. coordDim = sysDimItem;
  27828. sysDimItem = {};
  27829. }
  27830. else {
  27831. coordDim = sysDimItem.name;
  27832. var ordinalMeta = sysDimItem.ordinalMeta;
  27833. sysDimItem.ordinalMeta = null;
  27834. sysDimItem = clone(sysDimItem);
  27835. sysDimItem.ordinalMeta = ordinalMeta;
  27836. // `coordDimIndex` should not be set directly.
  27837. sysDimItemDimsDef = sysDimItem.dimsDef;
  27838. sysDimItemOtherDims = sysDimItem.otherDims;
  27839. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  27840. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27841. }
  27842. var dataDims = encodeDef.get(coordDim);
  27843. // negative resultDimIdx means no need to mapping.
  27844. if (dataDims === false) {
  27845. return;
  27846. }
  27847. var dataDims = normalizeToArray(dataDims);
  27848. // dimensions provides default dim sequences.
  27849. if (!dataDims.length) {
  27850. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27851. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27852. availDimIdx++;
  27853. }
  27854. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27855. }
  27856. }
  27857. // Apply templates.
  27858. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27859. var resultItem = result[resultDimIdx];
  27860. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27861. if (resultItem.name == null && sysDimItemDimsDef) {
  27862. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27863. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27864. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27865. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27866. }
  27867. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27868. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27869. });
  27870. });
  27871. function applyDim(resultItem, coordDim, coordDimIndex) {
  27872. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27873. resultItem.otherDims[coordDim] = coordDimIndex;
  27874. }
  27875. else {
  27876. resultItem.coordDim = coordDim;
  27877. resultItem.coordDimIndex = coordDimIndex;
  27878. coordDimNameMap.set(coordDim, true);
  27879. }
  27880. }
  27881. // Make sure the first extra dim is 'value'.
  27882. var generateCoord = opt.generateCoord;
  27883. var generateCoordCount = opt.generateCoordCount;
  27884. var fromZero = generateCoordCount != null;
  27885. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27886. var extra = generateCoord || 'value';
  27887. // Set dim `name` and other `coordDim` and other props.
  27888. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27889. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  27890. var coordDim = resultItem.coordDim;
  27891. if (coordDim == null) {
  27892. resultItem.coordDim = genName(
  27893. extra, coordDimNameMap, fromZero
  27894. );
  27895. resultItem.coordDimIndex = 0;
  27896. if (!generateCoord || generateCoordCount <= 0) {
  27897. resultItem.isExtraCoord = true;
  27898. }
  27899. generateCoordCount--;
  27900. }
  27901. resultItem.name == null && (resultItem.name = genName(
  27902. resultItem.coordDim,
  27903. dataDimNameMap
  27904. ));
  27905. if (resultItem.type == null
  27906. && (
  27907. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  27908. // Consider the case:
  27909. // {
  27910. // dataset: {source: [
  27911. // ['2001', 123],
  27912. // ['2002', 456],
  27913. // ...
  27914. // ['The others', 987],
  27915. // ]},
  27916. // series: {type: 'pie'}
  27917. // }
  27918. // The first colum should better be treated as a "ordinal" although it
  27919. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  27920. || (resultItem.isExtraCoord
  27921. && (resultItem.otherDims.itemName != null
  27922. || resultItem.otherDims.seriesName != null
  27923. )
  27924. )
  27925. )
  27926. ) {
  27927. resultItem.type = 'ordinal';
  27928. }
  27929. }
  27930. return result;
  27931. }
  27932. // ??? TODO
  27933. // Originally detect dimCount by data[0]. Should we
  27934. // optimize it to only by sysDims and dimensions and encode.
  27935. // So only necessary dims will be initialized.
  27936. // But
  27937. // (1) custom series should be considered. where other dims
  27938. // may be visited.
  27939. // (2) sometimes user need to calcualte bubble size or use visualMap
  27940. // on other dimensions besides coordSys needed.
  27941. // So, dims that is not used by system, should be shared in storage?
  27942. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27943. // Note that the result dimCount should not small than columns count
  27944. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27945. var dimCount = Math.max(
  27946. source.dimensionsDetectCount || 1,
  27947. sysDims.length,
  27948. dimsDef.length,
  27949. optDimCount || 0
  27950. );
  27951. each$1(sysDims, function (sysDimItem) {
  27952. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27953. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27954. });
  27955. return dimCount;
  27956. }
  27957. function genName(name, map$$1, fromZero) {
  27958. if (fromZero || map$$1.get(name) != null) {
  27959. var i = 0;
  27960. while (map$$1.get(name + i) != null) {
  27961. i++;
  27962. }
  27963. name += i;
  27964. }
  27965. map$$1.set(name, true);
  27966. return name;
  27967. }
  27968. /*
  27969. * Licensed to the Apache Software Foundation (ASF) under one
  27970. * or more contributor license agreements. See the NOTICE file
  27971. * distributed with this work for additional information
  27972. * regarding copyright ownership. The ASF licenses this file
  27973. * to you under the Apache License, Version 2.0 (the
  27974. * "License"); you may not use this file except in compliance
  27975. * with the License. You may obtain a copy of the License at
  27976. *
  27977. * http://www.apache.org/licenses/LICENSE-2.0
  27978. *
  27979. * Unless required by applicable law or agreed to in writing,
  27980. * software distributed under the License is distributed on an
  27981. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27982. * KIND, either express or implied. See the License for the
  27983. * specific language governing permissions and limitations
  27984. * under the License.
  27985. */
  27986. /**
  27987. * Substitute `completeDimensions`.
  27988. * `completeDimensions` is to be deprecated.
  27989. */
  27990. /**
  27991. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27992. * @param {Object|Array} [opt]
  27993. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27994. * @param {number} [opt.dimensionsCount]
  27995. * @param {string} [opt.generateCoord]
  27996. * @param {string} [opt.generateCoordCount]
  27997. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27998. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27999. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28000. * @return {Array.<Object>} dimensionsInfo
  28001. */
  28002. var createDimensions = function (source, opt) {
  28003. opt = opt || {};
  28004. return completeDimensions(opt.coordDimensions || [], source, {
  28005. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28006. encodeDef: opt.encodeDefine || source.encodeDefine,
  28007. dimCount: opt.dimensionsCount,
  28008. encodeDefaulter: opt.encodeDefaulter,
  28009. generateCoord: opt.generateCoord,
  28010. generateCoordCount: opt.generateCoordCount
  28011. });
  28012. };
  28013. /*
  28014. * Licensed to the Apache Software Foundation (ASF) under one
  28015. * or more contributor license agreements. See the NOTICE file
  28016. * distributed with this work for additional information
  28017. * regarding copyright ownership. The ASF licenses this file
  28018. * to you under the Apache License, Version 2.0 (the
  28019. * "License"); you may not use this file except in compliance
  28020. * with the License. You may obtain a copy of the License at
  28021. *
  28022. * http://www.apache.org/licenses/LICENSE-2.0
  28023. *
  28024. * Unless required by applicable law or agreed to in writing,
  28025. * software distributed under the License is distributed on an
  28026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28027. * KIND, either express or implied. See the License for the
  28028. * specific language governing permissions and limitations
  28029. * under the License.
  28030. */
  28031. /**
  28032. * Helper for model references.
  28033. * There are many manners to refer axis/coordSys.
  28034. */
  28035. // TODO
  28036. // merge relevant logic to this file?
  28037. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28038. /**
  28039. * @class
  28040. * For example:
  28041. * {
  28042. * coordSysName: 'cartesian2d',
  28043. * coordSysDims: ['x', 'y', ...],
  28044. * axisMap: HashMap({
  28045. * x: xAxisModel,
  28046. * y: yAxisModel
  28047. * }),
  28048. * categoryAxisMap: HashMap({
  28049. * x: xAxisModel,
  28050. * y: undefined
  28051. * }),
  28052. * // The index of the first category axis in `coordSysDims`.
  28053. * // `null/undefined` means no category axis exists.
  28054. * firstCategoryDimIndex: 1,
  28055. * // To replace user specified encode.
  28056. * }
  28057. */
  28058. function CoordSysInfo(coordSysName) {
  28059. /**
  28060. * @type {string}
  28061. */
  28062. this.coordSysName = coordSysName;
  28063. /**
  28064. * @type {Array.<string>}
  28065. */
  28066. this.coordSysDims = [];
  28067. /**
  28068. * @type {module:zrender/core/util#HashMap}
  28069. */
  28070. this.axisMap = createHashMap();
  28071. /**
  28072. * @type {module:zrender/core/util#HashMap}
  28073. */
  28074. this.categoryAxisMap = createHashMap();
  28075. /**
  28076. * @type {number}
  28077. */
  28078. this.firstCategoryDimIndex = null;
  28079. }
  28080. /**
  28081. * @return {module:model/referHelper#CoordSysInfo}
  28082. */
  28083. function getCoordSysInfoBySeries(seriesModel) {
  28084. var coordSysName = seriesModel.get('coordinateSystem');
  28085. var result = new CoordSysInfo(coordSysName);
  28086. var fetch = fetchers[coordSysName];
  28087. if (fetch) {
  28088. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28089. return result;
  28090. }
  28091. }
  28092. var fetchers = {
  28093. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28094. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28095. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28096. if (__DEV__) {
  28097. if (!xAxisModel) {
  28098. throw new Error('xAxis "' + retrieve(
  28099. seriesModel.get('xAxisIndex'),
  28100. seriesModel.get('xAxisId'),
  28101. 0
  28102. ) + '" not found');
  28103. }
  28104. if (!yAxisModel) {
  28105. throw new Error('yAxis "' + retrieve(
  28106. seriesModel.get('xAxisIndex'),
  28107. seriesModel.get('yAxisId'),
  28108. 0
  28109. ) + '" not found');
  28110. }
  28111. }
  28112. result.coordSysDims = ['x', 'y'];
  28113. axisMap.set('x', xAxisModel);
  28114. axisMap.set('y', yAxisModel);
  28115. if (isCategory(xAxisModel)) {
  28116. categoryAxisMap.set('x', xAxisModel);
  28117. result.firstCategoryDimIndex = 0;
  28118. }
  28119. if (isCategory(yAxisModel)) {
  28120. categoryAxisMap.set('y', yAxisModel);
  28121. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28122. }
  28123. },
  28124. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28125. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28126. if (__DEV__) {
  28127. if (!singleAxisModel) {
  28128. throw new Error('singleAxis should be specified.');
  28129. }
  28130. }
  28131. result.coordSysDims = ['single'];
  28132. axisMap.set('single', singleAxisModel);
  28133. if (isCategory(singleAxisModel)) {
  28134. categoryAxisMap.set('single', singleAxisModel);
  28135. result.firstCategoryDimIndex = 0;
  28136. }
  28137. },
  28138. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28139. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28140. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28141. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28142. if (__DEV__) {
  28143. if (!angleAxisModel) {
  28144. throw new Error('angleAxis option not found');
  28145. }
  28146. if (!radiusAxisModel) {
  28147. throw new Error('radiusAxis option not found');
  28148. }
  28149. }
  28150. result.coordSysDims = ['radius', 'angle'];
  28151. axisMap.set('radius', radiusAxisModel);
  28152. axisMap.set('angle', angleAxisModel);
  28153. if (isCategory(radiusAxisModel)) {
  28154. categoryAxisMap.set('radius', radiusAxisModel);
  28155. result.firstCategoryDimIndex = 0;
  28156. }
  28157. if (isCategory(angleAxisModel)) {
  28158. categoryAxisMap.set('angle', angleAxisModel);
  28159. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28160. }
  28161. },
  28162. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28163. result.coordSysDims = ['lng', 'lat'];
  28164. },
  28165. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28166. var ecModel = seriesModel.ecModel;
  28167. var parallelModel = ecModel.getComponent(
  28168. 'parallel', seriesModel.get('parallelIndex')
  28169. );
  28170. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28171. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28172. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28173. var axisDim = coordSysDims[index];
  28174. axisMap.set(axisDim, axisModel);
  28175. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28176. categoryAxisMap.set(axisDim, axisModel);
  28177. result.firstCategoryDimIndex = index;
  28178. }
  28179. });
  28180. }
  28181. };
  28182. function isCategory(axisModel) {
  28183. return axisModel.get('type') === 'category';
  28184. }
  28185. /*
  28186. * Licensed to the Apache Software Foundation (ASF) under one
  28187. * or more contributor license agreements. See the NOTICE file
  28188. * distributed with this work for additional information
  28189. * regarding copyright ownership. The ASF licenses this file
  28190. * to you under the Apache License, Version 2.0 (the
  28191. * "License"); you may not use this file except in compliance
  28192. * with the License. You may obtain a copy of the License at
  28193. *
  28194. * http://www.apache.org/licenses/LICENSE-2.0
  28195. *
  28196. * Unless required by applicable law or agreed to in writing,
  28197. * software distributed under the License is distributed on an
  28198. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28199. * KIND, either express or implied. See the License for the
  28200. * specific language governing permissions and limitations
  28201. * under the License.
  28202. */
  28203. /**
  28204. * Note that it is too complicated to support 3d stack by value
  28205. * (have to create two-dimension inverted index), so in 3d case
  28206. * we just support that stacked by index.
  28207. *
  28208. * @param {module:echarts/model/Series} seriesModel
  28209. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28210. * The input dimensionInfoList will be modified.
  28211. * @param {Object} [opt]
  28212. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28213. * @param {boolean} [opt.byIndex=false]
  28214. * @return {Object} calculationInfo
  28215. * {
  28216. * stackedDimension: string
  28217. * stackedByDimension: string
  28218. * isStackedByIndex: boolean
  28219. * stackedOverDimension: string
  28220. * stackResultDimension: string
  28221. * }
  28222. */
  28223. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28224. opt = opt || {};
  28225. var byIndex = opt.byIndex;
  28226. var stackedCoordDimension = opt.stackedCoordDimension;
  28227. // Compatibal: when `stack` is set as '', do not stack.
  28228. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28229. var stackedByDimInfo;
  28230. var stackedDimInfo;
  28231. var stackResultDimension;
  28232. var stackedOverDimension;
  28233. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28234. if (isString(dimensionInfo)) {
  28235. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28236. }
  28237. if (mayStack && !dimensionInfo.isExtraCoord) {
  28238. // Find the first ordinal dimension as the stackedByDimInfo.
  28239. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28240. stackedByDimInfo = dimensionInfo;
  28241. }
  28242. // Find the first stackable dimension as the stackedDimInfo.
  28243. if (!stackedDimInfo
  28244. && dimensionInfo.type !== 'ordinal'
  28245. && dimensionInfo.type !== 'time'
  28246. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28247. ) {
  28248. stackedDimInfo = dimensionInfo;
  28249. }
  28250. }
  28251. });
  28252. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28253. // Compatible with previous design, value axis (time axis) only stack by index.
  28254. // It may make sense if the user provides elaborately constructed data.
  28255. byIndex = true;
  28256. }
  28257. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28258. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28259. // might not be a good way.
  28260. if (stackedDimInfo) {
  28261. // Use a weird name that not duplicated with other names.
  28262. stackResultDimension = '__\0ecstackresult';
  28263. stackedOverDimension = '__\0ecstackedover';
  28264. // Create inverted index to fast query index by value.
  28265. if (stackedByDimInfo) {
  28266. stackedByDimInfo.createInvertedIndices = true;
  28267. }
  28268. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28269. var stackedDimType = stackedDimInfo.type;
  28270. var stackedDimCoordIndex = 0;
  28271. each$1(dimensionInfoList, function (dimensionInfo) {
  28272. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28273. stackedDimCoordIndex++;
  28274. }
  28275. });
  28276. dimensionInfoList.push({
  28277. name: stackResultDimension,
  28278. coordDim: stackedDimCoordDim,
  28279. coordDimIndex: stackedDimCoordIndex,
  28280. type: stackedDimType,
  28281. isExtraCoord: true,
  28282. isCalculationCoord: true
  28283. });
  28284. stackedDimCoordIndex++;
  28285. dimensionInfoList.push({
  28286. name: stackedOverDimension,
  28287. // This dimension contains stack base (generally, 0), so do not set it as
  28288. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28289. coordDim: stackedOverDimension,
  28290. coordDimIndex: stackedDimCoordIndex,
  28291. type: stackedDimType,
  28292. isExtraCoord: true,
  28293. isCalculationCoord: true
  28294. });
  28295. }
  28296. return {
  28297. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28298. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28299. isStackedByIndex: byIndex,
  28300. stackedOverDimension: stackedOverDimension,
  28301. stackResultDimension: stackResultDimension
  28302. };
  28303. }
  28304. /**
  28305. * @param {module:echarts/data/List} data
  28306. * @param {string} stackedDim
  28307. */
  28308. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28309. // Each single series only maps to one pair of axis. So we do not need to
  28310. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28311. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28312. // && (
  28313. // stackedByDim != null
  28314. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28315. // : data.getCalculationInfo('isStackedByIndex')
  28316. // );
  28317. }
  28318. /**
  28319. * @param {module:echarts/data/List} data
  28320. * @param {string} targetDim
  28321. * @param {string} [stackedByDim] If not input this parameter, check whether
  28322. * stacked by index.
  28323. * @return {string} dimension
  28324. */
  28325. function getStackedDimension(data, targetDim) {
  28326. return isDimensionStacked(data, targetDim)
  28327. ? data.getCalculationInfo('stackResultDimension')
  28328. : targetDim;
  28329. }
  28330. /*
  28331. * Licensed to the Apache Software Foundation (ASF) under one
  28332. * or more contributor license agreements. See the NOTICE file
  28333. * distributed with this work for additional information
  28334. * regarding copyright ownership. The ASF licenses this file
  28335. * to you under the Apache License, Version 2.0 (the
  28336. * "License"); you may not use this file except in compliance
  28337. * with the License. You may obtain a copy of the License at
  28338. *
  28339. * http://www.apache.org/licenses/LICENSE-2.0
  28340. *
  28341. * Unless required by applicable law or agreed to in writing,
  28342. * software distributed under the License is distributed on an
  28343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28344. * KIND, either express or implied. See the License for the
  28345. * specific language governing permissions and limitations
  28346. * under the License.
  28347. */
  28348. /**
  28349. * @param {module:echarts/data/Source|Array} source Or raw data.
  28350. * @param {module:echarts/model/Series} seriesModel
  28351. * @param {Object} [opt]
  28352. * @param {string} [opt.generateCoord]
  28353. * @param {boolean} [opt.useEncodeDefaulter]
  28354. */
  28355. function createListFromArray(source, seriesModel, opt) {
  28356. opt = opt || {};
  28357. if (!Source.isInstance(source)) {
  28358. source = Source.seriesDataToSource(source);
  28359. }
  28360. var coordSysName = seriesModel.get('coordinateSystem');
  28361. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28362. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28363. var coordSysDimDefs;
  28364. if (coordSysInfo) {
  28365. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28366. var dimInfo = {name: dim};
  28367. var axisModel = coordSysInfo.axisMap.get(dim);
  28368. if (axisModel) {
  28369. var axisType = axisModel.get('type');
  28370. dimInfo.type = getDimensionTypeByAxis(axisType);
  28371. // dimInfo.stackable = isStackable(axisType);
  28372. }
  28373. return dimInfo;
  28374. });
  28375. }
  28376. if (!coordSysDimDefs) {
  28377. // Get dimensions from registered coordinate system
  28378. coordSysDimDefs = (registeredCoordSys && (
  28379. registeredCoordSys.getDimensionsInfo
  28380. ? registeredCoordSys.getDimensionsInfo()
  28381. : registeredCoordSys.dimensions.slice()
  28382. )) || ['x', 'y'];
  28383. }
  28384. var dimInfoList = createDimensions(source, {
  28385. coordDimensions: coordSysDimDefs,
  28386. generateCoord: opt.generateCoord,
  28387. encodeDefaulter: opt.useEncodeDefaulter
  28388. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28389. : null
  28390. });
  28391. var firstCategoryDimIndex;
  28392. var hasNameEncode;
  28393. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  28394. var coordDim = dimInfo.coordDim;
  28395. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28396. if (categoryAxisModel) {
  28397. if (firstCategoryDimIndex == null) {
  28398. firstCategoryDimIndex = dimIndex;
  28399. }
  28400. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28401. }
  28402. if (dimInfo.otherDims.itemName != null) {
  28403. hasNameEncode = true;
  28404. }
  28405. });
  28406. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28407. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28408. }
  28409. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28410. var list = new List(dimInfoList, seriesModel);
  28411. list.setCalculationInfo(stackCalculationInfo);
  28412. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  28413. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28414. // Use dataIndex as ordinal value in categoryAxis
  28415. return dimIndex === firstCategoryDimIndex
  28416. ? dataIndex
  28417. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28418. }
  28419. : null;
  28420. list.hasItemOption = false;
  28421. list.initData(source, null, dimValueGetter);
  28422. return list;
  28423. }
  28424. function isNeedCompleteOrdinalData(source) {
  28425. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28426. var sampleItem = firstDataNotNull(source.data || []);
  28427. return sampleItem != null
  28428. && !isArray(getDataItemValue(sampleItem));
  28429. }
  28430. }
  28431. function firstDataNotNull(data) {
  28432. var i = 0;
  28433. while (i < data.length && data[i] == null) {
  28434. i++;
  28435. }
  28436. return data[i];
  28437. }
  28438. /*
  28439. * Licensed to the Apache Software Foundation (ASF) under one
  28440. * or more contributor license agreements. See the NOTICE file
  28441. * distributed with this work for additional information
  28442. * regarding copyright ownership. The ASF licenses this file
  28443. * to you under the Apache License, Version 2.0 (the
  28444. * "License"); you may not use this file except in compliance
  28445. * with the License. You may obtain a copy of the License at
  28446. *
  28447. * http://www.apache.org/licenses/LICENSE-2.0
  28448. *
  28449. * Unless required by applicable law or agreed to in writing,
  28450. * software distributed under the License is distributed on an
  28451. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28452. * KIND, either express or implied. See the License for the
  28453. * specific language governing permissions and limitations
  28454. * under the License.
  28455. */
  28456. SeriesModel.extend({
  28457. type: 'series.line',
  28458. dependencies: ['grid', 'polar'],
  28459. getInitialData: function (option, ecModel) {
  28460. if (__DEV__) {
  28461. var coordSys = option.coordinateSystem;
  28462. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  28463. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  28464. }
  28465. }
  28466. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  28467. },
  28468. defaultOption: {
  28469. zlevel: 0,
  28470. z: 2,
  28471. coordinateSystem: 'cartesian2d',
  28472. legendHoverLink: true,
  28473. hoverAnimation: true,
  28474. // stack: null
  28475. // xAxisIndex: 0,
  28476. // yAxisIndex: 0,
  28477. // polarIndex: 0,
  28478. // If clip the overflow value
  28479. clip: true,
  28480. // cursor: null,
  28481. label: {
  28482. position: 'top'
  28483. },
  28484. // itemStyle: {
  28485. // },
  28486. lineStyle: {
  28487. width: 2,
  28488. type: 'solid'
  28489. },
  28490. // areaStyle: {
  28491. // origin of areaStyle. Valid values:
  28492. // `'auto'/null/undefined`: from axisLine to data
  28493. // `'start'`: from min to data
  28494. // `'end'`: from data to max
  28495. // origin: 'auto'
  28496. // },
  28497. // false, 'start', 'end', 'middle'
  28498. step: false,
  28499. // Disabled if step is true
  28500. smooth: false,
  28501. smoothMonotone: null,
  28502. symbol: 'emptyCircle',
  28503. symbolSize: 4,
  28504. symbolRotate: null,
  28505. showSymbol: true,
  28506. // `false`: follow the label interval strategy.
  28507. // `true`: show all symbols.
  28508. // `'auto'`: If possible, show all symbols, otherwise
  28509. // follow the label interval strategy.
  28510. showAllSymbol: 'auto',
  28511. // Whether to connect break point.
  28512. connectNulls: false,
  28513. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  28514. sampling: 'none',
  28515. animationEasing: 'linear',
  28516. // Disable progressive
  28517. progressive: 0,
  28518. hoverLayerThreshold: Infinity
  28519. }
  28520. });
  28521. /*
  28522. * Licensed to the Apache Software Foundation (ASF) under one
  28523. * or more contributor license agreements. See the NOTICE file
  28524. * distributed with this work for additional information
  28525. * regarding copyright ownership. The ASF licenses this file
  28526. * to you under the Apache License, Version 2.0 (the
  28527. * "License"); you may not use this file except in compliance
  28528. * with the License. You may obtain a copy of the License at
  28529. *
  28530. * http://www.apache.org/licenses/LICENSE-2.0
  28531. *
  28532. * Unless required by applicable law or agreed to in writing,
  28533. * software distributed under the License is distributed on an
  28534. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28535. * KIND, either express or implied. See the License for the
  28536. * specific language governing permissions and limitations
  28537. * under the License.
  28538. */
  28539. // Symbol factory
  28540. /**
  28541. * Triangle shape
  28542. * @inner
  28543. */
  28544. var Triangle = extendShape({
  28545. type: 'triangle',
  28546. shape: {
  28547. cx: 0,
  28548. cy: 0,
  28549. width: 0,
  28550. height: 0
  28551. },
  28552. buildPath: function (path, shape) {
  28553. var cx = shape.cx;
  28554. var cy = shape.cy;
  28555. var width = shape.width / 2;
  28556. var height = shape.height / 2;
  28557. path.moveTo(cx, cy - height);
  28558. path.lineTo(cx + width, cy + height);
  28559. path.lineTo(cx - width, cy + height);
  28560. path.closePath();
  28561. }
  28562. });
  28563. /**
  28564. * Diamond shape
  28565. * @inner
  28566. */
  28567. var Diamond = extendShape({
  28568. type: 'diamond',
  28569. shape: {
  28570. cx: 0,
  28571. cy: 0,
  28572. width: 0,
  28573. height: 0
  28574. },
  28575. buildPath: function (path, shape) {
  28576. var cx = shape.cx;
  28577. var cy = shape.cy;
  28578. var width = shape.width / 2;
  28579. var height = shape.height / 2;
  28580. path.moveTo(cx, cy - height);
  28581. path.lineTo(cx + width, cy);
  28582. path.lineTo(cx, cy + height);
  28583. path.lineTo(cx - width, cy);
  28584. path.closePath();
  28585. }
  28586. });
  28587. /**
  28588. * Pin shape
  28589. * @inner
  28590. */
  28591. var Pin = extendShape({
  28592. type: 'pin',
  28593. shape: {
  28594. // x, y on the cusp
  28595. x: 0,
  28596. y: 0,
  28597. width: 0,
  28598. height: 0
  28599. },
  28600. buildPath: function (path, shape) {
  28601. var x = shape.x;
  28602. var y = shape.y;
  28603. var w = shape.width / 5 * 3;
  28604. // Height must be larger than width
  28605. var h = Math.max(w, shape.height);
  28606. var r = w / 2;
  28607. // Dist on y with tangent point and circle center
  28608. var dy = r * r / (h - r);
  28609. var cy = y - h + r + dy;
  28610. var angle = Math.asin(dy / r);
  28611. // Dist on x with tangent point and circle center
  28612. var dx = Math.cos(angle) * r;
  28613. var tanX = Math.sin(angle);
  28614. var tanY = Math.cos(angle);
  28615. var cpLen = r * 0.6;
  28616. var cpLen2 = r * 0.7;
  28617. path.moveTo(x - dx, cy + dy);
  28618. path.arc(
  28619. x, cy, r,
  28620. Math.PI - angle,
  28621. Math.PI * 2 + angle
  28622. );
  28623. path.bezierCurveTo(
  28624. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28625. x, y - cpLen2,
  28626. x, y
  28627. );
  28628. path.bezierCurveTo(
  28629. x, y - cpLen2,
  28630. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28631. x - dx, cy + dy
  28632. );
  28633. path.closePath();
  28634. }
  28635. });
  28636. /**
  28637. * Arrow shape
  28638. * @inner
  28639. */
  28640. var Arrow = extendShape({
  28641. type: 'arrow',
  28642. shape: {
  28643. x: 0,
  28644. y: 0,
  28645. width: 0,
  28646. height: 0
  28647. },
  28648. buildPath: function (ctx, shape) {
  28649. var height = shape.height;
  28650. var width = shape.width;
  28651. var x = shape.x;
  28652. var y = shape.y;
  28653. var dx = width / 3 * 2;
  28654. ctx.moveTo(x, y);
  28655. ctx.lineTo(x + dx, y + height);
  28656. ctx.lineTo(x, y + height / 4 * 3);
  28657. ctx.lineTo(x - dx, y + height);
  28658. ctx.lineTo(x, y);
  28659. ctx.closePath();
  28660. }
  28661. });
  28662. /**
  28663. * Map of path contructors
  28664. * @type {Object.<string, module:zrender/graphic/Path>}
  28665. */
  28666. var symbolCtors = {
  28667. line: Line,
  28668. rect: Rect,
  28669. roundRect: Rect,
  28670. square: Rect,
  28671. circle: Circle,
  28672. diamond: Diamond,
  28673. pin: Pin,
  28674. arrow: Arrow,
  28675. triangle: Triangle
  28676. };
  28677. var symbolShapeMakers = {
  28678. line: function (x, y, w, h, shape) {
  28679. // FIXME
  28680. shape.x1 = x;
  28681. shape.y1 = y + h / 2;
  28682. shape.x2 = x + w;
  28683. shape.y2 = y + h / 2;
  28684. },
  28685. rect: function (x, y, w, h, shape) {
  28686. shape.x = x;
  28687. shape.y = y;
  28688. shape.width = w;
  28689. shape.height = h;
  28690. },
  28691. roundRect: function (x, y, w, h, shape) {
  28692. shape.x = x;
  28693. shape.y = y;
  28694. shape.width = w;
  28695. shape.height = h;
  28696. shape.r = Math.min(w, h) / 4;
  28697. },
  28698. square: function (x, y, w, h, shape) {
  28699. var size = Math.min(w, h);
  28700. shape.x = x;
  28701. shape.y = y;
  28702. shape.width = size;
  28703. shape.height = size;
  28704. },
  28705. circle: function (x, y, w, h, shape) {
  28706. // Put circle in the center of square
  28707. shape.cx = x + w / 2;
  28708. shape.cy = y + h / 2;
  28709. shape.r = Math.min(w, h) / 2;
  28710. },
  28711. diamond: function (x, y, w, h, shape) {
  28712. shape.cx = x + w / 2;
  28713. shape.cy = y + h / 2;
  28714. shape.width = w;
  28715. shape.height = h;
  28716. },
  28717. pin: function (x, y, w, h, shape) {
  28718. shape.x = x + w / 2;
  28719. shape.y = y + h / 2;
  28720. shape.width = w;
  28721. shape.height = h;
  28722. },
  28723. arrow: function (x, y, w, h, shape) {
  28724. shape.x = x + w / 2;
  28725. shape.y = y + h / 2;
  28726. shape.width = w;
  28727. shape.height = h;
  28728. },
  28729. triangle: function (x, y, w, h, shape) {
  28730. shape.cx = x + w / 2;
  28731. shape.cy = y + h / 2;
  28732. shape.width = w;
  28733. shape.height = h;
  28734. }
  28735. };
  28736. var symbolBuildProxies = {};
  28737. each$1(symbolCtors, function (Ctor, name) {
  28738. symbolBuildProxies[name] = new Ctor();
  28739. });
  28740. var SymbolClz$2 = extendShape({
  28741. type: 'symbol',
  28742. shape: {
  28743. symbolType: '',
  28744. x: 0,
  28745. y: 0,
  28746. width: 0,
  28747. height: 0
  28748. },
  28749. calculateTextPosition: function (out, style, rect) {
  28750. var res = calculateTextPosition(out, style, rect);
  28751. var shape = this.shape;
  28752. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28753. res.y = rect.y + rect.height * 0.4;
  28754. }
  28755. return res;
  28756. },
  28757. buildPath: function (ctx, shape, inBundle) {
  28758. var symbolType = shape.symbolType;
  28759. if (symbolType !== 'none') {
  28760. var proxySymbol = symbolBuildProxies[symbolType];
  28761. if (!proxySymbol) {
  28762. // Default rect
  28763. symbolType = 'rect';
  28764. proxySymbol = symbolBuildProxies[symbolType];
  28765. }
  28766. symbolShapeMakers[symbolType](
  28767. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28768. );
  28769. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28770. }
  28771. }
  28772. });
  28773. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28774. function symbolPathSetColor(color, innerColor) {
  28775. if (this.type !== 'image') {
  28776. var symbolStyle = this.style;
  28777. var symbolShape = this.shape;
  28778. if (symbolShape && symbolShape.symbolType === 'line') {
  28779. symbolStyle.stroke = color;
  28780. }
  28781. else if (this.__isEmptyBrush) {
  28782. symbolStyle.stroke = color;
  28783. symbolStyle.fill = innerColor || '#fff';
  28784. }
  28785. else {
  28786. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28787. symbolStyle.fill && (symbolStyle.fill = color);
  28788. symbolStyle.stroke && (symbolStyle.stroke = color);
  28789. }
  28790. this.dirty(false);
  28791. }
  28792. }
  28793. /**
  28794. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28795. * @param {string} symbolType
  28796. * @param {number} x
  28797. * @param {number} y
  28798. * @param {number} w
  28799. * @param {number} h
  28800. * @param {string} color
  28801. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28802. * for path and image only.
  28803. */
  28804. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28805. // TODO Support image object, DynamicImage.
  28806. var isEmpty = symbolType.indexOf('empty') === 0;
  28807. if (isEmpty) {
  28808. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28809. }
  28810. var symbolPath;
  28811. if (symbolType.indexOf('image://') === 0) {
  28812. symbolPath = makeImage(
  28813. symbolType.slice(8),
  28814. new BoundingRect(x, y, w, h),
  28815. keepAspect ? 'center' : 'cover'
  28816. );
  28817. }
  28818. else if (symbolType.indexOf('path://') === 0) {
  28819. symbolPath = makePath(
  28820. symbolType.slice(7),
  28821. {},
  28822. new BoundingRect(x, y, w, h),
  28823. keepAspect ? 'center' : 'cover'
  28824. );
  28825. }
  28826. else {
  28827. symbolPath = new SymbolClz$2({
  28828. shape: {
  28829. symbolType: symbolType,
  28830. x: x,
  28831. y: y,
  28832. width: w,
  28833. height: h
  28834. }
  28835. });
  28836. }
  28837. symbolPath.__isEmptyBrush = isEmpty;
  28838. symbolPath.setColor = symbolPathSetColor;
  28839. symbolPath.setColor(color);
  28840. return symbolPath;
  28841. }
  28842. /*
  28843. * Licensed to the Apache Software Foundation (ASF) under one
  28844. * or more contributor license agreements. See the NOTICE file
  28845. * distributed with this work for additional information
  28846. * regarding copyright ownership. The ASF licenses this file
  28847. * to you under the Apache License, Version 2.0 (the
  28848. * "License"); you may not use this file except in compliance
  28849. * with the License. You may obtain a copy of the License at
  28850. *
  28851. * http://www.apache.org/licenses/LICENSE-2.0
  28852. *
  28853. * Unless required by applicable law or agreed to in writing,
  28854. * software distributed under the License is distributed on an
  28855. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28856. * KIND, either express or implied. See the License for the
  28857. * specific language governing permissions and limitations
  28858. * under the License.
  28859. */
  28860. /**
  28861. * @param {module:echarts/data/List} data
  28862. * @param {number} dataIndex
  28863. * @return {string} label string. Not null/undefined
  28864. */
  28865. function getDefaultLabel(data, dataIndex) {
  28866. var labelDims = data.mapDimension('defaultedLabel', true);
  28867. var len = labelDims.length;
  28868. // Simple optimization (in lots of cases, label dims length is 1)
  28869. if (len === 1) {
  28870. return retrieveRawValue(data, dataIndex, labelDims[0]);
  28871. }
  28872. else if (len) {
  28873. var vals = [];
  28874. for (var i = 0; i < labelDims.length; i++) {
  28875. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  28876. vals.push(val);
  28877. }
  28878. return vals.join(' ');
  28879. }
  28880. }
  28881. /*
  28882. * Licensed to the Apache Software Foundation (ASF) under one
  28883. * or more contributor license agreements. See the NOTICE file
  28884. * distributed with this work for additional information
  28885. * regarding copyright ownership. The ASF licenses this file
  28886. * to you under the Apache License, Version 2.0 (the
  28887. * "License"); you may not use this file except in compliance
  28888. * with the License. You may obtain a copy of the License at
  28889. *
  28890. * http://www.apache.org/licenses/LICENSE-2.0
  28891. *
  28892. * Unless required by applicable law or agreed to in writing,
  28893. * software distributed under the License is distributed on an
  28894. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28895. * KIND, either express or implied. See the License for the
  28896. * specific language governing permissions and limitations
  28897. * under the License.
  28898. */
  28899. /**
  28900. * @module echarts/chart/helper/Symbol
  28901. */
  28902. /**
  28903. * @constructor
  28904. * @alias {module:echarts/chart/helper/Symbol}
  28905. * @param {module:echarts/data/List} data
  28906. * @param {number} idx
  28907. * @extends {module:zrender/graphic/Group}
  28908. */
  28909. function SymbolClz(data, idx, seriesScope) {
  28910. Group.call(this);
  28911. this.updateData(data, idx, seriesScope);
  28912. }
  28913. var symbolProto = SymbolClz.prototype;
  28914. /**
  28915. * @public
  28916. * @static
  28917. * @param {module:echarts/data/List} data
  28918. * @param {number} dataIndex
  28919. * @return {Array.<number>} [width, height]
  28920. */
  28921. var getSymbolSize = SymbolClz.getSymbolSize = function (data, idx) {
  28922. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  28923. return symbolSize instanceof Array
  28924. ? symbolSize.slice()
  28925. : [+symbolSize, +symbolSize];
  28926. };
  28927. function getScale(symbolSize) {
  28928. return [symbolSize[0] / 2, symbolSize[1] / 2];
  28929. }
  28930. function driftSymbol(dx, dy) {
  28931. this.parent.drift(dx, dy);
  28932. }
  28933. symbolProto._createSymbol = function (
  28934. symbolType,
  28935. data,
  28936. idx,
  28937. symbolSize,
  28938. keepAspect
  28939. ) {
  28940. // Remove paths created before
  28941. this.removeAll();
  28942. var color = data.getItemVisual(idx, 'color');
  28943. // var symbolPath = createSymbol(
  28944. // symbolType, -0.5, -0.5, 1, 1, color
  28945. // );
  28946. // If width/height are set too small (e.g., set to 1) on ios10
  28947. // and macOS Sierra, a circle stroke become a rect, no matter what
  28948. // the scale is set. So we set width/height as 2. See #4150.
  28949. var symbolPath = createSymbol(
  28950. symbolType, -1, -1, 2, 2, color, keepAspect
  28951. );
  28952. symbolPath.attr({
  28953. z2: 100,
  28954. culling: true,
  28955. scale: getScale(symbolSize)
  28956. });
  28957. // Rewrite drift method
  28958. symbolPath.drift = driftSymbol;
  28959. this._symbolType = symbolType;
  28960. this.add(symbolPath);
  28961. };
  28962. /**
  28963. * Stop animation
  28964. * @param {boolean} toLastFrame
  28965. */
  28966. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  28967. this.childAt(0).stopAnimation(toLastFrame);
  28968. };
  28969. /**
  28970. * FIXME:
  28971. * Caution: This method breaks the encapsulation of this module,
  28972. * but it indeed brings convenience. So do not use the method
  28973. * unless you detailedly know all the implements of `Symbol`,
  28974. * especially animation.
  28975. *
  28976. * Get symbol path element.
  28977. */
  28978. symbolProto.getSymbolPath = function () {
  28979. return this.childAt(0);
  28980. };
  28981. /**
  28982. * Get scale(aka, current symbol size).
  28983. * Including the change caused by animation
  28984. */
  28985. symbolProto.getScale = function () {
  28986. return this.childAt(0).scale;
  28987. };
  28988. /**
  28989. * Highlight symbol
  28990. */
  28991. symbolProto.highlight = function () {
  28992. this.childAt(0).trigger('emphasis');
  28993. };
  28994. /**
  28995. * Downplay symbol
  28996. */
  28997. symbolProto.downplay = function () {
  28998. this.childAt(0).trigger('normal');
  28999. };
  29000. /**
  29001. * @param {number} zlevel
  29002. * @param {number} z
  29003. */
  29004. symbolProto.setZ = function (zlevel, z) {
  29005. var symbolPath = this.childAt(0);
  29006. symbolPath.zlevel = zlevel;
  29007. symbolPath.z = z;
  29008. };
  29009. symbolProto.setDraggable = function (draggable) {
  29010. var symbolPath = this.childAt(0);
  29011. symbolPath.draggable = draggable;
  29012. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  29013. };
  29014. /**
  29015. * Update symbol properties
  29016. * @param {module:echarts/data/List} data
  29017. * @param {number} idx
  29018. * @param {Object} [seriesScope]
  29019. * @param {Object} [seriesScope.itemStyle]
  29020. * @param {Object} [seriesScope.hoverItemStyle]
  29021. * @param {Object} [seriesScope.symbolRotate]
  29022. * @param {Object} [seriesScope.symbolOffset]
  29023. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  29024. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  29025. * @param {boolean} [seriesScope.hoverAnimation]
  29026. * @param {Object} [seriesScope.cursorStyle]
  29027. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29028. * @param {string} [seriesScope.symbolInnerColor]
  29029. * @param {Object} [seriesScope.fadeIn=false]
  29030. */
  29031. symbolProto.updateData = function (data, idx, seriesScope) {
  29032. this.silent = false;
  29033. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29034. var seriesModel = data.hostModel;
  29035. var symbolSize = getSymbolSize(data, idx);
  29036. var isInit = symbolType !== this._symbolType;
  29037. if (isInit) {
  29038. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29039. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29040. }
  29041. else {
  29042. var symbolPath = this.childAt(0);
  29043. symbolPath.silent = false;
  29044. updateProps(symbolPath, {
  29045. scale: getScale(symbolSize)
  29046. }, seriesModel, idx);
  29047. }
  29048. this._updateCommon(data, idx, symbolSize, seriesScope);
  29049. if (isInit) {
  29050. var symbolPath = this.childAt(0);
  29051. var fadeIn = seriesScope && seriesScope.fadeIn;
  29052. var target = {scale: symbolPath.scale.slice()};
  29053. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29054. symbolPath.scale = [0, 0];
  29055. fadeIn && (symbolPath.style.opacity = 0);
  29056. initProps(symbolPath, target, seriesModel, idx);
  29057. }
  29058. this._seriesModel = seriesModel;
  29059. };
  29060. // Update common properties
  29061. var normalStyleAccessPath = ['itemStyle'];
  29062. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29063. var normalLabelAccessPath = ['label'];
  29064. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29065. /**
  29066. * @param {module:echarts/data/List} data
  29067. * @param {number} idx
  29068. * @param {Array.<number>} symbolSize
  29069. * @param {Object} [seriesScope]
  29070. */
  29071. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29072. var symbolPath = this.childAt(0);
  29073. var seriesModel = data.hostModel;
  29074. var color = data.getItemVisual(idx, 'color');
  29075. // Reset style
  29076. if (symbolPath.type !== 'image') {
  29077. symbolPath.useStyle({
  29078. strokeNoScale: true
  29079. });
  29080. }
  29081. else {
  29082. symbolPath.setStyle({
  29083. opacity: null,
  29084. shadowBlur: null,
  29085. shadowOffsetX: null,
  29086. shadowOffsetY: null,
  29087. shadowColor: null
  29088. });
  29089. }
  29090. var itemStyle = seriesScope && seriesScope.itemStyle;
  29091. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29092. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29093. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29094. var labelModel = seriesScope && seriesScope.labelModel;
  29095. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29096. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29097. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29098. if (!seriesScope || data.hasItemOption) {
  29099. var itemModel = (seriesScope && seriesScope.itemModel)
  29100. ? seriesScope.itemModel : data.getItemModel(idx);
  29101. // Color must be excluded.
  29102. // Because symbol provide setColor individually to set fill and stroke
  29103. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29104. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29105. symbolRotate = itemModel.getShallow('symbolRotate');
  29106. symbolOffset = itemModel.getShallow('symbolOffset');
  29107. labelModel = itemModel.getModel(normalLabelAccessPath);
  29108. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29109. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29110. cursorStyle = itemModel.getShallow('cursor');
  29111. }
  29112. else {
  29113. hoverItemStyle = extend({}, hoverItemStyle);
  29114. }
  29115. var elStyle = symbolPath.style;
  29116. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29117. if (symbolOffset) {
  29118. symbolPath.attr('position', [
  29119. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29120. parsePercent$1(symbolOffset[1], symbolSize[1])
  29121. ]);
  29122. }
  29123. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29124. // PENDING setColor before setStyle!!!
  29125. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29126. symbolPath.setStyle(itemStyle);
  29127. var opacity = data.getItemVisual(idx, 'opacity');
  29128. if (opacity != null) {
  29129. elStyle.opacity = opacity;
  29130. }
  29131. var liftZ = data.getItemVisual(idx, 'liftZ');
  29132. var z2Origin = symbolPath.__z2Origin;
  29133. if (liftZ != null) {
  29134. if (z2Origin == null) {
  29135. symbolPath.__z2Origin = symbolPath.z2;
  29136. symbolPath.z2 += liftZ;
  29137. }
  29138. }
  29139. else if (z2Origin != null) {
  29140. symbolPath.z2 = z2Origin;
  29141. symbolPath.__z2Origin = null;
  29142. }
  29143. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29144. setLabelStyle(
  29145. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29146. {
  29147. labelFetcher: seriesModel,
  29148. labelDataIndex: idx,
  29149. defaultText: getLabelDefaultText,
  29150. isRectText: true,
  29151. autoColor: color
  29152. }
  29153. );
  29154. // Do not execute util needed.
  29155. function getLabelDefaultText(idx, opt) {
  29156. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29157. }
  29158. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  29159. symbolPath.hoverStyle = hoverItemStyle;
  29160. symbolPath.highDownOnUpdate = (
  29161. hoverAnimation && seriesModel.isAnimationEnabled()
  29162. ) ? highDownOnUpdate : null;
  29163. setHoverStyle(symbolPath);
  29164. };
  29165. function highDownOnUpdate(fromState, toState) {
  29166. // Do not support this hover animation util some scenario required.
  29167. // Animation can only be supported in hover layer when using `el.incremetal`.
  29168. if (this.incremental || this.useHoverLayer) {
  29169. return;
  29170. }
  29171. if (toState === 'emphasis') {
  29172. var scale = this.__symbolOriginalScale;
  29173. var ratio = scale[1] / scale[0];
  29174. var emphasisOpt = {
  29175. scale: [
  29176. Math.max(scale[0] * 1.1, scale[0] + 3),
  29177. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29178. ]
  29179. };
  29180. // FIXME
  29181. // modify it after support stop specified animation.
  29182. // toState === fromState
  29183. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  29184. this.animateTo(emphasisOpt, 400, 'elasticOut');
  29185. }
  29186. else if (toState === 'normal') {
  29187. this.animateTo({
  29188. scale: this.__symbolOriginalScale
  29189. }, 400, 'elasticOut');
  29190. }
  29191. }
  29192. /**
  29193. * @param {Function} cb
  29194. * @param {Object} [opt]
  29195. * @param {Object} [opt.keepLabel=true]
  29196. */
  29197. symbolProto.fadeOut = function (cb, opt) {
  29198. var symbolPath = this.childAt(0);
  29199. // Avoid mistaken hover when fading out
  29200. this.silent = symbolPath.silent = true;
  29201. // Not show text when animating
  29202. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29203. updateProps(
  29204. symbolPath,
  29205. {
  29206. style: {opacity: 0},
  29207. scale: [0, 0]
  29208. },
  29209. this._seriesModel,
  29210. this.dataIndex,
  29211. cb
  29212. );
  29213. };
  29214. inherits(SymbolClz, Group);
  29215. /*
  29216. * Licensed to the Apache Software Foundation (ASF) under one
  29217. * or more contributor license agreements. See the NOTICE file
  29218. * distributed with this work for additional information
  29219. * regarding copyright ownership. The ASF licenses this file
  29220. * to you under the Apache License, Version 2.0 (the
  29221. * "License"); you may not use this file except in compliance
  29222. * with the License. You may obtain a copy of the License at
  29223. *
  29224. * http://www.apache.org/licenses/LICENSE-2.0
  29225. *
  29226. * Unless required by applicable law or agreed to in writing,
  29227. * software distributed under the License is distributed on an
  29228. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29229. * KIND, either express or implied. See the License for the
  29230. * specific language governing permissions and limitations
  29231. * under the License.
  29232. */
  29233. /**
  29234. * @module echarts/chart/helper/SymbolDraw
  29235. */
  29236. /**
  29237. * @constructor
  29238. * @alias module:echarts/chart/helper/SymbolDraw
  29239. * @param {module:zrender/graphic/Group} [symbolCtor]
  29240. */
  29241. function SymbolDraw(symbolCtor) {
  29242. this.group = new Group();
  29243. this._symbolCtor = symbolCtor || SymbolClz;
  29244. }
  29245. var symbolDrawProto = SymbolDraw.prototype;
  29246. function symbolNeedsDraw(data, point, idx, opt) {
  29247. return point && !isNaN(point[0]) && !isNaN(point[1])
  29248. && !(opt.isIgnore && opt.isIgnore(idx))
  29249. // We do not set clipShape on group, because it will cut part of
  29250. // the symbol element shape. We use the same clip shape here as
  29251. // the line clip.
  29252. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29253. && data.getItemVisual(idx, 'symbol') !== 'none';
  29254. }
  29255. /**
  29256. * Update symbols draw by new data
  29257. * @param {module:echarts/data/List} data
  29258. * @param {Object} [opt] Or isIgnore
  29259. * @param {Function} [opt.isIgnore]
  29260. * @param {Object} [opt.clipShape]
  29261. */
  29262. symbolDrawProto.updateData = function (data, opt) {
  29263. opt = normalizeUpdateOpt(opt);
  29264. var group = this.group;
  29265. var seriesModel = data.hostModel;
  29266. var oldData = this._data;
  29267. var SymbolCtor = this._symbolCtor;
  29268. var seriesScope = makeSeriesScope(data);
  29269. // There is no oldLineData only when first rendering or switching from
  29270. // stream mode to normal mode, where previous elements should be removed.
  29271. if (!oldData) {
  29272. group.removeAll();
  29273. }
  29274. data.diff(oldData)
  29275. .add(function (newIdx) {
  29276. var point = data.getItemLayout(newIdx);
  29277. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29278. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29279. symbolEl.attr('position', point);
  29280. data.setItemGraphicEl(newIdx, symbolEl);
  29281. group.add(symbolEl);
  29282. }
  29283. })
  29284. .update(function (newIdx, oldIdx) {
  29285. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29286. var point = data.getItemLayout(newIdx);
  29287. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29288. group.remove(symbolEl);
  29289. return;
  29290. }
  29291. if (!symbolEl) {
  29292. symbolEl = new SymbolCtor(data, newIdx);
  29293. symbolEl.attr('position', point);
  29294. }
  29295. else {
  29296. symbolEl.updateData(data, newIdx, seriesScope);
  29297. updateProps(symbolEl, {
  29298. position: point
  29299. }, seriesModel);
  29300. }
  29301. // Add back
  29302. group.add(symbolEl);
  29303. data.setItemGraphicEl(newIdx, symbolEl);
  29304. })
  29305. .remove(function (oldIdx) {
  29306. var el = oldData.getItemGraphicEl(oldIdx);
  29307. el && el.fadeOut(function () {
  29308. group.remove(el);
  29309. });
  29310. })
  29311. .execute();
  29312. this._data = data;
  29313. };
  29314. symbolDrawProto.isPersistent = function () {
  29315. return true;
  29316. };
  29317. symbolDrawProto.updateLayout = function () {
  29318. var data = this._data;
  29319. if (data) {
  29320. // Not use animation
  29321. data.eachItemGraphicEl(function (el, idx) {
  29322. var point = data.getItemLayout(idx);
  29323. el.attr('position', point);
  29324. });
  29325. }
  29326. };
  29327. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29328. this._seriesScope = makeSeriesScope(data);
  29329. this._data = null;
  29330. this.group.removeAll();
  29331. };
  29332. /**
  29333. * Update symbols draw by new data
  29334. * @param {module:echarts/data/List} data
  29335. * @param {Object} [opt] Or isIgnore
  29336. * @param {Function} [opt.isIgnore]
  29337. * @param {Object} [opt.clipShape]
  29338. */
  29339. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29340. opt = normalizeUpdateOpt(opt);
  29341. function updateIncrementalAndHover(el) {
  29342. if (!el.isGroup) {
  29343. el.incremental = el.useHoverLayer = true;
  29344. }
  29345. }
  29346. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29347. var point = data.getItemLayout(idx);
  29348. if (symbolNeedsDraw(data, point, idx, opt)) {
  29349. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29350. el.traverse(updateIncrementalAndHover);
  29351. el.attr('position', point);
  29352. this.group.add(el);
  29353. data.setItemGraphicEl(idx, el);
  29354. }
  29355. }
  29356. };
  29357. function normalizeUpdateOpt(opt) {
  29358. if (opt != null && !isObject$1(opt)) {
  29359. opt = {isIgnore: opt};
  29360. }
  29361. return opt || {};
  29362. }
  29363. symbolDrawProto.remove = function (enableAnimation) {
  29364. var group = this.group;
  29365. var data = this._data;
  29366. // Incremental model do not have this._data.
  29367. if (data && enableAnimation) {
  29368. data.eachItemGraphicEl(function (el) {
  29369. el.fadeOut(function () {
  29370. group.remove(el);
  29371. });
  29372. });
  29373. }
  29374. else {
  29375. group.removeAll();
  29376. }
  29377. };
  29378. function makeSeriesScope(data) {
  29379. var seriesModel = data.hostModel;
  29380. return {
  29381. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29382. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29383. symbolRotate: seriesModel.get('symbolRotate'),
  29384. symbolOffset: seriesModel.get('symbolOffset'),
  29385. hoverAnimation: seriesModel.get('hoverAnimation'),
  29386. labelModel: seriesModel.getModel('label'),
  29387. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29388. cursorStyle: seriesModel.get('cursor')
  29389. };
  29390. }
  29391. /*
  29392. * Licensed to the Apache Software Foundation (ASF) under one
  29393. * or more contributor license agreements. See the NOTICE file
  29394. * distributed with this work for additional information
  29395. * regarding copyright ownership. The ASF licenses this file
  29396. * to you under the Apache License, Version 2.0 (the
  29397. * "License"); you may not use this file except in compliance
  29398. * with the License. You may obtain a copy of the License at
  29399. *
  29400. * http://www.apache.org/licenses/LICENSE-2.0
  29401. *
  29402. * Unless required by applicable law or agreed to in writing,
  29403. * software distributed under the License is distributed on an
  29404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29405. * KIND, either express or implied. See the License for the
  29406. * specific language governing permissions and limitations
  29407. * under the License.
  29408. */
  29409. /**
  29410. * @param {Object} coordSys
  29411. * @param {module:echarts/data/List} data
  29412. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29413. */
  29414. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29415. var baseAxis = coordSys.getBaseAxis();
  29416. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29417. var valueStart = getValueStart(valueAxis, valueOrigin);
  29418. var baseAxisDim = baseAxis.dim;
  29419. var valueAxisDim = valueAxis.dim;
  29420. var valueDim = data.mapDimension(valueAxisDim);
  29421. var baseDim = data.mapDimension(baseAxisDim);
  29422. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29423. var dims = map(coordSys.dimensions, function (coordDim) {
  29424. return data.mapDimension(coordDim);
  29425. });
  29426. var stacked;
  29427. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29428. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  29429. dims[0] = stackResultDim;
  29430. }
  29431. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  29432. dims[1] = stackResultDim;
  29433. }
  29434. return {
  29435. dataDimsForPoint: dims,
  29436. valueStart: valueStart,
  29437. valueAxisDim: valueAxisDim,
  29438. baseAxisDim: baseAxisDim,
  29439. stacked: !!stacked,
  29440. valueDim: valueDim,
  29441. baseDim: baseDim,
  29442. baseDataOffset: baseDataOffset,
  29443. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29444. };
  29445. }
  29446. function getValueStart(valueAxis, valueOrigin) {
  29447. var valueStart = 0;
  29448. var extent = valueAxis.scale.getExtent();
  29449. if (valueOrigin === 'start') {
  29450. valueStart = extent[0];
  29451. }
  29452. else if (valueOrigin === 'end') {
  29453. valueStart = extent[1];
  29454. }
  29455. // auto
  29456. else {
  29457. // Both positive
  29458. if (extent[0] > 0) {
  29459. valueStart = extent[0];
  29460. }
  29461. // Both negative
  29462. else if (extent[1] < 0) {
  29463. valueStart = extent[1];
  29464. }
  29465. // If is one positive, and one negative, onZero shall be true
  29466. }
  29467. return valueStart;
  29468. }
  29469. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  29470. var value = NaN;
  29471. if (dataCoordInfo.stacked) {
  29472. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  29473. }
  29474. if (isNaN(value)) {
  29475. value = dataCoordInfo.valueStart;
  29476. }
  29477. var baseDataOffset = dataCoordInfo.baseDataOffset;
  29478. var stackedData = [];
  29479. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  29480. stackedData[1 - baseDataOffset] = value;
  29481. return coordSys.dataToPoint(stackedData);
  29482. }
  29483. /*
  29484. * Licensed to the Apache Software Foundation (ASF) under one
  29485. * or more contributor license agreements. See the NOTICE file
  29486. * distributed with this work for additional information
  29487. * regarding copyright ownership. The ASF licenses this file
  29488. * to you under the Apache License, Version 2.0 (the
  29489. * "License"); you may not use this file except in compliance
  29490. * with the License. You may obtain a copy of the License at
  29491. *
  29492. * http://www.apache.org/licenses/LICENSE-2.0
  29493. *
  29494. * Unless required by applicable law or agreed to in writing,
  29495. * software distributed under the License is distributed on an
  29496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29497. * KIND, either express or implied. See the License for the
  29498. * specific language governing permissions and limitations
  29499. * under the License.
  29500. */
  29501. // var arrayDiff = require('zrender/src/core/arrayDiff');
  29502. // 'zrender/src/core/arrayDiff' has been used before, but it did
  29503. // not do well in performance when roam with fixed dataZoom window.
  29504. // function convertToIntId(newIdList, oldIdList) {
  29505. // // Generate int id instead of string id.
  29506. // // Compare string maybe slow in score function of arrDiff
  29507. // // Assume id in idList are all unique
  29508. // var idIndicesMap = {};
  29509. // var idx = 0;
  29510. // for (var i = 0; i < newIdList.length; i++) {
  29511. // idIndicesMap[newIdList[i]] = idx;
  29512. // newIdList[i] = idx++;
  29513. // }
  29514. // for (var i = 0; i < oldIdList.length; i++) {
  29515. // var oldId = oldIdList[i];
  29516. // // Same with newIdList
  29517. // if (idIndicesMap[oldId]) {
  29518. // oldIdList[i] = idIndicesMap[oldId];
  29519. // }
  29520. // else {
  29521. // oldIdList[i] = idx++;
  29522. // }
  29523. // }
  29524. // }
  29525. function diffData(oldData, newData) {
  29526. var diffResult = [];
  29527. newData.diff(oldData)
  29528. .add(function (idx) {
  29529. diffResult.push({cmd: '+', idx: idx});
  29530. })
  29531. .update(function (newIdx, oldIdx) {
  29532. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  29533. })
  29534. .remove(function (idx) {
  29535. diffResult.push({cmd: '-', idx: idx});
  29536. })
  29537. .execute();
  29538. return diffResult;
  29539. }
  29540. var lineAnimationDiff = function (
  29541. oldData, newData,
  29542. oldStackedOnPoints, newStackedOnPoints,
  29543. oldCoordSys, newCoordSys,
  29544. oldValueOrigin, newValueOrigin
  29545. ) {
  29546. var diff = diffData(oldData, newData);
  29547. // var newIdList = newData.mapArray(newData.getId);
  29548. // var oldIdList = oldData.mapArray(oldData.getId);
  29549. // convertToIntId(newIdList, oldIdList);
  29550. // // FIXME One data ?
  29551. // diff = arrayDiff(oldIdList, newIdList);
  29552. var currPoints = [];
  29553. var nextPoints = [];
  29554. // Points for stacking base line
  29555. var currStackedPoints = [];
  29556. var nextStackedPoints = [];
  29557. var status = [];
  29558. var sortedIndices = [];
  29559. var rawIndices = [];
  29560. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  29561. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  29562. for (var i = 0; i < diff.length; i++) {
  29563. var diffItem = diff[i];
  29564. var pointAdded = true;
  29565. // FIXME, animation is not so perfect when dataZoom window moves fast
  29566. // Which is in case remvoing or add more than one data in the tail or head
  29567. switch (diffItem.cmd) {
  29568. case '=':
  29569. var currentPt = oldData.getItemLayout(diffItem.idx);
  29570. var nextPt = newData.getItemLayout(diffItem.idx1);
  29571. // If previous data is NaN, use next point directly
  29572. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  29573. currentPt = nextPt.slice();
  29574. }
  29575. currPoints.push(currentPt);
  29576. nextPoints.push(nextPt);
  29577. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  29578. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  29579. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  29580. break;
  29581. case '+':
  29582. var idx = diffItem.idx;
  29583. currPoints.push(
  29584. oldCoordSys.dataToPoint([
  29585. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  29586. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  29587. ])
  29588. );
  29589. nextPoints.push(newData.getItemLayout(idx).slice());
  29590. currStackedPoints.push(
  29591. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  29592. );
  29593. nextStackedPoints.push(newStackedOnPoints[idx]);
  29594. rawIndices.push(newData.getRawIndex(idx));
  29595. break;
  29596. case '-':
  29597. var idx = diffItem.idx;
  29598. var rawIndex = oldData.getRawIndex(idx);
  29599. // Data is replaced. In the case of dynamic data queue
  29600. // FIXME FIXME FIXME
  29601. if (rawIndex !== idx) {
  29602. currPoints.push(oldData.getItemLayout(idx));
  29603. nextPoints.push(newCoordSys.dataToPoint([
  29604. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  29605. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  29606. ]));
  29607. currStackedPoints.push(oldStackedOnPoints[idx]);
  29608. nextStackedPoints.push(
  29609. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  29610. );
  29611. rawIndices.push(rawIndex);
  29612. }
  29613. else {
  29614. pointAdded = false;
  29615. }
  29616. }
  29617. // Original indices
  29618. if (pointAdded) {
  29619. status.push(diffItem);
  29620. sortedIndices.push(sortedIndices.length);
  29621. }
  29622. }
  29623. // Diff result may be crossed if all items are changed
  29624. // Sort by data index
  29625. sortedIndices.sort(function (a, b) {
  29626. return rawIndices[a] - rawIndices[b];
  29627. });
  29628. var sortedCurrPoints = [];
  29629. var sortedNextPoints = [];
  29630. var sortedCurrStackedPoints = [];
  29631. var sortedNextStackedPoints = [];
  29632. var sortedStatus = [];
  29633. for (var i = 0; i < sortedIndices.length; i++) {
  29634. var idx = sortedIndices[i];
  29635. sortedCurrPoints[i] = currPoints[idx];
  29636. sortedNextPoints[i] = nextPoints[idx];
  29637. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  29638. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  29639. sortedStatus[i] = status[idx];
  29640. }
  29641. return {
  29642. current: sortedCurrPoints,
  29643. next: sortedNextPoints,
  29644. stackedOnCurrent: sortedCurrStackedPoints,
  29645. stackedOnNext: sortedNextStackedPoints,
  29646. status: sortedStatus
  29647. };
  29648. };
  29649. /*
  29650. * Licensed to the Apache Software Foundation (ASF) under one
  29651. * or more contributor license agreements. See the NOTICE file
  29652. * distributed with this work for additional information
  29653. * regarding copyright ownership. The ASF licenses this file
  29654. * to you under the Apache License, Version 2.0 (the
  29655. * "License"); you may not use this file except in compliance
  29656. * with the License. You may obtain a copy of the License at
  29657. *
  29658. * http://www.apache.org/licenses/LICENSE-2.0
  29659. *
  29660. * Unless required by applicable law or agreed to in writing,
  29661. * software distributed under the License is distributed on an
  29662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29663. * KIND, either express or implied. See the License for the
  29664. * specific language governing permissions and limitations
  29665. * under the License.
  29666. */
  29667. // Poly path support NaN point
  29668. var vec2Min = min;
  29669. var vec2Max = max;
  29670. var scaleAndAdd$1 = scaleAndAdd;
  29671. var v2Copy = copy;
  29672. // Temporary variable
  29673. var v = [];
  29674. var cp0 = [];
  29675. var cp1 = [];
  29676. function isPointNull(p) {
  29677. return isNaN(p[0]) || isNaN(p[1]);
  29678. }
  29679. function drawSegment(
  29680. ctx, points, start, segLen, allLen,
  29681. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29682. ) {
  29683. // if (smoothMonotone == null) {
  29684. // if (isMono(points, 'x')) {
  29685. // return drawMono(ctx, points, start, segLen, allLen,
  29686. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  29687. // }
  29688. // else if (isMono(points, 'y')) {
  29689. // return drawMono(ctx, points, start, segLen, allLen,
  29690. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  29691. // }
  29692. // else {
  29693. // return drawNonMono.apply(this, arguments);
  29694. // }
  29695. // }
  29696. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  29697. // return drawMono.apply(this, arguments);
  29698. // }
  29699. // else {
  29700. // return drawNonMono.apply(this, arguments);
  29701. // }
  29702. if (smoothMonotone === 'none' || !smoothMonotone) {
  29703. return drawNonMono.apply(this, arguments);
  29704. }
  29705. else {
  29706. return drawMono.apply(this, arguments);
  29707. }
  29708. }
  29709. /**
  29710. * Check if points is in monotone.
  29711. *
  29712. * @param {number[][]} points Array of points which is in [x, y] form
  29713. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  29714. * dimension that is checking.
  29715. * If is 'none', `drawNonMono` should be
  29716. * called.
  29717. * If is undefined, either being monotone
  29718. * in 'x' or 'y' will call `drawMono`.
  29719. */
  29720. // function isMono(points, smoothMonotone) {
  29721. // if (points.length <= 1) {
  29722. // return true;
  29723. // }
  29724. // var dim = smoothMonotone === 'x' ? 0 : 1;
  29725. // var last = points[0][dim];
  29726. // var lastDiff = 0;
  29727. // for (var i = 1; i < points.length; ++i) {
  29728. // var diff = points[i][dim] - last;
  29729. // if (!isNaN(diff) && !isNaN(lastDiff)
  29730. // && diff !== 0 && lastDiff !== 0
  29731. // && ((diff >= 0) !== (lastDiff >= 0))
  29732. // ) {
  29733. // return false;
  29734. // }
  29735. // if (!isNaN(diff) && diff !== 0) {
  29736. // lastDiff = diff;
  29737. // last = points[i][dim];
  29738. // }
  29739. // }
  29740. // return true;
  29741. // }
  29742. /**
  29743. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  29744. * control points will be used. This should be used when points are monotone
  29745. * either in x or y dimension.
  29746. */
  29747. function drawMono(
  29748. ctx, points, start, segLen, allLen,
  29749. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29750. ) {
  29751. var prevIdx = 0;
  29752. var idx = start;
  29753. for (var k = 0; k < segLen; k++) {
  29754. var p = points[idx];
  29755. if (idx >= allLen || idx < 0) {
  29756. break;
  29757. }
  29758. if (isPointNull(p)) {
  29759. if (connectNulls) {
  29760. idx += dir;
  29761. continue;
  29762. }
  29763. break;
  29764. }
  29765. if (idx === start) {
  29766. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29767. }
  29768. else {
  29769. if (smooth > 0) {
  29770. var prevP = points[prevIdx];
  29771. var dim = smoothMonotone === 'y' ? 1 : 0;
  29772. // Length of control point to p, either in x or y, but not both
  29773. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  29774. v2Copy(cp0, prevP);
  29775. cp0[dim] = prevP[dim] + ctrlLen;
  29776. v2Copy(cp1, p);
  29777. cp1[dim] = p[dim] - ctrlLen;
  29778. ctx.bezierCurveTo(
  29779. cp0[0], cp0[1],
  29780. cp1[0], cp1[1],
  29781. p[0], p[1]
  29782. );
  29783. }
  29784. else {
  29785. ctx.lineTo(p[0], p[1]);
  29786. }
  29787. }
  29788. prevIdx = idx;
  29789. idx += dir;
  29790. }
  29791. return k;
  29792. }
  29793. /**
  29794. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  29795. * situations. This should be used when points are non-monotone neither in x or
  29796. * y dimension.
  29797. */
  29798. function drawNonMono(
  29799. ctx, points, start, segLen, allLen,
  29800. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29801. ) {
  29802. var prevIdx = 0;
  29803. var idx = start;
  29804. for (var k = 0; k < segLen; k++) {
  29805. var p = points[idx];
  29806. if (idx >= allLen || idx < 0) {
  29807. break;
  29808. }
  29809. if (isPointNull(p)) {
  29810. if (connectNulls) {
  29811. idx += dir;
  29812. continue;
  29813. }
  29814. break;
  29815. }
  29816. if (idx === start) {
  29817. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29818. v2Copy(cp0, p);
  29819. }
  29820. else {
  29821. if (smooth > 0) {
  29822. var nextIdx = idx + dir;
  29823. var nextP = points[nextIdx];
  29824. if (connectNulls) {
  29825. // Find next point not null
  29826. while (nextP && isPointNull(points[nextIdx])) {
  29827. nextIdx += dir;
  29828. nextP = points[nextIdx];
  29829. }
  29830. }
  29831. var ratioNextSeg = 0.5;
  29832. var prevP = points[prevIdx];
  29833. var nextP = points[nextIdx];
  29834. // Last point
  29835. if (!nextP || isPointNull(nextP)) {
  29836. v2Copy(cp1, p);
  29837. }
  29838. else {
  29839. // If next data is null in not connect case
  29840. if (isPointNull(nextP) && !connectNulls) {
  29841. nextP = p;
  29842. }
  29843. sub(v, nextP, prevP);
  29844. var lenPrevSeg;
  29845. var lenNextSeg;
  29846. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  29847. var dim = smoothMonotone === 'x' ? 0 : 1;
  29848. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  29849. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  29850. }
  29851. else {
  29852. lenPrevSeg = dist(p, prevP);
  29853. lenNextSeg = dist(p, nextP);
  29854. }
  29855. // Use ratio of seg length
  29856. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  29857. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  29858. }
  29859. // Smooth constraint
  29860. vec2Min(cp0, cp0, smoothMax);
  29861. vec2Max(cp0, cp0, smoothMin);
  29862. vec2Min(cp1, cp1, smoothMax);
  29863. vec2Max(cp1, cp1, smoothMin);
  29864. ctx.bezierCurveTo(
  29865. cp0[0], cp0[1],
  29866. cp1[0], cp1[1],
  29867. p[0], p[1]
  29868. );
  29869. // cp0 of next segment
  29870. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  29871. }
  29872. else {
  29873. ctx.lineTo(p[0], p[1]);
  29874. }
  29875. }
  29876. prevIdx = idx;
  29877. idx += dir;
  29878. }
  29879. return k;
  29880. }
  29881. function getBoundingBox(points, smoothConstraint) {
  29882. var ptMin = [Infinity, Infinity];
  29883. var ptMax = [-Infinity, -Infinity];
  29884. if (smoothConstraint) {
  29885. for (var i = 0; i < points.length; i++) {
  29886. var pt = points[i];
  29887. if (pt[0] < ptMin[0]) {
  29888. ptMin[0] = pt[0];
  29889. }
  29890. if (pt[1] < ptMin[1]) {
  29891. ptMin[1] = pt[1];
  29892. }
  29893. if (pt[0] > ptMax[0]) {
  29894. ptMax[0] = pt[0];
  29895. }
  29896. if (pt[1] > ptMax[1]) {
  29897. ptMax[1] = pt[1];
  29898. }
  29899. }
  29900. }
  29901. return {
  29902. min: smoothConstraint ? ptMin : ptMax,
  29903. max: smoothConstraint ? ptMax : ptMin
  29904. };
  29905. }
  29906. var Polyline$1 = Path.extend({
  29907. type: 'ec-polyline',
  29908. shape: {
  29909. points: [],
  29910. smooth: 0,
  29911. smoothConstraint: true,
  29912. smoothMonotone: null,
  29913. connectNulls: false
  29914. },
  29915. style: {
  29916. fill: null,
  29917. stroke: '#000'
  29918. },
  29919. brush: fixClipWithShadow(Path.prototype.brush),
  29920. buildPath: function (ctx, shape) {
  29921. var points = shape.points;
  29922. var i = 0;
  29923. var len$$1 = points.length;
  29924. var result = getBoundingBox(points, shape.smoothConstraint);
  29925. if (shape.connectNulls) {
  29926. // Must remove first and last null values avoid draw error in polygon
  29927. for (; len$$1 > 0; len$$1--) {
  29928. if (!isPointNull(points[len$$1 - 1])) {
  29929. break;
  29930. }
  29931. }
  29932. for (; i < len$$1; i++) {
  29933. if (!isPointNull(points[i])) {
  29934. break;
  29935. }
  29936. }
  29937. }
  29938. while (i < len$$1) {
  29939. i += drawSegment(
  29940. ctx, points, i, len$$1, len$$1,
  29941. 1, result.min, result.max, shape.smooth,
  29942. shape.smoothMonotone, shape.connectNulls
  29943. ) + 1;
  29944. }
  29945. }
  29946. });
  29947. var Polygon$1 = Path.extend({
  29948. type: 'ec-polygon',
  29949. shape: {
  29950. points: [],
  29951. // Offset between stacked base points and points
  29952. stackedOnPoints: [],
  29953. smooth: 0,
  29954. stackedOnSmooth: 0,
  29955. smoothConstraint: true,
  29956. smoothMonotone: null,
  29957. connectNulls: false
  29958. },
  29959. brush: fixClipWithShadow(Path.prototype.brush),
  29960. buildPath: function (ctx, shape) {
  29961. var points = shape.points;
  29962. var stackedOnPoints = shape.stackedOnPoints;
  29963. var i = 0;
  29964. var len$$1 = points.length;
  29965. var smoothMonotone = shape.smoothMonotone;
  29966. var bbox = getBoundingBox(points, shape.smoothConstraint);
  29967. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  29968. if (shape.connectNulls) {
  29969. // Must remove first and last null values avoid draw error in polygon
  29970. for (; len$$1 > 0; len$$1--) {
  29971. if (!isPointNull(points[len$$1 - 1])) {
  29972. break;
  29973. }
  29974. }
  29975. for (; i < len$$1; i++) {
  29976. if (!isPointNull(points[i])) {
  29977. break;
  29978. }
  29979. }
  29980. }
  29981. while (i < len$$1) {
  29982. var k = drawSegment(
  29983. ctx, points, i, len$$1, len$$1,
  29984. 1, bbox.min, bbox.max, shape.smooth,
  29985. smoothMonotone, shape.connectNulls
  29986. );
  29987. drawSegment(
  29988. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  29989. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  29990. smoothMonotone, shape.connectNulls
  29991. );
  29992. i += k + 1;
  29993. ctx.closePath();
  29994. }
  29995. }
  29996. });
  29997. /*
  29998. * Licensed to the Apache Software Foundation (ASF) under one
  29999. * or more contributor license agreements. See the NOTICE file
  30000. * distributed with this work for additional information
  30001. * regarding copyright ownership. The ASF licenses this file
  30002. * to you under the Apache License, Version 2.0 (the
  30003. * "License"); you may not use this file except in compliance
  30004. * with the License. You may obtain a copy of the License at
  30005. *
  30006. * http://www.apache.org/licenses/LICENSE-2.0
  30007. *
  30008. * Unless required by applicable law or agreed to in writing,
  30009. * software distributed under the License is distributed on an
  30010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30011. * KIND, either express or implied. See the License for the
  30012. * specific language governing permissions and limitations
  30013. * under the License.
  30014. */
  30015. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  30016. var rect = cartesian.getArea();
  30017. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  30018. var x = rect.x;
  30019. var y = rect.y;
  30020. var width = rect.width;
  30021. var height = rect.height;
  30022. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  30023. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  30024. x -= lineWidth / 2;
  30025. y -= lineWidth / 2;
  30026. width += lineWidth;
  30027. height += lineWidth;
  30028. var clipPath = new Rect({
  30029. shape: {
  30030. x: x,
  30031. y: y,
  30032. width: width,
  30033. height: height
  30034. }
  30035. });
  30036. if (hasAnimation) {
  30037. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30038. initProps(clipPath, {
  30039. shape: {
  30040. width: width,
  30041. height: height
  30042. }
  30043. }, seriesModel);
  30044. }
  30045. return clipPath;
  30046. }
  30047. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  30048. var sectorArea = polar.getArea();
  30049. // Avoid float number rounding error for symbol on the edge of axis extent.
  30050. var clipPath = new Sector({
  30051. shape: {
  30052. cx: round$1(polar.cx, 1),
  30053. cy: round$1(polar.cy, 1),
  30054. r0: round$1(sectorArea.r0, 1),
  30055. r: round$1(sectorArea.r, 1),
  30056. startAngle: sectorArea.startAngle,
  30057. endAngle: sectorArea.endAngle,
  30058. clockwise: sectorArea.clockwise
  30059. }
  30060. });
  30061. if (hasAnimation) {
  30062. clipPath.shape.endAngle = sectorArea.startAngle;
  30063. initProps(clipPath, {
  30064. shape: {
  30065. endAngle: sectorArea.endAngle
  30066. }
  30067. }, seriesModel);
  30068. }
  30069. return clipPath;
  30070. }
  30071. function createClipPath(coordSys, hasAnimation, seriesModel) {
  30072. if (!coordSys) {
  30073. return null;
  30074. }
  30075. else if (coordSys.type === 'polar') {
  30076. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30077. }
  30078. else if (coordSys.type === 'cartesian2d') {
  30079. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  30080. }
  30081. return null;
  30082. }
  30083. /*
  30084. * Licensed to the Apache Software Foundation (ASF) under one
  30085. * or more contributor license agreements. See the NOTICE file
  30086. * distributed with this work for additional information
  30087. * regarding copyright ownership. The ASF licenses this file
  30088. * to you under the Apache License, Version 2.0 (the
  30089. * "License"); you may not use this file except in compliance
  30090. * with the License. You may obtain a copy of the License at
  30091. *
  30092. * http://www.apache.org/licenses/LICENSE-2.0
  30093. *
  30094. * Unless required by applicable law or agreed to in writing,
  30095. * software distributed under the License is distributed on an
  30096. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30097. * KIND, either express or implied. See the License for the
  30098. * specific language governing permissions and limitations
  30099. * under the License.
  30100. */
  30101. // FIXME step not support polar
  30102. function isPointsSame(points1, points2) {
  30103. if (points1.length !== points2.length) {
  30104. return;
  30105. }
  30106. for (var i = 0; i < points1.length; i++) {
  30107. var p1 = points1[i];
  30108. var p2 = points2[i];
  30109. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30110. return;
  30111. }
  30112. }
  30113. return true;
  30114. }
  30115. function getSmooth(smooth) {
  30116. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30117. }
  30118. /**
  30119. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30120. * @param {module:echarts/data/List} data
  30121. * @param {Object} dataCoordInfo
  30122. * @param {Array.<Array.<number>>} points
  30123. */
  30124. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30125. if (!dataCoordInfo.valueDim) {
  30126. return [];
  30127. }
  30128. var points = [];
  30129. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30130. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30131. }
  30132. return points;
  30133. }
  30134. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30135. var baseAxis = coordSys.getBaseAxis();
  30136. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30137. var stepPoints = [];
  30138. for (var i = 0; i < points.length - 1; i++) {
  30139. var nextPt = points[i + 1];
  30140. var pt = points[i];
  30141. stepPoints.push(pt);
  30142. var stepPt = [];
  30143. switch (stepTurnAt) {
  30144. case 'end':
  30145. stepPt[baseIndex] = nextPt[baseIndex];
  30146. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30147. // default is start
  30148. stepPoints.push(stepPt);
  30149. break;
  30150. case 'middle':
  30151. // default is start
  30152. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30153. var stepPt2 = [];
  30154. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30155. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30156. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30157. stepPoints.push(stepPt);
  30158. stepPoints.push(stepPt2);
  30159. break;
  30160. default:
  30161. stepPt[baseIndex] = pt[baseIndex];
  30162. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30163. // default is start
  30164. stepPoints.push(stepPt);
  30165. }
  30166. }
  30167. // Last points
  30168. points[i] && stepPoints.push(points[i]);
  30169. return stepPoints;
  30170. }
  30171. function getVisualGradient(data, coordSys) {
  30172. var visualMetaList = data.getVisual('visualMeta');
  30173. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30174. // When data.count() is 0, gradient range can not be calculated.
  30175. return;
  30176. }
  30177. if (coordSys.type !== 'cartesian2d') {
  30178. if (__DEV__) {
  30179. console.warn('Visual map on line style is only supported on cartesian2d.');
  30180. }
  30181. return;
  30182. }
  30183. var coordDim;
  30184. var visualMeta;
  30185. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30186. var dimIndex = visualMetaList[i].dimension;
  30187. var dimName = data.dimensions[dimIndex];
  30188. var dimInfo = data.getDimensionInfo(dimName);
  30189. coordDim = dimInfo && dimInfo.coordDim;
  30190. // Can only be x or y
  30191. if (coordDim === 'x' || coordDim === 'y') {
  30192. visualMeta = visualMetaList[i];
  30193. break;
  30194. }
  30195. }
  30196. if (!visualMeta) {
  30197. if (__DEV__) {
  30198. console.warn('Visual map on line style only support x or y dimension.');
  30199. }
  30200. return;
  30201. }
  30202. // If the area to be rendered is bigger than area defined by LinearGradient,
  30203. // the canvas spec prescribes that the color of the first stop and the last
  30204. // stop should be used. But if two stops are added at offset 0, in effect
  30205. // browsers use the color of the second stop to render area outside
  30206. // LinearGradient. So we can only infinitesimally extend area defined in
  30207. // LinearGradient to render `outerColors`.
  30208. var axis = coordSys.getAxis(coordDim);
  30209. // dataToCoor mapping may not be linear, but must be monotonic.
  30210. var colorStops = map(visualMeta.stops, function (stop) {
  30211. return {
  30212. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30213. color: stop.color
  30214. };
  30215. });
  30216. var stopLen = colorStops.length;
  30217. var outerColors = visualMeta.outerColors.slice();
  30218. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30219. colorStops.reverse();
  30220. outerColors.reverse();
  30221. }
  30222. var tinyExtent = 10; // Arbitrary value: 10px
  30223. var minCoord = colorStops[0].coord - tinyExtent;
  30224. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30225. var coordSpan = maxCoord - minCoord;
  30226. if (coordSpan < 1e-3) {
  30227. return 'transparent';
  30228. }
  30229. each$1(colorStops, function (stop) {
  30230. stop.offset = (stop.coord - minCoord) / coordSpan;
  30231. });
  30232. colorStops.push({
  30233. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30234. color: outerColors[1] || 'transparent'
  30235. });
  30236. colorStops.unshift({ // notice colorStops.length have been changed.
  30237. offset: stopLen ? colorStops[0].offset : 0.5,
  30238. color: outerColors[0] || 'transparent'
  30239. });
  30240. // zrUtil.each(colorStops, function (colorStop) {
  30241. // // Make sure each offset has rounded px to avoid not sharp edge
  30242. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30243. // });
  30244. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30245. gradient[coordDim] = minCoord;
  30246. gradient[coordDim + '2'] = maxCoord;
  30247. return gradient;
  30248. }
  30249. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30250. var showAllSymbol = seriesModel.get('showAllSymbol');
  30251. var isAuto = showAllSymbol === 'auto';
  30252. if (showAllSymbol && !isAuto) {
  30253. return;
  30254. }
  30255. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30256. if (!categoryAxis) {
  30257. return;
  30258. }
  30259. // Note that category label interval strategy might bring some weird effect
  30260. // in some scenario: users may wonder why some of the symbols are not
  30261. // displayed. So we show all symbols as possible as we can.
  30262. if (isAuto
  30263. // Simplify the logic, do not determine label overlap here.
  30264. && canShowAllSymbolForCategory(categoryAxis, data)
  30265. ) {
  30266. return;
  30267. }
  30268. // Otherwise follow the label interval strategy on category axis.
  30269. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30270. var labelMap = {};
  30271. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30272. labelMap[labelItem.tickValue] = 1;
  30273. });
  30274. return function (dataIndex) {
  30275. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30276. };
  30277. }
  30278. function canShowAllSymbolForCategory(categoryAxis, data) {
  30279. // In mose cases, line is monotonous on category axis, and the label size
  30280. // is close with each other. So we check the symbol size and some of the
  30281. // label size alone with the category axis to estimate whether all symbol
  30282. // can be shown without overlap.
  30283. var axisExtent = categoryAxis.getExtent();
  30284. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30285. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30286. // Sampling some points, max 5.
  30287. var dataLen = data.count();
  30288. var step = Math.max(1, Math.round(dataLen / 5));
  30289. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30290. if (SymbolClz.getSymbolSize(
  30291. data, dataIndex
  30292. // Only for cartesian, where `isHorizontal` exists.
  30293. )[categoryAxis.isHorizontal() ? 1 : 0]
  30294. // Empirical number
  30295. * 1.5 > availSize
  30296. ) {
  30297. return false;
  30298. }
  30299. }
  30300. return true;
  30301. }
  30302. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  30303. if (coordSys.type === 'cartesian2d') {
  30304. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  30305. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  30306. // Expand clip shape to avoid clipping when line value exceeds axis
  30307. if (!seriesModel.get('clip', true)) {
  30308. var rectShape = clipPath.shape;
  30309. var expandSize = Math.max(rectShape.width, rectShape.height);
  30310. if (isHorizontal) {
  30311. rectShape.y -= expandSize;
  30312. rectShape.height += expandSize * 2;
  30313. }
  30314. else {
  30315. rectShape.x -= expandSize;
  30316. rectShape.width += expandSize * 2;
  30317. }
  30318. }
  30319. return clipPath;
  30320. }
  30321. else {
  30322. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30323. }
  30324. }
  30325. Chart.extend({
  30326. type: 'line',
  30327. init: function () {
  30328. var lineGroup = new Group();
  30329. var symbolDraw = new SymbolDraw();
  30330. this.group.add(symbolDraw.group);
  30331. this._symbolDraw = symbolDraw;
  30332. this._lineGroup = lineGroup;
  30333. },
  30334. render: function (seriesModel, ecModel, api) {
  30335. var coordSys = seriesModel.coordinateSystem;
  30336. var group = this.group;
  30337. var data = seriesModel.getData();
  30338. var lineStyleModel = seriesModel.getModel('lineStyle');
  30339. var areaStyleModel = seriesModel.getModel('areaStyle');
  30340. var points = data.mapArray(data.getItemLayout);
  30341. var isCoordSysPolar = coordSys.type === 'polar';
  30342. var prevCoordSys = this._coordSys;
  30343. var symbolDraw = this._symbolDraw;
  30344. var polyline = this._polyline;
  30345. var polygon = this._polygon;
  30346. var lineGroup = this._lineGroup;
  30347. var hasAnimation = seriesModel.get('animation');
  30348. var isAreaChart = !areaStyleModel.isEmpty();
  30349. var valueOrigin = areaStyleModel.get('origin');
  30350. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30351. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30352. var showSymbol = seriesModel.get('showSymbol');
  30353. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30354. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30355. // Remove temporary symbols
  30356. var oldData = this._data;
  30357. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30358. if (el.__temp) {
  30359. group.remove(el);
  30360. oldData.setItemGraphicEl(idx, null);
  30361. }
  30362. });
  30363. // Remove previous created symbols if showSymbol changed to false
  30364. if (!showSymbol) {
  30365. symbolDraw.remove();
  30366. }
  30367. group.add(lineGroup);
  30368. // FIXME step not support polar
  30369. var step = !isCoordSysPolar && seriesModel.get('step');
  30370. var clipShapeForSymbol;
  30371. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  30372. clipShapeForSymbol = coordSys.getArea();
  30373. // Avoid float number rounding error for symbol on the edge of axis extent.
  30374. // See #7913 and `test/dataZoom-clip.html`.
  30375. if (clipShapeForSymbol.width != null) {
  30376. clipShapeForSymbol.x -= 0.1;
  30377. clipShapeForSymbol.y -= 0.1;
  30378. clipShapeForSymbol.width += 0.2;
  30379. clipShapeForSymbol.height += 0.2;
  30380. }
  30381. else if (clipShapeForSymbol.r0) {
  30382. clipShapeForSymbol.r0 -= 0.5;
  30383. clipShapeForSymbol.r1 += 0.5;
  30384. }
  30385. }
  30386. this._clipShapeForSymbol = clipShapeForSymbol;
  30387. // Initialization animation or coordinate system changed
  30388. if (
  30389. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30390. ) {
  30391. showSymbol && symbolDraw.updateData(data, {
  30392. isIgnore: isIgnoreFunc,
  30393. clipShape: clipShapeForSymbol
  30394. });
  30395. if (step) {
  30396. // TODO If stacked series is not step
  30397. points = turnPointsIntoStep(points, coordSys, step);
  30398. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30399. }
  30400. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30401. if (isAreaChart) {
  30402. polygon = this._newPolygon(
  30403. points, stackedOnPoints,
  30404. coordSys, hasAnimation
  30405. );
  30406. }
  30407. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  30408. }
  30409. else {
  30410. if (isAreaChart && !polygon) {
  30411. // If areaStyle is added
  30412. polygon = this._newPolygon(
  30413. points, stackedOnPoints,
  30414. coordSys, hasAnimation
  30415. );
  30416. }
  30417. else if (polygon && !isAreaChart) {
  30418. // If areaStyle is removed
  30419. lineGroup.remove(polygon);
  30420. polygon = this._polygon = null;
  30421. }
  30422. // Update clipPath
  30423. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  30424. // Always update, or it is wrong in the case turning on legend
  30425. // because points are not changed
  30426. showSymbol && symbolDraw.updateData(data, {
  30427. isIgnore: isIgnoreFunc,
  30428. clipShape: clipShapeForSymbol
  30429. });
  30430. // Stop symbol animation and sync with line points
  30431. // FIXME performance?
  30432. data.eachItemGraphicEl(function (el) {
  30433. el.stopAnimation(true);
  30434. });
  30435. // In the case data zoom triggerred refreshing frequently
  30436. // Data may not change if line has a category axis. So it should animate nothing
  30437. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30438. || !isPointsSame(this._points, points)
  30439. ) {
  30440. if (hasAnimation) {
  30441. this._updateAnimation(
  30442. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30443. );
  30444. }
  30445. else {
  30446. // Not do it in update with animation
  30447. if (step) {
  30448. // TODO If stacked series is not step
  30449. points = turnPointsIntoStep(points, coordSys, step);
  30450. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30451. }
  30452. polyline.setShape({
  30453. points: points
  30454. });
  30455. polygon && polygon.setShape({
  30456. points: points,
  30457. stackedOnPoints: stackedOnPoints
  30458. });
  30459. }
  30460. }
  30461. }
  30462. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30463. polyline.useStyle(defaults(
  30464. // Use color in lineStyle first
  30465. lineStyleModel.getLineStyle(),
  30466. {
  30467. fill: 'none',
  30468. stroke: visualColor,
  30469. lineJoin: 'bevel'
  30470. }
  30471. ));
  30472. var smooth = seriesModel.get('smooth');
  30473. smooth = getSmooth(seriesModel.get('smooth'));
  30474. polyline.setShape({
  30475. smooth: smooth,
  30476. smoothMonotone: seriesModel.get('smoothMonotone'),
  30477. connectNulls: seriesModel.get('connectNulls')
  30478. });
  30479. if (polygon) {
  30480. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30481. var stackedOnSmooth = 0;
  30482. polygon.useStyle(defaults(
  30483. areaStyleModel.getAreaStyle(),
  30484. {
  30485. fill: visualColor,
  30486. opacity: 0.7,
  30487. lineJoin: 'bevel'
  30488. }
  30489. ));
  30490. if (stackedOnSeries) {
  30491. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30492. }
  30493. polygon.setShape({
  30494. smooth: smooth,
  30495. stackedOnSmooth: stackedOnSmooth,
  30496. smoothMonotone: seriesModel.get('smoothMonotone'),
  30497. connectNulls: seriesModel.get('connectNulls')
  30498. });
  30499. }
  30500. this._data = data;
  30501. // Save the coordinate system for transition animation when data changed
  30502. this._coordSys = coordSys;
  30503. this._stackedOnPoints = stackedOnPoints;
  30504. this._points = points;
  30505. this._step = step;
  30506. this._valueOrigin = valueOrigin;
  30507. },
  30508. dispose: function () {},
  30509. highlight: function (seriesModel, ecModel, api, payload) {
  30510. var data = seriesModel.getData();
  30511. var dataIndex = queryDataIndex(data, payload);
  30512. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  30513. var symbol = data.getItemGraphicEl(dataIndex);
  30514. if (!symbol) {
  30515. // Create a temporary symbol if it is not exists
  30516. var pt = data.getItemLayout(dataIndex);
  30517. if (!pt) {
  30518. // Null data
  30519. return;
  30520. }
  30521. // fix #11360: should't draw symbol outside clipShapeForSymbol
  30522. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  30523. return;
  30524. }
  30525. symbol = new SymbolClz(data, dataIndex);
  30526. symbol.position = pt;
  30527. symbol.setZ(
  30528. seriesModel.get('zlevel'),
  30529. seriesModel.get('z')
  30530. );
  30531. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  30532. symbol.__temp = true;
  30533. data.setItemGraphicEl(dataIndex, symbol);
  30534. // Stop scale animation
  30535. symbol.stopSymbolAnimation(true);
  30536. this.group.add(symbol);
  30537. }
  30538. symbol.highlight();
  30539. }
  30540. else {
  30541. // Highlight whole series
  30542. Chart.prototype.highlight.call(
  30543. this, seriesModel, ecModel, api, payload
  30544. );
  30545. }
  30546. },
  30547. downplay: function (seriesModel, ecModel, api, payload) {
  30548. var data = seriesModel.getData();
  30549. var dataIndex = queryDataIndex(data, payload);
  30550. if (dataIndex != null && dataIndex >= 0) {
  30551. var symbol = data.getItemGraphicEl(dataIndex);
  30552. if (symbol) {
  30553. if (symbol.__temp) {
  30554. data.setItemGraphicEl(dataIndex, null);
  30555. this.group.remove(symbol);
  30556. }
  30557. else {
  30558. symbol.downplay();
  30559. }
  30560. }
  30561. }
  30562. else {
  30563. // FIXME
  30564. // can not downplay completely.
  30565. // Downplay whole series
  30566. Chart.prototype.downplay.call(
  30567. this, seriesModel, ecModel, api, payload
  30568. );
  30569. }
  30570. },
  30571. /**
  30572. * @param {module:zrender/container/Group} group
  30573. * @param {Array.<Array.<number>>} points
  30574. * @private
  30575. */
  30576. _newPolyline: function (points) {
  30577. var polyline = this._polyline;
  30578. // Remove previous created polyline
  30579. if (polyline) {
  30580. this._lineGroup.remove(polyline);
  30581. }
  30582. polyline = new Polyline$1({
  30583. shape: {
  30584. points: points
  30585. },
  30586. silent: true,
  30587. z2: 10
  30588. });
  30589. this._lineGroup.add(polyline);
  30590. this._polyline = polyline;
  30591. return polyline;
  30592. },
  30593. /**
  30594. * @param {module:zrender/container/Group} group
  30595. * @param {Array.<Array.<number>>} stackedOnPoints
  30596. * @param {Array.<Array.<number>>} points
  30597. * @private
  30598. */
  30599. _newPolygon: function (points, stackedOnPoints) {
  30600. var polygon = this._polygon;
  30601. // Remove previous created polygon
  30602. if (polygon) {
  30603. this._lineGroup.remove(polygon);
  30604. }
  30605. polygon = new Polygon$1({
  30606. shape: {
  30607. points: points,
  30608. stackedOnPoints: stackedOnPoints
  30609. },
  30610. silent: true
  30611. });
  30612. this._lineGroup.add(polygon);
  30613. this._polygon = polygon;
  30614. return polygon;
  30615. },
  30616. /**
  30617. * @private
  30618. */
  30619. // FIXME Two value axis
  30620. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  30621. var polyline = this._polyline;
  30622. var polygon = this._polygon;
  30623. var seriesModel = data.hostModel;
  30624. var diff = lineAnimationDiff(
  30625. this._data, data,
  30626. this._stackedOnPoints, stackedOnPoints,
  30627. this._coordSys, coordSys,
  30628. this._valueOrigin, valueOrigin
  30629. );
  30630. var current = diff.current;
  30631. var stackedOnCurrent = diff.stackedOnCurrent;
  30632. var next = diff.next;
  30633. var stackedOnNext = diff.stackedOnNext;
  30634. if (step) {
  30635. // TODO If stacked series is not step
  30636. current = turnPointsIntoStep(diff.current, coordSys, step);
  30637. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  30638. next = turnPointsIntoStep(diff.next, coordSys, step);
  30639. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  30640. }
  30641. // `diff.current` is subset of `current` (which should be ensured by
  30642. // turnPointsIntoStep), so points in `__points` can be updated when
  30643. // points in `current` are update during animation.
  30644. polyline.shape.__points = diff.current;
  30645. polyline.shape.points = current;
  30646. updateProps(polyline, {
  30647. shape: {
  30648. points: next
  30649. }
  30650. }, seriesModel);
  30651. if (polygon) {
  30652. polygon.setShape({
  30653. points: current,
  30654. stackedOnPoints: stackedOnCurrent
  30655. });
  30656. updateProps(polygon, {
  30657. shape: {
  30658. points: next,
  30659. stackedOnPoints: stackedOnNext
  30660. }
  30661. }, seriesModel);
  30662. }
  30663. var updatedDataInfo = [];
  30664. var diffStatus = diff.status;
  30665. for (var i = 0; i < diffStatus.length; i++) {
  30666. var cmd = diffStatus[i].cmd;
  30667. if (cmd === '=') {
  30668. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  30669. if (el) {
  30670. updatedDataInfo.push({
  30671. el: el,
  30672. ptIdx: i // Index of points
  30673. });
  30674. }
  30675. }
  30676. }
  30677. if (polyline.animators && polyline.animators.length) {
  30678. polyline.animators[0].during(function () {
  30679. for (var i = 0; i < updatedDataInfo.length; i++) {
  30680. var el = updatedDataInfo[i].el;
  30681. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  30682. }
  30683. });
  30684. }
  30685. },
  30686. remove: function (ecModel) {
  30687. var group = this.group;
  30688. var oldData = this._data;
  30689. this._lineGroup.removeAll();
  30690. this._symbolDraw.remove(true);
  30691. // Remove temporary created elements when highlighting
  30692. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30693. if (el.__temp) {
  30694. group.remove(el);
  30695. oldData.setItemGraphicEl(idx, null);
  30696. }
  30697. });
  30698. this._polyline =
  30699. this._polygon =
  30700. this._coordSys =
  30701. this._points =
  30702. this._stackedOnPoints =
  30703. this._data = null;
  30704. }
  30705. });
  30706. /*
  30707. * Licensed to the Apache Software Foundation (ASF) under one
  30708. * or more contributor license agreements. See the NOTICE file
  30709. * distributed with this work for additional information
  30710. * regarding copyright ownership. The ASF licenses this file
  30711. * to you under the Apache License, Version 2.0 (the
  30712. * "License"); you may not use this file except in compliance
  30713. * with the License. You may obtain a copy of the License at
  30714. *
  30715. * http://www.apache.org/licenses/LICENSE-2.0
  30716. *
  30717. * Unless required by applicable law or agreed to in writing,
  30718. * software distributed under the License is distributed on an
  30719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30720. * KIND, either express or implied. See the License for the
  30721. * specific language governing permissions and limitations
  30722. * under the License.
  30723. */
  30724. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  30725. // Encoding visual for all series include which is filtered for legend drawing
  30726. return {
  30727. seriesType: seriesType,
  30728. // For legend.
  30729. performRawSeries: true,
  30730. reset: function (seriesModel, ecModel, api) {
  30731. var data = seriesModel.getData();
  30732. var symbolType = seriesModel.get('symbol');
  30733. var symbolSize = seriesModel.get('symbolSize');
  30734. var keepAspect = seriesModel.get('symbolKeepAspect');
  30735. var hasSymbolTypeCallback = isFunction$1(symbolType);
  30736. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  30737. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  30738. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  30739. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  30740. data.setVisual({
  30741. legendSymbol: legendSymbol || seriesSymbol,
  30742. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  30743. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  30744. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  30745. // some cases but generally it is not recommanded.
  30746. symbol: seriesSymbol,
  30747. symbolSize: seriesSymbolSize,
  30748. symbolKeepAspect: keepAspect
  30749. });
  30750. // Only visible series has each data be visual encoded
  30751. if (ecModel.isSeriesFiltered(seriesModel)) {
  30752. return;
  30753. }
  30754. function dataEach(data, idx) {
  30755. if (hasCallback) {
  30756. var rawValue = seriesModel.getRawValue(idx);
  30757. var params = seriesModel.getDataParams(idx);
  30758. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  30759. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  30760. }
  30761. if (data.hasItemOption) {
  30762. var itemModel = data.getItemModel(idx);
  30763. var itemSymbolType = itemModel.getShallow('symbol', true);
  30764. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  30765. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  30766. // If has item symbol
  30767. if (itemSymbolType != null) {
  30768. data.setItemVisual(idx, 'symbol', itemSymbolType);
  30769. }
  30770. if (itemSymbolSize != null) {
  30771. // PENDING Transform symbolSize ?
  30772. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  30773. }
  30774. if (itemSymbolKeepAspect != null) {
  30775. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  30776. }
  30777. }
  30778. }
  30779. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  30780. }
  30781. };
  30782. };
  30783. /*
  30784. * Licensed to the Apache Software Foundation (ASF) under one
  30785. * or more contributor license agreements. See the NOTICE file
  30786. * distributed with this work for additional information
  30787. * regarding copyright ownership. The ASF licenses this file
  30788. * to you under the Apache License, Version 2.0 (the
  30789. * "License"); you may not use this file except in compliance
  30790. * with the License. You may obtain a copy of the License at
  30791. *
  30792. * http://www.apache.org/licenses/LICENSE-2.0
  30793. *
  30794. * Unless required by applicable law or agreed to in writing,
  30795. * software distributed under the License is distributed on an
  30796. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30797. * KIND, either express or implied. See the License for the
  30798. * specific language governing permissions and limitations
  30799. * under the License.
  30800. */
  30801. /* global Float32Array */
  30802. var layoutPoints = function (seriesType) {
  30803. return {
  30804. seriesType: seriesType,
  30805. plan: createRenderPlanner(),
  30806. reset: function (seriesModel) {
  30807. var data = seriesModel.getData();
  30808. var coordSys = seriesModel.coordinateSystem;
  30809. var pipelineContext = seriesModel.pipelineContext;
  30810. var isLargeRender = pipelineContext.large;
  30811. if (!coordSys) {
  30812. return;
  30813. }
  30814. var dims = map(coordSys.dimensions, function (dim) {
  30815. return data.mapDimension(dim);
  30816. }).slice(0, 2);
  30817. var dimLen = dims.length;
  30818. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30819. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  30820. dims[0] = stackResultDim;
  30821. }
  30822. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  30823. dims[1] = stackResultDim;
  30824. }
  30825. function progress(params, data) {
  30826. var segCount = params.end - params.start;
  30827. var points = isLargeRender && new Float32Array(segCount * dimLen);
  30828. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  30829. var point;
  30830. if (dimLen === 1) {
  30831. var x = data.get(dims[0], i);
  30832. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  30833. }
  30834. else {
  30835. var x = tmpIn[0] = data.get(dims[0], i);
  30836. var y = tmpIn[1] = data.get(dims[1], i);
  30837. // Also {Array.<number>}, not undefined to avoid if...else... statement
  30838. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  30839. }
  30840. if (isLargeRender) {
  30841. points[offset++] = point ? point[0] : NaN;
  30842. points[offset++] = point ? point[1] : NaN;
  30843. }
  30844. else {
  30845. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  30846. }
  30847. }
  30848. isLargeRender && data.setLayout('symbolPoints', points);
  30849. }
  30850. return dimLen && {progress: progress};
  30851. }
  30852. };
  30853. };
  30854. /*
  30855. * Licensed to the Apache Software Foundation (ASF) under one
  30856. * or more contributor license agreements. See the NOTICE file
  30857. * distributed with this work for additional information
  30858. * regarding copyright ownership. The ASF licenses this file
  30859. * to you under the Apache License, Version 2.0 (the
  30860. * "License"); you may not use this file except in compliance
  30861. * with the License. You may obtain a copy of the License at
  30862. *
  30863. * http://www.apache.org/licenses/LICENSE-2.0
  30864. *
  30865. * Unless required by applicable law or agreed to in writing,
  30866. * software distributed under the License is distributed on an
  30867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30868. * KIND, either express or implied. See the License for the
  30869. * specific language governing permissions and limitations
  30870. * under the License.
  30871. */
  30872. var samplers = {
  30873. average: function (frame) {
  30874. var sum = 0;
  30875. var count = 0;
  30876. for (var i = 0; i < frame.length; i++) {
  30877. if (!isNaN(frame[i])) {
  30878. sum += frame[i];
  30879. count++;
  30880. }
  30881. }
  30882. // Return NaN if count is 0
  30883. return count === 0 ? NaN : sum / count;
  30884. },
  30885. sum: function (frame) {
  30886. var sum = 0;
  30887. for (var i = 0; i < frame.length; i++) {
  30888. // Ignore NaN
  30889. sum += frame[i] || 0;
  30890. }
  30891. return sum;
  30892. },
  30893. max: function (frame) {
  30894. var max = -Infinity;
  30895. for (var i = 0; i < frame.length; i++) {
  30896. frame[i] > max && (max = frame[i]);
  30897. }
  30898. // NaN will cause illegal axis extent.
  30899. return isFinite(max) ? max : NaN;
  30900. },
  30901. min: function (frame) {
  30902. var min = Infinity;
  30903. for (var i = 0; i < frame.length; i++) {
  30904. frame[i] < min && (min = frame[i]);
  30905. }
  30906. // NaN will cause illegal axis extent.
  30907. return isFinite(min) ? min : NaN;
  30908. },
  30909. // TODO
  30910. // Median
  30911. nearest: function (frame) {
  30912. return frame[0];
  30913. }
  30914. };
  30915. var indexSampler = function (frame, value) {
  30916. return Math.round(frame.length / 2);
  30917. };
  30918. var dataSample = function (seriesType) {
  30919. return {
  30920. seriesType: seriesType,
  30921. modifyOutputEnd: true,
  30922. reset: function (seriesModel, ecModel, api) {
  30923. var data = seriesModel.getData();
  30924. var sampling = seriesModel.get('sampling');
  30925. var coordSys = seriesModel.coordinateSystem;
  30926. // Only cartesian2d support down sampling
  30927. if (coordSys.type === 'cartesian2d' && sampling) {
  30928. var baseAxis = coordSys.getBaseAxis();
  30929. var valueAxis = coordSys.getOtherAxis(baseAxis);
  30930. var extent = baseAxis.getExtent();
  30931. // Coordinste system has been resized
  30932. var size = extent[1] - extent[0];
  30933. var rate = Math.round(data.count() / size);
  30934. if (rate > 1) {
  30935. var sampler;
  30936. if (typeof sampling === 'string') {
  30937. sampler = samplers[sampling];
  30938. }
  30939. else if (typeof sampling === 'function') {
  30940. sampler = sampling;
  30941. }
  30942. if (sampler) {
  30943. // Only support sample the first dim mapped from value axis.
  30944. seriesModel.setData(data.downSample(
  30945. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  30946. ));
  30947. }
  30948. }
  30949. }
  30950. }
  30951. };
  30952. };
  30953. /*
  30954. * Licensed to the Apache Software Foundation (ASF) under one
  30955. * or more contributor license agreements. See the NOTICE file
  30956. * distributed with this work for additional information
  30957. * regarding copyright ownership. The ASF licenses this file
  30958. * to you under the Apache License, Version 2.0 (the
  30959. * "License"); you may not use this file except in compliance
  30960. * with the License. You may obtain a copy of the License at
  30961. *
  30962. * http://www.apache.org/licenses/LICENSE-2.0
  30963. *
  30964. * Unless required by applicable law or agreed to in writing,
  30965. * software distributed under the License is distributed on an
  30966. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30967. * KIND, either express or implied. See the License for the
  30968. * specific language governing permissions and limitations
  30969. * under the License.
  30970. */
  30971. /**
  30972. * // Scale class management
  30973. * @module echarts/scale/Scale
  30974. */
  30975. /**
  30976. * @param {Object} [setting]
  30977. */
  30978. function Scale(setting) {
  30979. this._setting = setting || {};
  30980. /**
  30981. * Extent
  30982. * @type {Array.<number>}
  30983. * @protected
  30984. */
  30985. this._extent = [Infinity, -Infinity];
  30986. /**
  30987. * Step is calculated in adjustExtent
  30988. * @type {Array.<number>}
  30989. * @protected
  30990. */
  30991. this._interval = 0;
  30992. this.init && this.init.apply(this, arguments);
  30993. }
  30994. /**
  30995. * Parse input val to valid inner number.
  30996. * @param {*} val
  30997. * @return {number}
  30998. */
  30999. Scale.prototype.parse = function (val) {
  31000. // Notice: This would be a trap here, If the implementation
  31001. // of this method depends on extent, and this method is used
  31002. // before extent set (like in dataZoom), it would be wrong.
  31003. // Nevertheless, parse does not depend on extent generally.
  31004. return val;
  31005. };
  31006. Scale.prototype.getSetting = function (name) {
  31007. return this._setting[name];
  31008. };
  31009. Scale.prototype.contain = function (val) {
  31010. var extent = this._extent;
  31011. return val >= extent[0] && val <= extent[1];
  31012. };
  31013. /**
  31014. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  31015. * @param {number} val
  31016. * @return {number}
  31017. */
  31018. Scale.prototype.normalize = function (val) {
  31019. var extent = this._extent;
  31020. if (extent[1] === extent[0]) {
  31021. return 0.5;
  31022. }
  31023. return (val - extent[0]) / (extent[1] - extent[0]);
  31024. };
  31025. /**
  31026. * Scale normalized value
  31027. * @param {number} val
  31028. * @return {number}
  31029. */
  31030. Scale.prototype.scale = function (val) {
  31031. var extent = this._extent;
  31032. return val * (extent[1] - extent[0]) + extent[0];
  31033. };
  31034. /**
  31035. * Set extent from data
  31036. * @param {Array.<number>} other
  31037. */
  31038. Scale.prototype.unionExtent = function (other) {
  31039. var extent = this._extent;
  31040. other[0] < extent[0] && (extent[0] = other[0]);
  31041. other[1] > extent[1] && (extent[1] = other[1]);
  31042. // not setExtent because in log axis it may transformed to power
  31043. // this.setExtent(extent[0], extent[1]);
  31044. };
  31045. /**
  31046. * Set extent from data
  31047. * @param {module:echarts/data/List} data
  31048. * @param {string} dim
  31049. */
  31050. Scale.prototype.unionExtentFromData = function (data, dim) {
  31051. this.unionExtent(data.getApproximateExtent(dim));
  31052. };
  31053. /**
  31054. * Get extent
  31055. * @return {Array.<number>}
  31056. */
  31057. Scale.prototype.getExtent = function () {
  31058. return this._extent.slice();
  31059. };
  31060. /**
  31061. * Set extent
  31062. * @param {number} start
  31063. * @param {number} end
  31064. */
  31065. Scale.prototype.setExtent = function (start, end) {
  31066. var thisExtent = this._extent;
  31067. if (!isNaN(start)) {
  31068. thisExtent[0] = start;
  31069. }
  31070. if (!isNaN(end)) {
  31071. thisExtent[1] = end;
  31072. }
  31073. };
  31074. /**
  31075. * When axis extent depends on data and no data exists,
  31076. * axis ticks should not be drawn, which is named 'blank'.
  31077. */
  31078. Scale.prototype.isBlank = function () {
  31079. return this._isBlank;
  31080. },
  31081. /**
  31082. * When axis extent depends on data and no data exists,
  31083. * axis ticks should not be drawn, which is named 'blank'.
  31084. */
  31085. Scale.prototype.setBlank = function (isBlank) {
  31086. this._isBlank = isBlank;
  31087. };
  31088. /**
  31089. * @abstract
  31090. * @param {*} tick
  31091. * @return {string} label of the tick.
  31092. */
  31093. Scale.prototype.getLabel = null;
  31094. enableClassExtend(Scale);
  31095. enableClassManagement(Scale, {
  31096. registerWhenExtend: true
  31097. });
  31098. /*
  31099. * Licensed to the Apache Software Foundation (ASF) under one
  31100. * or more contributor license agreements. See the NOTICE file
  31101. * distributed with this work for additional information
  31102. * regarding copyright ownership. The ASF licenses this file
  31103. * to you under the Apache License, Version 2.0 (the
  31104. * "License"); you may not use this file except in compliance
  31105. * with the License. You may obtain a copy of the License at
  31106. *
  31107. * http://www.apache.org/licenses/LICENSE-2.0
  31108. *
  31109. * Unless required by applicable law or agreed to in writing,
  31110. * software distributed under the License is distributed on an
  31111. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31112. * KIND, either express or implied. See the License for the
  31113. * specific language governing permissions and limitations
  31114. * under the License.
  31115. */
  31116. /**
  31117. * @constructor
  31118. * @param {Object} [opt]
  31119. * @param {Object} [opt.categories=[]]
  31120. * @param {Object} [opt.needCollect=false]
  31121. * @param {Object} [opt.deduplication=false]
  31122. */
  31123. function OrdinalMeta(opt) {
  31124. /**
  31125. * @readOnly
  31126. * @type {Array.<string>}
  31127. */
  31128. this.categories = opt.categories || [];
  31129. /**
  31130. * @private
  31131. * @type {boolean}
  31132. */
  31133. this._needCollect = opt.needCollect;
  31134. /**
  31135. * @private
  31136. * @type {boolean}
  31137. */
  31138. this._deduplication = opt.deduplication;
  31139. /**
  31140. * @private
  31141. * @type {boolean}
  31142. */
  31143. this._map;
  31144. }
  31145. /**
  31146. * @param {module:echarts/model/Model} axisModel
  31147. * @return {module:echarts/data/OrdinalMeta}
  31148. */
  31149. OrdinalMeta.createByAxisModel = function (axisModel) {
  31150. var option = axisModel.option;
  31151. var data = option.data;
  31152. var categories = data && map(data, getName);
  31153. return new OrdinalMeta({
  31154. categories: categories,
  31155. needCollect: !categories,
  31156. // deduplication is default in axis.
  31157. deduplication: option.dedplication !== false
  31158. });
  31159. };
  31160. var proto$1 = OrdinalMeta.prototype;
  31161. /**
  31162. * @param {string} category
  31163. * @return {number} ordinal
  31164. */
  31165. proto$1.getOrdinal = function (category) {
  31166. return getOrCreateMap(this).get(category);
  31167. };
  31168. /**
  31169. * @param {*} category
  31170. * @return {number} The ordinal. If not found, return NaN.
  31171. */
  31172. proto$1.parseAndCollect = function (category) {
  31173. var index;
  31174. var needCollect = this._needCollect;
  31175. // The value of category dim can be the index of the given category set.
  31176. // This feature is only supported when !needCollect, because we should
  31177. // consider a common case: a value is 2017, which is a number but is
  31178. // expected to be tread as a category. This case usually happen in dataset,
  31179. // where it happent to be no need of the index feature.
  31180. if (typeof category !== 'string' && !needCollect) {
  31181. return category;
  31182. }
  31183. // Optimize for the scenario:
  31184. // category is ['2012-01-01', '2012-01-02', ...], where the input
  31185. // data has been ensured not duplicate and is large data.
  31186. // Notice, if a dataset dimension provide categroies, usually echarts
  31187. // should remove duplication except user tell echarts dont do that
  31188. // (set axis.deduplication = false), because echarts do not know whether
  31189. // the values in the category dimension has duplication (consider the
  31190. // parallel-aqi example)
  31191. if (needCollect && !this._deduplication) {
  31192. index = this.categories.length;
  31193. this.categories[index] = category;
  31194. return index;
  31195. }
  31196. var map$$1 = getOrCreateMap(this);
  31197. index = map$$1.get(category);
  31198. if (index == null) {
  31199. if (needCollect) {
  31200. index = this.categories.length;
  31201. this.categories[index] = category;
  31202. map$$1.set(category, index);
  31203. }
  31204. else {
  31205. index = NaN;
  31206. }
  31207. }
  31208. return index;
  31209. };
  31210. // Consider big data, do not create map until needed.
  31211. function getOrCreateMap(ordinalMeta) {
  31212. return ordinalMeta._map || (
  31213. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  31214. );
  31215. }
  31216. function getName(obj) {
  31217. if (isObject$1(obj) && obj.value != null) {
  31218. return obj.value;
  31219. }
  31220. else {
  31221. return obj + '';
  31222. }
  31223. }
  31224. /*
  31225. * Licensed to the Apache Software Foundation (ASF) under one
  31226. * or more contributor license agreements. See the NOTICE file
  31227. * distributed with this work for additional information
  31228. * regarding copyright ownership. The ASF licenses this file
  31229. * to you under the Apache License, Version 2.0 (the
  31230. * "License"); you may not use this file except in compliance
  31231. * with the License. You may obtain a copy of the License at
  31232. *
  31233. * http://www.apache.org/licenses/LICENSE-2.0
  31234. *
  31235. * Unless required by applicable law or agreed to in writing,
  31236. * software distributed under the License is distributed on an
  31237. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31238. * KIND, either express or implied. See the License for the
  31239. * specific language governing permissions and limitations
  31240. * under the License.
  31241. */
  31242. /**
  31243. * Linear continuous scale
  31244. * @module echarts/coord/scale/Ordinal
  31245. *
  31246. * http://en.wikipedia.org/wiki/Level_of_measurement
  31247. */
  31248. // FIXME only one data
  31249. var scaleProto = Scale.prototype;
  31250. var OrdinalScale = Scale.extend({
  31251. type: 'ordinal',
  31252. /**
  31253. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  31254. */
  31255. init: function (ordinalMeta, extent) {
  31256. // Caution: Should not use instanceof, consider ec-extensions using
  31257. // import approach to get OrdinalMeta class.
  31258. if (!ordinalMeta || isArray(ordinalMeta)) {
  31259. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  31260. }
  31261. this._ordinalMeta = ordinalMeta;
  31262. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  31263. },
  31264. parse: function (val) {
  31265. return typeof val === 'string'
  31266. ? this._ordinalMeta.getOrdinal(val)
  31267. // val might be float.
  31268. : Math.round(val);
  31269. },
  31270. contain: function (rank) {
  31271. rank = this.parse(rank);
  31272. return scaleProto.contain.call(this, rank)
  31273. && this._ordinalMeta.categories[rank] != null;
  31274. },
  31275. /**
  31276. * Normalize given rank or name to linear [0, 1]
  31277. * @param {number|string} [val]
  31278. * @return {number}
  31279. */
  31280. normalize: function (val) {
  31281. return scaleProto.normalize.call(this, this.parse(val));
  31282. },
  31283. scale: function (val) {
  31284. return Math.round(scaleProto.scale.call(this, val));
  31285. },
  31286. /**
  31287. * @return {Array}
  31288. */
  31289. getTicks: function () {
  31290. var ticks = [];
  31291. var extent = this._extent;
  31292. var rank = extent[0];
  31293. while (rank <= extent[1]) {
  31294. ticks.push(rank);
  31295. rank++;
  31296. }
  31297. return ticks;
  31298. },
  31299. /**
  31300. * Get item on rank n
  31301. * @param {number} n
  31302. * @return {string}
  31303. */
  31304. getLabel: function (n) {
  31305. if (!this.isBlank()) {
  31306. // Note that if no data, ordinalMeta.categories is an empty array.
  31307. return this._ordinalMeta.categories[n];
  31308. }
  31309. },
  31310. /**
  31311. * @return {number}
  31312. */
  31313. count: function () {
  31314. return this._extent[1] - this._extent[0] + 1;
  31315. },
  31316. /**
  31317. * @override
  31318. */
  31319. unionExtentFromData: function (data, dim) {
  31320. this.unionExtent(data.getApproximateExtent(dim));
  31321. },
  31322. getOrdinalMeta: function () {
  31323. return this._ordinalMeta;
  31324. },
  31325. niceTicks: noop,
  31326. niceExtent: noop
  31327. });
  31328. /**
  31329. * @return {module:echarts/scale/Time}
  31330. */
  31331. OrdinalScale.create = function () {
  31332. return new OrdinalScale();
  31333. };
  31334. /*
  31335. * Licensed to the Apache Software Foundation (ASF) under one
  31336. * or more contributor license agreements. See the NOTICE file
  31337. * distributed with this work for additional information
  31338. * regarding copyright ownership. The ASF licenses this file
  31339. * to you under the Apache License, Version 2.0 (the
  31340. * "License"); you may not use this file except in compliance
  31341. * with the License. You may obtain a copy of the License at
  31342. *
  31343. * http://www.apache.org/licenses/LICENSE-2.0
  31344. *
  31345. * Unless required by applicable law or agreed to in writing,
  31346. * software distributed under the License is distributed on an
  31347. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31348. * KIND, either express or implied. See the License for the
  31349. * specific language governing permissions and limitations
  31350. * under the License.
  31351. */
  31352. /**
  31353. * For testable.
  31354. */
  31355. var roundNumber$1 = round$1;
  31356. /**
  31357. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  31358. * Should be extent[0] < extent[1].
  31359. * @param {number} splitNumber splitNumber should be >= 1.
  31360. * @param {number} [minInterval]
  31361. * @param {number} [maxInterval]
  31362. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  31363. */
  31364. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  31365. var result = {};
  31366. var span = extent[1] - extent[0];
  31367. var interval = result.interval = nice(span / splitNumber, true);
  31368. if (minInterval != null && interval < minInterval) {
  31369. interval = result.interval = minInterval;
  31370. }
  31371. if (maxInterval != null && interval > maxInterval) {
  31372. interval = result.interval = maxInterval;
  31373. }
  31374. // Tow more digital for tick.
  31375. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  31376. // Niced extent inside original extent
  31377. var niceTickExtent = result.niceTickExtent = [
  31378. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  31379. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  31380. ];
  31381. fixExtent(niceTickExtent, extent);
  31382. return result;
  31383. }
  31384. /**
  31385. * @param {number} interval
  31386. * @return {number} interval precision
  31387. */
  31388. function getIntervalPrecision(interval) {
  31389. // Tow more digital for tick.
  31390. return getPrecisionSafe(interval) + 2;
  31391. }
  31392. function clamp(niceTickExtent, idx, extent) {
  31393. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  31394. }
  31395. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  31396. function fixExtent(niceTickExtent, extent) {
  31397. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  31398. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  31399. clamp(niceTickExtent, 0, extent);
  31400. clamp(niceTickExtent, 1, extent);
  31401. if (niceTickExtent[0] > niceTickExtent[1]) {
  31402. niceTickExtent[0] = niceTickExtent[1];
  31403. }
  31404. }
  31405. /*
  31406. * Licensed to the Apache Software Foundation (ASF) under one
  31407. * or more contributor license agreements. See the NOTICE file
  31408. * distributed with this work for additional information
  31409. * regarding copyright ownership. The ASF licenses this file
  31410. * to you under the Apache License, Version 2.0 (the
  31411. * "License"); you may not use this file except in compliance
  31412. * with the License. You may obtain a copy of the License at
  31413. *
  31414. * http://www.apache.org/licenses/LICENSE-2.0
  31415. *
  31416. * Unless required by applicable law or agreed to in writing,
  31417. * software distributed under the License is distributed on an
  31418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31419. * KIND, either express or implied. See the License for the
  31420. * specific language governing permissions and limitations
  31421. * under the License.
  31422. */
  31423. /**
  31424. * Interval scale
  31425. * @module echarts/scale/Interval
  31426. */
  31427. var roundNumber = round$1;
  31428. /**
  31429. * @alias module:echarts/coord/scale/Interval
  31430. * @constructor
  31431. */
  31432. var IntervalScale = Scale.extend({
  31433. type: 'interval',
  31434. _interval: 0,
  31435. _intervalPrecision: 2,
  31436. setExtent: function (start, end) {
  31437. var thisExtent = this._extent;
  31438. //start,end may be a Number like '25',so...
  31439. if (!isNaN(start)) {
  31440. thisExtent[0] = parseFloat(start);
  31441. }
  31442. if (!isNaN(end)) {
  31443. thisExtent[1] = parseFloat(end);
  31444. }
  31445. },
  31446. unionExtent: function (other) {
  31447. var extent = this._extent;
  31448. other[0] < extent[0] && (extent[0] = other[0]);
  31449. other[1] > extent[1] && (extent[1] = other[1]);
  31450. // unionExtent may called by it's sub classes
  31451. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  31452. },
  31453. /**
  31454. * Get interval
  31455. */
  31456. getInterval: function () {
  31457. return this._interval;
  31458. },
  31459. /**
  31460. * Set interval
  31461. */
  31462. setInterval: function (interval) {
  31463. this._interval = interval;
  31464. // Dropped auto calculated niceExtent and use user setted extent
  31465. // We assume user wan't to set both interval, min, max to get a better result
  31466. this._niceExtent = this._extent.slice();
  31467. this._intervalPrecision = getIntervalPrecision(interval);
  31468. },
  31469. /**
  31470. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  31471. * @return {Array.<number>}
  31472. */
  31473. getTicks: function (expandToNicedExtent) {
  31474. var interval = this._interval;
  31475. var extent = this._extent;
  31476. var niceTickExtent = this._niceExtent;
  31477. var intervalPrecision = this._intervalPrecision;
  31478. var ticks = [];
  31479. // If interval is 0, return [];
  31480. if (!interval) {
  31481. return ticks;
  31482. }
  31483. // Consider this case: using dataZoom toolbox, zoom and zoom.
  31484. var safeLimit = 10000;
  31485. if (extent[0] < niceTickExtent[0]) {
  31486. if (expandToNicedExtent) {
  31487. ticks.push(roundNumber(niceTickExtent[0] - interval));
  31488. }
  31489. else {
  31490. ticks.push(extent[0]);
  31491. }
  31492. }
  31493. var tick = niceTickExtent[0];
  31494. while (tick <= niceTickExtent[1]) {
  31495. ticks.push(tick);
  31496. // Avoid rounding error
  31497. tick = roundNumber(tick + interval, intervalPrecision);
  31498. if (tick === ticks[ticks.length - 1]) {
  31499. // Consider out of safe float point, e.g.,
  31500. // -3711126.9907707 + 2e-10 === -3711126.9907707
  31501. break;
  31502. }
  31503. if (ticks.length > safeLimit) {
  31504. return [];
  31505. }
  31506. }
  31507. // Consider this case: the last item of ticks is smaller
  31508. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  31509. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  31510. if (extent[1] > lastNiceTick) {
  31511. if (expandToNicedExtent) {
  31512. ticks.push(lastNiceTick + interval);
  31513. }
  31514. else {
  31515. ticks.push(extent[1]);
  31516. }
  31517. }
  31518. return ticks;
  31519. },
  31520. /**
  31521. * @param {number} [splitNumber=5]
  31522. * @return {Array.<Array.<number>>}
  31523. */
  31524. getMinorTicks: function (splitNumber) {
  31525. var ticks = this.getTicks(true);
  31526. var minorTicks = [];
  31527. var extent = this.getExtent();
  31528. for (var i = 1; i < ticks.length; i++) {
  31529. var nextTick = ticks[i];
  31530. var prevTick = ticks[i - 1];
  31531. var count = 0;
  31532. var minorTicksGroup = [];
  31533. var interval = nextTick - prevTick;
  31534. var minorInterval = interval / splitNumber;
  31535. while (count < splitNumber - 1) {
  31536. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  31537. // For the first and last interval. The count may be less than splitNumber.
  31538. if (minorTick > extent[0] && minorTick < extent[1]) {
  31539. minorTicksGroup.push(minorTick);
  31540. }
  31541. count++;
  31542. }
  31543. minorTicks.push(minorTicksGroup);
  31544. }
  31545. return minorTicks;
  31546. },
  31547. /**
  31548. * @param {number} data
  31549. * @param {Object} [opt]
  31550. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  31551. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  31552. * @return {string}
  31553. */
  31554. getLabel: function (data, opt) {
  31555. if (data == null) {
  31556. return '';
  31557. }
  31558. var precision = opt && opt.precision;
  31559. if (precision == null) {
  31560. precision = getPrecisionSafe(data) || 0;
  31561. }
  31562. else if (precision === 'auto') {
  31563. // Should be more precise then tick.
  31564. precision = this._intervalPrecision;
  31565. }
  31566. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  31567. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  31568. data = roundNumber(data, precision, true);
  31569. return addCommas(data);
  31570. },
  31571. /**
  31572. * Update interval and extent of intervals for nice ticks
  31573. *
  31574. * @param {number} [splitNumber = 5] Desired number of ticks
  31575. * @param {number} [minInterval]
  31576. * @param {number} [maxInterval]
  31577. */
  31578. niceTicks: function (splitNumber, minInterval, maxInterval) {
  31579. splitNumber = splitNumber || 5;
  31580. var extent = this._extent;
  31581. var span = extent[1] - extent[0];
  31582. if (!isFinite(span)) {
  31583. return;
  31584. }
  31585. // User may set axis min 0 and data are all negative
  31586. // FIXME If it needs to reverse ?
  31587. if (span < 0) {
  31588. span = -span;
  31589. extent.reverse();
  31590. }
  31591. var result = intervalScaleNiceTicks(
  31592. extent, splitNumber, minInterval, maxInterval
  31593. );
  31594. this._intervalPrecision = result.intervalPrecision;
  31595. this._interval = result.interval;
  31596. this._niceExtent = result.niceTickExtent;
  31597. },
  31598. /**
  31599. * Nice extent.
  31600. * @param {Object} opt
  31601. * @param {number} [opt.splitNumber = 5] Given approx tick number
  31602. * @param {boolean} [opt.fixMin=false]
  31603. * @param {boolean} [opt.fixMax=false]
  31604. * @param {boolean} [opt.minInterval]
  31605. * @param {boolean} [opt.maxInterval]
  31606. */
  31607. niceExtent: function (opt) {
  31608. var extent = this._extent;
  31609. // If extent start and end are same, expand them
  31610. if (extent[0] === extent[1]) {
  31611. if (extent[0] !== 0) {
  31612. // Expand extent
  31613. var expandSize = extent[0];
  31614. // In the fowllowing case
  31615. // Axis has been fixed max 100
  31616. // Plus data are all 100 and axis extent are [100, 100].
  31617. // Extend to the both side will cause expanded max is larger than fixed max.
  31618. // So only expand to the smaller side.
  31619. if (!opt.fixMax) {
  31620. extent[1] += expandSize / 2;
  31621. extent[0] -= expandSize / 2;
  31622. }
  31623. else {
  31624. extent[0] -= expandSize / 2;
  31625. }
  31626. }
  31627. else {
  31628. extent[1] = 1;
  31629. }
  31630. }
  31631. var span = extent[1] - extent[0];
  31632. // If there are no data and extent are [Infinity, -Infinity]
  31633. if (!isFinite(span)) {
  31634. extent[0] = 0;
  31635. extent[1] = 1;
  31636. }
  31637. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31638. // var extent = this._extent;
  31639. var interval = this._interval;
  31640. if (!opt.fixMin) {
  31641. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  31642. }
  31643. if (!opt.fixMax) {
  31644. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  31645. }
  31646. }
  31647. });
  31648. /**
  31649. * @return {module:echarts/scale/Time}
  31650. */
  31651. IntervalScale.create = function () {
  31652. return new IntervalScale();
  31653. };
  31654. /*
  31655. * Licensed to the Apache Software Foundation (ASF) under one
  31656. * or more contributor license agreements. See the NOTICE file
  31657. * distributed with this work for additional information
  31658. * regarding copyright ownership. The ASF licenses this file
  31659. * to you under the Apache License, Version 2.0 (the
  31660. * "License"); you may not use this file except in compliance
  31661. * with the License. You may obtain a copy of the License at
  31662. *
  31663. * http://www.apache.org/licenses/LICENSE-2.0
  31664. *
  31665. * Unless required by applicable law or agreed to in writing,
  31666. * software distributed under the License is distributed on an
  31667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31668. * KIND, either express or implied. See the License for the
  31669. * specific language governing permissions and limitations
  31670. * under the License.
  31671. */
  31672. /* global Float32Array */
  31673. var STACK_PREFIX = '__ec_stack_';
  31674. var LARGE_BAR_MIN_WIDTH = 0.5;
  31675. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  31676. function getSeriesStackId(seriesModel) {
  31677. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  31678. }
  31679. function getAxisKey(axis) {
  31680. return axis.dim + axis.index;
  31681. }
  31682. /**
  31683. * @param {Object} opt
  31684. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  31685. * @param {number} opt.count Positive interger.
  31686. * @param {number} [opt.barWidth]
  31687. * @param {number} [opt.barMaxWidth]
  31688. * @param {number} [opt.barMinWidth]
  31689. * @param {number} [opt.barGap]
  31690. * @param {number} [opt.barCategoryGap]
  31691. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  31692. */
  31693. function prepareLayoutBarSeries(seriesType, ecModel) {
  31694. var seriesModels = [];
  31695. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31696. // Check series coordinate, do layout for cartesian2d only
  31697. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  31698. seriesModels.push(seriesModel);
  31699. }
  31700. });
  31701. return seriesModels;
  31702. }
  31703. /**
  31704. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  31705. * values.
  31706. * This works for time axes, value axes, and log axes.
  31707. * For a single time axis, return value is in the form like
  31708. * {'x_0': [1000000]}.
  31709. * The value of 1000000 is in milliseconds.
  31710. */
  31711. function getValueAxesMinGaps(barSeries) {
  31712. /**
  31713. * Map from axis.index to values.
  31714. * For a single time axis, axisValues is in the form like
  31715. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  31716. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  31717. * series.
  31718. */
  31719. var axisValues = {};
  31720. each$1(barSeries, function (seriesModel) {
  31721. var cartesian = seriesModel.coordinateSystem;
  31722. var baseAxis = cartesian.getBaseAxis();
  31723. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  31724. return;
  31725. }
  31726. var data = seriesModel.getData();
  31727. var key = baseAxis.dim + '_' + baseAxis.index;
  31728. var dim = data.mapDimension(baseAxis.dim);
  31729. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  31730. var value = data.get(dim, i);
  31731. if (!axisValues[key]) {
  31732. // No previous data for the axis
  31733. axisValues[key] = [value];
  31734. }
  31735. else {
  31736. // No value in previous series
  31737. axisValues[key].push(value);
  31738. }
  31739. // Ignore duplicated time values in the same axis
  31740. }
  31741. });
  31742. var axisMinGaps = [];
  31743. for (var key in axisValues) {
  31744. if (axisValues.hasOwnProperty(key)) {
  31745. var valuesInAxis = axisValues[key];
  31746. if (valuesInAxis) {
  31747. // Sort axis values into ascending order to calculate gaps
  31748. valuesInAxis.sort(function (a, b) {
  31749. return a - b;
  31750. });
  31751. var min = null;
  31752. for (var j = 1; j < valuesInAxis.length; ++j) {
  31753. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  31754. if (delta > 0) {
  31755. // Ignore 0 delta because they are of the same axis value
  31756. min = min === null ? delta : Math.min(min, delta);
  31757. }
  31758. }
  31759. // Set to null if only have one data
  31760. axisMinGaps[key] = min;
  31761. }
  31762. }
  31763. }
  31764. return axisMinGaps;
  31765. }
  31766. function makeColumnLayout(barSeries) {
  31767. var axisMinGaps = getValueAxesMinGaps(barSeries);
  31768. var seriesInfoList = [];
  31769. each$1(barSeries, function (seriesModel) {
  31770. var cartesian = seriesModel.coordinateSystem;
  31771. var baseAxis = cartesian.getBaseAxis();
  31772. var axisExtent = baseAxis.getExtent();
  31773. var bandWidth;
  31774. if (baseAxis.type === 'category') {
  31775. bandWidth = baseAxis.getBandWidth();
  31776. }
  31777. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  31778. var key = baseAxis.dim + '_' + baseAxis.index;
  31779. var minGap = axisMinGaps[key];
  31780. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  31781. var scale = baseAxis.scale.getExtent();
  31782. var scaleSpan = Math.abs(scale[1] - scale[0]);
  31783. bandWidth = minGap
  31784. ? extentSpan / scaleSpan * minGap
  31785. : extentSpan; // When there is only one data value
  31786. }
  31787. else {
  31788. var data = seriesModel.getData();
  31789. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  31790. }
  31791. var barWidth = parsePercent$1(
  31792. seriesModel.get('barWidth'), bandWidth
  31793. );
  31794. var barMaxWidth = parsePercent$1(
  31795. seriesModel.get('barMaxWidth'), bandWidth
  31796. );
  31797. var barMinWidth = parsePercent$1(
  31798. // barMinWidth by default is 1 in cartesian. Because in value axis,
  31799. // the auto-calculated bar width might be less than 1.
  31800. seriesModel.get('barMinWidth') || 1, bandWidth
  31801. );
  31802. var barGap = seriesModel.get('barGap');
  31803. var barCategoryGap = seriesModel.get('barCategoryGap');
  31804. seriesInfoList.push({
  31805. bandWidth: bandWidth,
  31806. barWidth: barWidth,
  31807. barMaxWidth: barMaxWidth,
  31808. barMinWidth: barMinWidth,
  31809. barGap: barGap,
  31810. barCategoryGap: barCategoryGap,
  31811. axisKey: getAxisKey(baseAxis),
  31812. stackId: getSeriesStackId(seriesModel)
  31813. });
  31814. });
  31815. return doCalBarWidthAndOffset(seriesInfoList);
  31816. }
  31817. function doCalBarWidthAndOffset(seriesInfoList) {
  31818. // Columns info on each category axis. Key is cartesian name
  31819. var columnsMap = {};
  31820. each$1(seriesInfoList, function (seriesInfo, idx) {
  31821. var axisKey = seriesInfo.axisKey;
  31822. var bandWidth = seriesInfo.bandWidth;
  31823. var columnsOnAxis = columnsMap[axisKey] || {
  31824. bandWidth: bandWidth,
  31825. remainedWidth: bandWidth,
  31826. autoWidthCount: 0,
  31827. categoryGap: '20%',
  31828. gap: '30%',
  31829. stacks: {}
  31830. };
  31831. var stacks = columnsOnAxis.stacks;
  31832. columnsMap[axisKey] = columnsOnAxis;
  31833. var stackId = seriesInfo.stackId;
  31834. if (!stacks[stackId]) {
  31835. columnsOnAxis.autoWidthCount++;
  31836. }
  31837. stacks[stackId] = stacks[stackId] || {
  31838. width: 0,
  31839. maxWidth: 0
  31840. };
  31841. // Caution: In a single coordinate system, these barGrid attributes
  31842. // will be shared by series. Consider that they have default values,
  31843. // only the attributes set on the last series will work.
  31844. // Do not change this fact unless there will be a break change.
  31845. var barWidth = seriesInfo.barWidth;
  31846. if (barWidth && !stacks[stackId].width) {
  31847. // See #6312, do not restrict width.
  31848. stacks[stackId].width = barWidth;
  31849. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  31850. columnsOnAxis.remainedWidth -= barWidth;
  31851. }
  31852. var barMaxWidth = seriesInfo.barMaxWidth;
  31853. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  31854. var barMinWidth = seriesInfo.barMinWidth;
  31855. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  31856. var barGap = seriesInfo.barGap;
  31857. (barGap != null) && (columnsOnAxis.gap = barGap);
  31858. var barCategoryGap = seriesInfo.barCategoryGap;
  31859. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  31860. });
  31861. var result = {};
  31862. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  31863. result[coordSysName] = {};
  31864. var stacks = columnsOnAxis.stacks;
  31865. var bandWidth = columnsOnAxis.bandWidth;
  31866. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  31867. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  31868. var remainedWidth = columnsOnAxis.remainedWidth;
  31869. var autoWidthCount = columnsOnAxis.autoWidthCount;
  31870. var autoWidth = (remainedWidth - categoryGap)
  31871. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31872. autoWidth = Math.max(autoWidth, 0);
  31873. // Find if any auto calculated bar exceeded maxBarWidth
  31874. each$1(stacks, function (column) {
  31875. var maxWidth = column.maxWidth;
  31876. var minWidth = column.minWidth;
  31877. if (!column.width) {
  31878. var finalWidth = autoWidth;
  31879. if (maxWidth && maxWidth < finalWidth) {
  31880. finalWidth = Math.min(maxWidth, remainedWidth);
  31881. }
  31882. // `minWidth` has higher priority. `minWidth` decide that wheter the
  31883. // bar is able to be visible. So `minWidth` should not be restricted
  31884. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  31885. // the extreme cases for `value` axis, bars are allowed to overlap
  31886. // with each other if `minWidth` specified.
  31887. if (minWidth && minWidth > finalWidth) {
  31888. finalWidth = minWidth;
  31889. }
  31890. if (finalWidth !== autoWidth) {
  31891. column.width = finalWidth;
  31892. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31893. autoWidthCount--;
  31894. }
  31895. }
  31896. else {
  31897. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  31898. // CSS does. Becuase barWidth can be a percent value, where
  31899. // `barMaxWidth` can be used to restrict the final width.
  31900. var finalWidth = column.width;
  31901. if (maxWidth) {
  31902. finalWidth = Math.min(finalWidth, maxWidth);
  31903. }
  31904. // `minWidth` has higher priority, as described above
  31905. if (minWidth) {
  31906. finalWidth = Math.max(finalWidth, minWidth);
  31907. }
  31908. column.width = finalWidth;
  31909. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31910. autoWidthCount--;
  31911. }
  31912. });
  31913. // Recalculate width again
  31914. autoWidth = (remainedWidth - categoryGap)
  31915. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31916. autoWidth = Math.max(autoWidth, 0);
  31917. var widthSum = 0;
  31918. var lastColumn;
  31919. each$1(stacks, function (column, idx) {
  31920. if (!column.width) {
  31921. column.width = autoWidth;
  31922. }
  31923. lastColumn = column;
  31924. widthSum += column.width * (1 + barGapPercent);
  31925. });
  31926. if (lastColumn) {
  31927. widthSum -= lastColumn.width * barGapPercent;
  31928. }
  31929. var offset = -widthSum / 2;
  31930. each$1(stacks, function (column, stackId) {
  31931. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  31932. bandWidth: bandWidth,
  31933. offset: offset,
  31934. width: column.width
  31935. };
  31936. offset += column.width * (1 + barGapPercent);
  31937. });
  31938. });
  31939. return result;
  31940. }
  31941. /**
  31942. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  31943. * @param {module:echarts/coord/Axis} axis
  31944. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  31945. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  31946. */
  31947. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  31948. if (barWidthAndOffset && axis) {
  31949. var result = barWidthAndOffset[getAxisKey(axis)];
  31950. if (result != null && seriesModel != null) {
  31951. result = result[getSeriesStackId(seriesModel)];
  31952. }
  31953. return result;
  31954. }
  31955. }
  31956. /**
  31957. * @param {string} seriesType
  31958. * @param {module:echarts/model/Global} ecModel
  31959. */
  31960. function layout(seriesType, ecModel) {
  31961. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  31962. var barWidthAndOffset = makeColumnLayout(seriesModels);
  31963. var lastStackCoords = {};
  31964. each$1(seriesModels, function (seriesModel) {
  31965. var data = seriesModel.getData();
  31966. var cartesian = seriesModel.coordinateSystem;
  31967. var baseAxis = cartesian.getBaseAxis();
  31968. var stackId = getSeriesStackId(seriesModel);
  31969. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  31970. var columnOffset = columnLayoutInfo.offset;
  31971. var columnWidth = columnLayoutInfo.width;
  31972. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31973. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  31974. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  31975. data.setLayout({
  31976. bandWidth: columnLayoutInfo.bandWidth,
  31977. offset: columnOffset,
  31978. size: columnWidth
  31979. });
  31980. var valueDim = data.mapDimension(valueAxis.dim);
  31981. var baseDim = data.mapDimension(baseAxis.dim);
  31982. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  31983. var isValueAxisH = valueAxis.isHorizontal();
  31984. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  31985. for (var idx = 0, len = data.count(); idx < len; idx++) {
  31986. var value = data.get(valueDim, idx);
  31987. var baseValue = data.get(baseDim, idx);
  31988. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  31989. if (isNaN(value) || isNaN(baseValue)) {
  31990. continue;
  31991. }
  31992. var sign = value >= 0 ? 'p' : 'n';
  31993. var baseCoord = valueAxisStart;
  31994. // Because of the barMinHeight, we can not use the value in
  31995. // stackResultDimension directly.
  31996. if (stacked) {
  31997. // Only ordinal axis can be stacked.
  31998. if (!lastStackCoords[stackId][baseValue]) {
  31999. lastStackCoords[stackId][baseValue] = {
  32000. p: valueAxisStart, // Positive stack
  32001. n: valueAxisStart // Negative stack
  32002. };
  32003. }
  32004. // Should also consider #4243
  32005. baseCoord = lastStackCoords[stackId][baseValue][sign];
  32006. }
  32007. var x;
  32008. var y;
  32009. var width;
  32010. var height;
  32011. if (isValueAxisH) {
  32012. var coord = cartesian.dataToPoint([value, baseValue]);
  32013. x = baseCoord;
  32014. y = coord[1] + columnOffset;
  32015. width = coord[0] - valueAxisStart;
  32016. height = columnWidth;
  32017. if (Math.abs(width) < barMinHeight) {
  32018. width = (width < 0 ? -1 : 1) * barMinHeight;
  32019. }
  32020. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  32021. }
  32022. else {
  32023. var coord = cartesian.dataToPoint([baseValue, value]);
  32024. x = coord[0] + columnOffset;
  32025. y = baseCoord;
  32026. width = columnWidth;
  32027. height = coord[1] - valueAxisStart;
  32028. if (Math.abs(height) < barMinHeight) {
  32029. // Include zero to has a positive bar
  32030. height = (height <= 0 ? -1 : 1) * barMinHeight;
  32031. }
  32032. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  32033. }
  32034. data.setItemLayout(idx, {
  32035. x: x,
  32036. y: y,
  32037. width: width,
  32038. height: height
  32039. });
  32040. }
  32041. }, this);
  32042. }
  32043. // TODO: Do not support stack in large mode yet.
  32044. var largeLayout = {
  32045. seriesType: 'bar',
  32046. plan: createRenderPlanner(),
  32047. reset: function (seriesModel) {
  32048. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  32049. return;
  32050. }
  32051. var data = seriesModel.getData();
  32052. var cartesian = seriesModel.coordinateSystem;
  32053. var baseAxis = cartesian.getBaseAxis();
  32054. var valueAxis = cartesian.getOtherAxis(baseAxis);
  32055. var valueDim = data.mapDimension(valueAxis.dim);
  32056. var baseDim = data.mapDimension(baseAxis.dim);
  32057. var valueAxisHorizontal = valueAxis.isHorizontal();
  32058. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  32059. var barWidth = retrieveColumnLayout(
  32060. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  32061. ).width;
  32062. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  32063. barWidth = LARGE_BAR_MIN_WIDTH;
  32064. }
  32065. return {progress: progress};
  32066. function progress(params, data) {
  32067. var count = params.count;
  32068. var largePoints = new LargeArr(count * 2);
  32069. var largeDataIndices = new LargeArr(count);
  32070. var dataIndex;
  32071. var coord = [];
  32072. var valuePair = [];
  32073. var pointsOffset = 0;
  32074. var idxOffset = 0;
  32075. while ((dataIndex = params.next()) != null) {
  32076. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  32077. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  32078. coord = cartesian.dataToPoint(valuePair, null, coord);
  32079. // Data index might not be in order, depends on `progressiveChunkMode`.
  32080. largePoints[pointsOffset++] = coord[0];
  32081. largePoints[pointsOffset++] = coord[1];
  32082. largeDataIndices[idxOffset++] = dataIndex;
  32083. }
  32084. data.setLayout({
  32085. largePoints: largePoints,
  32086. largeDataIndices: largeDataIndices,
  32087. barWidth: barWidth,
  32088. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  32089. valueAxisHorizontal: valueAxisHorizontal
  32090. });
  32091. }
  32092. }
  32093. };
  32094. function isOnCartesian(seriesModel) {
  32095. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  32096. }
  32097. function isInLargeMode(seriesModel) {
  32098. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  32099. }
  32100. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  32101. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  32102. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  32103. }
  32104. /*
  32105. * Licensed to the Apache Software Foundation (ASF) under one
  32106. * or more contributor license agreements. See the NOTICE file
  32107. * distributed with this work for additional information
  32108. * regarding copyright ownership. The ASF licenses this file
  32109. * to you under the Apache License, Version 2.0 (the
  32110. * "License"); you may not use this file except in compliance
  32111. * with the License. You may obtain a copy of the License at
  32112. *
  32113. * http://www.apache.org/licenses/LICENSE-2.0
  32114. *
  32115. * Unless required by applicable law or agreed to in writing,
  32116. * software distributed under the License is distributed on an
  32117. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32118. * KIND, either express or implied. See the License for the
  32119. * specific language governing permissions and limitations
  32120. * under the License.
  32121. */
  32122. /*
  32123. * A third-party license is embeded for some of the code in this file:
  32124. * The "scaleLevels" was originally copied from "d3.js" with some
  32125. * modifications made for this project.
  32126. * (See more details in the comment on the definition of "scaleLevels" below.)
  32127. * The use of the source code of this file is also subject to the terms
  32128. * and consitions of the license of "d3.js" (BSD-3Clause, see
  32129. * </licenses/LICENSE-d3>).
  32130. */
  32131. // [About UTC and local time zone]:
  32132. // In most cases, `number.parseDate` will treat input data string as local time
  32133. // (except time zone is specified in time string). And `format.formateTime` returns
  32134. // local time by default. option.useUTC is false by default. This design have
  32135. // concidered these common case:
  32136. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  32137. // in local time by default.
  32138. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  32139. // as its original time, without any time difference.
  32140. var intervalScaleProto = IntervalScale.prototype;
  32141. var mathCeil = Math.ceil;
  32142. var mathFloor = Math.floor;
  32143. var ONE_SECOND = 1000;
  32144. var ONE_MINUTE = ONE_SECOND * 60;
  32145. var ONE_HOUR = ONE_MINUTE * 60;
  32146. var ONE_DAY = ONE_HOUR * 24;
  32147. // FIXME 公用?
  32148. var bisect = function (a, x, lo, hi) {
  32149. while (lo < hi) {
  32150. var mid = lo + hi >>> 1;
  32151. if (a[mid][1] < x) {
  32152. lo = mid + 1;
  32153. }
  32154. else {
  32155. hi = mid;
  32156. }
  32157. }
  32158. return lo;
  32159. };
  32160. /**
  32161. * @alias module:echarts/coord/scale/Time
  32162. * @constructor
  32163. */
  32164. var TimeScale = IntervalScale.extend({
  32165. type: 'time',
  32166. /**
  32167. * @override
  32168. */
  32169. getLabel: function (val) {
  32170. var stepLvl = this._stepLvl;
  32171. var date = new Date(val);
  32172. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  32173. },
  32174. /**
  32175. * @override
  32176. */
  32177. niceExtent: function (opt) {
  32178. var extent = this._extent;
  32179. // If extent start and end are same, expand them
  32180. if (extent[0] === extent[1]) {
  32181. // Expand extent
  32182. extent[0] -= ONE_DAY;
  32183. extent[1] += ONE_DAY;
  32184. }
  32185. // If there are no data and extent are [Infinity, -Infinity]
  32186. if (extent[1] === -Infinity && extent[0] === Infinity) {
  32187. var d = new Date();
  32188. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  32189. extent[0] = extent[1] - ONE_DAY;
  32190. }
  32191. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  32192. // var extent = this._extent;
  32193. var interval = this._interval;
  32194. if (!opt.fixMin) {
  32195. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  32196. }
  32197. if (!opt.fixMax) {
  32198. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  32199. }
  32200. },
  32201. /**
  32202. * @override
  32203. */
  32204. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  32205. approxTickNum = approxTickNum || 10;
  32206. var extent = this._extent;
  32207. var span = extent[1] - extent[0];
  32208. var approxInterval = span / approxTickNum;
  32209. if (minInterval != null && approxInterval < minInterval) {
  32210. approxInterval = minInterval;
  32211. }
  32212. if (maxInterval != null && approxInterval > maxInterval) {
  32213. approxInterval = maxInterval;
  32214. }
  32215. var scaleLevelsLen = scaleLevels.length;
  32216. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  32217. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  32218. var interval = level[1];
  32219. // Same with interval scale if span is much larger than 1 year
  32220. if (level[0] === 'year') {
  32221. var yearSpan = span / interval;
  32222. // From "Nice Numbers for Graph Labels" of Graphic Gems
  32223. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  32224. var yearStep = nice(yearSpan / approxTickNum, true);
  32225. interval *= yearStep;
  32226. }
  32227. var timezoneOffset = this.getSetting('useUTC')
  32228. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  32229. var niceExtent = [
  32230. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  32231. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  32232. ];
  32233. fixExtent(niceExtent, extent);
  32234. this._stepLvl = level;
  32235. // Interval will be used in getTicks
  32236. this._interval = interval;
  32237. this._niceExtent = niceExtent;
  32238. },
  32239. parse: function (val) {
  32240. // val might be float.
  32241. return +parseDate(val);
  32242. }
  32243. });
  32244. each$1(['contain', 'normalize'], function (methodName) {
  32245. TimeScale.prototype[methodName] = function (val) {
  32246. return intervalScaleProto[methodName].call(this, this.parse(val));
  32247. };
  32248. });
  32249. /**
  32250. * This implementation was originally copied from "d3.js"
  32251. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  32252. * with some modifications made for this program.
  32253. * See the license statement at the head of this file.
  32254. */
  32255. var scaleLevels = [
  32256. // Format interval
  32257. ['hh:mm:ss', ONE_SECOND], // 1s
  32258. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  32259. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  32260. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  32261. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  32262. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  32263. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  32264. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  32265. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  32266. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  32267. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  32268. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  32269. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  32270. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  32271. ['MM-dd\nyyyy', ONE_DAY], // 1d
  32272. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  32273. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  32274. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  32275. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  32276. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  32277. ['week', ONE_DAY * 7], // 7d
  32278. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  32279. ['week', ONE_DAY * 14], // 2w
  32280. ['week', ONE_DAY * 21], // 3w
  32281. ['month', ONE_DAY * 31], // 1M
  32282. ['week', ONE_DAY * 42], // 6w
  32283. ['month', ONE_DAY * 62], // 2M
  32284. ['week', ONE_DAY * 70], // 10w
  32285. ['quarter', ONE_DAY * 95], // 3M
  32286. ['month', ONE_DAY * 31 * 4], // 4M
  32287. ['month', ONE_DAY * 31 * 5], // 5M
  32288. ['half-year', ONE_DAY * 380 / 2], // 6M
  32289. ['month', ONE_DAY * 31 * 8], // 8M
  32290. ['month', ONE_DAY * 31 * 10], // 10M
  32291. ['year', ONE_DAY * 380] // 1Y
  32292. ];
  32293. /**
  32294. * @param {module:echarts/model/Model}
  32295. * @return {module:echarts/scale/Time}
  32296. */
  32297. TimeScale.create = function (model) {
  32298. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  32299. };
  32300. /*
  32301. * Licensed to the Apache Software Foundation (ASF) under one
  32302. * or more contributor license agreements. See the NOTICE file
  32303. * distributed with this work for additional information
  32304. * regarding copyright ownership. The ASF licenses this file
  32305. * to you under the Apache License, Version 2.0 (the
  32306. * "License"); you may not use this file except in compliance
  32307. * with the License. You may obtain a copy of the License at
  32308. *
  32309. * http://www.apache.org/licenses/LICENSE-2.0
  32310. *
  32311. * Unless required by applicable law or agreed to in writing,
  32312. * software distributed under the License is distributed on an
  32313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32314. * KIND, either express or implied. See the License for the
  32315. * specific language governing permissions and limitations
  32316. * under the License.
  32317. */
  32318. /**
  32319. * Log scale
  32320. * @module echarts/scale/Log
  32321. */
  32322. // Use some method of IntervalScale
  32323. var scaleProto$1 = Scale.prototype;
  32324. var intervalScaleProto$1 = IntervalScale.prototype;
  32325. var getPrecisionSafe$1 = getPrecisionSafe;
  32326. var roundingErrorFix = round$1;
  32327. var mathFloor$1 = Math.floor;
  32328. var mathCeil$1 = Math.ceil;
  32329. var mathPow$1 = Math.pow;
  32330. var mathLog = Math.log;
  32331. var LogScale = Scale.extend({
  32332. type: 'log',
  32333. base: 10,
  32334. $constructor: function () {
  32335. Scale.apply(this, arguments);
  32336. this._originalScale = new IntervalScale();
  32337. },
  32338. /**
  32339. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  32340. * @return {Array.<number>}
  32341. */
  32342. getTicks: function (expandToNicedExtent) {
  32343. var originalScale = this._originalScale;
  32344. var extent = this._extent;
  32345. var originalExtent = originalScale.getExtent();
  32346. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  32347. var powVal = round$1(mathPow$1(this.base, val));
  32348. // Fix #4158
  32349. powVal = (val === extent[0] && originalScale.__fixMin)
  32350. ? fixRoundingError(powVal, originalExtent[0])
  32351. : powVal;
  32352. powVal = (val === extent[1] && originalScale.__fixMax)
  32353. ? fixRoundingError(powVal, originalExtent[1])
  32354. : powVal;
  32355. return powVal;
  32356. }, this);
  32357. },
  32358. /**
  32359. * @param {number} splitNumber
  32360. * @return {Array.<Array.<number>>}
  32361. */
  32362. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  32363. /**
  32364. * @param {number} val
  32365. * @return {string}
  32366. */
  32367. getLabel: intervalScaleProto$1.getLabel,
  32368. /**
  32369. * @param {number} val
  32370. * @return {number}
  32371. */
  32372. scale: function (val) {
  32373. val = scaleProto$1.scale.call(this, val);
  32374. return mathPow$1(this.base, val);
  32375. },
  32376. /**
  32377. * @param {number} start
  32378. * @param {number} end
  32379. */
  32380. setExtent: function (start, end) {
  32381. var base = this.base;
  32382. start = mathLog(start) / mathLog(base);
  32383. end = mathLog(end) / mathLog(base);
  32384. intervalScaleProto$1.setExtent.call(this, start, end);
  32385. },
  32386. /**
  32387. * @return {number} end
  32388. */
  32389. getExtent: function () {
  32390. var base = this.base;
  32391. var extent = scaleProto$1.getExtent.call(this);
  32392. extent[0] = mathPow$1(base, extent[0]);
  32393. extent[1] = mathPow$1(base, extent[1]);
  32394. // Fix #4158
  32395. var originalScale = this._originalScale;
  32396. var originalExtent = originalScale.getExtent();
  32397. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  32398. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  32399. return extent;
  32400. },
  32401. /**
  32402. * @param {Array.<number>} extent
  32403. */
  32404. unionExtent: function (extent) {
  32405. this._originalScale.unionExtent(extent);
  32406. var base = this.base;
  32407. extent[0] = mathLog(extent[0]) / mathLog(base);
  32408. extent[1] = mathLog(extent[1]) / mathLog(base);
  32409. scaleProto$1.unionExtent.call(this, extent);
  32410. },
  32411. /**
  32412. * @override
  32413. */
  32414. unionExtentFromData: function (data, dim) {
  32415. // TODO
  32416. // filter value that <= 0
  32417. this.unionExtent(data.getApproximateExtent(dim));
  32418. },
  32419. /**
  32420. * Update interval and extent of intervals for nice ticks
  32421. * @param {number} [approxTickNum = 10] Given approx tick number
  32422. */
  32423. niceTicks: function (approxTickNum) {
  32424. approxTickNum = approxTickNum || 10;
  32425. var extent = this._extent;
  32426. var span = extent[1] - extent[0];
  32427. if (span === Infinity || span <= 0) {
  32428. return;
  32429. }
  32430. var interval = quantity(span);
  32431. var err = approxTickNum / span * interval;
  32432. // Filter ticks to get closer to the desired count.
  32433. if (err <= 0.5) {
  32434. interval *= 10;
  32435. }
  32436. // Interval should be integer
  32437. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  32438. interval *= 10;
  32439. }
  32440. var niceExtent = [
  32441. round$1(mathCeil$1(extent[0] / interval) * interval),
  32442. round$1(mathFloor$1(extent[1] / interval) * interval)
  32443. ];
  32444. this._interval = interval;
  32445. this._niceExtent = niceExtent;
  32446. },
  32447. /**
  32448. * Nice extent.
  32449. * @override
  32450. */
  32451. niceExtent: function (opt) {
  32452. intervalScaleProto$1.niceExtent.call(this, opt);
  32453. var originalScale = this._originalScale;
  32454. originalScale.__fixMin = opt.fixMin;
  32455. originalScale.__fixMax = opt.fixMax;
  32456. }
  32457. });
  32458. each$1(['contain', 'normalize'], function (methodName) {
  32459. LogScale.prototype[methodName] = function (val) {
  32460. val = mathLog(val) / mathLog(this.base);
  32461. return scaleProto$1[methodName].call(this, val);
  32462. };
  32463. });
  32464. LogScale.create = function () {
  32465. return new LogScale();
  32466. };
  32467. function fixRoundingError(val, originalVal) {
  32468. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  32469. }
  32470. /*
  32471. * Licensed to the Apache Software Foundation (ASF) under one
  32472. * or more contributor license agreements. See the NOTICE file
  32473. * distributed with this work for additional information
  32474. * regarding copyright ownership. The ASF licenses this file
  32475. * to you under the Apache License, Version 2.0 (the
  32476. * "License"); you may not use this file except in compliance
  32477. * with the License. You may obtain a copy of the License at
  32478. *
  32479. * http://www.apache.org/licenses/LICENSE-2.0
  32480. *
  32481. * Unless required by applicable law or agreed to in writing,
  32482. * software distributed under the License is distributed on an
  32483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32484. * KIND, either express or implied. See the License for the
  32485. * specific language governing permissions and limitations
  32486. * under the License.
  32487. */
  32488. /**
  32489. * Get axis scale extent before niced.
  32490. * Item of returned array can only be number (including Infinity and NaN).
  32491. */
  32492. function getScaleExtent(scale, model) {
  32493. var scaleType = scale.type;
  32494. var min = model.getMin();
  32495. var max = model.getMax();
  32496. var fixMin = min != null;
  32497. var fixMax = max != null;
  32498. var originalExtent = scale.getExtent();
  32499. var axisDataLen;
  32500. var boundaryGap;
  32501. var span;
  32502. if (scaleType === 'ordinal') {
  32503. axisDataLen = model.getCategories().length;
  32504. }
  32505. else {
  32506. boundaryGap = model.get('boundaryGap');
  32507. if (!isArray(boundaryGap)) {
  32508. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  32509. }
  32510. if (typeof boundaryGap[0] === 'boolean') {
  32511. if (__DEV__) {
  32512. console.warn('Boolean type for boundaryGap is only '
  32513. + 'allowed for ordinal axis. Please use string in '
  32514. + 'percentage instead, e.g., "20%". Currently, '
  32515. + 'boundaryGap is set to be 0.');
  32516. }
  32517. boundaryGap = [0, 0];
  32518. }
  32519. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  32520. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  32521. span = (originalExtent[1] - originalExtent[0])
  32522. || Math.abs(originalExtent[0]);
  32523. }
  32524. // Notice: When min/max is not set (that is, when there are null/undefined,
  32525. // which is the most common case), these cases should be ensured:
  32526. // (1) For 'ordinal', show all axis.data.
  32527. // (2) For others:
  32528. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  32529. // disabled).
  32530. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  32531. // be the result that originalExtent enlarged by boundaryGap.
  32532. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  32533. // FIXME
  32534. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  32535. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  32536. // that the results processed by boundaryGap are positive/negative?
  32537. if (min == null) {
  32538. min = scaleType === 'ordinal'
  32539. ? (axisDataLen ? 0 : NaN)
  32540. : originalExtent[0] - boundaryGap[0] * span;
  32541. }
  32542. if (max == null) {
  32543. max = scaleType === 'ordinal'
  32544. ? (axisDataLen ? axisDataLen - 1 : NaN)
  32545. : originalExtent[1] + boundaryGap[1] * span;
  32546. }
  32547. if (min === 'dataMin') {
  32548. min = originalExtent[0];
  32549. }
  32550. else if (typeof min === 'function') {
  32551. min = min({
  32552. min: originalExtent[0],
  32553. max: originalExtent[1]
  32554. });
  32555. }
  32556. if (max === 'dataMax') {
  32557. max = originalExtent[1];
  32558. }
  32559. else if (typeof max === 'function') {
  32560. max = max({
  32561. min: originalExtent[0],
  32562. max: originalExtent[1]
  32563. });
  32564. }
  32565. (min == null || !isFinite(min)) && (min = NaN);
  32566. (max == null || !isFinite(max)) && (max = NaN);
  32567. scale.setBlank(
  32568. eqNaN(min)
  32569. || eqNaN(max)
  32570. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  32571. );
  32572. // Evaluate if axis needs cross zero
  32573. if (model.getNeedCrossZero()) {
  32574. // Axis is over zero and min is not set
  32575. if (min > 0 && max > 0 && !fixMin) {
  32576. min = 0;
  32577. }
  32578. // Axis is under zero and max is not set
  32579. if (min < 0 && max < 0 && !fixMax) {
  32580. max = 0;
  32581. }
  32582. }
  32583. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  32584. // is base axis
  32585. // FIXME
  32586. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  32587. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  32588. // Should not depend on series type `bar`?
  32589. // (3) Fix that might overlap when using dataZoom.
  32590. // (4) Consider other chart types using `barGrid`?
  32591. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  32592. var ecModel = model.ecModel;
  32593. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  32594. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  32595. var isBaseAxisAndHasBarSeries;
  32596. each$1(barSeriesModels, function (seriesModel) {
  32597. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  32598. });
  32599. if (isBaseAxisAndHasBarSeries) {
  32600. // Calculate placement of bars on axis
  32601. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  32602. // Adjust axis min and max to account for overflow
  32603. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  32604. min = adjustedScale.min;
  32605. max = adjustedScale.max;
  32606. }
  32607. }
  32608. return [min, max];
  32609. }
  32610. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  32611. // Get Axis Length
  32612. var axisExtent = model.axis.getExtent();
  32613. var axisLength = axisExtent[1] - axisExtent[0];
  32614. // Get bars on current base axis and calculate min and max overflow
  32615. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  32616. if (barsOnCurrentAxis === undefined) {
  32617. return {min: min, max: max};
  32618. }
  32619. var minOverflow = Infinity;
  32620. each$1(barsOnCurrentAxis, function (item) {
  32621. minOverflow = Math.min(item.offset, minOverflow);
  32622. });
  32623. var maxOverflow = -Infinity;
  32624. each$1(barsOnCurrentAxis, function (item) {
  32625. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  32626. });
  32627. minOverflow = Math.abs(minOverflow);
  32628. maxOverflow = Math.abs(maxOverflow);
  32629. var totalOverFlow = minOverflow + maxOverflow;
  32630. // Calulate required buffer based on old range and overflow
  32631. var oldRange = max - min;
  32632. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  32633. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  32634. max += overflowBuffer * (maxOverflow / totalOverFlow);
  32635. min -= overflowBuffer * (minOverflow / totalOverFlow);
  32636. return {min: min, max: max};
  32637. }
  32638. function niceScaleExtent(scale, model) {
  32639. var extent = getScaleExtent(scale, model);
  32640. var fixMin = model.getMin() != null;
  32641. var fixMax = model.getMax() != null;
  32642. var splitNumber = model.get('splitNumber');
  32643. if (scale.type === 'log') {
  32644. scale.base = model.get('logBase');
  32645. }
  32646. var scaleType = scale.type;
  32647. scale.setExtent(extent[0], extent[1]);
  32648. scale.niceExtent({
  32649. splitNumber: splitNumber,
  32650. fixMin: fixMin,
  32651. fixMax: fixMax,
  32652. minInterval: (scaleType === 'interval' || scaleType === 'time')
  32653. ? model.get('minInterval') : null,
  32654. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  32655. ? model.get('maxInterval') : null
  32656. });
  32657. // If some one specified the min, max. And the default calculated interval
  32658. // is not good enough. He can specify the interval. It is often appeared
  32659. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32660. // to be 60.
  32661. // FIXME
  32662. var interval = model.get('interval');
  32663. if (interval != null) {
  32664. scale.setInterval && scale.setInterval(interval);
  32665. }
  32666. }
  32667. /**
  32668. * @param {module:echarts/model/Model} model
  32669. * @param {string} [axisType] Default retrieve from model.type
  32670. * @return {module:echarts/scale/*}
  32671. */
  32672. function createScaleByModel(model, axisType) {
  32673. axisType = axisType || model.get('type');
  32674. if (axisType) {
  32675. switch (axisType) {
  32676. // Buildin scale
  32677. case 'category':
  32678. return new OrdinalScale(
  32679. model.getOrdinalMeta
  32680. ? model.getOrdinalMeta()
  32681. : model.getCategories(),
  32682. [Infinity, -Infinity]
  32683. );
  32684. case 'value':
  32685. return new IntervalScale();
  32686. // Extended scale, like time and log
  32687. default:
  32688. return (Scale.getClass(axisType) || IntervalScale).create(model);
  32689. }
  32690. }
  32691. }
  32692. /**
  32693. * Check if the axis corss 0
  32694. */
  32695. function ifAxisCrossZero(axis) {
  32696. var dataExtent = axis.scale.getExtent();
  32697. var min = dataExtent[0];
  32698. var max = dataExtent[1];
  32699. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  32700. }
  32701. /**
  32702. * @param {module:echarts/coord/Axis} axis
  32703. * @return {Function} Label formatter function.
  32704. * param: {number} tickValue,
  32705. * param: {number} idx, the index in all ticks.
  32706. * If category axis, this param is not requied.
  32707. * return: {string} label string.
  32708. */
  32709. function makeLabelFormatter(axis) {
  32710. var labelFormatter = axis.getLabelModel().get('formatter');
  32711. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32712. if (typeof labelFormatter === 'string') {
  32713. labelFormatter = (function (tpl) {
  32714. return function (val) {
  32715. // For category axis, get raw value; for numeric axis,
  32716. // get foramtted label like '1,333,444'.
  32717. val = axis.scale.getLabel(val);
  32718. return tpl.replace('{value}', val != null ? val : '');
  32719. };
  32720. })(labelFormatter);
  32721. // Consider empty array
  32722. return labelFormatter;
  32723. }
  32724. else if (typeof labelFormatter === 'function') {
  32725. return function (tickValue, idx) {
  32726. // The original intention of `idx` is "the index of the tick in all ticks".
  32727. // But the previous implementation of category axis do not consider the
  32728. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32729. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32730. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32731. // the definition here for back compatibility.
  32732. if (categoryTickStart != null) {
  32733. idx = tickValue - categoryTickStart;
  32734. }
  32735. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  32736. };
  32737. }
  32738. else {
  32739. return function (tick) {
  32740. return axis.scale.getLabel(tick);
  32741. };
  32742. }
  32743. }
  32744. function getAxisRawValue(axis, value) {
  32745. // In category axis with data zoom, tick is not the original
  32746. // index of axis.data. So tick should not be exposed to user
  32747. // in category axis.
  32748. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  32749. }
  32750. /**
  32751. * @param {module:echarts/coord/Axis} axis
  32752. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  32753. */
  32754. function estimateLabelUnionRect(axis) {
  32755. var axisModel = axis.model;
  32756. var scale = axis.scale;
  32757. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  32758. return;
  32759. }
  32760. var isCategory = axis.type === 'category';
  32761. var realNumberScaleTicks;
  32762. var tickCount;
  32763. var categoryScaleExtent = scale.getExtent();
  32764. // Optimize for large category data, avoid call `getTicks()`.
  32765. if (isCategory) {
  32766. tickCount = scale.count();
  32767. }
  32768. else {
  32769. realNumberScaleTicks = scale.getTicks();
  32770. tickCount = realNumberScaleTicks.length;
  32771. }
  32772. var axisLabelModel = axis.getLabelModel();
  32773. var labelFormatter = makeLabelFormatter(axis);
  32774. var rect;
  32775. var step = 1;
  32776. // Simple optimization for large amount of labels
  32777. if (tickCount > 40) {
  32778. step = Math.ceil(tickCount / 40);
  32779. }
  32780. for (var i = 0; i < tickCount; i += step) {
  32781. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  32782. var label = labelFormatter(tickValue);
  32783. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32784. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32785. rect ? rect.union(singleRect) : (rect = singleRect);
  32786. }
  32787. return rect;
  32788. }
  32789. function rotateTextRect(textRect, rotate) {
  32790. var rotateRadians = rotate * Math.PI / 180;
  32791. var boundingBox = textRect.plain();
  32792. var beforeWidth = boundingBox.width;
  32793. var beforeHeight = boundingBox.height;
  32794. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  32795. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  32796. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  32797. return rotatedRect;
  32798. }
  32799. /**
  32800. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  32801. * @return {number|String} Can be null|'auto'|number|function
  32802. */
  32803. function getOptionCategoryInterval(model) {
  32804. var interval = model.get('interval');
  32805. return interval == null ? 'auto' : interval;
  32806. }
  32807. /**
  32808. * Set `categoryInterval` as 0 implicitly indicates that
  32809. * show all labels reguardless of overlap.
  32810. * @param {Object} axis axisModel.axis
  32811. * @return {boolean}
  32812. */
  32813. function shouldShowAllLabels(axis) {
  32814. return axis.type === 'category'
  32815. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32816. }
  32817. /*
  32818. * Licensed to the Apache Software Foundation (ASF) under one
  32819. * or more contributor license agreements. See the NOTICE file
  32820. * distributed with this work for additional information
  32821. * regarding copyright ownership. The ASF licenses this file
  32822. * to you under the Apache License, Version 2.0 (the
  32823. * "License"); you may not use this file except in compliance
  32824. * with the License. You may obtain a copy of the License at
  32825. *
  32826. * http://www.apache.org/licenses/LICENSE-2.0
  32827. *
  32828. * Unless required by applicable law or agreed to in writing,
  32829. * software distributed under the License is distributed on an
  32830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32831. * KIND, either express or implied. See the License for the
  32832. * specific language governing permissions and limitations
  32833. * under the License.
  32834. */
  32835. /**
  32836. * Cartesian coordinate system
  32837. * @module echarts/coord/Cartesian
  32838. *
  32839. */
  32840. function dimAxisMapper(dim) {
  32841. return this._axes[dim];
  32842. }
  32843. /**
  32844. * @alias module:echarts/coord/Cartesian
  32845. * @constructor
  32846. */
  32847. var Cartesian = function (name) {
  32848. this._axes = {};
  32849. this._dimList = [];
  32850. /**
  32851. * @type {string}
  32852. */
  32853. this.name = name || '';
  32854. };
  32855. Cartesian.prototype = {
  32856. constructor: Cartesian,
  32857. type: 'cartesian',
  32858. /**
  32859. * Get axis
  32860. * @param {number|string} dim
  32861. * @return {module:echarts/coord/Cartesian~Axis}
  32862. */
  32863. getAxis: function (dim) {
  32864. return this._axes[dim];
  32865. },
  32866. /**
  32867. * Get axes list
  32868. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  32869. */
  32870. getAxes: function () {
  32871. return map(this._dimList, dimAxisMapper, this);
  32872. },
  32873. /**
  32874. * Get axes list by given scale type
  32875. */
  32876. getAxesByScale: function (scaleType) {
  32877. scaleType = scaleType.toLowerCase();
  32878. return filter(
  32879. this.getAxes(),
  32880. function (axis) {
  32881. return axis.scale.type === scaleType;
  32882. }
  32883. );
  32884. },
  32885. /**
  32886. * Add axis
  32887. * @param {module:echarts/coord/Cartesian.Axis}
  32888. */
  32889. addAxis: function (axis) {
  32890. var dim = axis.dim;
  32891. this._axes[dim] = axis;
  32892. this._dimList.push(dim);
  32893. },
  32894. /**
  32895. * Convert data to coord in nd space
  32896. * @param {Array.<number>|Object.<string, number>} val
  32897. * @return {Array.<number>|Object.<string, number>}
  32898. */
  32899. dataToCoord: function (val) {
  32900. return this._dataCoordConvert(val, 'dataToCoord');
  32901. },
  32902. /**
  32903. * Convert coord in nd space to data
  32904. * @param {Array.<number>|Object.<string, number>} val
  32905. * @return {Array.<number>|Object.<string, number>}
  32906. */
  32907. coordToData: function (val) {
  32908. return this._dataCoordConvert(val, 'coordToData');
  32909. },
  32910. _dataCoordConvert: function (input, method) {
  32911. var dimList = this._dimList;
  32912. var output = input instanceof Array ? [] : {};
  32913. for (var i = 0; i < dimList.length; i++) {
  32914. var dim = dimList[i];
  32915. var axis = this._axes[dim];
  32916. output[dim] = axis[method](input[dim]);
  32917. }
  32918. return output;
  32919. }
  32920. };
  32921. /*
  32922. * Licensed to the Apache Software Foundation (ASF) under one
  32923. * or more contributor license agreements. See the NOTICE file
  32924. * distributed with this work for additional information
  32925. * regarding copyright ownership. The ASF licenses this file
  32926. * to you under the Apache License, Version 2.0 (the
  32927. * "License"); you may not use this file except in compliance
  32928. * with the License. You may obtain a copy of the License at
  32929. *
  32930. * http://www.apache.org/licenses/LICENSE-2.0
  32931. *
  32932. * Unless required by applicable law or agreed to in writing,
  32933. * software distributed under the License is distributed on an
  32934. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32935. * KIND, either express or implied. See the License for the
  32936. * specific language governing permissions and limitations
  32937. * under the License.
  32938. */
  32939. function Cartesian2D(name) {
  32940. Cartesian.call(this, name);
  32941. }
  32942. Cartesian2D.prototype = {
  32943. constructor: Cartesian2D,
  32944. type: 'cartesian2d',
  32945. /**
  32946. * @type {Array.<string>}
  32947. * @readOnly
  32948. */
  32949. dimensions: ['x', 'y'],
  32950. /**
  32951. * Base axis will be used on stacking.
  32952. *
  32953. * @return {module:echarts/coord/cartesian/Axis2D}
  32954. */
  32955. getBaseAxis: function () {
  32956. return this.getAxesByScale('ordinal')[0]
  32957. || this.getAxesByScale('time')[0]
  32958. || this.getAxis('x');
  32959. },
  32960. /**
  32961. * If contain point
  32962. * @param {Array.<number>} point
  32963. * @return {boolean}
  32964. */
  32965. containPoint: function (point) {
  32966. var axisX = this.getAxis('x');
  32967. var axisY = this.getAxis('y');
  32968. return axisX.contain(axisX.toLocalCoord(point[0]))
  32969. && axisY.contain(axisY.toLocalCoord(point[1]));
  32970. },
  32971. /**
  32972. * If contain data
  32973. * @param {Array.<number>} data
  32974. * @return {boolean}
  32975. */
  32976. containData: function (data) {
  32977. return this.getAxis('x').containData(data[0])
  32978. && this.getAxis('y').containData(data[1]);
  32979. },
  32980. /**
  32981. * @param {Array.<number>} data
  32982. * @param {Array.<number>} out
  32983. * @return {Array.<number>}
  32984. */
  32985. dataToPoint: function (data, reserved, out) {
  32986. var xAxis = this.getAxis('x');
  32987. var yAxis = this.getAxis('y');
  32988. out = out || [];
  32989. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  32990. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  32991. return out;
  32992. },
  32993. /**
  32994. * @param {Array.<number>} data
  32995. * @param {Array.<number>} out
  32996. * @return {Array.<number>}
  32997. */
  32998. clampData: function (data, out) {
  32999. var xScale = this.getAxis('x').scale;
  33000. var yScale = this.getAxis('y').scale;
  33001. var xAxisExtent = xScale.getExtent();
  33002. var yAxisExtent = yScale.getExtent();
  33003. var x = xScale.parse(data[0]);
  33004. var y = yScale.parse(data[1]);
  33005. out = out || [];
  33006. out[0] = Math.min(
  33007. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33008. Math.max(xAxisExtent[0], xAxisExtent[1])
  33009. );
  33010. out[1] = Math.min(
  33011. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33012. Math.max(yAxisExtent[0], yAxisExtent[1])
  33013. );
  33014. return out;
  33015. },
  33016. /**
  33017. * @param {Array.<number>} point
  33018. * @param {Array.<number>} out
  33019. * @return {Array.<number>}
  33020. */
  33021. pointToData: function (point, out) {
  33022. var xAxis = this.getAxis('x');
  33023. var yAxis = this.getAxis('y');
  33024. out = out || [];
  33025. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33026. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33027. return out;
  33028. },
  33029. /**
  33030. * Get other axis
  33031. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33032. */
  33033. getOtherAxis: function (axis) {
  33034. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33035. },
  33036. /**
  33037. * Get rect area of cartesian.
  33038. * Area will have a contain function to determine if a point is in the coordinate system.
  33039. * @return {BoundingRect}
  33040. */
  33041. getArea: function () {
  33042. var xExtent = this.getAxis('x').getGlobalExtent();
  33043. var yExtent = this.getAxis('y').getGlobalExtent();
  33044. var x = Math.min(xExtent[0], xExtent[1]);
  33045. var y = Math.min(yExtent[0], yExtent[1]);
  33046. var width = Math.max(xExtent[0], xExtent[1]) - x;
  33047. var height = Math.max(yExtent[0], yExtent[1]) - y;
  33048. var rect = new BoundingRect(x, y, width, height);
  33049. return rect;
  33050. }
  33051. };
  33052. inherits(Cartesian2D, Cartesian);
  33053. /*
  33054. * Licensed to the Apache Software Foundation (ASF) under one
  33055. * or more contributor license agreements. See the NOTICE file
  33056. * distributed with this work for additional information
  33057. * regarding copyright ownership. The ASF licenses this file
  33058. * to you under the Apache License, Version 2.0 (the
  33059. * "License"); you may not use this file except in compliance
  33060. * with the License. You may obtain a copy of the License at
  33061. *
  33062. * http://www.apache.org/licenses/LICENSE-2.0
  33063. *
  33064. * Unless required by applicable law or agreed to in writing,
  33065. * software distributed under the License is distributed on an
  33066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33067. * KIND, either express or implied. See the License for the
  33068. * specific language governing permissions and limitations
  33069. * under the License.
  33070. */
  33071. var inner$6 = makeInner();
  33072. /**
  33073. * @param {module:echats/coord/Axis} axis
  33074. * @return {Object} {
  33075. * labels: [{
  33076. * formattedLabel: string,
  33077. * rawLabel: string,
  33078. * tickValue: number
  33079. * }, ...],
  33080. * labelCategoryInterval: number
  33081. * }
  33082. */
  33083. function createAxisLabels(axis) {
  33084. // Only ordinal scale support tick interval
  33085. return axis.type === 'category'
  33086. ? makeCategoryLabels(axis)
  33087. : makeRealNumberLabels(axis);
  33088. }
  33089. /**
  33090. * @param {module:echats/coord/Axis} axis
  33091. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  33092. * @return {Object} {
  33093. * ticks: Array.<number>
  33094. * tickCategoryInterval: number
  33095. * }
  33096. */
  33097. function createAxisTicks(axis, tickModel) {
  33098. // Only ordinal scale support tick interval
  33099. return axis.type === 'category'
  33100. ? makeCategoryTicks(axis, tickModel)
  33101. : {ticks: axis.scale.getTicks()};
  33102. }
  33103. function makeCategoryLabels(axis) {
  33104. var labelModel = axis.getLabelModel();
  33105. var result = makeCategoryLabelsActually(axis, labelModel);
  33106. return (!labelModel.get('show') || axis.scale.isBlank())
  33107. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  33108. : result;
  33109. }
  33110. function makeCategoryLabelsActually(axis, labelModel) {
  33111. var labelsCache = getListCache(axis, 'labels');
  33112. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  33113. var result = listCacheGet(labelsCache, optionLabelInterval);
  33114. if (result) {
  33115. return result;
  33116. }
  33117. var labels;
  33118. var numericLabelInterval;
  33119. if (isFunction$1(optionLabelInterval)) {
  33120. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  33121. }
  33122. else {
  33123. numericLabelInterval = optionLabelInterval === 'auto'
  33124. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  33125. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  33126. }
  33127. // Cache to avoid calling interval function repeatly.
  33128. return listCacheSet(labelsCache, optionLabelInterval, {
  33129. labels: labels, labelCategoryInterval: numericLabelInterval
  33130. });
  33131. }
  33132. function makeCategoryTicks(axis, tickModel) {
  33133. var ticksCache = getListCache(axis, 'ticks');
  33134. var optionTickInterval = getOptionCategoryInterval(tickModel);
  33135. var result = listCacheGet(ticksCache, optionTickInterval);
  33136. if (result) {
  33137. return result;
  33138. }
  33139. var ticks;
  33140. var tickCategoryInterval;
  33141. // Optimize for the case that large category data and no label displayed,
  33142. // we should not return all ticks.
  33143. if (!tickModel.get('show') || axis.scale.isBlank()) {
  33144. ticks = [];
  33145. }
  33146. if (isFunction$1(optionTickInterval)) {
  33147. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  33148. }
  33149. // Always use label interval by default despite label show. Consider this
  33150. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  33151. // labels. `splitLine` and `axisTick` should be consistent in this case.
  33152. else if (optionTickInterval === 'auto') {
  33153. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  33154. tickCategoryInterval = labelsResult.labelCategoryInterval;
  33155. ticks = map(labelsResult.labels, function (labelItem) {
  33156. return labelItem.tickValue;
  33157. });
  33158. }
  33159. else {
  33160. tickCategoryInterval = optionTickInterval;
  33161. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  33162. }
  33163. // Cache to avoid calling interval function repeatly.
  33164. return listCacheSet(ticksCache, optionTickInterval, {
  33165. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  33166. });
  33167. }
  33168. function makeRealNumberLabels(axis) {
  33169. var ticks = axis.scale.getTicks();
  33170. var labelFormatter = makeLabelFormatter(axis);
  33171. return {
  33172. labels: map(ticks, function (tickValue, idx) {
  33173. return {
  33174. formattedLabel: labelFormatter(tickValue, idx),
  33175. rawLabel: axis.scale.getLabel(tickValue),
  33176. tickValue: tickValue
  33177. };
  33178. })
  33179. };
  33180. }
  33181. // Large category data calculation is performence sensitive, and ticks and label
  33182. // probably be fetched by multiple times. So we cache the result.
  33183. // axis is created each time during a ec process, so we do not need to clear cache.
  33184. function getListCache(axis, prop) {
  33185. // Because key can be funciton, and cache size always be small, we use array cache.
  33186. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  33187. }
  33188. function listCacheGet(cache, key) {
  33189. for (var i = 0; i < cache.length; i++) {
  33190. if (cache[i].key === key) {
  33191. return cache[i].value;
  33192. }
  33193. }
  33194. }
  33195. function listCacheSet(cache, key, value) {
  33196. cache.push({key: key, value: value});
  33197. return value;
  33198. }
  33199. function makeAutoCategoryInterval(axis) {
  33200. var result = inner$6(axis).autoInterval;
  33201. return result != null
  33202. ? result
  33203. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  33204. }
  33205. /**
  33206. * Calculate interval for category axis ticks and labels.
  33207. * To get precise result, at least one of `getRotate` and `isHorizontal`
  33208. * should be implemented in axis.
  33209. */
  33210. function calculateCategoryInterval(axis) {
  33211. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  33212. var labelFormatter = makeLabelFormatter(axis);
  33213. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  33214. var ordinalScale = axis.scale;
  33215. var ordinalExtent = ordinalScale.getExtent();
  33216. // Providing this method is for optimization:
  33217. // avoid generating a long array by `getTicks`
  33218. // in large category data case.
  33219. var tickCount = ordinalScale.count();
  33220. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  33221. return 0;
  33222. }
  33223. var step = 1;
  33224. // Simple optimization. Empirical value: tick count should less than 40.
  33225. if (tickCount > 40) {
  33226. step = Math.max(1, Math.floor(tickCount / 40));
  33227. }
  33228. var tickValue = ordinalExtent[0];
  33229. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  33230. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  33231. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  33232. var maxW = 0;
  33233. var maxH = 0;
  33234. // Caution: Performance sensitive for large category data.
  33235. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  33236. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33237. var width = 0;
  33238. var height = 0;
  33239. // Not precise, do not consider align and vertical align
  33240. // and each distance from axis line yet.
  33241. var rect = getBoundingRect(
  33242. labelFormatter(tickValue), params.font, 'center', 'top'
  33243. );
  33244. // Magic number
  33245. width = rect.width * 1.3;
  33246. height = rect.height * 1.3;
  33247. // Min size, void long loop.
  33248. maxW = Math.max(maxW, width, 7);
  33249. maxH = Math.max(maxH, height, 7);
  33250. }
  33251. var dw = maxW / unitW;
  33252. var dh = maxH / unitH;
  33253. // 0/0 is NaN, 1/0 is Infinity.
  33254. isNaN(dw) && (dw = Infinity);
  33255. isNaN(dh) && (dh = Infinity);
  33256. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  33257. var cache = inner$6(axis.model);
  33258. var axisExtent = axis.getExtent();
  33259. var lastAutoInterval = cache.lastAutoInterval;
  33260. var lastTickCount = cache.lastTickCount;
  33261. // Use cache to keep interval stable while moving zoom window,
  33262. // otherwise the calculated interval might jitter when the zoom
  33263. // window size is close to the interval-changing size.
  33264. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  33265. // The jitter will cause that sometimes the displayed labels are
  33266. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  33267. if (lastAutoInterval != null
  33268. && lastTickCount != null
  33269. && Math.abs(lastAutoInterval - interval) <= 1
  33270. && Math.abs(lastTickCount - tickCount) <= 1
  33271. // Always choose the bigger one, otherwise the critical
  33272. // point is not the same when zooming in or zooming out.
  33273. && lastAutoInterval > interval
  33274. // If the axis change is caused by chart resize, the cache should not
  33275. // be used. Otherwise some hiden labels might not be shown again.
  33276. && cache.axisExtend0 === axisExtent[0]
  33277. && cache.axisExtend1 === axisExtent[1]
  33278. ) {
  33279. interval = lastAutoInterval;
  33280. }
  33281. // Only update cache if cache not used, otherwise the
  33282. // changing of interval is too insensitive.
  33283. else {
  33284. cache.lastTickCount = tickCount;
  33285. cache.lastAutoInterval = interval;
  33286. cache.axisExtend0 = axisExtent[0];
  33287. cache.axisExtend1 = axisExtent[1];
  33288. }
  33289. return interval;
  33290. }
  33291. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33292. var labelModel = axis.getLabelModel();
  33293. return {
  33294. axisRotate: axis.getRotate
  33295. ? axis.getRotate()
  33296. : (axis.isHorizontal && !axis.isHorizontal())
  33297. ? 90
  33298. : 0,
  33299. labelRotate: labelModel.get('rotate') || 0,
  33300. font: labelModel.getFont()
  33301. };
  33302. }
  33303. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33304. var labelFormatter = makeLabelFormatter(axis);
  33305. var ordinalScale = axis.scale;
  33306. var ordinalExtent = ordinalScale.getExtent();
  33307. var labelModel = axis.getLabelModel();
  33308. var result = [];
  33309. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33310. var step = Math.max((categoryInterval || 0) + 1, 1);
  33311. var startTick = ordinalExtent[0];
  33312. var tickCount = ordinalScale.count();
  33313. // Calculate start tick based on zero if possible to keep label consistent
  33314. // while zooming and moving while interval > 0. Otherwise the selection
  33315. // of displayable ticks and symbols probably keep changing.
  33316. // 3 is empirical value.
  33317. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33318. startTick = Math.round(Math.ceil(startTick / step) * step);
  33319. }
  33320. // (1) Only add min max label here but leave overlap checking
  33321. // to render stage, which also ensure the returned list
  33322. // suitable for splitLine and splitArea rendering.
  33323. // (2) Scales except category always contain min max label so
  33324. // do not need to perform this process.
  33325. var showAllLabel = shouldShowAllLabels(axis);
  33326. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33327. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33328. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33329. addItem(ordinalExtent[0]);
  33330. }
  33331. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33332. var tickValue = startTick;
  33333. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33334. addItem(tickValue);
  33335. }
  33336. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33337. addItem(ordinalExtent[1]);
  33338. }
  33339. function addItem(tVal) {
  33340. result.push(onlyTick
  33341. ? tVal
  33342. : {
  33343. formattedLabel: labelFormatter(tVal),
  33344. rawLabel: ordinalScale.getLabel(tVal),
  33345. tickValue: tVal
  33346. }
  33347. );
  33348. }
  33349. return result;
  33350. }
  33351. // When interval is function, the result `false` means ignore the tick.
  33352. // It is time consuming for large category data.
  33353. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33354. var ordinalScale = axis.scale;
  33355. var labelFormatter = makeLabelFormatter(axis);
  33356. var result = [];
  33357. each$1(ordinalScale.getTicks(), function (tickValue) {
  33358. var rawLabel = ordinalScale.getLabel(tickValue);
  33359. if (categoryInterval(tickValue, rawLabel)) {
  33360. result.push(onlyTick
  33361. ? tickValue
  33362. : {
  33363. formattedLabel: labelFormatter(tickValue),
  33364. rawLabel: rawLabel,
  33365. tickValue: tickValue
  33366. }
  33367. );
  33368. }
  33369. });
  33370. return result;
  33371. }
  33372. /*
  33373. * Licensed to the Apache Software Foundation (ASF) under one
  33374. * or more contributor license agreements. See the NOTICE file
  33375. * distributed with this work for additional information
  33376. * regarding copyright ownership. The ASF licenses this file
  33377. * to you under the Apache License, Version 2.0 (the
  33378. * "License"); you may not use this file except in compliance
  33379. * with the License. You may obtain a copy of the License at
  33380. *
  33381. * http://www.apache.org/licenses/LICENSE-2.0
  33382. *
  33383. * Unless required by applicable law or agreed to in writing,
  33384. * software distributed under the License is distributed on an
  33385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33386. * KIND, either express or implied. See the License for the
  33387. * specific language governing permissions and limitations
  33388. * under the License.
  33389. */
  33390. var NORMALIZED_EXTENT = [0, 1];
  33391. /**
  33392. * Base class of Axis.
  33393. * @constructor
  33394. */
  33395. var Axis = function (dim, scale, extent) {
  33396. /**
  33397. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  33398. * @type {string}
  33399. */
  33400. this.dim = dim;
  33401. /**
  33402. * Axis scale
  33403. * @type {module:echarts/coord/scale/*}
  33404. */
  33405. this.scale = scale;
  33406. /**
  33407. * @type {Array.<number>}
  33408. * @private
  33409. */
  33410. this._extent = extent || [0, 0];
  33411. /**
  33412. * @type {boolean}
  33413. */
  33414. this.inverse = false;
  33415. /**
  33416. * Usually true when axis has a ordinal scale
  33417. * @type {boolean}
  33418. */
  33419. this.onBand = false;
  33420. };
  33421. Axis.prototype = {
  33422. constructor: Axis,
  33423. /**
  33424. * If axis extent contain given coord
  33425. * @param {number} coord
  33426. * @return {boolean}
  33427. */
  33428. contain: function (coord) {
  33429. var extent = this._extent;
  33430. var min = Math.min(extent[0], extent[1]);
  33431. var max = Math.max(extent[0], extent[1]);
  33432. return coord >= min && coord <= max;
  33433. },
  33434. /**
  33435. * If axis extent contain given data
  33436. * @param {number} data
  33437. * @return {boolean}
  33438. */
  33439. containData: function (data) {
  33440. return this.scale.contain(data);
  33441. },
  33442. /**
  33443. * Get coord extent.
  33444. * @return {Array.<number>}
  33445. */
  33446. getExtent: function () {
  33447. return this._extent.slice();
  33448. },
  33449. /**
  33450. * Get precision used for formatting
  33451. * @param {Array.<number>} [dataExtent]
  33452. * @return {number}
  33453. */
  33454. getPixelPrecision: function (dataExtent) {
  33455. return getPixelPrecision(
  33456. dataExtent || this.scale.getExtent(),
  33457. this._extent
  33458. );
  33459. },
  33460. /**
  33461. * Set coord extent
  33462. * @param {number} start
  33463. * @param {number} end
  33464. */
  33465. setExtent: function (start, end) {
  33466. var extent = this._extent;
  33467. extent[0] = start;
  33468. extent[1] = end;
  33469. },
  33470. /**
  33471. * Convert data to coord. Data is the rank if it has an ordinal scale
  33472. * @param {number} data
  33473. * @param {boolean} clamp
  33474. * @return {number}
  33475. */
  33476. dataToCoord: function (data, clamp) {
  33477. var extent = this._extent;
  33478. var scale = this.scale;
  33479. data = scale.normalize(data);
  33480. if (this.onBand && scale.type === 'ordinal') {
  33481. extent = extent.slice();
  33482. fixExtentWithBands(extent, scale.count());
  33483. }
  33484. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33485. },
  33486. /**
  33487. * Convert coord to data. Data is the rank if it has an ordinal scale
  33488. * @param {number} coord
  33489. * @param {boolean} clamp
  33490. * @return {number}
  33491. */
  33492. coordToData: function (coord, clamp) {
  33493. var extent = this._extent;
  33494. var scale = this.scale;
  33495. if (this.onBand && scale.type === 'ordinal') {
  33496. extent = extent.slice();
  33497. fixExtentWithBands(extent, scale.count());
  33498. }
  33499. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33500. return this.scale.scale(t);
  33501. },
  33502. /**
  33503. * Convert pixel point to data in axis
  33504. * @param {Array.<number>} point
  33505. * @param {boolean} clamp
  33506. * @return {number} data
  33507. */
  33508. pointToData: function (point, clamp) {
  33509. // Should be implemented in derived class if necessary.
  33510. },
  33511. /**
  33512. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33513. * `axis.getTicksCoords` considers `onBand`, which is used by
  33514. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33515. * @param {Object} [opt]
  33516. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  33517. * @param {boolean} [opt.clamp] If `true`, the first and the last
  33518. * tick must be at the axis end points. Otherwise, clip ticks
  33519. * that outside the axis extent.
  33520. * @return {Array.<Object>} [{
  33521. * coord: ...,
  33522. * tickValue: ...
  33523. * }, ...]
  33524. */
  33525. getTicksCoords: function (opt) {
  33526. opt = opt || {};
  33527. var tickModel = opt.tickModel || this.getTickModel();
  33528. var result = createAxisTicks(this, tickModel);
  33529. var ticks = result.ticks;
  33530. var ticksCoords = map(ticks, function (tickValue) {
  33531. return {
  33532. coord: this.dataToCoord(tickValue),
  33533. tickValue: tickValue
  33534. };
  33535. }, this);
  33536. var alignWithLabel = tickModel.get('alignWithLabel');
  33537. fixOnBandTicksCoords(
  33538. this, ticksCoords, alignWithLabel, opt.clamp
  33539. );
  33540. return ticksCoords;
  33541. },
  33542. /**
  33543. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  33544. */
  33545. getMinorTicksCoords: function () {
  33546. if (this.scale.type === 'ordinal') {
  33547. // Category axis doesn't support minor ticks
  33548. return [];
  33549. }
  33550. var minorTickModel = this.model.getModel('minorTick');
  33551. var splitNumber = minorTickModel.get('splitNumber');
  33552. // Protection.
  33553. if (!(splitNumber > 0 && splitNumber < 100)) {
  33554. splitNumber = 5;
  33555. }
  33556. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33557. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33558. return map(minorTicksGroup, function (minorTick) {
  33559. return {
  33560. coord: this.dataToCoord(minorTick),
  33561. tickValue: minorTick
  33562. };
  33563. }, this);
  33564. }, this);
  33565. return minorTicksCoords;
  33566. },
  33567. /**
  33568. * @return {Array.<Object>} [{
  33569. * formattedLabel: string,
  33570. * rawLabel: axis.scale.getLabel(tickValue)
  33571. * tickValue: number
  33572. * }, ...]
  33573. */
  33574. getViewLabels: function () {
  33575. return createAxisLabels(this).labels;
  33576. },
  33577. /**
  33578. * @return {module:echarts/coord/model/Model}
  33579. */
  33580. getLabelModel: function () {
  33581. return this.model.getModel('axisLabel');
  33582. },
  33583. /**
  33584. * Notice here we only get the default tick model. For splitLine
  33585. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33586. * manually when calling `getTicksCoords`.
  33587. * In GL, this method may be overrided to:
  33588. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33589. * @return {module:echarts/coord/model/Model}
  33590. */
  33591. getTickModel: function () {
  33592. return this.model.getModel('axisTick');
  33593. },
  33594. /**
  33595. * Get width of band
  33596. * @return {number}
  33597. */
  33598. getBandWidth: function () {
  33599. var axisExtent = this._extent;
  33600. var dataExtent = this.scale.getExtent();
  33601. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  33602. // Fix #2728, avoid NaN when only one data.
  33603. len === 0 && (len = 1);
  33604. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33605. return Math.abs(size) / len;
  33606. },
  33607. /**
  33608. * @abstract
  33609. * @return {boolean} Is horizontal
  33610. */
  33611. isHorizontal: null,
  33612. /**
  33613. * @abstract
  33614. * @return {number} Get axis rotate, by degree.
  33615. */
  33616. getRotate: null,
  33617. /**
  33618. * Only be called in category axis.
  33619. * Can be overrided, consider other axes like in 3D.
  33620. * @return {number} Auto interval for cateogry axis tick and label
  33621. */
  33622. calculateCategoryInterval: function () {
  33623. return calculateCategoryInterval(this);
  33624. }
  33625. };
  33626. function fixExtentWithBands(extent, nTick) {
  33627. var size = extent[1] - extent[0];
  33628. var len = nTick;
  33629. var margin = size / len / 2;
  33630. extent[0] += margin;
  33631. extent[1] -= margin;
  33632. }
  33633. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33634. // |---1---|---2---|---3---|---4---|.
  33635. // So the displayed ticks and splitLine/splitArea should between
  33636. // each data item, otherwise cause misleading (e.g., split tow bars
  33637. // of a single data item when there are two bar series).
  33638. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33639. // splitLine/spliteArea should layout appropriately corresponding
  33640. // to displayed labels. (So we should not use `getBandWidth` in this
  33641. // case).
  33642. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33643. var ticksLen = ticksCoords.length;
  33644. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33645. return;
  33646. }
  33647. var axisExtent = axis.getExtent();
  33648. var last;
  33649. var diffSize;
  33650. if (ticksLen === 1) {
  33651. ticksCoords[0].coord = axisExtent[0];
  33652. last = ticksCoords[1] = {coord: axisExtent[0]};
  33653. }
  33654. else {
  33655. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33656. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33657. each$1(ticksCoords, function (ticksItem) {
  33658. ticksItem.coord -= shift / 2;
  33659. });
  33660. var dataExtent = axis.scale.getExtent();
  33661. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33662. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  33663. ticksCoords.push(last);
  33664. }
  33665. var inverse = axisExtent[0] > axisExtent[1];
  33666. // Handling clamp.
  33667. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33668. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  33669. }
  33670. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33671. ticksCoords.unshift({coord: axisExtent[0]});
  33672. }
  33673. if (littleThan(axisExtent[1], last.coord)) {
  33674. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  33675. }
  33676. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33677. ticksCoords.push({coord: axisExtent[1]});
  33678. }
  33679. function littleThan(a, b) {
  33680. // Avoid rounding error cause calculated tick coord different with extent.
  33681. // It may cause an extra unecessary tick added.
  33682. a = round$1(a);
  33683. b = round$1(b);
  33684. return inverse ? a > b : a < b;
  33685. }
  33686. }
  33687. /*
  33688. * Licensed to the Apache Software Foundation (ASF) under one
  33689. * or more contributor license agreements. See the NOTICE file
  33690. * distributed with this work for additional information
  33691. * regarding copyright ownership. The ASF licenses this file
  33692. * to you under the Apache License, Version 2.0 (the
  33693. * "License"); you may not use this file except in compliance
  33694. * with the License. You may obtain a copy of the License at
  33695. *
  33696. * http://www.apache.org/licenses/LICENSE-2.0
  33697. *
  33698. * Unless required by applicable law or agreed to in writing,
  33699. * software distributed under the License is distributed on an
  33700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33701. * KIND, either express or implied. See the License for the
  33702. * specific language governing permissions and limitations
  33703. * under the License.
  33704. */
  33705. /**
  33706. * Extend axis 2d
  33707. * @constructor module:echarts/coord/cartesian/Axis2D
  33708. * @extends {module:echarts/coord/cartesian/Axis}
  33709. * @param {string} dim
  33710. * @param {*} scale
  33711. * @param {Array.<number>} coordExtent
  33712. * @param {string} axisType
  33713. * @param {string} position
  33714. */
  33715. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33716. Axis.call(this, dim, scale, coordExtent);
  33717. /**
  33718. * Axis type
  33719. * - 'category'
  33720. * - 'value'
  33721. * - 'time'
  33722. * - 'log'
  33723. * @type {string}
  33724. */
  33725. this.type = axisType || 'value';
  33726. /**
  33727. * Axis position
  33728. * - 'top'
  33729. * - 'bottom'
  33730. * - 'left'
  33731. * - 'right'
  33732. */
  33733. this.position = position || 'bottom';
  33734. };
  33735. Axis2D.prototype = {
  33736. constructor: Axis2D,
  33737. /**
  33738. * Index of axis, can be used as key
  33739. */
  33740. index: 0,
  33741. /**
  33742. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33743. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33744. * If not on zero of other axis, return null/undefined.
  33745. * If no axes, return an empty array.
  33746. */
  33747. getAxesOnZeroOf: null,
  33748. /**
  33749. * Axis model
  33750. * @param {module:echarts/coord/cartesian/AxisModel}
  33751. */
  33752. model: null,
  33753. isHorizontal: function () {
  33754. var position = this.position;
  33755. return position === 'top' || position === 'bottom';
  33756. },
  33757. /**
  33758. * Each item cooresponds to this.getExtent(), which
  33759. * means globalExtent[0] may greater than globalExtent[1],
  33760. * unless `asc` is input.
  33761. *
  33762. * @param {boolean} [asc]
  33763. * @return {Array.<number>}
  33764. */
  33765. getGlobalExtent: function (asc) {
  33766. var ret = this.getExtent();
  33767. ret[0] = this.toGlobalCoord(ret[0]);
  33768. ret[1] = this.toGlobalCoord(ret[1]);
  33769. asc && ret[0] > ret[1] && ret.reverse();
  33770. return ret;
  33771. },
  33772. getOtherAxis: function () {
  33773. this.grid.getOtherAxis();
  33774. },
  33775. /**
  33776. * @override
  33777. */
  33778. pointToData: function (point, clamp) {
  33779. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33780. },
  33781. /**
  33782. * Transform global coord to local coord,
  33783. * i.e. var localCoord = axis.toLocalCoord(80);
  33784. * designate by module:echarts/coord/cartesian/Grid.
  33785. * @type {Function}
  33786. */
  33787. toLocalCoord: null,
  33788. /**
  33789. * Transform global coord to local coord,
  33790. * i.e. var globalCoord = axis.toLocalCoord(40);
  33791. * designate by module:echarts/coord/cartesian/Grid.
  33792. * @type {Function}
  33793. */
  33794. toGlobalCoord: null
  33795. };
  33796. inherits(Axis2D, Axis);
  33797. /*
  33798. * Licensed to the Apache Software Foundation (ASF) under one
  33799. * or more contributor license agreements. See the NOTICE file
  33800. * distributed with this work for additional information
  33801. * regarding copyright ownership. The ASF licenses this file
  33802. * to you under the Apache License, Version 2.0 (the
  33803. * "License"); you may not use this file except in compliance
  33804. * with the License. You may obtain a copy of the License at
  33805. *
  33806. * http://www.apache.org/licenses/LICENSE-2.0
  33807. *
  33808. * Unless required by applicable law or agreed to in writing,
  33809. * software distributed under the License is distributed on an
  33810. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33811. * KIND, either express or implied. See the License for the
  33812. * specific language governing permissions and limitations
  33813. * under the License.
  33814. */
  33815. var defaultOption = {
  33816. show: true,
  33817. zlevel: 0,
  33818. z: 0,
  33819. // Inverse the axis.
  33820. inverse: false,
  33821. // Axis name displayed.
  33822. name: '',
  33823. // 'start' | 'middle' | 'end'
  33824. nameLocation: 'end',
  33825. // By degree. By defualt auto rotate by nameLocation.
  33826. nameRotate: null,
  33827. nameTruncate: {
  33828. maxWidth: null,
  33829. ellipsis: '...',
  33830. placeholder: '.'
  33831. },
  33832. // Use global text style by default.
  33833. nameTextStyle: {},
  33834. // The gap between axisName and axisLine.
  33835. nameGap: 15,
  33836. // Default `false` to support tooltip.
  33837. silent: false,
  33838. // Default `false` to avoid legacy user event listener fail.
  33839. triggerEvent: false,
  33840. tooltip: {
  33841. show: false
  33842. },
  33843. axisPointer: {},
  33844. axisLine: {
  33845. show: true,
  33846. onZero: true,
  33847. onZeroAxisIndex: null,
  33848. lineStyle: {
  33849. color: '#333',
  33850. width: 1,
  33851. type: 'solid'
  33852. },
  33853. // The arrow at both ends the the axis.
  33854. symbol: ['none', 'none'],
  33855. symbolSize: [10, 15]
  33856. },
  33857. axisTick: {
  33858. show: true,
  33859. // Whether axisTick is inside the grid or outside the grid.
  33860. inside: false,
  33861. // The length of axisTick.
  33862. length: 5,
  33863. lineStyle: {
  33864. width: 1
  33865. }
  33866. },
  33867. axisLabel: {
  33868. show: true,
  33869. // Whether axisLabel is inside the grid or outside the grid.
  33870. inside: false,
  33871. rotate: 0,
  33872. // true | false | null/undefined (auto)
  33873. showMinLabel: null,
  33874. // true | false | null/undefined (auto)
  33875. showMaxLabel: null,
  33876. margin: 8,
  33877. // formatter: null,
  33878. fontSize: 12
  33879. },
  33880. splitLine: {
  33881. show: true,
  33882. lineStyle: {
  33883. color: ['#ccc'],
  33884. width: 1,
  33885. type: 'solid'
  33886. }
  33887. },
  33888. splitArea: {
  33889. show: false,
  33890. areaStyle: {
  33891. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33892. }
  33893. }
  33894. };
  33895. var axisDefault = {};
  33896. axisDefault.categoryAxis = merge({
  33897. // The gap at both ends of the axis. For categoryAxis, boolean.
  33898. boundaryGap: true,
  33899. // Set false to faster category collection.
  33900. // Only usefull in the case like: category is
  33901. // ['2012-01-01', '2012-01-02', ...], where the input
  33902. // data has been ensured not duplicate and is large data.
  33903. // null means "auto":
  33904. // if axis.data provided, do not deduplication,
  33905. // else do deduplication.
  33906. deduplication: null,
  33907. // splitArea: {
  33908. // show: false
  33909. // },
  33910. splitLine: {
  33911. show: false
  33912. },
  33913. axisTick: {
  33914. // If tick is align with label when boundaryGap is true
  33915. alignWithLabel: false,
  33916. interval: 'auto'
  33917. },
  33918. axisLabel: {
  33919. interval: 'auto'
  33920. }
  33921. }, defaultOption);
  33922. axisDefault.valueAxis = merge({
  33923. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33924. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33925. boundaryGap: [0, 0],
  33926. // TODO
  33927. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33928. // Min value of the axis. can be:
  33929. // + a number
  33930. // + 'dataMin': use the min value in data.
  33931. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33932. // min: null,
  33933. // Max value of the axis. can be:
  33934. // + a number
  33935. // + 'dataMax': use the max value in data.
  33936. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33937. // max: null,
  33938. // Readonly prop, specifies start value of the range when using data zoom.
  33939. // rangeStart: null
  33940. // Readonly prop, specifies end value of the range when using data zoom.
  33941. // rangeEnd: null
  33942. // Optional value can be:
  33943. // + `false`: always include value 0.
  33944. // + `true`: the extent do not consider value 0.
  33945. // scale: false,
  33946. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33947. splitNumber: 5,
  33948. // Interval specifies the span of the ticks is mandatorily.
  33949. // interval: null
  33950. // Specify min interval when auto calculate tick interval.
  33951. // minInterval: null
  33952. // Specify max interval when auto calculate tick interval.
  33953. // maxInterval: null
  33954. minorTick: {
  33955. // Minor tick, not available for cateogry axis.
  33956. show: false,
  33957. // Split number of minor ticks. The value should be in range of (0, 100)
  33958. splitNumber: 5,
  33959. // Lenght of minor tick
  33960. length: 3,
  33961. // Same inside with axisTick
  33962. // Line style
  33963. lineStyle: {
  33964. // Default to be same with axisTick
  33965. }
  33966. },
  33967. minorSplitLine: {
  33968. show: false,
  33969. lineStyle: {
  33970. color: '#eee',
  33971. width: 1
  33972. }
  33973. }
  33974. }, defaultOption);
  33975. axisDefault.timeAxis = defaults({
  33976. scale: true,
  33977. min: 'dataMin',
  33978. max: 'dataMax'
  33979. }, axisDefault.valueAxis);
  33980. axisDefault.logAxis = defaults({
  33981. scale: true,
  33982. logBase: 10
  33983. }, axisDefault.valueAxis);
  33984. /*
  33985. * Licensed to the Apache Software Foundation (ASF) under one
  33986. * or more contributor license agreements. See the NOTICE file
  33987. * distributed with this work for additional information
  33988. * regarding copyright ownership. The ASF licenses this file
  33989. * to you under the Apache License, Version 2.0 (the
  33990. * "License"); you may not use this file except in compliance
  33991. * with the License. You may obtain a copy of the License at
  33992. *
  33993. * http://www.apache.org/licenses/LICENSE-2.0
  33994. *
  33995. * Unless required by applicable law or agreed to in writing,
  33996. * software distributed under the License is distributed on an
  33997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33998. * KIND, either express or implied. See the License for the
  33999. * specific language governing permissions and limitations
  34000. * under the License.
  34001. */
  34002. // FIXME axisType is fixed ?
  34003. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  34004. /**
  34005. * Generate sub axis model class
  34006. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  34007. * @param {module:echarts/model/Component} BaseAxisModelClass
  34008. * @param {Function} axisTypeDefaulter
  34009. * @param {Object} [extraDefaultOption]
  34010. */
  34011. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  34012. each$1(AXIS_TYPES, function (axisType) {
  34013. BaseAxisModelClass.extend({
  34014. /**
  34015. * @readOnly
  34016. */
  34017. type: axisName + 'Axis.' + axisType,
  34018. mergeDefaultAndTheme: function (option, ecModel) {
  34019. var layoutMode = this.layoutMode;
  34020. var inputPositionParams = layoutMode
  34021. ? getLayoutParams(option) : {};
  34022. var themeModel = ecModel.getTheme();
  34023. merge(option, themeModel.get(axisType + 'Axis'));
  34024. merge(option, this.getDefaultOption());
  34025. option.type = axisTypeDefaulter(axisName, option);
  34026. if (layoutMode) {
  34027. mergeLayoutParam(option, inputPositionParams, layoutMode);
  34028. }
  34029. },
  34030. /**
  34031. * @override
  34032. */
  34033. optionUpdated: function () {
  34034. var thisOption = this.option;
  34035. if (thisOption.type === 'category') {
  34036. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  34037. }
  34038. },
  34039. /**
  34040. * Should not be called before all of 'getInitailData' finished.
  34041. * Because categories are collected during initializing data.
  34042. */
  34043. getCategories: function (rawData) {
  34044. var option = this.option;
  34045. // FIXME
  34046. // warning if called before all of 'getInitailData' finished.
  34047. if (option.type === 'category') {
  34048. if (rawData) {
  34049. return option.data;
  34050. }
  34051. return this.__ordinalMeta.categories;
  34052. }
  34053. },
  34054. getOrdinalMeta: function () {
  34055. return this.__ordinalMeta;
  34056. },
  34057. defaultOption: mergeAll(
  34058. [
  34059. {},
  34060. axisDefault[axisType + 'Axis'],
  34061. extraDefaultOption
  34062. ],
  34063. true
  34064. )
  34065. });
  34066. });
  34067. ComponentModel.registerSubTypeDefaulter(
  34068. axisName + 'Axis',
  34069. curry(axisTypeDefaulter, axisName)
  34070. );
  34071. };
  34072. /*
  34073. * Licensed to the Apache Software Foundation (ASF) under one
  34074. * or more contributor license agreements. See the NOTICE file
  34075. * distributed with this work for additional information
  34076. * regarding copyright ownership. The ASF licenses this file
  34077. * to you under the Apache License, Version 2.0 (the
  34078. * "License"); you may not use this file except in compliance
  34079. * with the License. You may obtain a copy of the License at
  34080. *
  34081. * http://www.apache.org/licenses/LICENSE-2.0
  34082. *
  34083. * Unless required by applicable law or agreed to in writing,
  34084. * software distributed under the License is distributed on an
  34085. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34086. * KIND, either express or implied. See the License for the
  34087. * specific language governing permissions and limitations
  34088. * under the License.
  34089. */
  34090. // import * as axisHelper from './axisHelper';
  34091. var axisModelCommonMixin = {
  34092. /**
  34093. * @param {boolean} origin
  34094. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  34095. */
  34096. getMin: function (origin) {
  34097. var option = this.option;
  34098. var min = (!origin && option.rangeStart != null)
  34099. ? option.rangeStart : option.min;
  34100. if (this.axis
  34101. && min != null
  34102. && min !== 'dataMin'
  34103. && typeof min !== 'function'
  34104. && !eqNaN(min)
  34105. ) {
  34106. min = this.axis.scale.parse(min);
  34107. }
  34108. return min;
  34109. },
  34110. /**
  34111. * @param {boolean} origin
  34112. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  34113. */
  34114. getMax: function (origin) {
  34115. var option = this.option;
  34116. var max = (!origin && option.rangeEnd != null)
  34117. ? option.rangeEnd : option.max;
  34118. if (this.axis
  34119. && max != null
  34120. && max !== 'dataMax'
  34121. && typeof max !== 'function'
  34122. && !eqNaN(max)
  34123. ) {
  34124. max = this.axis.scale.parse(max);
  34125. }
  34126. return max;
  34127. },
  34128. /**
  34129. * @return {boolean}
  34130. */
  34131. getNeedCrossZero: function () {
  34132. var option = this.option;
  34133. return (option.rangeStart != null || option.rangeEnd != null)
  34134. ? false : !option.scale;
  34135. },
  34136. /**
  34137. * Should be implemented by each axis model if necessary.
  34138. * @return {module:echarts/model/Component} coordinate system model
  34139. */
  34140. getCoordSysModel: noop,
  34141. /**
  34142. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  34143. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  34144. */
  34145. setRange: function (rangeStart, rangeEnd) {
  34146. this.option.rangeStart = rangeStart;
  34147. this.option.rangeEnd = rangeEnd;
  34148. },
  34149. /**
  34150. * Reset range
  34151. */
  34152. resetRange: function () {
  34153. // rangeStart and rangeEnd is readonly.
  34154. this.option.rangeStart = this.option.rangeEnd = null;
  34155. }
  34156. };
  34157. /*
  34158. * Licensed to the Apache Software Foundation (ASF) under one
  34159. * or more contributor license agreements. See the NOTICE file
  34160. * distributed with this work for additional information
  34161. * regarding copyright ownership. The ASF licenses this file
  34162. * to you under the Apache License, Version 2.0 (the
  34163. * "License"); you may not use this file except in compliance
  34164. * with the License. You may obtain a copy of the License at
  34165. *
  34166. * http://www.apache.org/licenses/LICENSE-2.0
  34167. *
  34168. * Unless required by applicable law or agreed to in writing,
  34169. * software distributed under the License is distributed on an
  34170. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34171. * KIND, either express or implied. See the License for the
  34172. * specific language governing permissions and limitations
  34173. * under the License.
  34174. */
  34175. var AxisModel = ComponentModel.extend({
  34176. type: 'cartesian2dAxis',
  34177. /**
  34178. * @type {module:echarts/coord/cartesian/Axis2D}
  34179. */
  34180. axis: null,
  34181. /**
  34182. * @override
  34183. */
  34184. init: function () {
  34185. AxisModel.superApply(this, 'init', arguments);
  34186. this.resetRange();
  34187. },
  34188. /**
  34189. * @override
  34190. */
  34191. mergeOption: function () {
  34192. AxisModel.superApply(this, 'mergeOption', arguments);
  34193. this.resetRange();
  34194. },
  34195. /**
  34196. * @override
  34197. */
  34198. restoreData: function () {
  34199. AxisModel.superApply(this, 'restoreData', arguments);
  34200. this.resetRange();
  34201. },
  34202. /**
  34203. * @override
  34204. * @return {module:echarts/model/Component}
  34205. */
  34206. getCoordSysModel: function () {
  34207. return this.ecModel.queryComponents({
  34208. mainType: 'grid',
  34209. index: this.option.gridIndex,
  34210. id: this.option.gridId
  34211. })[0];
  34212. }
  34213. });
  34214. function getAxisType(axisDim, option) {
  34215. // Default axis with data is category axis
  34216. return option.type || (option.data ? 'category' : 'value');
  34217. }
  34218. merge(AxisModel.prototype, axisModelCommonMixin);
  34219. var extraOption = {
  34220. // gridIndex: 0,
  34221. // gridId: '',
  34222. // Offset is for multiple axis on the same position
  34223. offset: 0
  34224. };
  34225. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  34226. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  34227. /*
  34228. * Licensed to the Apache Software Foundation (ASF) under one
  34229. * or more contributor license agreements. See the NOTICE file
  34230. * distributed with this work for additional information
  34231. * regarding copyright ownership. The ASF licenses this file
  34232. * to you under the Apache License, Version 2.0 (the
  34233. * "License"); you may not use this file except in compliance
  34234. * with the License. You may obtain a copy of the License at
  34235. *
  34236. * http://www.apache.org/licenses/LICENSE-2.0
  34237. *
  34238. * Unless required by applicable law or agreed to in writing,
  34239. * software distributed under the License is distributed on an
  34240. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34241. * KIND, either express or implied. See the License for the
  34242. * specific language governing permissions and limitations
  34243. * under the License.
  34244. */
  34245. // Grid 是在有直角坐标系的时候必须要存在的
  34246. // 所以这里也要被 Cartesian2D 依赖
  34247. ComponentModel.extend({
  34248. type: 'grid',
  34249. dependencies: ['xAxis', 'yAxis'],
  34250. layoutMode: 'box',
  34251. /**
  34252. * @type {module:echarts/coord/cartesian/Grid}
  34253. */
  34254. coordinateSystem: null,
  34255. defaultOption: {
  34256. show: false,
  34257. zlevel: 0,
  34258. z: 0,
  34259. left: '10%',
  34260. top: 60,
  34261. right: '10%',
  34262. bottom: 60,
  34263. // If grid size contain label
  34264. containLabel: false,
  34265. // width: {totalWidth} - left - right,
  34266. // height: {totalHeight} - top - bottom,
  34267. backgroundColor: 'rgba(0,0,0,0)',
  34268. borderWidth: 1,
  34269. borderColor: '#ccc'
  34270. }
  34271. });
  34272. /*
  34273. * Licensed to the Apache Software Foundation (ASF) under one
  34274. * or more contributor license agreements. See the NOTICE file
  34275. * distributed with this work for additional information
  34276. * regarding copyright ownership. The ASF licenses this file
  34277. * to you under the Apache License, Version 2.0 (the
  34278. * "License"); you may not use this file except in compliance
  34279. * with the License. You may obtain a copy of the License at
  34280. *
  34281. * http://www.apache.org/licenses/LICENSE-2.0
  34282. *
  34283. * Unless required by applicable law or agreed to in writing,
  34284. * software distributed under the License is distributed on an
  34285. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34286. * KIND, either express or implied. See the License for the
  34287. * specific language governing permissions and limitations
  34288. * under the License.
  34289. */
  34290. /**
  34291. * Grid is a region which contains at most 4 cartesian systems
  34292. *
  34293. * TODO Default cartesian
  34294. */
  34295. // Depends on GridModel, AxisModel, which performs preprocess.
  34296. /**
  34297. * Check if the axis is used in the specified grid
  34298. * @inner
  34299. */
  34300. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  34301. return axisModel.getCoordSysModel() === gridModel;
  34302. }
  34303. function Grid(gridModel, ecModel, api) {
  34304. /**
  34305. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  34306. * @private
  34307. */
  34308. this._coordsMap = {};
  34309. /**
  34310. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  34311. * @private
  34312. */
  34313. this._coordsList = [];
  34314. /**
  34315. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  34316. * @private
  34317. */
  34318. this._axesMap = {};
  34319. /**
  34320. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  34321. * @private
  34322. */
  34323. this._axesList = [];
  34324. this._initCartesian(gridModel, ecModel, api);
  34325. this.model = gridModel;
  34326. }
  34327. var gridProto = Grid.prototype;
  34328. gridProto.type = 'grid';
  34329. gridProto.axisPointerEnabled = true;
  34330. gridProto.getRect = function () {
  34331. return this._rect;
  34332. };
  34333. gridProto.update = function (ecModel, api) {
  34334. var axesMap = this._axesMap;
  34335. this._updateScale(ecModel, this.model);
  34336. each$1(axesMap.x, function (xAxis) {
  34337. niceScaleExtent(xAxis.scale, xAxis.model);
  34338. });
  34339. each$1(axesMap.y, function (yAxis) {
  34340. niceScaleExtent(yAxis.scale, yAxis.model);
  34341. });
  34342. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  34343. var onZeroRecords = {};
  34344. each$1(axesMap.x, function (xAxis) {
  34345. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  34346. });
  34347. each$1(axesMap.y, function (yAxis) {
  34348. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  34349. });
  34350. // Resize again if containLabel is enabled
  34351. // FIXME It may cause getting wrong grid size in data processing stage
  34352. this.resize(this.model, api);
  34353. };
  34354. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  34355. axis.getAxesOnZeroOf = function () {
  34356. // TODO: onZero of multiple axes.
  34357. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  34358. };
  34359. // onZero can not be enabled in these two situations:
  34360. // 1. When any other axis is a category axis.
  34361. // 2. When no axis is cross 0 point.
  34362. var otherAxes = axesMap[otherAxisDim];
  34363. var otherAxisOnZeroOf;
  34364. var axisModel = axis.model;
  34365. var onZero = axisModel.get('axisLine.onZero');
  34366. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  34367. if (!onZero) {
  34368. return;
  34369. }
  34370. // If target axis is specified.
  34371. if (onZeroAxisIndex != null) {
  34372. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  34373. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  34374. }
  34375. }
  34376. else {
  34377. // Find the first available other axis.
  34378. for (var idx in otherAxes) {
  34379. if (otherAxes.hasOwnProperty(idx)
  34380. && canOnZeroToAxis(otherAxes[idx])
  34381. // Consider that two Y axes on one value axis,
  34382. // if both onZero, the two Y axes overlap.
  34383. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  34384. ) {
  34385. otherAxisOnZeroOf = otherAxes[idx];
  34386. break;
  34387. }
  34388. }
  34389. }
  34390. if (otherAxisOnZeroOf) {
  34391. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  34392. }
  34393. function getOnZeroRecordKey(axis) {
  34394. return axis.dim + '_' + axis.index;
  34395. }
  34396. }
  34397. function canOnZeroToAxis(axis) {
  34398. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  34399. }
  34400. /**
  34401. * Resize the grid
  34402. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34403. * @param {module:echarts/ExtensionAPI} api
  34404. */
  34405. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  34406. var gridRect = getLayoutRect(
  34407. gridModel.getBoxLayoutParams(), {
  34408. width: api.getWidth(),
  34409. height: api.getHeight()
  34410. });
  34411. this._rect = gridRect;
  34412. var axesList = this._axesList;
  34413. adjustAxes();
  34414. // Minus label size
  34415. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  34416. each$1(axesList, function (axis) {
  34417. if (!axis.model.get('axisLabel.inside')) {
  34418. var labelUnionRect = estimateLabelUnionRect(axis);
  34419. if (labelUnionRect) {
  34420. var dim = axis.isHorizontal() ? 'height' : 'width';
  34421. var margin = axis.model.get('axisLabel.margin');
  34422. gridRect[dim] -= labelUnionRect[dim] + margin;
  34423. if (axis.position === 'top') {
  34424. gridRect.y += labelUnionRect.height + margin;
  34425. }
  34426. else if (axis.position === 'left') {
  34427. gridRect.x += labelUnionRect.width + margin;
  34428. }
  34429. }
  34430. }
  34431. });
  34432. adjustAxes();
  34433. }
  34434. function adjustAxes() {
  34435. each$1(axesList, function (axis) {
  34436. var isHorizontal = axis.isHorizontal();
  34437. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  34438. var idx = axis.inverse ? 1 : 0;
  34439. axis.setExtent(extent[idx], extent[1 - idx]);
  34440. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34441. });
  34442. }
  34443. };
  34444. /**
  34445. * @param {string} axisType
  34446. * @param {number} [axisIndex]
  34447. */
  34448. gridProto.getAxis = function (axisType, axisIndex) {
  34449. var axesMapOnDim = this._axesMap[axisType];
  34450. if (axesMapOnDim != null) {
  34451. if (axisIndex == null) {
  34452. // Find first axis
  34453. for (var name in axesMapOnDim) {
  34454. if (axesMapOnDim.hasOwnProperty(name)) {
  34455. return axesMapOnDim[name];
  34456. }
  34457. }
  34458. }
  34459. return axesMapOnDim[axisIndex];
  34460. }
  34461. };
  34462. /**
  34463. * @return {Array.<module:echarts/coord/Axis>}
  34464. */
  34465. gridProto.getAxes = function () {
  34466. return this._axesList.slice();
  34467. };
  34468. /**
  34469. * Usage:
  34470. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34471. * grid.getCartesian(xAxisIndex);
  34472. * grid.getCartesian(null, yAxisIndex);
  34473. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34474. *
  34475. * @param {number|Object} [xAxisIndex]
  34476. * @param {number} [yAxisIndex]
  34477. */
  34478. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34479. if (xAxisIndex != null && yAxisIndex != null) {
  34480. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34481. return this._coordsMap[key];
  34482. }
  34483. if (isObject$1(xAxisIndex)) {
  34484. yAxisIndex = xAxisIndex.yAxisIndex;
  34485. xAxisIndex = xAxisIndex.xAxisIndex;
  34486. }
  34487. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34488. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34489. if (coordList[i].getAxis('x').index === xAxisIndex
  34490. || coordList[i].getAxis('y').index === yAxisIndex
  34491. ) {
  34492. return coordList[i];
  34493. }
  34494. }
  34495. };
  34496. gridProto.getCartesians = function () {
  34497. return this._coordsList.slice();
  34498. };
  34499. /**
  34500. * @implements
  34501. * see {module:echarts/CoodinateSystem}
  34502. */
  34503. gridProto.convertToPixel = function (ecModel, finder, value) {
  34504. var target = this._findConvertTarget(ecModel, finder);
  34505. return target.cartesian
  34506. ? target.cartesian.dataToPoint(value)
  34507. : target.axis
  34508. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34509. : null;
  34510. };
  34511. /**
  34512. * @implements
  34513. * see {module:echarts/CoodinateSystem}
  34514. */
  34515. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34516. var target = this._findConvertTarget(ecModel, finder);
  34517. return target.cartesian
  34518. ? target.cartesian.pointToData(value)
  34519. : target.axis
  34520. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34521. : null;
  34522. };
  34523. /**
  34524. * @inner
  34525. */
  34526. gridProto._findConvertTarget = function (ecModel, finder) {
  34527. var seriesModel = finder.seriesModel;
  34528. var xAxisModel = finder.xAxisModel
  34529. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34530. var yAxisModel = finder.yAxisModel
  34531. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34532. var gridModel = finder.gridModel;
  34533. var coordsList = this._coordsList;
  34534. var cartesian;
  34535. var axis;
  34536. if (seriesModel) {
  34537. cartesian = seriesModel.coordinateSystem;
  34538. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34539. }
  34540. else if (xAxisModel && yAxisModel) {
  34541. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34542. }
  34543. else if (xAxisModel) {
  34544. axis = this.getAxis('x', xAxisModel.componentIndex);
  34545. }
  34546. else if (yAxisModel) {
  34547. axis = this.getAxis('y', yAxisModel.componentIndex);
  34548. }
  34549. // Lowest priority.
  34550. else if (gridModel) {
  34551. var grid = gridModel.coordinateSystem;
  34552. if (grid === this) {
  34553. cartesian = this._coordsList[0];
  34554. }
  34555. }
  34556. return {cartesian: cartesian, axis: axis};
  34557. };
  34558. /**
  34559. * @implements
  34560. * see {module:echarts/CoodinateSystem}
  34561. */
  34562. gridProto.containPoint = function (point) {
  34563. var coord = this._coordsList[0];
  34564. if (coord) {
  34565. return coord.containPoint(point);
  34566. }
  34567. };
  34568. /**
  34569. * Initialize cartesian coordinate systems
  34570. * @private
  34571. */
  34572. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34573. var axisPositionUsed = {
  34574. left: false,
  34575. right: false,
  34576. top: false,
  34577. bottom: false
  34578. };
  34579. var axesMap = {
  34580. x: {},
  34581. y: {}
  34582. };
  34583. var axesCount = {
  34584. x: 0,
  34585. y: 0
  34586. };
  34587. /// Create axis
  34588. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34589. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34590. if (!axesCount.x || !axesCount.y) {
  34591. // Roll back when there no either x or y axis
  34592. this._axesMap = {};
  34593. this._axesList = [];
  34594. return;
  34595. }
  34596. this._axesMap = axesMap;
  34597. /// Create cartesian2d
  34598. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34599. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34600. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34601. var cartesian = new Cartesian2D(key);
  34602. cartesian.grid = this;
  34603. cartesian.model = gridModel;
  34604. this._coordsMap[key] = cartesian;
  34605. this._coordsList.push(cartesian);
  34606. cartesian.addAxis(xAxis);
  34607. cartesian.addAxis(yAxis);
  34608. }, this);
  34609. }, this);
  34610. function createAxisCreator(axisType) {
  34611. return function (axisModel, idx) {
  34612. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34613. return;
  34614. }
  34615. var axisPosition = axisModel.get('position');
  34616. if (axisType === 'x') {
  34617. // Fix position
  34618. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34619. // Default bottom of X
  34620. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  34621. }
  34622. }
  34623. else {
  34624. // Fix position
  34625. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34626. // Default left of Y
  34627. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  34628. }
  34629. }
  34630. axisPositionUsed[axisPosition] = true;
  34631. var axis = new Axis2D(
  34632. axisType, createScaleByModel(axisModel),
  34633. [0, 0],
  34634. axisModel.get('type'),
  34635. axisPosition
  34636. );
  34637. var isCategory = axis.type === 'category';
  34638. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34639. axis.inverse = axisModel.get('inverse');
  34640. // Inject axis into axisModel
  34641. axisModel.axis = axis;
  34642. // Inject axisModel into axis
  34643. axis.model = axisModel;
  34644. // Inject grid info axis
  34645. axis.grid = this;
  34646. // Index of axis, can be used as key
  34647. axis.index = idx;
  34648. this._axesList.push(axis);
  34649. axesMap[axisType][idx] = axis;
  34650. axesCount[axisType]++;
  34651. };
  34652. }
  34653. };
  34654. /**
  34655. * Update cartesian properties from series
  34656. * @param {module:echarts/model/Option} option
  34657. * @private
  34658. */
  34659. gridProto._updateScale = function (ecModel, gridModel) {
  34660. // Reset scale
  34661. each$1(this._axesList, function (axis) {
  34662. axis.scale.setExtent(Infinity, -Infinity);
  34663. });
  34664. ecModel.eachSeries(function (seriesModel) {
  34665. if (isCartesian2D(seriesModel)) {
  34666. var axesModels = findAxesModels(seriesModel, ecModel);
  34667. var xAxisModel = axesModels[0];
  34668. var yAxisModel = axesModels[1];
  34669. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34670. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34671. ) {
  34672. return;
  34673. }
  34674. var cartesian = this.getCartesian(
  34675. xAxisModel.componentIndex, yAxisModel.componentIndex
  34676. );
  34677. var data = seriesModel.getData();
  34678. var xAxis = cartesian.getAxis('x');
  34679. var yAxis = cartesian.getAxis('y');
  34680. if (data.type === 'list') {
  34681. unionExtent(data, xAxis, seriesModel);
  34682. unionExtent(data, yAxis, seriesModel);
  34683. }
  34684. }
  34685. }, this);
  34686. function unionExtent(data, axis, seriesModel) {
  34687. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34688. axis.scale.unionExtentFromData(
  34689. // For example, the extent of the orginal dimension
  34690. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34691. // is [7, 9], the final extent should not include [0.1, 0.5].
  34692. data, getStackedDimension(data, dim)
  34693. );
  34694. });
  34695. }
  34696. };
  34697. /**
  34698. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34699. * @return {Object} {baseAxes: [], otherAxes: []}
  34700. */
  34701. gridProto.getTooltipAxes = function (dim) {
  34702. var baseAxes = [];
  34703. var otherAxes = [];
  34704. each$1(this.getCartesians(), function (cartesian) {
  34705. var baseAxis = (dim != null && dim !== 'auto')
  34706. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34707. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34708. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34709. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34710. });
  34711. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34712. };
  34713. /**
  34714. * @inner
  34715. */
  34716. function updateAxisTransform(axis, coordBase) {
  34717. var axisExtent = axis.getExtent();
  34718. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34719. // Fast transform
  34720. axis.toGlobalCoord = axis.dim === 'x'
  34721. ? function (coord) {
  34722. return coord + coordBase;
  34723. }
  34724. : function (coord) {
  34725. return axisExtentSum - coord + coordBase;
  34726. };
  34727. axis.toLocalCoord = axis.dim === 'x'
  34728. ? function (coord) {
  34729. return coord - coordBase;
  34730. }
  34731. : function (coord) {
  34732. return axisExtentSum - coord + coordBase;
  34733. };
  34734. }
  34735. var axesTypes = ['xAxis', 'yAxis'];
  34736. /**
  34737. * @inner
  34738. */
  34739. function findAxesModels(seriesModel, ecModel) {
  34740. return map(axesTypes, function (axisType) {
  34741. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34742. if (__DEV__) {
  34743. if (!axisModel) {
  34744. throw new Error(axisType + ' "' + retrieve(
  34745. seriesModel.get(axisType + 'Index'),
  34746. seriesModel.get(axisType + 'Id'),
  34747. 0
  34748. ) + '" not found');
  34749. }
  34750. }
  34751. return axisModel;
  34752. });
  34753. }
  34754. /**
  34755. * @inner
  34756. */
  34757. function isCartesian2D(seriesModel) {
  34758. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34759. }
  34760. Grid.create = function (ecModel, api) {
  34761. var grids = [];
  34762. ecModel.eachComponent('grid', function (gridModel, idx) {
  34763. var grid = new Grid(gridModel, ecModel, api);
  34764. grid.name = 'grid_' + idx;
  34765. // dataSampling requires axis extent, so resize
  34766. // should be performed in create stage.
  34767. grid.resize(gridModel, api, true);
  34768. gridModel.coordinateSystem = grid;
  34769. grids.push(grid);
  34770. });
  34771. // Inject the coordinateSystems into seriesModel
  34772. ecModel.eachSeries(function (seriesModel) {
  34773. if (!isCartesian2D(seriesModel)) {
  34774. return;
  34775. }
  34776. var axesModels = findAxesModels(seriesModel, ecModel);
  34777. var xAxisModel = axesModels[0];
  34778. var yAxisModel = axesModels[1];
  34779. var gridModel = xAxisModel.getCoordSysModel();
  34780. if (__DEV__) {
  34781. if (!gridModel) {
  34782. throw new Error(
  34783. 'Grid "' + retrieve(
  34784. xAxisModel.get('gridIndex'),
  34785. xAxisModel.get('gridId'),
  34786. 0
  34787. ) + '" not found'
  34788. );
  34789. }
  34790. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34791. throw new Error('xAxis and yAxis must use the same grid');
  34792. }
  34793. }
  34794. var grid = gridModel.coordinateSystem;
  34795. seriesModel.coordinateSystem = grid.getCartesian(
  34796. xAxisModel.componentIndex, yAxisModel.componentIndex
  34797. );
  34798. });
  34799. return grids;
  34800. };
  34801. // For deciding which dimensions to use when creating list data
  34802. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34803. CoordinateSystemManager.register('cartesian2d', Grid);
  34804. /*
  34805. * Licensed to the Apache Software Foundation (ASF) under one
  34806. * or more contributor license agreements. See the NOTICE file
  34807. * distributed with this work for additional information
  34808. * regarding copyright ownership. The ASF licenses this file
  34809. * to you under the Apache License, Version 2.0 (the
  34810. * "License"); you may not use this file except in compliance
  34811. * with the License. You may obtain a copy of the License at
  34812. *
  34813. * http://www.apache.org/licenses/LICENSE-2.0
  34814. *
  34815. * Unless required by applicable law or agreed to in writing,
  34816. * software distributed under the License is distributed on an
  34817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34818. * KIND, either express or implied. See the License for the
  34819. * specific language governing permissions and limitations
  34820. * under the License.
  34821. */
  34822. var PI$2 = Math.PI;
  34823. /**
  34824. * A final axis is translated and rotated from a "standard axis".
  34825. * So opt.position and opt.rotation is required.
  34826. *
  34827. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34828. * for example: (0, 0) ------------> (0, 50)
  34829. *
  34830. * nameDirection or tickDirection or labelDirection is 1 means tick
  34831. * or label is below the standard axis, whereas is -1 means above
  34832. * the standard axis. labelOffset means offset between label and axis,
  34833. * which is useful when 'onZero', where axisLabel is in the grid and
  34834. * label in outside grid.
  34835. *
  34836. * Tips: like always,
  34837. * positive rotation represents anticlockwise, and negative rotation
  34838. * represents clockwise.
  34839. * The direction of position coordinate is the same as the direction
  34840. * of screen coordinate.
  34841. *
  34842. * Do not need to consider axis 'inverse', which is auto processed by
  34843. * axis extent.
  34844. *
  34845. * @param {module:zrender/container/Group} group
  34846. * @param {Object} axisModel
  34847. * @param {Object} opt Standard axis parameters.
  34848. * @param {Array.<number>} opt.position [x, y]
  34849. * @param {number} opt.rotation by radian
  34850. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34851. * @param {number} [opt.tickDirection=1] 1 or -1
  34852. * @param {number} [opt.labelDirection=1] 1 or -1
  34853. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34854. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34855. * @param {string} [opt.axisName] default get from axisModel.
  34856. * @param {number} [opt.axisNameAvailableWidth]
  34857. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34858. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34859. * @param {number} [opt.nameTruncateMaxWidth]
  34860. */
  34861. var AxisBuilder = function (axisModel, opt) {
  34862. /**
  34863. * @readOnly
  34864. */
  34865. this.opt = opt;
  34866. /**
  34867. * @readOnly
  34868. */
  34869. this.axisModel = axisModel;
  34870. // Default value
  34871. defaults(
  34872. opt,
  34873. {
  34874. labelOffset: 0,
  34875. nameDirection: 1,
  34876. tickDirection: 1,
  34877. labelDirection: 1,
  34878. silent: true
  34879. }
  34880. );
  34881. /**
  34882. * @readOnly
  34883. */
  34884. this.group = new Group();
  34885. // FIXME Not use a seperate text group?
  34886. var dumbGroup = new Group({
  34887. position: opt.position.slice(),
  34888. rotation: opt.rotation
  34889. });
  34890. // this.group.add(dumbGroup);
  34891. // this._dumbGroup = dumbGroup;
  34892. dumbGroup.updateTransform();
  34893. this._transform = dumbGroup.transform;
  34894. this._dumbGroup = dumbGroup;
  34895. };
  34896. AxisBuilder.prototype = {
  34897. constructor: AxisBuilder,
  34898. hasBuilder: function (name) {
  34899. return !!builders[name];
  34900. },
  34901. add: function (name) {
  34902. builders[name].call(this);
  34903. },
  34904. getGroup: function () {
  34905. return this.group;
  34906. }
  34907. };
  34908. var builders = {
  34909. /**
  34910. * @private
  34911. */
  34912. axisLine: function () {
  34913. var opt = this.opt;
  34914. var axisModel = this.axisModel;
  34915. if (!axisModel.get('axisLine.show')) {
  34916. return;
  34917. }
  34918. var extent = this.axisModel.axis.getExtent();
  34919. var matrix = this._transform;
  34920. var pt1 = [extent[0], 0];
  34921. var pt2 = [extent[1], 0];
  34922. if (matrix) {
  34923. applyTransform(pt1, pt1, matrix);
  34924. applyTransform(pt2, pt2, matrix);
  34925. }
  34926. var lineStyle = extend(
  34927. {
  34928. lineCap: 'round'
  34929. },
  34930. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34931. );
  34932. this.group.add(new Line({
  34933. // Id for animation
  34934. anid: 'line',
  34935. subPixelOptimize: true,
  34936. shape: {
  34937. x1: pt1[0],
  34938. y1: pt1[1],
  34939. x2: pt2[0],
  34940. y2: pt2[1]
  34941. },
  34942. style: lineStyle,
  34943. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34944. silent: true,
  34945. z2: 1
  34946. }));
  34947. var arrows = axisModel.get('axisLine.symbol');
  34948. var arrowSize = axisModel.get('axisLine.symbolSize');
  34949. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34950. if (typeof arrowOffset === 'number') {
  34951. arrowOffset = [arrowOffset, arrowOffset];
  34952. }
  34953. if (arrows != null) {
  34954. if (typeof arrows === 'string') {
  34955. // Use the same arrow for start and end point
  34956. arrows = [arrows, arrows];
  34957. }
  34958. if (typeof arrowSize === 'string'
  34959. || typeof arrowSize === 'number'
  34960. ) {
  34961. // Use the same size for width and height
  34962. arrowSize = [arrowSize, arrowSize];
  34963. }
  34964. var symbolWidth = arrowSize[0];
  34965. var symbolHeight = arrowSize[1];
  34966. each$1([{
  34967. rotate: opt.rotation + Math.PI / 2,
  34968. offset: arrowOffset[0],
  34969. r: 0
  34970. }, {
  34971. rotate: opt.rotation - Math.PI / 2,
  34972. offset: arrowOffset[1],
  34973. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34974. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34975. }], function (point, index) {
  34976. if (arrows[index] !== 'none' && arrows[index] != null) {
  34977. var symbol = createSymbol(
  34978. arrows[index],
  34979. -symbolWidth / 2,
  34980. -symbolHeight / 2,
  34981. symbolWidth,
  34982. symbolHeight,
  34983. lineStyle.stroke,
  34984. true
  34985. );
  34986. // Calculate arrow position with offset
  34987. var r = point.r + point.offset;
  34988. var pos = [
  34989. pt1[0] + r * Math.cos(opt.rotation),
  34990. pt1[1] - r * Math.sin(opt.rotation)
  34991. ];
  34992. symbol.attr({
  34993. rotation: point.rotate,
  34994. position: pos,
  34995. silent: true,
  34996. z2: 11
  34997. });
  34998. this.group.add(symbol);
  34999. }
  35000. }, this);
  35001. }
  35002. },
  35003. /**
  35004. * @private
  35005. */
  35006. axisTickLabel: function () {
  35007. var axisModel = this.axisModel;
  35008. var opt = this.opt;
  35009. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  35010. var labelEls = buildAxisLabel(this, axisModel, opt);
  35011. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  35012. buildAxisMinorTicks(this, axisModel, opt);
  35013. },
  35014. /**
  35015. * @private
  35016. */
  35017. axisName: function () {
  35018. var opt = this.opt;
  35019. var axisModel = this.axisModel;
  35020. var name = retrieve(opt.axisName, axisModel.get('name'));
  35021. if (!name) {
  35022. return;
  35023. }
  35024. var nameLocation = axisModel.get('nameLocation');
  35025. var nameDirection = opt.nameDirection;
  35026. var textStyleModel = axisModel.getModel('nameTextStyle');
  35027. var gap = axisModel.get('nameGap') || 0;
  35028. var extent = this.axisModel.axis.getExtent();
  35029. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  35030. var pos = [
  35031. nameLocation === 'start'
  35032. ? extent[0] - gapSignal * gap
  35033. : nameLocation === 'end'
  35034. ? extent[1] + gapSignal * gap
  35035. : (extent[0] + extent[1]) / 2, // 'middle'
  35036. // Reuse labelOffset.
  35037. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  35038. ];
  35039. var labelLayout;
  35040. var nameRotation = axisModel.get('nameRotate');
  35041. if (nameRotation != null) {
  35042. nameRotation = nameRotation * PI$2 / 180; // To radian.
  35043. }
  35044. var axisNameAvailableWidth;
  35045. if (isNameLocationCenter(nameLocation)) {
  35046. labelLayout = innerTextLayout(
  35047. opt.rotation,
  35048. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  35049. nameDirection
  35050. );
  35051. }
  35052. else {
  35053. labelLayout = endTextLayout(
  35054. opt, nameLocation, nameRotation || 0, extent
  35055. );
  35056. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  35057. if (axisNameAvailableWidth != null) {
  35058. axisNameAvailableWidth = Math.abs(
  35059. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  35060. );
  35061. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  35062. }
  35063. }
  35064. var textFont = textStyleModel.getFont();
  35065. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  35066. var ellipsis = truncateOpt.ellipsis;
  35067. var maxWidth = retrieve(
  35068. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  35069. );
  35070. // FIXME
  35071. // truncate rich text? (consider performance)
  35072. var truncatedText = (ellipsis != null && maxWidth != null)
  35073. ? truncateText$1(
  35074. name, maxWidth, textFont, ellipsis,
  35075. {minChar: 2, placeholder: truncateOpt.placeholder}
  35076. )
  35077. : name;
  35078. var tooltipOpt = axisModel.get('tooltip', true);
  35079. var mainType = axisModel.mainType;
  35080. var formatterParams = {
  35081. componentType: mainType,
  35082. name: name,
  35083. $vars: ['name']
  35084. };
  35085. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  35086. var textEl = new Text({
  35087. // Id for animation
  35088. anid: 'name',
  35089. __fullText: name,
  35090. __truncatedText: truncatedText,
  35091. position: pos,
  35092. rotation: labelLayout.rotation,
  35093. silent: isLabelSilent(axisModel),
  35094. z2: 1,
  35095. tooltip: (tooltipOpt && tooltipOpt.show)
  35096. ? extend({
  35097. content: name,
  35098. formatter: function () {
  35099. return name;
  35100. },
  35101. formatterParams: formatterParams
  35102. }, tooltipOpt)
  35103. : null
  35104. });
  35105. setTextStyle(textEl.style, textStyleModel, {
  35106. text: truncatedText,
  35107. textFont: textFont,
  35108. textFill: textStyleModel.getTextColor()
  35109. || axisModel.get('axisLine.lineStyle.color'),
  35110. textAlign: textStyleModel.get('align')
  35111. || labelLayout.textAlign,
  35112. textVerticalAlign: textStyleModel.get('verticalAlign')
  35113. || labelLayout.textVerticalAlign
  35114. });
  35115. if (axisModel.get('triggerEvent')) {
  35116. textEl.eventData = makeAxisEventDataBase(axisModel);
  35117. textEl.eventData.targetType = 'axisName';
  35118. textEl.eventData.name = name;
  35119. }
  35120. // FIXME
  35121. this._dumbGroup.add(textEl);
  35122. textEl.updateTransform();
  35123. this.group.add(textEl);
  35124. textEl.decomposeTransform();
  35125. }
  35126. };
  35127. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  35128. var eventData = {
  35129. componentType: axisModel.mainType,
  35130. componentIndex: axisModel.componentIndex
  35131. };
  35132. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  35133. return eventData;
  35134. };
  35135. /**
  35136. * @public
  35137. * @static
  35138. * @param {Object} opt
  35139. * @param {number} axisRotation in radian
  35140. * @param {number} textRotation in radian
  35141. * @param {number} direction
  35142. * @return {Object} {
  35143. * rotation, // according to axis
  35144. * textAlign,
  35145. * textVerticalAlign
  35146. * }
  35147. */
  35148. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  35149. var rotationDiff = remRadian(textRotation - axisRotation);
  35150. var textAlign;
  35151. var textVerticalAlign;
  35152. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  35153. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  35154. textAlign = 'center';
  35155. }
  35156. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  35157. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  35158. textAlign = 'center';
  35159. }
  35160. else {
  35161. textVerticalAlign = 'middle';
  35162. if (rotationDiff > 0 && rotationDiff < PI$2) {
  35163. textAlign = direction > 0 ? 'right' : 'left';
  35164. }
  35165. else {
  35166. textAlign = direction > 0 ? 'left' : 'right';
  35167. }
  35168. }
  35169. return {
  35170. rotation: rotationDiff,
  35171. textAlign: textAlign,
  35172. textVerticalAlign: textVerticalAlign
  35173. };
  35174. };
  35175. function endTextLayout(opt, textPosition, textRotate, extent) {
  35176. var rotationDiff = remRadian(textRotate - opt.rotation);
  35177. var textAlign;
  35178. var textVerticalAlign;
  35179. var inverse = extent[0] > extent[1];
  35180. var onLeft = (textPosition === 'start' && !inverse)
  35181. || (textPosition !== 'start' && inverse);
  35182. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  35183. textVerticalAlign = onLeft ? 'bottom' : 'top';
  35184. textAlign = 'center';
  35185. }
  35186. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  35187. textVerticalAlign = onLeft ? 'top' : 'bottom';
  35188. textAlign = 'center';
  35189. }
  35190. else {
  35191. textVerticalAlign = 'middle';
  35192. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  35193. textAlign = onLeft ? 'left' : 'right';
  35194. }
  35195. else {
  35196. textAlign = onLeft ? 'right' : 'left';
  35197. }
  35198. }
  35199. return {
  35200. rotation: rotationDiff,
  35201. textAlign: textAlign,
  35202. textVerticalAlign: textVerticalAlign
  35203. };
  35204. }
  35205. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  35206. var tooltipOpt = axisModel.get('tooltip');
  35207. return axisModel.get('silent')
  35208. // Consider mouse cursor, add these restrictions.
  35209. || !(
  35210. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  35211. );
  35212. };
  35213. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  35214. if (shouldShowAllLabels(axisModel.axis)) {
  35215. return;
  35216. }
  35217. // If min or max are user set, we need to check
  35218. // If the tick on min(max) are overlap on their neighbour tick
  35219. // If they are overlapped, we need to hide the min(max) tick label
  35220. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  35221. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  35222. // FIXME
  35223. // Have not consider onBand yet, where tick els is more than label els.
  35224. labelEls = labelEls || [];
  35225. tickEls = tickEls || [];
  35226. var firstLabel = labelEls[0];
  35227. var nextLabel = labelEls[1];
  35228. var lastLabel = labelEls[labelEls.length - 1];
  35229. var prevLabel = labelEls[labelEls.length - 2];
  35230. var firstTick = tickEls[0];
  35231. var nextTick = tickEls[1];
  35232. var lastTick = tickEls[tickEls.length - 1];
  35233. var prevTick = tickEls[tickEls.length - 2];
  35234. if (showMinLabel === false) {
  35235. ignoreEl(firstLabel);
  35236. ignoreEl(firstTick);
  35237. }
  35238. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  35239. if (showMinLabel) {
  35240. ignoreEl(nextLabel);
  35241. ignoreEl(nextTick);
  35242. }
  35243. else {
  35244. ignoreEl(firstLabel);
  35245. ignoreEl(firstTick);
  35246. }
  35247. }
  35248. if (showMaxLabel === false) {
  35249. ignoreEl(lastLabel);
  35250. ignoreEl(lastTick);
  35251. }
  35252. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  35253. if (showMaxLabel) {
  35254. ignoreEl(prevLabel);
  35255. ignoreEl(prevTick);
  35256. }
  35257. else {
  35258. ignoreEl(lastLabel);
  35259. ignoreEl(lastTick);
  35260. }
  35261. }
  35262. }
  35263. function ignoreEl(el) {
  35264. el && (el.ignore = true);
  35265. }
  35266. function isTwoLabelOverlapped(current, next, labelLayout) {
  35267. // current and next has the same rotation.
  35268. var firstRect = current && current.getBoundingRect().clone();
  35269. var nextRect = next && next.getBoundingRect().clone();
  35270. if (!firstRect || !nextRect) {
  35271. return;
  35272. }
  35273. // When checking intersect of two rotated labels, we use mRotationBack
  35274. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  35275. var mRotationBack = identity([]);
  35276. rotate(mRotationBack, mRotationBack, -current.rotation);
  35277. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  35278. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  35279. return firstRect.intersect(nextRect);
  35280. }
  35281. function isNameLocationCenter(nameLocation) {
  35282. return nameLocation === 'middle' || nameLocation === 'center';
  35283. }
  35284. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  35285. var tickEls = [];
  35286. var pt1 = [];
  35287. var pt2 = [];
  35288. for (var i = 0; i < ticksCoords.length; i++) {
  35289. var tickCoord = ticksCoords[i].coord;
  35290. pt1[0] = tickCoord;
  35291. pt1[1] = 0;
  35292. pt2[0] = tickCoord;
  35293. pt2[1] = tickEndCoord;
  35294. if (tickTransform) {
  35295. applyTransform(pt1, pt1, tickTransform);
  35296. applyTransform(pt2, pt2, tickTransform);
  35297. }
  35298. // Tick line, Not use group transform to have better line draw
  35299. var tickEl = new Line({
  35300. // Id for animation
  35301. anid: aniid + '_' + ticksCoords[i].tickValue,
  35302. subPixelOptimize: true,
  35303. shape: {
  35304. x1: pt1[0],
  35305. y1: pt1[1],
  35306. x2: pt2[0],
  35307. y2: pt2[1]
  35308. },
  35309. style: tickLineStyle,
  35310. z2: 2,
  35311. silent: true
  35312. });
  35313. tickEls.push(tickEl);
  35314. }
  35315. return tickEls;
  35316. }
  35317. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  35318. var axis = axisModel.axis;
  35319. var tickModel = axisModel.getModel('axisTick');
  35320. if (!tickModel.get('show') || axis.scale.isBlank()) {
  35321. return;
  35322. }
  35323. var lineStyleModel = tickModel.getModel('lineStyle');
  35324. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  35325. var ticksCoords = axis.getTicksCoords();
  35326. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  35327. lineStyleModel.getLineStyle(),
  35328. {
  35329. stroke: axisModel.get('axisLine.lineStyle.color')
  35330. }
  35331. ), 'ticks');
  35332. for (var i = 0; i < ticksEls.length; i++) {
  35333. axisBuilder.group.add(ticksEls[i]);
  35334. }
  35335. return ticksEls;
  35336. }
  35337. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  35338. var axis = axisModel.axis;
  35339. var minorTickModel = axisModel.getModel('minorTick');
  35340. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  35341. return;
  35342. }
  35343. var minorTicksCoords = axis.getMinorTicksCoords();
  35344. if (!minorTicksCoords.length) {
  35345. return;
  35346. }
  35347. var lineStyleModel = minorTickModel.getModel('lineStyle');
  35348. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  35349. var minorTickLineStyle = defaults(
  35350. lineStyleModel.getLineStyle(),
  35351. defaults(
  35352. axisModel.getModel('axisTick').getLineStyle(),
  35353. {
  35354. stroke: axisModel.get('axisLine.lineStyle.color')
  35355. }
  35356. )
  35357. );
  35358. for (var i = 0; i < minorTicksCoords.length; i++) {
  35359. var minorTicksEls = createTicks(
  35360. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  35361. );
  35362. for (var k = 0; k < minorTicksEls.length; k++) {
  35363. axisBuilder.group.add(minorTicksEls[k]);
  35364. }
  35365. }
  35366. }
  35367. function buildAxisLabel(axisBuilder, axisModel, opt) {
  35368. var axis = axisModel.axis;
  35369. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  35370. if (!show || axis.scale.isBlank()) {
  35371. return;
  35372. }
  35373. var labelModel = axisModel.getModel('axisLabel');
  35374. var labelMargin = labelModel.get('margin');
  35375. var labels = axis.getViewLabels();
  35376. // Special label rotate.
  35377. var labelRotation = (
  35378. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  35379. ) * PI$2 / 180;
  35380. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  35381. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  35382. var labelEls = [];
  35383. var silent = isLabelSilent(axisModel);
  35384. var triggerEvent = axisModel.get('triggerEvent');
  35385. each$1(labels, function (labelItem, index) {
  35386. var tickValue = labelItem.tickValue;
  35387. var formattedLabel = labelItem.formattedLabel;
  35388. var rawLabel = labelItem.rawLabel;
  35389. var itemLabelModel = labelModel;
  35390. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  35391. itemLabelModel = new Model(
  35392. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  35393. );
  35394. }
  35395. var textColor = itemLabelModel.getTextColor()
  35396. || axisModel.get('axisLine.lineStyle.color');
  35397. var tickCoord = axis.dataToCoord(tickValue);
  35398. var pos = [
  35399. tickCoord,
  35400. opt.labelOffset + opt.labelDirection * labelMargin
  35401. ];
  35402. var textEl = new Text({
  35403. // Id for animation
  35404. anid: 'label_' + tickValue,
  35405. position: pos,
  35406. rotation: labelLayout.rotation,
  35407. silent: silent,
  35408. z2: 10
  35409. });
  35410. setTextStyle(textEl.style, itemLabelModel, {
  35411. text: formattedLabel,
  35412. textAlign: itemLabelModel.getShallow('align', true)
  35413. || labelLayout.textAlign,
  35414. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  35415. || itemLabelModel.getShallow('baseline', true)
  35416. || labelLayout.textVerticalAlign,
  35417. textFill: typeof textColor === 'function'
  35418. ? textColor(
  35419. // (1) In category axis with data zoom, tick is not the original
  35420. // index of axis.data. So tick should not be exposed to user
  35421. // in category axis.
  35422. // (2) Compatible with previous version, which always use formatted label as
  35423. // input. But in interval scale the formatted label is like '223,445', which
  35424. // maked user repalce ','. So we modify it to return original val but remain
  35425. // it as 'string' to avoid error in replacing.
  35426. axis.type === 'category'
  35427. ? rawLabel
  35428. : axis.type === 'value'
  35429. ? tickValue + ''
  35430. : tickValue,
  35431. index
  35432. )
  35433. : textColor
  35434. });
  35435. // Pack data for mouse event
  35436. if (triggerEvent) {
  35437. textEl.eventData = makeAxisEventDataBase(axisModel);
  35438. textEl.eventData.targetType = 'axisLabel';
  35439. textEl.eventData.value = rawLabel;
  35440. }
  35441. // FIXME
  35442. axisBuilder._dumbGroup.add(textEl);
  35443. textEl.updateTransform();
  35444. labelEls.push(textEl);
  35445. axisBuilder.group.add(textEl);
  35446. textEl.decomposeTransform();
  35447. });
  35448. return labelEls;
  35449. }
  35450. /*
  35451. * Licensed to the Apache Software Foundation (ASF) under one
  35452. * or more contributor license agreements. See the NOTICE file
  35453. * distributed with this work for additional information
  35454. * regarding copyright ownership. The ASF licenses this file
  35455. * to you under the Apache License, Version 2.0 (the
  35456. * "License"); you may not use this file except in compliance
  35457. * with the License. You may obtain a copy of the License at
  35458. *
  35459. * http://www.apache.org/licenses/LICENSE-2.0
  35460. *
  35461. * Unless required by applicable law or agreed to in writing,
  35462. * software distributed under the License is distributed on an
  35463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35464. * KIND, either express or implied. See the License for the
  35465. * specific language governing permissions and limitations
  35466. * under the License.
  35467. */
  35468. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  35469. // allAxesInfo should be updated when setOption performed.
  35470. function fixValue(axisModel) {
  35471. var axisInfo = getAxisInfo(axisModel);
  35472. if (!axisInfo) {
  35473. return;
  35474. }
  35475. var axisPointerModel = axisInfo.axisPointerModel;
  35476. var scale = axisInfo.axis.scale;
  35477. var option = axisPointerModel.option;
  35478. var status = axisPointerModel.get('status');
  35479. var value = axisPointerModel.get('value');
  35480. // Parse init value for category and time axis.
  35481. if (value != null) {
  35482. value = scale.parse(value);
  35483. }
  35484. var useHandle = isHandleTrigger(axisPointerModel);
  35485. // If `handle` used, `axisPointer` will always be displayed, so value
  35486. // and status should be initialized.
  35487. if (status == null) {
  35488. option.status = useHandle ? 'show' : 'hide';
  35489. }
  35490. var extent = scale.getExtent().slice();
  35491. extent[0] > extent[1] && extent.reverse();
  35492. if (// Pick a value on axis when initializing.
  35493. value == null
  35494. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35495. // where we should re-pick a value to keep `handle` displaying normally.
  35496. || value > extent[1]
  35497. ) {
  35498. // Make handle displayed on the end of the axis when init, which looks better.
  35499. value = extent[1];
  35500. }
  35501. if (value < extent[0]) {
  35502. value = extent[0];
  35503. }
  35504. option.value = value;
  35505. if (useHandle) {
  35506. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35507. }
  35508. }
  35509. function getAxisInfo(axisModel) {
  35510. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35511. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35512. }
  35513. function getAxisPointerModel(axisModel) {
  35514. var axisInfo = getAxisInfo(axisModel);
  35515. return axisInfo && axisInfo.axisPointerModel;
  35516. }
  35517. function isHandleTrigger(axisPointerModel) {
  35518. return !!axisPointerModel.get('handle.show');
  35519. }
  35520. /**
  35521. * @param {module:echarts/model/Model} model
  35522. * @return {string} unique key
  35523. */
  35524. function makeKey(model) {
  35525. return model.type + '||' + model.id;
  35526. }
  35527. /*
  35528. * Licensed to the Apache Software Foundation (ASF) under one
  35529. * or more contributor license agreements. See the NOTICE file
  35530. * distributed with this work for additional information
  35531. * regarding copyright ownership. The ASF licenses this file
  35532. * to you under the Apache License, Version 2.0 (the
  35533. * "License"); you may not use this file except in compliance
  35534. * with the License. You may obtain a copy of the License at
  35535. *
  35536. * http://www.apache.org/licenses/LICENSE-2.0
  35537. *
  35538. * Unless required by applicable law or agreed to in writing,
  35539. * software distributed under the License is distributed on an
  35540. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35541. * KIND, either express or implied. See the License for the
  35542. * specific language governing permissions and limitations
  35543. * under the License.
  35544. */
  35545. /**
  35546. * Base class of AxisView.
  35547. */
  35548. var AxisView = extendComponentView({
  35549. type: 'axis',
  35550. /**
  35551. * @private
  35552. */
  35553. _axisPointer: null,
  35554. /**
  35555. * @protected
  35556. * @type {string}
  35557. */
  35558. axisPointerClass: null,
  35559. /**
  35560. * @override
  35561. */
  35562. render: function (axisModel, ecModel, api, payload) {
  35563. // FIXME
  35564. // This process should proformed after coordinate systems updated
  35565. // (axis scale updated), and should be performed each time update.
  35566. // So put it here temporarily, although it is not appropriate to
  35567. // put a model-writing procedure in `view`.
  35568. this.axisPointerClass && fixValue(axisModel);
  35569. AxisView.superApply(this, 'render', arguments);
  35570. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35571. },
  35572. /**
  35573. * Action handler.
  35574. * @public
  35575. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35576. * @param {module:echarts/model/Global} ecModel
  35577. * @param {module:echarts/ExtensionAPI} api
  35578. * @param {Object} payload
  35579. */
  35580. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35581. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35582. },
  35583. /**
  35584. * @override
  35585. */
  35586. remove: function (ecModel, api) {
  35587. var axisPointer = this._axisPointer;
  35588. axisPointer && axisPointer.remove(api);
  35589. AxisView.superApply(this, 'remove', arguments);
  35590. },
  35591. /**
  35592. * @override
  35593. */
  35594. dispose: function (ecModel, api) {
  35595. disposeAxisPointer(this, api);
  35596. AxisView.superApply(this, 'dispose', arguments);
  35597. }
  35598. });
  35599. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35600. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35601. if (!Clazz) {
  35602. return;
  35603. }
  35604. var axisPointerModel = getAxisPointerModel(axisModel);
  35605. axisPointerModel
  35606. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35607. .render(axisModel, axisPointerModel, api, forceRender)
  35608. : disposeAxisPointer(axisView, api);
  35609. }
  35610. function disposeAxisPointer(axisView, ecModel, api) {
  35611. var axisPointer = axisView._axisPointer;
  35612. axisPointer && axisPointer.dispose(ecModel, api);
  35613. axisView._axisPointer = null;
  35614. }
  35615. var axisPointerClazz = [];
  35616. AxisView.registerAxisPointerClass = function (type, clazz) {
  35617. if (__DEV__) {
  35618. if (axisPointerClazz[type]) {
  35619. throw new Error('axisPointer ' + type + ' exists');
  35620. }
  35621. }
  35622. axisPointerClazz[type] = clazz;
  35623. };
  35624. AxisView.getAxisPointerClass = function (type) {
  35625. return type && axisPointerClazz[type];
  35626. };
  35627. /*
  35628. * Licensed to the Apache Software Foundation (ASF) under one
  35629. * or more contributor license agreements. See the NOTICE file
  35630. * distributed with this work for additional information
  35631. * regarding copyright ownership. The ASF licenses this file
  35632. * to you under the Apache License, Version 2.0 (the
  35633. * "License"); you may not use this file except in compliance
  35634. * with the License. You may obtain a copy of the License at
  35635. *
  35636. * http://www.apache.org/licenses/LICENSE-2.0
  35637. *
  35638. * Unless required by applicable law or agreed to in writing,
  35639. * software distributed under the License is distributed on an
  35640. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35641. * KIND, either express or implied. See the License for the
  35642. * specific language governing permissions and limitations
  35643. * under the License.
  35644. */
  35645. /**
  35646. * Can only be called after coordinate system creation stage.
  35647. * (Can be called before coordinate system update stage).
  35648. *
  35649. * @param {Object} opt {labelInside}
  35650. * @return {Object} {
  35651. * position, rotation, labelDirection, labelOffset,
  35652. * tickDirection, labelRotate, z2
  35653. * }
  35654. */
  35655. function layout$1(gridModel, axisModel, opt) {
  35656. opt = opt || {};
  35657. var grid = gridModel.coordinateSystem;
  35658. var axis = axisModel.axis;
  35659. var layout = {};
  35660. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35661. var rawAxisPosition = axis.position;
  35662. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35663. var axisDim = axis.dim;
  35664. var rect = grid.getRect();
  35665. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35666. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35667. var axisOffset = axisModel.get('offset') || 0;
  35668. var posBound = axisDim === 'x'
  35669. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35670. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35671. if (otherAxisOnZeroOf) {
  35672. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35673. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35674. }
  35675. // Axis position
  35676. layout.position = [
  35677. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35678. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35679. ];
  35680. // Axis rotation
  35681. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35682. // Tick and label direction, x y is axisDim
  35683. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35684. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35685. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35686. if (axisModel.get('axisTick.inside')) {
  35687. layout.tickDirection = -layout.tickDirection;
  35688. }
  35689. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35690. layout.labelDirection = -layout.labelDirection;
  35691. }
  35692. // Special label rotation
  35693. var labelRotate = axisModel.get('axisLabel.rotate');
  35694. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35695. // Over splitLine and splitArea
  35696. layout.z2 = 1;
  35697. return layout;
  35698. }
  35699. /*
  35700. * Licensed to the Apache Software Foundation (ASF) under one
  35701. * or more contributor license agreements. See the NOTICE file
  35702. * distributed with this work for additional information
  35703. * regarding copyright ownership. The ASF licenses this file
  35704. * to you under the Apache License, Version 2.0 (the
  35705. * "License"); you may not use this file except in compliance
  35706. * with the License. You may obtain a copy of the License at
  35707. *
  35708. * http://www.apache.org/licenses/LICENSE-2.0
  35709. *
  35710. * Unless required by applicable law or agreed to in writing,
  35711. * software distributed under the License is distributed on an
  35712. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35713. * KIND, either express or implied. See the License for the
  35714. * specific language governing permissions and limitations
  35715. * under the License.
  35716. */
  35717. var axisBuilderAttrs = [
  35718. 'axisLine', 'axisTickLabel', 'axisName'
  35719. ];
  35720. var selfBuilderAttrs = [
  35721. 'splitArea', 'splitLine', 'minorSplitLine'
  35722. ];
  35723. var CartesianAxisView = AxisView.extend({
  35724. type: 'cartesianAxis',
  35725. axisPointerClass: 'CartesianAxisPointer',
  35726. /**
  35727. * @override
  35728. */
  35729. render: function (axisModel, ecModel, api, payload) {
  35730. this.group.removeAll();
  35731. var oldAxisGroup = this._axisGroup;
  35732. this._axisGroup = new Group();
  35733. this.group.add(this._axisGroup);
  35734. if (!axisModel.get('show')) {
  35735. return;
  35736. }
  35737. var gridModel = axisModel.getCoordSysModel();
  35738. var layout = layout$1(gridModel, axisModel);
  35739. var axisBuilder = new AxisBuilder(axisModel, layout);
  35740. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35741. this._axisGroup.add(axisBuilder.getGroup());
  35742. each$1(selfBuilderAttrs, function (name) {
  35743. if (axisModel.get(name + '.show')) {
  35744. this['_' + name](axisModel, gridModel);
  35745. }
  35746. }, this);
  35747. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35748. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35749. },
  35750. remove: function () {
  35751. this._splitAreaColors = null;
  35752. },
  35753. /**
  35754. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35755. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35756. * @private
  35757. */
  35758. _splitLine: function (axisModel, gridModel) {
  35759. var axis = axisModel.axis;
  35760. if (axis.scale.isBlank()) {
  35761. return;
  35762. }
  35763. var splitLineModel = axisModel.getModel('splitLine');
  35764. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35765. var lineColors = lineStyleModel.get('color');
  35766. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35767. var gridRect = gridModel.coordinateSystem.getRect();
  35768. var isHorizontal = axis.isHorizontal();
  35769. var lineCount = 0;
  35770. var ticksCoords = axis.getTicksCoords({
  35771. tickModel: splitLineModel
  35772. });
  35773. var p1 = [];
  35774. var p2 = [];
  35775. var lineStyle = lineStyleModel.getLineStyle();
  35776. for (var i = 0; i < ticksCoords.length; i++) {
  35777. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35778. if (isHorizontal) {
  35779. p1[0] = tickCoord;
  35780. p1[1] = gridRect.y;
  35781. p2[0] = tickCoord;
  35782. p2[1] = gridRect.y + gridRect.height;
  35783. }
  35784. else {
  35785. p1[0] = gridRect.x;
  35786. p1[1] = tickCoord;
  35787. p2[0] = gridRect.x + gridRect.width;
  35788. p2[1] = tickCoord;
  35789. }
  35790. var colorIndex = (lineCount++) % lineColors.length;
  35791. var tickValue = ticksCoords[i].tickValue;
  35792. this._axisGroup.add(new Line({
  35793. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35794. subPixelOptimize: true,
  35795. shape: {
  35796. x1: p1[0],
  35797. y1: p1[1],
  35798. x2: p2[0],
  35799. y2: p2[1]
  35800. },
  35801. style: defaults({
  35802. stroke: lineColors[colorIndex]
  35803. }, lineStyle),
  35804. silent: true
  35805. }));
  35806. }
  35807. },
  35808. /**
  35809. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35810. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35811. * @private
  35812. */
  35813. _minorSplitLine: function (axisModel, gridModel) {
  35814. var axis = axisModel.axis;
  35815. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  35816. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  35817. var gridRect = gridModel.coordinateSystem.getRect();
  35818. var isHorizontal = axis.isHorizontal();
  35819. var minorTicksCoords = axis.getMinorTicksCoords();
  35820. if (!minorTicksCoords.length) {
  35821. return;
  35822. }
  35823. var p1 = [];
  35824. var p2 = [];
  35825. var lineStyle = lineStyleModel.getLineStyle();
  35826. for (var i = 0; i < minorTicksCoords.length; i++) {
  35827. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  35828. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  35829. if (isHorizontal) {
  35830. p1[0] = tickCoord;
  35831. p1[1] = gridRect.y;
  35832. p2[0] = tickCoord;
  35833. p2[1] = gridRect.y + gridRect.height;
  35834. }
  35835. else {
  35836. p1[0] = gridRect.x;
  35837. p1[1] = tickCoord;
  35838. p2[0] = gridRect.x + gridRect.width;
  35839. p2[1] = tickCoord;
  35840. }
  35841. this._axisGroup.add(new Line({
  35842. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  35843. subPixelOptimize: true,
  35844. shape: {
  35845. x1: p1[0],
  35846. y1: p1[1],
  35847. x2: p2[0],
  35848. y2: p2[1]
  35849. },
  35850. style: lineStyle,
  35851. silent: true
  35852. }));
  35853. }
  35854. }
  35855. },
  35856. /**
  35857. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35858. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35859. * @private
  35860. */
  35861. _splitArea: function (axisModel, gridModel) {
  35862. var axis = axisModel.axis;
  35863. if (axis.scale.isBlank()) {
  35864. return;
  35865. }
  35866. var splitAreaModel = axisModel.getModel('splitArea');
  35867. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35868. var areaColors = areaStyleModel.get('color');
  35869. var gridRect = gridModel.coordinateSystem.getRect();
  35870. var ticksCoords = axis.getTicksCoords({
  35871. tickModel: splitAreaModel,
  35872. clamp: true
  35873. });
  35874. if (!ticksCoords.length) {
  35875. return;
  35876. }
  35877. // For Making appropriate splitArea animation, the color and anid
  35878. // should be corresponding to previous one if possible.
  35879. var areaColorsLen = areaColors.length;
  35880. var lastSplitAreaColors = this._splitAreaColors;
  35881. var newSplitAreaColors = createHashMap();
  35882. var colorIndex = 0;
  35883. if (lastSplitAreaColors) {
  35884. for (var i = 0; i < ticksCoords.length; i++) {
  35885. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35886. if (cIndex != null) {
  35887. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35888. break;
  35889. }
  35890. }
  35891. }
  35892. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35893. var areaStyle = areaStyleModel.getAreaStyle();
  35894. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35895. for (var i = 1; i < ticksCoords.length; i++) {
  35896. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35897. var x;
  35898. var y;
  35899. var width;
  35900. var height;
  35901. if (axis.isHorizontal()) {
  35902. x = prev;
  35903. y = gridRect.y;
  35904. width = tickCoord - x;
  35905. height = gridRect.height;
  35906. prev = x + width;
  35907. }
  35908. else {
  35909. x = gridRect.x;
  35910. y = prev;
  35911. width = gridRect.width;
  35912. height = tickCoord - y;
  35913. prev = y + height;
  35914. }
  35915. var tickValue = ticksCoords[i - 1].tickValue;
  35916. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35917. this._axisGroup.add(new Rect({
  35918. anid: tickValue != null ? 'area_' + tickValue : null,
  35919. shape: {
  35920. x: x,
  35921. y: y,
  35922. width: width,
  35923. height: height
  35924. },
  35925. style: defaults({
  35926. fill: areaColors[colorIndex]
  35927. }, areaStyle),
  35928. silent: true
  35929. }));
  35930. colorIndex = (colorIndex + 1) % areaColorsLen;
  35931. }
  35932. this._splitAreaColors = newSplitAreaColors;
  35933. }
  35934. });
  35935. CartesianAxisView.extend({
  35936. type: 'xAxis'
  35937. });
  35938. CartesianAxisView.extend({
  35939. type: 'yAxis'
  35940. });
  35941. /*
  35942. * Licensed to the Apache Software Foundation (ASF) under one
  35943. * or more contributor license agreements. See the NOTICE file
  35944. * distributed with this work for additional information
  35945. * regarding copyright ownership. The ASF licenses this file
  35946. * to you under the Apache License, Version 2.0 (the
  35947. * "License"); you may not use this file except in compliance
  35948. * with the License. You may obtain a copy of the License at
  35949. *
  35950. * http://www.apache.org/licenses/LICENSE-2.0
  35951. *
  35952. * Unless required by applicable law or agreed to in writing,
  35953. * software distributed under the License is distributed on an
  35954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35955. * KIND, either express or implied. See the License for the
  35956. * specific language governing permissions and limitations
  35957. * under the License.
  35958. */
  35959. /*
  35960. * Licensed to the Apache Software Foundation (ASF) under one
  35961. * or more contributor license agreements. See the NOTICE file
  35962. * distributed with this work for additional information
  35963. * regarding copyright ownership. The ASF licenses this file
  35964. * to you under the Apache License, Version 2.0 (the
  35965. * "License"); you may not use this file except in compliance
  35966. * with the License. You may obtain a copy of the License at
  35967. *
  35968. * http://www.apache.org/licenses/LICENSE-2.0
  35969. *
  35970. * Unless required by applicable law or agreed to in writing,
  35971. * software distributed under the License is distributed on an
  35972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35973. * KIND, either express or implied. See the License for the
  35974. * specific language governing permissions and limitations
  35975. * under the License.
  35976. */
  35977. // Grid view
  35978. extendComponentView({
  35979. type: 'grid',
  35980. render: function (gridModel, ecModel) {
  35981. this.group.removeAll();
  35982. if (gridModel.get('show')) {
  35983. this.group.add(new Rect({
  35984. shape: gridModel.coordinateSystem.getRect(),
  35985. style: defaults({
  35986. fill: gridModel.get('backgroundColor')
  35987. }, gridModel.getItemStyle()),
  35988. silent: true,
  35989. z2: -1
  35990. }));
  35991. }
  35992. }
  35993. });
  35994. registerPreprocessor(function (option) {
  35995. // Only create grid when need
  35996. if (option.xAxis && option.yAxis && !option.grid) {
  35997. option.grid = {};
  35998. }
  35999. });
  36000. /*
  36001. * Licensed to the Apache Software Foundation (ASF) under one
  36002. * or more contributor license agreements. See the NOTICE file
  36003. * distributed with this work for additional information
  36004. * regarding copyright ownership. The ASF licenses this file
  36005. * to you under the Apache License, Version 2.0 (the
  36006. * "License"); you may not use this file except in compliance
  36007. * with the License. You may obtain a copy of the License at
  36008. *
  36009. * http://www.apache.org/licenses/LICENSE-2.0
  36010. *
  36011. * Unless required by applicable law or agreed to in writing,
  36012. * software distributed under the License is distributed on an
  36013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36014. * KIND, either express or implied. See the License for the
  36015. * specific language governing permissions and limitations
  36016. * under the License.
  36017. */
  36018. // In case developer forget to include grid component
  36019. registerVisual(visualSymbol('line', 'circle', 'line'));
  36020. registerLayout(layoutPoints('line'));
  36021. // Down sample after filter
  36022. registerProcessor(
  36023. PRIORITY.PROCESSOR.STATISTIC,
  36024. dataSample('line')
  36025. );
  36026. /*
  36027. * Licensed to the Apache Software Foundation (ASF) under one
  36028. * or more contributor license agreements. See the NOTICE file
  36029. * distributed with this work for additional information
  36030. * regarding copyright ownership. The ASF licenses this file
  36031. * to you under the Apache License, Version 2.0 (the
  36032. * "License"); you may not use this file except in compliance
  36033. * with the License. You may obtain a copy of the License at
  36034. *
  36035. * http://www.apache.org/licenses/LICENSE-2.0
  36036. *
  36037. * Unless required by applicable law or agreed to in writing,
  36038. * software distributed under the License is distributed on an
  36039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36040. * KIND, either express or implied. See the License for the
  36041. * specific language governing permissions and limitations
  36042. * under the License.
  36043. */
  36044. var BaseBarSeries = SeriesModel.extend({
  36045. type: 'series.__base_bar__',
  36046. getInitialData: function (option, ecModel) {
  36047. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  36048. },
  36049. getMarkerPosition: function (value) {
  36050. var coordSys = this.coordinateSystem;
  36051. if (coordSys) {
  36052. // PENDING if clamp ?
  36053. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  36054. var data = this.getData();
  36055. var offset = data.getLayout('offset');
  36056. var size = data.getLayout('size');
  36057. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36058. pt[offsetIndex] += offset + size / 2;
  36059. return pt;
  36060. }
  36061. return [NaN, NaN];
  36062. },
  36063. defaultOption: {
  36064. zlevel: 0, // 一级层叠
  36065. z: 2, // 二级层叠
  36066. coordinateSystem: 'cartesian2d',
  36067. legendHoverLink: true,
  36068. // stack: null
  36069. // Cartesian coordinate system
  36070. // xAxisIndex: 0,
  36071. // yAxisIndex: 0,
  36072. // 最小高度改为0
  36073. barMinHeight: 0,
  36074. // 最小角度为0,仅对极坐标系下的柱状图有效
  36075. barMinAngle: 0,
  36076. // cursor: null,
  36077. large: false,
  36078. largeThreshold: 400,
  36079. progressive: 3e3,
  36080. progressiveChunkMode: 'mod',
  36081. // barMaxWidth: null,
  36082. // In cartesian, the default value is 1. Otherwise null.
  36083. // barMinWidth: null,
  36084. // 默认自适应
  36085. // barWidth: null,
  36086. // 柱间距离,默认为柱形宽度的30%,可设固定值
  36087. // barGap: '30%',
  36088. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  36089. // barCategoryGap: '20%',
  36090. // label: {
  36091. // show: false
  36092. // },
  36093. itemStyle: {},
  36094. emphasis: {}
  36095. }
  36096. });
  36097. /*
  36098. * Licensed to the Apache Software Foundation (ASF) under one
  36099. * or more contributor license agreements. See the NOTICE file
  36100. * distributed with this work for additional information
  36101. * regarding copyright ownership. The ASF licenses this file
  36102. * to you under the Apache License, Version 2.0 (the
  36103. * "License"); you may not use this file except in compliance
  36104. * with the License. You may obtain a copy of the License at
  36105. *
  36106. * http://www.apache.org/licenses/LICENSE-2.0
  36107. *
  36108. * Unless required by applicable law or agreed to in writing,
  36109. * software distributed under the License is distributed on an
  36110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36111. * KIND, either express or implied. See the License for the
  36112. * specific language governing permissions and limitations
  36113. * under the License.
  36114. */
  36115. BaseBarSeries.extend({
  36116. type: 'series.bar',
  36117. dependencies: ['grid', 'polar'],
  36118. brushSelector: 'rect',
  36119. /**
  36120. * @override
  36121. */
  36122. getProgressive: function () {
  36123. // Do not support progressive in normal mode.
  36124. return this.get('large')
  36125. ? this.get('progressive')
  36126. : false;
  36127. },
  36128. /**
  36129. * @override
  36130. */
  36131. getProgressiveThreshold: function () {
  36132. // Do not support progressive in normal mode.
  36133. var progressiveThreshold = this.get('progressiveThreshold');
  36134. var largeThreshold = this.get('largeThreshold');
  36135. if (largeThreshold > progressiveThreshold) {
  36136. progressiveThreshold = largeThreshold;
  36137. }
  36138. return progressiveThreshold;
  36139. },
  36140. defaultOption: {
  36141. // If clipped
  36142. // Only available on cartesian2d
  36143. clip: true,
  36144. // If use caps on two sides of bars
  36145. // Only available on tangential polar bar
  36146. roundCap: false
  36147. }
  36148. });
  36149. /*
  36150. * Licensed to the Apache Software Foundation (ASF) under one
  36151. * or more contributor license agreements. See the NOTICE file
  36152. * distributed with this work for additional information
  36153. * regarding copyright ownership. The ASF licenses this file
  36154. * to you under the Apache License, Version 2.0 (the
  36155. * "License"); you may not use this file except in compliance
  36156. * with the License. You may obtain a copy of the License at
  36157. *
  36158. * http://www.apache.org/licenses/LICENSE-2.0
  36159. *
  36160. * Unless required by applicable law or agreed to in writing,
  36161. * software distributed under the License is distributed on an
  36162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36163. * KIND, either express or implied. See the License for the
  36164. * specific language governing permissions and limitations
  36165. * under the License.
  36166. */
  36167. function setLabel(
  36168. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  36169. ) {
  36170. var labelModel = itemModel.getModel('label');
  36171. var hoverLabelModel = itemModel.getModel('emphasis.label');
  36172. setLabelStyle(
  36173. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  36174. {
  36175. labelFetcher: seriesModel,
  36176. labelDataIndex: dataIndex,
  36177. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  36178. isRectText: true,
  36179. autoColor: color
  36180. }
  36181. );
  36182. fixPosition(normalStyle);
  36183. fixPosition(hoverStyle);
  36184. }
  36185. function fixPosition(style, labelPositionOutside) {
  36186. if (style.textPosition === 'outside') {
  36187. style.textPosition = labelPositionOutside;
  36188. }
  36189. }
  36190. /*
  36191. * Licensed to the Apache Software Foundation (ASF) under one
  36192. * or more contributor license agreements. See the NOTICE file
  36193. * distributed with this work for additional information
  36194. * regarding copyright ownership. The ASF licenses this file
  36195. * to you under the Apache License, Version 2.0 (the
  36196. * "License"); you may not use this file except in compliance
  36197. * with the License. You may obtain a copy of the License at
  36198. *
  36199. * http://www.apache.org/licenses/LICENSE-2.0
  36200. *
  36201. * Unless required by applicable law or agreed to in writing,
  36202. * software distributed under the License is distributed on an
  36203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36204. * KIND, either express or implied. See the License for the
  36205. * specific language governing permissions and limitations
  36206. * under the License.
  36207. */
  36208. var getBarItemStyle = makeStyleMapper(
  36209. [
  36210. ['fill', 'color'],
  36211. ['stroke', 'borderColor'],
  36212. ['lineWidth', 'borderWidth'],
  36213. // Compatitable with 2
  36214. ['stroke', 'barBorderColor'],
  36215. ['lineWidth', 'barBorderWidth'],
  36216. ['opacity'],
  36217. ['shadowBlur'],
  36218. ['shadowOffsetX'],
  36219. ['shadowOffsetY'],
  36220. ['shadowColor']
  36221. ]
  36222. );
  36223. var barItemStyle = {
  36224. getBarItemStyle: function (excludes) {
  36225. var style = getBarItemStyle(this, excludes);
  36226. if (this.getBorderLineDash) {
  36227. var lineDash = this.getBorderLineDash();
  36228. lineDash && (style.lineDash = lineDash);
  36229. }
  36230. return style;
  36231. }
  36232. };
  36233. /*
  36234. * Licensed to the Apache Software Foundation (ASF) under one
  36235. * or more contributor license agreements. See the NOTICE file
  36236. * distributed with this work for additional information
  36237. * regarding copyright ownership. The ASF licenses this file
  36238. * to you under the Apache License, Version 2.0 (the
  36239. * "License"); you may not use this file except in compliance
  36240. * with the License. You may obtain a copy of the License at
  36241. *
  36242. * http://www.apache.org/licenses/LICENSE-2.0
  36243. *
  36244. * Unless required by applicable law or agreed to in writing,
  36245. * software distributed under the License is distributed on an
  36246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36247. * KIND, either express or implied. See the License for the
  36248. * specific language governing permissions and limitations
  36249. * under the License.
  36250. */
  36251. /**
  36252. * Sausage: similar to sector, but have half circle on both sides
  36253. * @public
  36254. */
  36255. var Sausage = extendShape({
  36256. type: 'sausage',
  36257. shape: {
  36258. cx: 0,
  36259. cy: 0,
  36260. r0: 0,
  36261. r: 0,
  36262. startAngle: 0,
  36263. endAngle: Math.PI * 2,
  36264. clockwise: true
  36265. },
  36266. buildPath: function (ctx, shape) {
  36267. var x = shape.cx;
  36268. var y = shape.cy;
  36269. var r0 = Math.max(shape.r0 || 0, 0);
  36270. var r = Math.max(shape.r, 0);
  36271. var dr = (r - r0) * 0.5;
  36272. var rCenter = r0 + dr;
  36273. var startAngle = shape.startAngle;
  36274. var endAngle = shape.endAngle;
  36275. var clockwise = shape.clockwise;
  36276. var unitStartX = Math.cos(startAngle);
  36277. var unitStartY = Math.sin(startAngle);
  36278. var unitEndX = Math.cos(endAngle);
  36279. var unitEndY = Math.sin(endAngle);
  36280. var lessThanCircle = clockwise
  36281. ? endAngle - startAngle < Math.PI * 2
  36282. : startAngle - endAngle < Math.PI * 2;
  36283. if (lessThanCircle) {
  36284. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  36285. ctx.arc(
  36286. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  36287. -Math.PI + startAngle, startAngle, !clockwise
  36288. );
  36289. }
  36290. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  36291. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  36292. ctx.arc(
  36293. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  36294. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  36295. );
  36296. if (r0 !== 0) {
  36297. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  36298. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  36299. }
  36300. ctx.closePath();
  36301. }
  36302. });
  36303. /*
  36304. * Licensed to the Apache Software Foundation (ASF) under one
  36305. * or more contributor license agreements. See the NOTICE file
  36306. * distributed with this work for additional information
  36307. * regarding copyright ownership. The ASF licenses this file
  36308. * to you under the Apache License, Version 2.0 (the
  36309. * "License"); you may not use this file except in compliance
  36310. * with the License. You may obtain a copy of the License at
  36311. *
  36312. * http://www.apache.org/licenses/LICENSE-2.0
  36313. *
  36314. * Unless required by applicable law or agreed to in writing,
  36315. * software distributed under the License is distributed on an
  36316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36317. * KIND, either express or implied. See the License for the
  36318. * specific language governing permissions and limitations
  36319. * under the License.
  36320. */
  36321. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  36322. var _eventPos = [0, 0];
  36323. // FIXME
  36324. // Just for compatible with ec2.
  36325. extend(Model.prototype, barItemStyle);
  36326. function getClipArea(coord, data) {
  36327. var coordSysClipArea = coord.getArea && coord.getArea();
  36328. if (coord.type === 'cartesian2d') {
  36329. var baseAxis = coord.getBaseAxis();
  36330. // When boundaryGap is false or using time axis. bar may exceed the grid.
  36331. // We should not clip this part.
  36332. // See test/bar2.html
  36333. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  36334. var expandWidth = data.getLayout('bandWidth');
  36335. if (baseAxis.isHorizontal()) {
  36336. coordSysClipArea.x -= expandWidth;
  36337. coordSysClipArea.width += expandWidth * 2;
  36338. }
  36339. else {
  36340. coordSysClipArea.y -= expandWidth;
  36341. coordSysClipArea.height += expandWidth * 2;
  36342. }
  36343. }
  36344. }
  36345. return coordSysClipArea;
  36346. }
  36347. extendChartView({
  36348. type: 'bar',
  36349. render: function (seriesModel, ecModel, api) {
  36350. this._updateDrawMode(seriesModel);
  36351. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36352. if (coordinateSystemType === 'cartesian2d'
  36353. || coordinateSystemType === 'polar'
  36354. ) {
  36355. this._isLargeDraw
  36356. ? this._renderLarge(seriesModel, ecModel, api)
  36357. : this._renderNormal(seriesModel, ecModel, api);
  36358. }
  36359. else if (__DEV__) {
  36360. console.warn('Only cartesian2d and polar supported for bar.');
  36361. }
  36362. return this.group;
  36363. },
  36364. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36365. this._clear();
  36366. this._updateDrawMode(seriesModel);
  36367. },
  36368. incrementalRender: function (params, seriesModel, ecModel, api) {
  36369. // Do not support progressive in normal mode.
  36370. this._incrementalRenderLarge(params, seriesModel);
  36371. },
  36372. _updateDrawMode: function (seriesModel) {
  36373. var isLargeDraw = seriesModel.pipelineContext.large;
  36374. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  36375. this._isLargeDraw = isLargeDraw;
  36376. this._clear();
  36377. }
  36378. },
  36379. _renderNormal: function (seriesModel, ecModel, api) {
  36380. var group = this.group;
  36381. var data = seriesModel.getData();
  36382. var oldData = this._data;
  36383. var coord = seriesModel.coordinateSystem;
  36384. var baseAxis = coord.getBaseAxis();
  36385. var isHorizontalOrRadial;
  36386. if (coord.type === 'cartesian2d') {
  36387. isHorizontalOrRadial = baseAxis.isHorizontal();
  36388. }
  36389. else if (coord.type === 'polar') {
  36390. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36391. }
  36392. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36393. var needsClip = seriesModel.get('clip', true);
  36394. var coordSysClipArea = getClipArea(coord, data);
  36395. // If there is clipPath created in large mode. Remove it.
  36396. group.removeClipPath();
  36397. // We don't use clipPath in normal mode because we needs a perfect animation
  36398. // And don't want the label are clipped.
  36399. var roundCap = seriesModel.get('roundCap', true);
  36400. data.diff(oldData)
  36401. .add(function (dataIndex) {
  36402. if (!data.hasValue(dataIndex)) {
  36403. return;
  36404. }
  36405. var itemModel = data.getItemModel(dataIndex);
  36406. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36407. if (needsClip) {
  36408. // Clip will modify the layout params.
  36409. // And return a boolean to determine if the shape are fully clipped.
  36410. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36411. if (isClipped) {
  36412. group.remove(el);
  36413. return;
  36414. }
  36415. }
  36416. var el = elementCreator[coord.type](
  36417. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  36418. );
  36419. data.setItemGraphicEl(dataIndex, el);
  36420. group.add(el);
  36421. updateStyle(
  36422. el, data, dataIndex, itemModel, layout,
  36423. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36424. );
  36425. })
  36426. .update(function (newIndex, oldIndex) {
  36427. var el = oldData.getItemGraphicEl(oldIndex);
  36428. if (!data.hasValue(newIndex)) {
  36429. group.remove(el);
  36430. return;
  36431. }
  36432. var itemModel = data.getItemModel(newIndex);
  36433. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36434. if (needsClip) {
  36435. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36436. if (isClipped) {
  36437. group.remove(el);
  36438. return;
  36439. }
  36440. }
  36441. if (el) {
  36442. updateProps(el, {shape: layout}, animationModel, newIndex);
  36443. }
  36444. else {
  36445. el = elementCreator[coord.type](
  36446. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  36447. );
  36448. }
  36449. data.setItemGraphicEl(newIndex, el);
  36450. // Add back
  36451. group.add(el);
  36452. updateStyle(
  36453. el, data, newIndex, itemModel, layout,
  36454. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36455. );
  36456. })
  36457. .remove(function (dataIndex) {
  36458. var el = oldData.getItemGraphicEl(dataIndex);
  36459. if (coord.type === 'cartesian2d') {
  36460. el && removeRect(dataIndex, animationModel, el);
  36461. }
  36462. else {
  36463. el && removeSector(dataIndex, animationModel, el);
  36464. }
  36465. })
  36466. .execute();
  36467. this._data = data;
  36468. },
  36469. _renderLarge: function (seriesModel, ecModel, api) {
  36470. this._clear();
  36471. createLarge(seriesModel, this.group);
  36472. // Use clipPath in large mode.
  36473. var clipPath = seriesModel.get('clip', true)
  36474. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  36475. : null;
  36476. if (clipPath) {
  36477. this.group.setClipPath(clipPath);
  36478. }
  36479. else {
  36480. this.group.removeClipPath();
  36481. }
  36482. },
  36483. _incrementalRenderLarge: function (params, seriesModel) {
  36484. createLarge(seriesModel, this.group, true);
  36485. },
  36486. dispose: noop,
  36487. remove: function (ecModel) {
  36488. this._clear(ecModel);
  36489. },
  36490. _clear: function (ecModel) {
  36491. var group = this.group;
  36492. var data = this._data;
  36493. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36494. data.eachItemGraphicEl(function (el) {
  36495. if (el.type === 'sector') {
  36496. removeSector(el.dataIndex, ecModel, el);
  36497. }
  36498. else {
  36499. removeRect(el.dataIndex, ecModel, el);
  36500. }
  36501. });
  36502. }
  36503. else {
  36504. group.removeAll();
  36505. }
  36506. this._data = null;
  36507. }
  36508. });
  36509. var mathMax$4 = Math.max;
  36510. var mathMin$4 = Math.min;
  36511. var clip = {
  36512. cartesian2d: function (coordSysBoundingRect, layout) {
  36513. var signWidth = layout.width < 0 ? -1 : 1;
  36514. var signHeight = layout.height < 0 ? -1 : 1;
  36515. // Needs positive width and height
  36516. if (signWidth < 0) {
  36517. layout.x += layout.width;
  36518. layout.width = -layout.width;
  36519. }
  36520. if (signHeight < 0) {
  36521. layout.y += layout.height;
  36522. layout.height = -layout.height;
  36523. }
  36524. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  36525. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  36526. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  36527. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  36528. layout.x = x;
  36529. layout.y = y;
  36530. layout.width = x2 - x;
  36531. layout.height = y2 - y;
  36532. var clipped = layout.width < 0 || layout.height < 0;
  36533. // Reverse back
  36534. if (signWidth < 0) {
  36535. layout.x += layout.width;
  36536. layout.width = -layout.width;
  36537. }
  36538. if (signHeight < 0) {
  36539. layout.y += layout.height;
  36540. layout.height = -layout.height;
  36541. }
  36542. return clipped;
  36543. },
  36544. polar: function (coordSysClipArea) {
  36545. return false;
  36546. }
  36547. };
  36548. var elementCreator = {
  36549. cartesian2d: function (
  36550. dataIndex, layout, isHorizontal,
  36551. animationModel, isUpdate
  36552. ) {
  36553. var rect = new Rect({shape: extend({}, layout)});
  36554. // Animation
  36555. if (animationModel) {
  36556. var rectShape = rect.shape;
  36557. var animateProperty = isHorizontal ? 'height' : 'width';
  36558. var animateTarget = {};
  36559. rectShape[animateProperty] = 0;
  36560. animateTarget[animateProperty] = layout[animateProperty];
  36561. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36562. shape: animateTarget
  36563. }, animationModel, dataIndex);
  36564. }
  36565. return rect;
  36566. },
  36567. polar: function (
  36568. dataIndex, layout, isRadial,
  36569. animationModel, isUpdate, roundCap
  36570. ) {
  36571. // Keep the same logic with bar in catesion: use end value to control
  36572. // direction. Notice that if clockwise is true (by default), the sector
  36573. // will always draw clockwisely, no matter whether endAngle is greater
  36574. // or less than startAngle.
  36575. var clockwise = layout.startAngle < layout.endAngle;
  36576. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  36577. var sector = new ShapeClass({
  36578. shape: defaults({clockwise: clockwise}, layout)
  36579. });
  36580. // Animation
  36581. if (animationModel) {
  36582. var sectorShape = sector.shape;
  36583. var animateProperty = isRadial ? 'r' : 'endAngle';
  36584. var animateTarget = {};
  36585. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36586. animateTarget[animateProperty] = layout[animateProperty];
  36587. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36588. shape: animateTarget
  36589. }, animationModel, dataIndex);
  36590. }
  36591. return sector;
  36592. }
  36593. };
  36594. function removeRect(dataIndex, animationModel, el) {
  36595. // Not show text when animating
  36596. el.style.text = null;
  36597. updateProps(el, {
  36598. shape: {
  36599. width: 0
  36600. }
  36601. }, animationModel, dataIndex, function () {
  36602. el.parent && el.parent.remove(el);
  36603. });
  36604. }
  36605. function removeSector(dataIndex, animationModel, el) {
  36606. // Not show text when animating
  36607. el.style.text = null;
  36608. updateProps(el, {
  36609. shape: {
  36610. r: el.shape.r0
  36611. }
  36612. }, animationModel, dataIndex, function () {
  36613. el.parent && el.parent.remove(el);
  36614. });
  36615. }
  36616. var getLayout = {
  36617. cartesian2d: function (data, dataIndex, itemModel) {
  36618. var layout = data.getItemLayout(dataIndex);
  36619. var fixedLineWidth = getLineWidth(itemModel, layout);
  36620. // fix layout with lineWidth
  36621. var signX = layout.width > 0 ? 1 : -1;
  36622. var signY = layout.height > 0 ? 1 : -1;
  36623. return {
  36624. x: layout.x + signX * fixedLineWidth / 2,
  36625. y: layout.y + signY * fixedLineWidth / 2,
  36626. width: layout.width - signX * fixedLineWidth,
  36627. height: layout.height - signY * fixedLineWidth
  36628. };
  36629. },
  36630. polar: function (data, dataIndex, itemModel) {
  36631. var layout = data.getItemLayout(dataIndex);
  36632. return {
  36633. cx: layout.cx,
  36634. cy: layout.cy,
  36635. r0: layout.r0,
  36636. r: layout.r,
  36637. startAngle: layout.startAngle,
  36638. endAngle: layout.endAngle
  36639. };
  36640. }
  36641. };
  36642. function isZeroOnPolar(layout) {
  36643. return layout.startAngle != null
  36644. && layout.endAngle != null
  36645. && layout.startAngle === layout.endAngle;
  36646. }
  36647. function updateStyle(
  36648. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36649. ) {
  36650. var color = data.getItemVisual(dataIndex, 'color');
  36651. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36652. var stroke = data.getVisual('borderColor');
  36653. var itemStyleModel = itemModel.getModel('itemStyle');
  36654. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36655. if (!isPolar) {
  36656. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36657. }
  36658. el.useStyle(defaults(
  36659. {
  36660. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  36661. fill: isZeroOnPolar(layout) ? 'none' : color,
  36662. opacity: opacity
  36663. },
  36664. itemStyleModel.getBarItemStyle()
  36665. ));
  36666. var cursorStyle = itemModel.getShallow('cursor');
  36667. cursorStyle && el.attr('cursor', cursorStyle);
  36668. var labelPositionOutside = isHorizontal
  36669. ? (layout.height > 0 ? 'bottom' : 'top')
  36670. : (layout.width > 0 ? 'left' : 'right');
  36671. if (!isPolar) {
  36672. setLabel(
  36673. el.style, hoverStyle, itemModel, color,
  36674. seriesModel, dataIndex, labelPositionOutside
  36675. );
  36676. }
  36677. if (isZeroOnPolar(layout)) {
  36678. hoverStyle.fill = hoverStyle.stroke = 'none';
  36679. }
  36680. setHoverStyle(el, hoverStyle);
  36681. }
  36682. // In case width or height are too small.
  36683. function getLineWidth(itemModel, rawLayout) {
  36684. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36685. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  36686. }
  36687. var LargePath = Path.extend({
  36688. type: 'largeBar',
  36689. shape: {points: []},
  36690. buildPath: function (ctx, shape) {
  36691. // Drawing lines is more efficient than drawing
  36692. // a whole line or drawing rects.
  36693. var points = shape.points;
  36694. var startPoint = this.__startPoint;
  36695. var baseDimIdx = this.__baseDimIdx;
  36696. for (var i = 0; i < points.length; i += 2) {
  36697. startPoint[baseDimIdx] = points[i + baseDimIdx];
  36698. ctx.moveTo(startPoint[0], startPoint[1]);
  36699. ctx.lineTo(points[i], points[i + 1]);
  36700. }
  36701. }
  36702. });
  36703. function createLarge(seriesModel, group, incremental) {
  36704. // TODO support polar
  36705. var data = seriesModel.getData();
  36706. var startPoint = [];
  36707. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36708. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  36709. var el = new LargePath({
  36710. shape: {points: data.getLayout('largePoints')},
  36711. incremental: !!incremental,
  36712. __startPoint: startPoint,
  36713. __baseDimIdx: baseDimIdx,
  36714. __largeDataIndices: data.getLayout('largeDataIndices'),
  36715. __barWidth: data.getLayout('barWidth')
  36716. });
  36717. group.add(el);
  36718. setLargeStyle(el, seriesModel, data);
  36719. // Enable tooltip and user mouse/touch event handlers.
  36720. el.seriesIndex = seriesModel.seriesIndex;
  36721. if (!seriesModel.get('silent')) {
  36722. el.on('mousedown', largePathUpdateDataIndex);
  36723. el.on('mousemove', largePathUpdateDataIndex);
  36724. }
  36725. }
  36726. // Use throttle to avoid frequently traverse to find dataIndex.
  36727. var largePathUpdateDataIndex = throttle(function (event) {
  36728. var largePath = this;
  36729. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  36730. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  36731. }, 30, false);
  36732. function largePathFindDataIndex(largePath, x, y) {
  36733. var baseDimIdx = largePath.__baseDimIdx;
  36734. var valueDimIdx = 1 - baseDimIdx;
  36735. var points = largePath.shape.points;
  36736. var largeDataIndices = largePath.__largeDataIndices;
  36737. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  36738. var startValueVal = largePath.__startPoint[valueDimIdx];
  36739. _eventPos[0] = x;
  36740. _eventPos[1] = y;
  36741. var pointerBaseVal = _eventPos[baseDimIdx];
  36742. var pointerValueVal = _eventPos[1 - baseDimIdx];
  36743. var baseLowerBound = pointerBaseVal - barWidthHalf;
  36744. var baseUpperBound = pointerBaseVal + barWidthHalf;
  36745. for (var i = 0, len = points.length / 2; i < len; i++) {
  36746. var ii = i * 2;
  36747. var barBaseVal = points[ii + baseDimIdx];
  36748. var barValueVal = points[ii + valueDimIdx];
  36749. if (
  36750. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  36751. && (
  36752. startValueVal <= barValueVal
  36753. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  36754. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  36755. )
  36756. ) {
  36757. return largeDataIndices[i];
  36758. }
  36759. }
  36760. return -1;
  36761. }
  36762. function setLargeStyle(el, seriesModel, data) {
  36763. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36764. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36765. el.useStyle(itemStyle);
  36766. el.style.fill = null;
  36767. el.style.stroke = borderColor;
  36768. el.style.lineWidth = data.getLayout('barWidth');
  36769. }
  36770. /*
  36771. * Licensed to the Apache Software Foundation (ASF) under one
  36772. * or more contributor license agreements. See the NOTICE file
  36773. * distributed with this work for additional information
  36774. * regarding copyright ownership. The ASF licenses this file
  36775. * to you under the Apache License, Version 2.0 (the
  36776. * "License"); you may not use this file except in compliance
  36777. * with the License. You may obtain a copy of the License at
  36778. *
  36779. * http://www.apache.org/licenses/LICENSE-2.0
  36780. *
  36781. * Unless required by applicable law or agreed to in writing,
  36782. * software distributed under the License is distributed on an
  36783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36784. * KIND, either express or implied. See the License for the
  36785. * specific language governing permissions and limitations
  36786. * under the License.
  36787. */
  36788. // In case developer forget to include grid component
  36789. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  36790. // Use higher prority to avoid to be blocked by other overall layout, which do not
  36791. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  36792. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  36793. registerVisual({
  36794. seriesType: 'bar',
  36795. reset: function (seriesModel) {
  36796. // Visual coding for legend
  36797. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  36798. }
  36799. });
  36800. /*
  36801. * Licensed to the Apache Software Foundation (ASF) under one
  36802. * or more contributor license agreements. See the NOTICE file
  36803. * distributed with this work for additional information
  36804. * regarding copyright ownership. The ASF licenses this file
  36805. * to you under the Apache License, Version 2.0 (the
  36806. * "License"); you may not use this file except in compliance
  36807. * with the License. You may obtain a copy of the License at
  36808. *
  36809. * http://www.apache.org/licenses/LICENSE-2.0
  36810. *
  36811. * Unless required by applicable law or agreed to in writing,
  36812. * software distributed under the License is distributed on an
  36813. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36814. * KIND, either express or implied. See the License for the
  36815. * specific language governing permissions and limitations
  36816. * under the License.
  36817. */
  36818. /**
  36819. * [Usage]:
  36820. * (1)
  36821. * createListSimply(seriesModel, ['value']);
  36822. * (2)
  36823. * createListSimply(seriesModel, {
  36824. * coordDimensions: ['value'],
  36825. * dimensionsCount: 5
  36826. * });
  36827. *
  36828. * @param {module:echarts/model/Series} seriesModel
  36829. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  36830. * The options in opt, see `echarts/data/helper/createDimensions`
  36831. * @param {Array.<string>} [nameList]
  36832. * @return {module:echarts/data/List}
  36833. */
  36834. var createListSimply = function (seriesModel, opt, nameList) {
  36835. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  36836. var source = seriesModel.getSource();
  36837. var dimensionsInfo = createDimensions(source, opt);
  36838. var list = new List(dimensionsInfo, seriesModel);
  36839. list.initData(source, nameList);
  36840. return list;
  36841. };
  36842. /*
  36843. * Licensed to the Apache Software Foundation (ASF) under one
  36844. * or more contributor license agreements. See the NOTICE file
  36845. * distributed with this work for additional information
  36846. * regarding copyright ownership. The ASF licenses this file
  36847. * to you under the Apache License, Version 2.0 (the
  36848. * "License"); you may not use this file except in compliance
  36849. * with the License. You may obtain a copy of the License at
  36850. *
  36851. * http://www.apache.org/licenses/LICENSE-2.0
  36852. *
  36853. * Unless required by applicable law or agreed to in writing,
  36854. * software distributed under the License is distributed on an
  36855. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36856. * KIND, either express or implied. See the License for the
  36857. * specific language governing permissions and limitations
  36858. * under the License.
  36859. */
  36860. /**
  36861. * Data selectable mixin for chart series.
  36862. * To eanble data select, option of series must have `selectedMode`.
  36863. * And each data item will use `selected` to toggle itself selected status
  36864. */
  36865. var dataSelectableMixin = {
  36866. /**
  36867. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36868. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36869. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36870. */
  36871. updateSelectedMap: function (targetList) {
  36872. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36873. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36874. targetMap.set(target.name, target);
  36875. return targetMap;
  36876. }, createHashMap());
  36877. },
  36878. /**
  36879. * Either name or id should be passed as input here.
  36880. * If both of them are defined, id is used.
  36881. *
  36882. * @param {string|undefined} name name of data
  36883. * @param {number|undefined} id dataIndex of data
  36884. */
  36885. // PENGING If selectedMode is null ?
  36886. select: function (name, id) {
  36887. var target = id != null
  36888. ? this._targetList[id]
  36889. : this._selectTargetMap.get(name);
  36890. var selectedMode = this.get('selectedMode');
  36891. if (selectedMode === 'single') {
  36892. this._selectTargetMap.each(function (target) {
  36893. target.selected = false;
  36894. });
  36895. }
  36896. target && (target.selected = true);
  36897. },
  36898. /**
  36899. * Either name or id should be passed as input here.
  36900. * If both of them are defined, id is used.
  36901. *
  36902. * @param {string|undefined} name name of data
  36903. * @param {number|undefined} id dataIndex of data
  36904. */
  36905. unSelect: function (name, id) {
  36906. var target = id != null
  36907. ? this._targetList[id]
  36908. : this._selectTargetMap.get(name);
  36909. // var selectedMode = this.get('selectedMode');
  36910. // selectedMode !== 'single' && target && (target.selected = false);
  36911. target && (target.selected = false);
  36912. },
  36913. /**
  36914. * Either name or id should be passed as input here.
  36915. * If both of them are defined, id is used.
  36916. *
  36917. * @param {string|undefined} name name of data
  36918. * @param {number|undefined} id dataIndex of data
  36919. */
  36920. toggleSelected: function (name, id) {
  36921. var target = id != null
  36922. ? this._targetList[id]
  36923. : this._selectTargetMap.get(name);
  36924. if (target != null) {
  36925. this[target.selected ? 'unSelect' : 'select'](name, id);
  36926. return target.selected;
  36927. }
  36928. },
  36929. /**
  36930. * Either name or id should be passed as input here.
  36931. * If both of them are defined, id is used.
  36932. *
  36933. * @param {string|undefined} name name of data
  36934. * @param {number|undefined} id dataIndex of data
  36935. */
  36936. isSelected: function (name, id) {
  36937. var target = id != null
  36938. ? this._targetList[id]
  36939. : this._selectTargetMap.get(name);
  36940. return target && target.selected;
  36941. }
  36942. };
  36943. /*
  36944. * Licensed to the Apache Software Foundation (ASF) under one
  36945. * or more contributor license agreements. See the NOTICE file
  36946. * distributed with this work for additional information
  36947. * regarding copyright ownership. The ASF licenses this file
  36948. * to you under the Apache License, Version 2.0 (the
  36949. * "License"); you may not use this file except in compliance
  36950. * with the License. You may obtain a copy of the License at
  36951. *
  36952. * http://www.apache.org/licenses/LICENSE-2.0
  36953. *
  36954. * Unless required by applicable law or agreed to in writing,
  36955. * software distributed under the License is distributed on an
  36956. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36957. * KIND, either express or implied. See the License for the
  36958. * specific language governing permissions and limitations
  36959. * under the License.
  36960. */
  36961. /**
  36962. * LegendVisualProvider is an bridge that pick encoded color from data and
  36963. * provide to the legend component.
  36964. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  36965. * @param {Function} getRawData Function to get raw data before filtered.
  36966. */
  36967. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  36968. this.getAllNames = function () {
  36969. var rawData = getRawData();
  36970. // We find the name from the raw data. In case it's filtered by the legend component.
  36971. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  36972. return rawData.mapArray(rawData.getName);
  36973. };
  36974. this.containName = function (name) {
  36975. var rawData = getRawData();
  36976. return rawData.indexOfName(name) >= 0;
  36977. };
  36978. this.indexOfName = function (name) {
  36979. // Only get data when necessary.
  36980. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  36981. // Invoking Series#getData immediately will throw an error.
  36982. var dataWithEncodedVisual = getDataWithEncodedVisual();
  36983. return dataWithEncodedVisual.indexOfName(name);
  36984. };
  36985. this.getItemVisual = function (dataIndex, key) {
  36986. // Get encoded visual properties from final filtered data.
  36987. var dataWithEncodedVisual = getDataWithEncodedVisual();
  36988. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  36989. };
  36990. }
  36991. /*
  36992. * Licensed to the Apache Software Foundation (ASF) under one
  36993. * or more contributor license agreements. See the NOTICE file
  36994. * distributed with this work for additional information
  36995. * regarding copyright ownership. The ASF licenses this file
  36996. * to you under the Apache License, Version 2.0 (the
  36997. * "License"); you may not use this file except in compliance
  36998. * with the License. You may obtain a copy of the License at
  36999. *
  37000. * http://www.apache.org/licenses/LICENSE-2.0
  37001. *
  37002. * Unless required by applicable law or agreed to in writing,
  37003. * software distributed under the License is distributed on an
  37004. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37005. * KIND, either express or implied. See the License for the
  37006. * specific language governing permissions and limitations
  37007. * under the License.
  37008. */
  37009. var PieSeries = extendSeriesModel({
  37010. type: 'series.pie',
  37011. // Overwrite
  37012. init: function (option) {
  37013. PieSeries.superApply(this, 'init', arguments);
  37014. // Enable legend selection for each data item
  37015. // Use a function instead of direct access because data reference may changed
  37016. this.legendVisualProvider = new LegendVisualProvider(
  37017. bind(this.getData, this), bind(this.getRawData, this)
  37018. );
  37019. this.updateSelectedMap(this._createSelectableList());
  37020. this._defaultLabelLine(option);
  37021. },
  37022. // Overwrite
  37023. mergeOption: function (newOption) {
  37024. PieSeries.superCall(this, 'mergeOption', newOption);
  37025. this.updateSelectedMap(this._createSelectableList());
  37026. },
  37027. getInitialData: function (option, ecModel) {
  37028. return createListSimply(this, {
  37029. coordDimensions: ['value'],
  37030. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  37031. });
  37032. },
  37033. _createSelectableList: function () {
  37034. var data = this.getRawData();
  37035. var valueDim = data.mapDimension('value');
  37036. var targetList = [];
  37037. for (var i = 0, len = data.count(); i < len; i++) {
  37038. targetList.push({
  37039. name: data.getName(i),
  37040. value: data.get(valueDim, i),
  37041. selected: retrieveRawAttr(data, i, 'selected')
  37042. });
  37043. }
  37044. return targetList;
  37045. },
  37046. // Overwrite
  37047. getDataParams: function (dataIndex) {
  37048. var data = this.getData();
  37049. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  37050. // FIXME toFixed?
  37051. var valueList = [];
  37052. data.each(data.mapDimension('value'), function (value) {
  37053. valueList.push(value);
  37054. });
  37055. params.percent = getPercentWithPrecision(
  37056. valueList,
  37057. dataIndex,
  37058. data.hostModel.get('percentPrecision')
  37059. );
  37060. params.$vars.push('percent');
  37061. return params;
  37062. },
  37063. _defaultLabelLine: function (option) {
  37064. // Extend labelLine emphasis
  37065. defaultEmphasis(option, 'labelLine', ['show']);
  37066. var labelLineNormalOpt = option.labelLine;
  37067. var labelLineEmphasisOpt = option.emphasis.labelLine;
  37068. // Not show label line if `label.normal.show = false`
  37069. labelLineNormalOpt.show = labelLineNormalOpt.show
  37070. && option.label.show;
  37071. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  37072. && option.emphasis.label.show;
  37073. },
  37074. defaultOption: {
  37075. zlevel: 0,
  37076. z: 2,
  37077. legendHoverLink: true,
  37078. hoverAnimation: true,
  37079. // 默认全局居中
  37080. center: ['50%', '50%'],
  37081. radius: [0, '75%'],
  37082. // 默认顺时针
  37083. clockwise: true,
  37084. startAngle: 90,
  37085. // 最小角度改为0
  37086. minAngle: 0,
  37087. // If the angle of a sector less than `minShowLabelAngle`,
  37088. // the label will not be displayed.
  37089. minShowLabelAngle: 0,
  37090. // 选中时扇区偏移量
  37091. selectedOffset: 10,
  37092. // 高亮扇区偏移量
  37093. hoverOffset: 10,
  37094. // If use strategy to avoid label overlapping
  37095. avoidLabelOverlap: true,
  37096. // 选择模式,默认关闭,可选single,multiple
  37097. // selectedMode: false,
  37098. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  37099. // roseType: null,
  37100. percentPrecision: 2,
  37101. // If still show when all data zero.
  37102. stillShowZeroSum: true,
  37103. // cursor: null,
  37104. left: 0,
  37105. top: 0,
  37106. right: 0,
  37107. bottom: 0,
  37108. width: null,
  37109. height: null,
  37110. label: {
  37111. // If rotate around circle
  37112. rotate: false,
  37113. show: true,
  37114. // 'outer', 'inside', 'center'
  37115. position: 'outer',
  37116. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  37117. alignTo: 'none',
  37118. // Closest distance between label and chart edge.
  37119. // Works only position is 'outer' and alignTo is 'edge'.
  37120. margin: '25%',
  37121. // Works only position is 'outer' and alignTo is not 'edge'.
  37122. bleedMargin: 10,
  37123. // Distance between text and label line.
  37124. distanceToLabelLine: 5
  37125. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37126. // 默认使用全局文本样式,详见TEXTSTYLE
  37127. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  37128. },
  37129. // Enabled when label.normal.position is 'outer'
  37130. labelLine: {
  37131. show: true,
  37132. // 引导线两段中的第一段长度
  37133. length: 15,
  37134. // 引导线两段中的第二段长度
  37135. length2: 15,
  37136. smooth: false,
  37137. lineStyle: {
  37138. // color: 各异,
  37139. width: 1,
  37140. type: 'solid'
  37141. }
  37142. },
  37143. itemStyle: {
  37144. borderWidth: 1
  37145. },
  37146. // Animation type. Valid values: expansion, scale
  37147. animationType: 'expansion',
  37148. // Animation type when update. Valid values: transition, expansion
  37149. animationTypeUpdate: 'transition',
  37150. animationEasing: 'cubicOut'
  37151. }
  37152. });
  37153. mixin(PieSeries, dataSelectableMixin);
  37154. /*
  37155. * Licensed to the Apache Software Foundation (ASF) under one
  37156. * or more contributor license agreements. See the NOTICE file
  37157. * distributed with this work for additional information
  37158. * regarding copyright ownership. The ASF licenses this file
  37159. * to you under the Apache License, Version 2.0 (the
  37160. * "License"); you may not use this file except in compliance
  37161. * with the License. You may obtain a copy of the License at
  37162. *
  37163. * http://www.apache.org/licenses/LICENSE-2.0
  37164. *
  37165. * Unless required by applicable law or agreed to in writing,
  37166. * software distributed under the License is distributed on an
  37167. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37168. * KIND, either express or implied. See the License for the
  37169. * specific language governing permissions and limitations
  37170. * under the License.
  37171. */
  37172. /**
  37173. * @param {module:echarts/model/Series} seriesModel
  37174. * @param {boolean} hasAnimation
  37175. * @inner
  37176. */
  37177. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  37178. var data = seriesModel.getData();
  37179. var dataIndex = this.dataIndex;
  37180. var name = data.getName(dataIndex);
  37181. var selectedOffset = seriesModel.get('selectedOffset');
  37182. api.dispatchAction({
  37183. type: 'pieToggleSelect',
  37184. from: uid,
  37185. name: name,
  37186. seriesId: seriesModel.id
  37187. });
  37188. data.each(function (idx) {
  37189. toggleItemSelected(
  37190. data.getItemGraphicEl(idx),
  37191. data.getItemLayout(idx),
  37192. seriesModel.isSelected(data.getName(idx)),
  37193. selectedOffset,
  37194. hasAnimation
  37195. );
  37196. });
  37197. }
  37198. /**
  37199. * @param {module:zrender/graphic/Sector} el
  37200. * @param {Object} layout
  37201. * @param {boolean} isSelected
  37202. * @param {number} selectedOffset
  37203. * @param {boolean} hasAnimation
  37204. * @inner
  37205. */
  37206. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  37207. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37208. var dx = Math.cos(midAngle);
  37209. var dy = Math.sin(midAngle);
  37210. var offset = isSelected ? selectedOffset : 0;
  37211. var position = [dx * offset, dy * offset];
  37212. hasAnimation
  37213. // animateTo will stop revious animation like update transition
  37214. ? el.animate()
  37215. .when(200, {
  37216. position: position
  37217. })
  37218. .start('bounceOut')
  37219. : el.attr('position', position);
  37220. }
  37221. /**
  37222. * Piece of pie including Sector, Label, LabelLine
  37223. * @constructor
  37224. * @extends {module:zrender/graphic/Group}
  37225. */
  37226. function PiePiece(data, idx) {
  37227. Group.call(this);
  37228. var sector = new Sector({
  37229. z2: 2
  37230. });
  37231. var polyline = new Polyline();
  37232. var text = new Text();
  37233. this.add(sector);
  37234. this.add(polyline);
  37235. this.add(text);
  37236. this.updateData(data, idx, true);
  37237. }
  37238. var piePieceProto = PiePiece.prototype;
  37239. piePieceProto.updateData = function (data, idx, firstCreate) {
  37240. var sector = this.childAt(0);
  37241. var labelLine = this.childAt(1);
  37242. var labelText = this.childAt(2);
  37243. var seriesModel = data.hostModel;
  37244. var itemModel = data.getItemModel(idx);
  37245. var layout = data.getItemLayout(idx);
  37246. var sectorShape = extend({}, layout);
  37247. sectorShape.label = null;
  37248. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  37249. if (firstCreate) {
  37250. sector.setShape(sectorShape);
  37251. var animationType = seriesModel.getShallow('animationType');
  37252. if (animationType === 'scale') {
  37253. sector.shape.r = layout.r0;
  37254. initProps(sector, {
  37255. shape: {
  37256. r: layout.r
  37257. }
  37258. }, seriesModel, idx);
  37259. }
  37260. // Expansion
  37261. else {
  37262. sector.shape.endAngle = layout.startAngle;
  37263. updateProps(sector, {
  37264. shape: {
  37265. endAngle: layout.endAngle
  37266. }
  37267. }, seriesModel, idx);
  37268. }
  37269. }
  37270. else {
  37271. if (animationTypeUpdate === 'expansion') {
  37272. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  37273. sector.setShape(sectorShape);
  37274. }
  37275. else {
  37276. // Transition animation from the old shape
  37277. updateProps(sector, {
  37278. shape: sectorShape
  37279. }, seriesModel, idx);
  37280. }
  37281. }
  37282. // Update common style
  37283. var visualColor = data.getItemVisual(idx, 'color');
  37284. sector.useStyle(
  37285. defaults(
  37286. {
  37287. lineJoin: 'bevel',
  37288. fill: visualColor
  37289. },
  37290. itemModel.getModel('itemStyle').getItemStyle()
  37291. )
  37292. );
  37293. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  37294. var cursorStyle = itemModel.getShallow('cursor');
  37295. cursorStyle && sector.attr('cursor', cursorStyle);
  37296. // Toggle selected
  37297. toggleItemSelected(
  37298. this,
  37299. data.getItemLayout(idx),
  37300. seriesModel.isSelected(null, idx),
  37301. seriesModel.get('selectedOffset'),
  37302. seriesModel.get('animation')
  37303. );
  37304. // Label and text animation should be applied only for transition type animation when update
  37305. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  37306. this._updateLabel(data, idx, withAnimation);
  37307. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  37308. ? function (fromState, toState) {
  37309. if (toState === 'emphasis') {
  37310. labelLine.ignore = labelLine.hoverIgnore;
  37311. labelText.ignore = labelText.hoverIgnore;
  37312. // Sector may has animation of updating data. Force to move to the last frame
  37313. // Or it may stopped on the wrong shape
  37314. sector.stopAnimation(true);
  37315. sector.animateTo({
  37316. shape: {
  37317. r: layout.r + seriesModel.get('hoverOffset')
  37318. }
  37319. }, 300, 'elasticOut');
  37320. }
  37321. else {
  37322. labelLine.ignore = labelLine.normalIgnore;
  37323. labelText.ignore = labelText.normalIgnore;
  37324. sector.stopAnimation(true);
  37325. sector.animateTo({
  37326. shape: {
  37327. r: layout.r
  37328. }
  37329. }, 300, 'elasticOut');
  37330. }
  37331. }
  37332. : null;
  37333. setHoverStyle(this);
  37334. };
  37335. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  37336. var labelLine = this.childAt(1);
  37337. var labelText = this.childAt(2);
  37338. var seriesModel = data.hostModel;
  37339. var itemModel = data.getItemModel(idx);
  37340. var layout = data.getItemLayout(idx);
  37341. var labelLayout = layout.label;
  37342. var visualColor = data.getItemVisual(idx, 'color');
  37343. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  37344. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  37345. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  37346. return;
  37347. }
  37348. var targetLineShape = {
  37349. points: labelLayout.linePoints || [
  37350. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  37351. ]
  37352. };
  37353. var targetTextStyle = {
  37354. x: labelLayout.x,
  37355. y: labelLayout.y
  37356. };
  37357. if (withAnimation) {
  37358. updateProps(labelLine, {
  37359. shape: targetLineShape
  37360. }, seriesModel, idx);
  37361. updateProps(labelText, {
  37362. style: targetTextStyle
  37363. }, seriesModel, idx);
  37364. }
  37365. else {
  37366. labelLine.attr({
  37367. shape: targetLineShape
  37368. });
  37369. labelText.attr({
  37370. style: targetTextStyle
  37371. });
  37372. }
  37373. labelText.attr({
  37374. rotation: labelLayout.rotation,
  37375. origin: [labelLayout.x, labelLayout.y],
  37376. z2: 10
  37377. });
  37378. var labelModel = itemModel.getModel('label');
  37379. var labelHoverModel = itemModel.getModel('emphasis.label');
  37380. var labelLineModel = itemModel.getModel('labelLine');
  37381. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  37382. var visualColor = data.getItemVisual(idx, 'color');
  37383. setLabelStyle(
  37384. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  37385. {
  37386. labelFetcher: data.hostModel,
  37387. labelDataIndex: idx,
  37388. defaultText: labelLayout.text,
  37389. autoColor: visualColor,
  37390. useInsideStyle: !!labelLayout.inside
  37391. },
  37392. {
  37393. textAlign: labelLayout.textAlign,
  37394. textVerticalAlign: labelLayout.verticalAlign,
  37395. opacity: data.getItemVisual(idx, 'opacity')
  37396. }
  37397. );
  37398. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  37399. labelText.hoverIgnore = !labelHoverModel.get('show');
  37400. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  37401. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  37402. // Default use item visual color
  37403. labelLine.setStyle({
  37404. stroke: visualColor,
  37405. opacity: data.getItemVisual(idx, 'opacity')
  37406. });
  37407. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  37408. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  37409. var smooth = labelLineModel.get('smooth');
  37410. if (smooth && smooth === true) {
  37411. smooth = 0.4;
  37412. }
  37413. labelLine.setShape({
  37414. smooth: smooth
  37415. });
  37416. };
  37417. inherits(PiePiece, Group);
  37418. // Pie view
  37419. var PieView = Chart.extend({
  37420. type: 'pie',
  37421. init: function () {
  37422. var sectorGroup = new Group();
  37423. this._sectorGroup = sectorGroup;
  37424. },
  37425. render: function (seriesModel, ecModel, api, payload) {
  37426. if (payload && (payload.from === this.uid)) {
  37427. return;
  37428. }
  37429. var data = seriesModel.getData();
  37430. var oldData = this._data;
  37431. var group = this.group;
  37432. var hasAnimation = ecModel.get('animation');
  37433. var isFirstRender = !oldData;
  37434. var animationType = seriesModel.get('animationType');
  37435. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  37436. var onSectorClick = curry(
  37437. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  37438. );
  37439. var selectedMode = seriesModel.get('selectedMode');
  37440. data.diff(oldData)
  37441. .add(function (idx) {
  37442. var piePiece = new PiePiece(data, idx);
  37443. // Default expansion animation
  37444. if (isFirstRender && animationType !== 'scale') {
  37445. piePiece.eachChild(function (child) {
  37446. child.stopAnimation(true);
  37447. });
  37448. }
  37449. selectedMode && piePiece.on('click', onSectorClick);
  37450. data.setItemGraphicEl(idx, piePiece);
  37451. group.add(piePiece);
  37452. })
  37453. .update(function (newIdx, oldIdx) {
  37454. var piePiece = oldData.getItemGraphicEl(oldIdx);
  37455. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  37456. piePiece.eachChild(function (child) {
  37457. child.stopAnimation(true);
  37458. });
  37459. }
  37460. piePiece.updateData(data, newIdx);
  37461. piePiece.off('click');
  37462. selectedMode && piePiece.on('click', onSectorClick);
  37463. group.add(piePiece);
  37464. data.setItemGraphicEl(newIdx, piePiece);
  37465. })
  37466. .remove(function (idx) {
  37467. var piePiece = oldData.getItemGraphicEl(idx);
  37468. group.remove(piePiece);
  37469. })
  37470. .execute();
  37471. if (
  37472. hasAnimation && data.count() > 0
  37473. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  37474. ) {
  37475. var shape = data.getItemLayout(0);
  37476. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  37477. shape = data.getItemLayout(s);
  37478. }
  37479. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  37480. var removeClipPath = bind(group.removeClipPath, group);
  37481. group.setClipPath(this._createClipPath(
  37482. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  37483. ));
  37484. }
  37485. else {
  37486. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  37487. group.removeClipPath();
  37488. }
  37489. this._data = data;
  37490. },
  37491. dispose: function () {},
  37492. _createClipPath: function (
  37493. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  37494. ) {
  37495. var clipPath = new Sector({
  37496. shape: {
  37497. cx: cx,
  37498. cy: cy,
  37499. r0: 0,
  37500. r: r,
  37501. startAngle: startAngle,
  37502. endAngle: startAngle,
  37503. clockwise: clockwise
  37504. }
  37505. });
  37506. var initOrUpdate = isFirstRender ? initProps : updateProps;
  37507. initOrUpdate(clipPath, {
  37508. shape: {
  37509. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  37510. }
  37511. }, seriesModel, cb);
  37512. return clipPath;
  37513. },
  37514. /**
  37515. * @implement
  37516. */
  37517. containPoint: function (point, seriesModel) {
  37518. var data = seriesModel.getData();
  37519. var itemLayout = data.getItemLayout(0);
  37520. if (itemLayout) {
  37521. var dx = point[0] - itemLayout.cx;
  37522. var dy = point[1] - itemLayout.cy;
  37523. var radius = Math.sqrt(dx * dx + dy * dy);
  37524. return radius <= itemLayout.r && radius >= itemLayout.r0;
  37525. }
  37526. }
  37527. });
  37528. /*
  37529. * Licensed to the Apache Software Foundation (ASF) under one
  37530. * or more contributor license agreements. See the NOTICE file
  37531. * distributed with this work for additional information
  37532. * regarding copyright ownership. The ASF licenses this file
  37533. * to you under the Apache License, Version 2.0 (the
  37534. * "License"); you may not use this file except in compliance
  37535. * with the License. You may obtain a copy of the License at
  37536. *
  37537. * http://www.apache.org/licenses/LICENSE-2.0
  37538. *
  37539. * Unless required by applicable law or agreed to in writing,
  37540. * software distributed under the License is distributed on an
  37541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37542. * KIND, either express or implied. See the License for the
  37543. * specific language governing permissions and limitations
  37544. * under the License.
  37545. */
  37546. var createDataSelectAction = function (seriesType, actionInfos) {
  37547. each$1(actionInfos, function (actionInfo) {
  37548. actionInfo.update = 'updateView';
  37549. /**
  37550. * @payload
  37551. * @property {string} seriesName
  37552. * @property {string} name
  37553. */
  37554. registerAction(actionInfo, function (payload, ecModel) {
  37555. var selected = {};
  37556. ecModel.eachComponent(
  37557. {mainType: 'series', subType: seriesType, query: payload},
  37558. function (seriesModel) {
  37559. if (seriesModel[actionInfo.method]) {
  37560. seriesModel[actionInfo.method](
  37561. payload.name,
  37562. payload.dataIndex
  37563. );
  37564. }
  37565. var data = seriesModel.getData();
  37566. // Create selected map
  37567. data.each(function (idx) {
  37568. var name = data.getName(idx);
  37569. selected[name] = seriesModel.isSelected(name)
  37570. || false;
  37571. });
  37572. }
  37573. );
  37574. return {
  37575. name: payload.name,
  37576. selected: selected,
  37577. seriesId: payload.seriesId
  37578. };
  37579. });
  37580. });
  37581. };
  37582. /*
  37583. * Licensed to the Apache Software Foundation (ASF) under one
  37584. * or more contributor license agreements. See the NOTICE file
  37585. * distributed with this work for additional information
  37586. * regarding copyright ownership. The ASF licenses this file
  37587. * to you under the Apache License, Version 2.0 (the
  37588. * "License"); you may not use this file except in compliance
  37589. * with the License. You may obtain a copy of the License at
  37590. *
  37591. * http://www.apache.org/licenses/LICENSE-2.0
  37592. *
  37593. * Unless required by applicable law or agreed to in writing,
  37594. * software distributed under the License is distributed on an
  37595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37596. * KIND, either express or implied. See the License for the
  37597. * specific language governing permissions and limitations
  37598. * under the License.
  37599. */
  37600. // Pick color from palette for each data item.
  37601. // Applicable for charts that require applying color palette
  37602. // in data level (like pie, funnel, chord).
  37603. var dataColor = function (seriesType) {
  37604. return {
  37605. getTargetSeries: function (ecModel) {
  37606. // Pie and funnel may use diferrent scope
  37607. var paletteScope = {};
  37608. var seiresModelMap = createHashMap();
  37609. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37610. seriesModel.__paletteScope = paletteScope;
  37611. seiresModelMap.set(seriesModel.uid, seriesModel);
  37612. });
  37613. return seiresModelMap;
  37614. },
  37615. reset: function (seriesModel, ecModel) {
  37616. var dataAll = seriesModel.getRawData();
  37617. var idxMap = {};
  37618. var data = seriesModel.getData();
  37619. data.each(function (idx) {
  37620. var rawIdx = data.getRawIndex(idx);
  37621. idxMap[rawIdx] = idx;
  37622. });
  37623. dataAll.each(function (rawIdx) {
  37624. var filteredIdx = idxMap[rawIdx];
  37625. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37626. var singleDataColor = filteredIdx != null
  37627. && data.getItemVisual(filteredIdx, 'color', true);
  37628. var singleDataBorderColor = filteredIdx != null
  37629. && data.getItemVisual(filteredIdx, 'borderColor', true);
  37630. var itemModel;
  37631. if (!singleDataColor || !singleDataBorderColor) {
  37632. // FIXME Performance
  37633. itemModel = dataAll.getItemModel(rawIdx);
  37634. }
  37635. if (!singleDataColor) {
  37636. var color = itemModel.get('itemStyle.color')
  37637. || seriesModel.getColorFromPalette(
  37638. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37639. dataAll.count()
  37640. );
  37641. // Data is not filtered
  37642. if (filteredIdx != null) {
  37643. data.setItemVisual(filteredIdx, 'color', color);
  37644. }
  37645. }
  37646. if (!singleDataBorderColor) {
  37647. var borderColor = itemModel.get('itemStyle.borderColor');
  37648. // Data is not filtered
  37649. if (filteredIdx != null) {
  37650. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  37651. }
  37652. }
  37653. });
  37654. }
  37655. };
  37656. };
  37657. /*
  37658. * Licensed to the Apache Software Foundation (ASF) under one
  37659. * or more contributor license agreements. See the NOTICE file
  37660. * distributed with this work for additional information
  37661. * regarding copyright ownership. The ASF licenses this file
  37662. * to you under the Apache License, Version 2.0 (the
  37663. * "License"); you may not use this file except in compliance
  37664. * with the License. You may obtain a copy of the License at
  37665. *
  37666. * http://www.apache.org/licenses/LICENSE-2.0
  37667. *
  37668. * Unless required by applicable law or agreed to in writing,
  37669. * software distributed under the License is distributed on an
  37670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37671. * KIND, either express or implied. See the License for the
  37672. * specific language governing permissions and limitations
  37673. * under the License.
  37674. */
  37675. // FIXME emphasis label position is not same with normal label position
  37676. var RADIAN$1 = Math.PI / 180;
  37677. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  37678. list.sort(function (a, b) {
  37679. return a.y - b.y;
  37680. });
  37681. function shiftDown(start, end, delta, dir) {
  37682. for (var j = start; j < end; j++) {
  37683. if (list[j].y + delta > viewTop + viewHeight) {
  37684. break;
  37685. }
  37686. list[j].y += delta;
  37687. if (j > start
  37688. && j + 1 < end
  37689. && list[j + 1].y > list[j].y + list[j].height
  37690. ) {
  37691. shiftUp(j, delta / 2);
  37692. return;
  37693. }
  37694. }
  37695. shiftUp(end - 1, delta / 2);
  37696. }
  37697. function shiftUp(end, delta) {
  37698. for (var j = end; j >= 0; j--) {
  37699. if (list[j].y - delta < viewTop) {
  37700. break;
  37701. }
  37702. list[j].y -= delta;
  37703. if (j > 0
  37704. && list[j].y > list[j - 1].y + list[j - 1].height
  37705. ) {
  37706. break;
  37707. }
  37708. }
  37709. }
  37710. function changeX(list, isDownList, cx, cy, r, dir) {
  37711. var lastDeltaX = dir > 0
  37712. ? isDownList // right-side
  37713. ? Number.MAX_VALUE // down
  37714. : 0 // up
  37715. : isDownList // left-side
  37716. ? Number.MAX_VALUE // down
  37717. : 0; // up
  37718. for (var i = 0, l = list.length; i < l; i++) {
  37719. if (list[i].labelAlignTo !== 'none') {
  37720. continue;
  37721. }
  37722. var deltaY = Math.abs(list[i].y - cy);
  37723. var length = list[i].len;
  37724. var length2 = list[i].len2;
  37725. var deltaX = (deltaY < r + length)
  37726. ? Math.sqrt(
  37727. (r + length + length2) * (r + length + length2)
  37728. - deltaY * deltaY
  37729. )
  37730. : Math.abs(list[i].x - cx);
  37731. if (isDownList && deltaX >= lastDeltaX) {
  37732. // right-down, left-down
  37733. deltaX = lastDeltaX - 10;
  37734. }
  37735. if (!isDownList && deltaX <= lastDeltaX) {
  37736. // right-up, left-up
  37737. deltaX = lastDeltaX + 10;
  37738. }
  37739. list[i].x = cx + deltaX * dir;
  37740. lastDeltaX = deltaX;
  37741. }
  37742. }
  37743. var lastY = 0;
  37744. var delta;
  37745. var len = list.length;
  37746. var upList = [];
  37747. var downList = [];
  37748. for (var i = 0; i < len; i++) {
  37749. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  37750. var dx = list[i].x - farthestX;
  37751. list[i].linePoints[1][0] += dx;
  37752. list[i].x = farthestX;
  37753. }
  37754. delta = list[i].y - lastY;
  37755. if (delta < 0) {
  37756. shiftDown(i, len, -delta, dir);
  37757. }
  37758. lastY = list[i].y + list[i].height;
  37759. }
  37760. if (viewHeight - lastY < 0) {
  37761. shiftUp(len - 1, lastY - viewHeight);
  37762. }
  37763. for (var i = 0; i < len; i++) {
  37764. if (list[i].y >= cy) {
  37765. downList.push(list[i]);
  37766. }
  37767. else {
  37768. upList.push(list[i]);
  37769. }
  37770. }
  37771. changeX(upList, false, cx, cy, r, dir);
  37772. changeX(downList, true, cx, cy, r, dir);
  37773. }
  37774. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37775. var leftList = [];
  37776. var rightList = [];
  37777. var leftmostX = Number.MAX_VALUE;
  37778. var rightmostX = -Number.MAX_VALUE;
  37779. for (var i = 0; i < labelLayoutList.length; i++) {
  37780. if (isPositionCenter(labelLayoutList[i])) {
  37781. continue;
  37782. }
  37783. if (labelLayoutList[i].x < cx) {
  37784. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  37785. leftList.push(labelLayoutList[i]);
  37786. }
  37787. else {
  37788. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  37789. rightList.push(labelLayoutList[i]);
  37790. }
  37791. }
  37792. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  37793. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  37794. for (var i = 0; i < labelLayoutList.length; i++) {
  37795. var layout = labelLayoutList[i];
  37796. if (isPositionCenter(layout)) {
  37797. continue;
  37798. }
  37799. var linePoints = layout.linePoints;
  37800. if (linePoints) {
  37801. var isAlignToEdge = layout.labelAlignTo === 'edge';
  37802. var realTextWidth = layout.textRect.width;
  37803. var targetTextWidth;
  37804. if (isAlignToEdge) {
  37805. if (layout.x < cx) {
  37806. targetTextWidth = linePoints[2][0] - layout.labelDistance
  37807. - viewLeft - layout.labelMargin;
  37808. }
  37809. else {
  37810. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  37811. - linePoints[2][0] - layout.labelDistance;
  37812. }
  37813. }
  37814. else {
  37815. if (layout.x < cx) {
  37816. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  37817. }
  37818. else {
  37819. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  37820. }
  37821. }
  37822. if (targetTextWidth < layout.textRect.width) {
  37823. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  37824. if (layout.labelAlignTo === 'edge') {
  37825. realTextWidth = getWidth(layout.text, layout.font);
  37826. }
  37827. }
  37828. var dist = linePoints[1][0] - linePoints[2][0];
  37829. if (isAlignToEdge) {
  37830. if (layout.x < cx) {
  37831. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  37832. }
  37833. else {
  37834. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  37835. - realTextWidth - layout.labelDistance;
  37836. }
  37837. }
  37838. else {
  37839. if (layout.x < cx) {
  37840. linePoints[2][0] = layout.x + layout.labelDistance;
  37841. }
  37842. else {
  37843. linePoints[2][0] = layout.x - layout.labelDistance;
  37844. }
  37845. linePoints[1][0] = linePoints[2][0] + dist;
  37846. }
  37847. linePoints[1][1] = linePoints[2][1] = layout.y;
  37848. }
  37849. }
  37850. }
  37851. function isPositionCenter(layout) {
  37852. // Not change x for center label
  37853. return layout.position === 'center';
  37854. }
  37855. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37856. var data = seriesModel.getData();
  37857. var labelLayoutList = [];
  37858. var cx;
  37859. var cy;
  37860. var hasLabelRotate = false;
  37861. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  37862. data.each(function (idx) {
  37863. var layout = data.getItemLayout(idx);
  37864. var itemModel = data.getItemModel(idx);
  37865. var labelModel = itemModel.getModel('label');
  37866. // Use position in normal or emphasis
  37867. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  37868. var labelDistance = labelModel.get('distanceToLabelLine');
  37869. var labelAlignTo = labelModel.get('alignTo');
  37870. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  37871. var bleedMargin = labelModel.get('bleedMargin');
  37872. var font = labelModel.getFont();
  37873. var labelLineModel = itemModel.getModel('labelLine');
  37874. var labelLineLen = labelLineModel.get('length');
  37875. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  37876. var labelLineLen2 = labelLineModel.get('length2');
  37877. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  37878. if (layout.angle < minShowLabelRadian) {
  37879. return;
  37880. }
  37881. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37882. var dx = Math.cos(midAngle);
  37883. var dy = Math.sin(midAngle);
  37884. var textX;
  37885. var textY;
  37886. var linePoints;
  37887. var textAlign;
  37888. cx = layout.cx;
  37889. cy = layout.cy;
  37890. var text = seriesModel.getFormattedLabel(idx, 'normal')
  37891. || data.getName(idx);
  37892. var textRect = getBoundingRect(
  37893. text, font, textAlign, 'top'
  37894. );
  37895. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  37896. if (labelPosition === 'center') {
  37897. textX = layout.cx;
  37898. textY = layout.cy;
  37899. textAlign = 'center';
  37900. }
  37901. else {
  37902. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  37903. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  37904. textX = x1 + dx * 3;
  37905. textY = y1 + dy * 3;
  37906. if (!isLabelInside) {
  37907. // For roseType
  37908. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  37909. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  37910. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  37911. var y3 = y2;
  37912. if (labelAlignTo === 'edge') {
  37913. // Adjust textX because text align of edge is opposite
  37914. textX = dx < 0
  37915. ? viewLeft + labelMargin
  37916. : viewLeft + viewWidth - labelMargin;
  37917. }
  37918. else {
  37919. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  37920. }
  37921. textY = y3;
  37922. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  37923. }
  37924. textAlign = isLabelInside
  37925. ? 'center'
  37926. : (labelAlignTo === 'edge'
  37927. ? (dx > 0 ? 'right' : 'left')
  37928. : (dx > 0 ? 'left' : 'right'));
  37929. }
  37930. var labelRotate;
  37931. var rotate = labelModel.get('rotate');
  37932. if (typeof rotate === 'number') {
  37933. labelRotate = rotate * (Math.PI / 180);
  37934. }
  37935. else {
  37936. labelRotate = rotate
  37937. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  37938. : 0;
  37939. }
  37940. hasLabelRotate = !!labelRotate;
  37941. layout.label = {
  37942. x: textX,
  37943. y: textY,
  37944. position: labelPosition,
  37945. height: textRect.height,
  37946. len: labelLineLen,
  37947. len2: labelLineLen2,
  37948. linePoints: linePoints,
  37949. textAlign: textAlign,
  37950. verticalAlign: 'middle',
  37951. rotation: labelRotate,
  37952. inside: isLabelInside,
  37953. labelDistance: labelDistance,
  37954. labelAlignTo: labelAlignTo,
  37955. labelMargin:labelMargin,
  37956. bleedMargin: bleedMargin,
  37957. textRect: textRect,
  37958. text: text,
  37959. font: font
  37960. };
  37961. // Not layout the inside label
  37962. if (!isLabelInside) {
  37963. labelLayoutList.push(layout.label);
  37964. }
  37965. });
  37966. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  37967. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  37968. }
  37969. };
  37970. /*
  37971. * Licensed to the Apache Software Foundation (ASF) under one
  37972. * or more contributor license agreements. See the NOTICE file
  37973. * distributed with this work for additional information
  37974. * regarding copyright ownership. The ASF licenses this file
  37975. * to you under the Apache License, Version 2.0 (the
  37976. * "License"); you may not use this file except in compliance
  37977. * with the License. You may obtain a copy of the License at
  37978. *
  37979. * http://www.apache.org/licenses/LICENSE-2.0
  37980. *
  37981. * Unless required by applicable law or agreed to in writing,
  37982. * software distributed under the License is distributed on an
  37983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37984. * KIND, either express or implied. See the License for the
  37985. * specific language governing permissions and limitations
  37986. * under the License.
  37987. */
  37988. var PI2$4 = Math.PI * 2;
  37989. var RADIAN = Math.PI / 180;
  37990. function getViewRect(seriesModel, api) {
  37991. return getLayoutRect(
  37992. seriesModel.getBoxLayoutParams(), {
  37993. width: api.getWidth(),
  37994. height: api.getHeight()
  37995. }
  37996. );
  37997. }
  37998. var pieLayout = function (seriesType, ecModel, api, payload) {
  37999. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38000. var data = seriesModel.getData();
  38001. var valueDim = data.mapDimension('value');
  38002. var viewRect = getViewRect(seriesModel, api);
  38003. var center = seriesModel.get('center');
  38004. var radius = seriesModel.get('radius');
  38005. if (!isArray(radius)) {
  38006. radius = [0, radius];
  38007. }
  38008. if (!isArray(center)) {
  38009. center = [center, center];
  38010. }
  38011. var width = parsePercent$1(viewRect.width, api.getWidth());
  38012. var height = parsePercent$1(viewRect.height, api.getHeight());
  38013. var size = Math.min(width, height);
  38014. var cx = parsePercent$1(center[0], width) + viewRect.x;
  38015. var cy = parsePercent$1(center[1], height) + viewRect.y;
  38016. var r0 = parsePercent$1(radius[0], size / 2);
  38017. var r = parsePercent$1(radius[1], size / 2);
  38018. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  38019. var minAngle = seriesModel.get('minAngle') * RADIAN;
  38020. var validDataCount = 0;
  38021. data.each(valueDim, function (value) {
  38022. !isNaN(value) && validDataCount++;
  38023. });
  38024. var sum = data.getSum(valueDim);
  38025. // Sum may be 0
  38026. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  38027. var clockwise = seriesModel.get('clockwise');
  38028. var roseType = seriesModel.get('roseType');
  38029. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  38030. // [0...max]
  38031. var extent = data.getDataExtent(valueDim);
  38032. extent[0] = 0;
  38033. // In the case some sector angle is smaller than minAngle
  38034. var restAngle = PI2$4;
  38035. var valueSumLargerThanMinAngle = 0;
  38036. var currentAngle = startAngle;
  38037. var dir = clockwise ? 1 : -1;
  38038. data.each(valueDim, function (value, idx) {
  38039. var angle;
  38040. if (isNaN(value)) {
  38041. data.setItemLayout(idx, {
  38042. angle: NaN,
  38043. startAngle: NaN,
  38044. endAngle: NaN,
  38045. clockwise: clockwise,
  38046. cx: cx,
  38047. cy: cy,
  38048. r0: r0,
  38049. r: roseType
  38050. ? NaN
  38051. : r,
  38052. viewRect: viewRect
  38053. });
  38054. return;
  38055. }
  38056. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  38057. if (roseType !== 'area') {
  38058. angle = (sum === 0 && stillShowZeroSum)
  38059. ? unitRadian : (value * unitRadian);
  38060. }
  38061. else {
  38062. angle = PI2$4 / validDataCount;
  38063. }
  38064. if (angle < minAngle) {
  38065. angle = minAngle;
  38066. restAngle -= minAngle;
  38067. }
  38068. else {
  38069. valueSumLargerThanMinAngle += value;
  38070. }
  38071. var endAngle = currentAngle + dir * angle;
  38072. data.setItemLayout(idx, {
  38073. angle: angle,
  38074. startAngle: currentAngle,
  38075. endAngle: endAngle,
  38076. clockwise: clockwise,
  38077. cx: cx,
  38078. cy: cy,
  38079. r0: r0,
  38080. r: roseType
  38081. ? linearMap(value, extent, [r0, r])
  38082. : r,
  38083. viewRect: viewRect
  38084. });
  38085. currentAngle = endAngle;
  38086. });
  38087. // Some sector is constrained by minAngle
  38088. // Rest sectors needs recalculate angle
  38089. if (restAngle < PI2$4 && validDataCount) {
  38090. // Average the angle if rest angle is not enough after all angles is
  38091. // Constrained by minAngle
  38092. if (restAngle <= 1e-3) {
  38093. var angle = PI2$4 / validDataCount;
  38094. data.each(valueDim, function (value, idx) {
  38095. if (!isNaN(value)) {
  38096. var layout = data.getItemLayout(idx);
  38097. layout.angle = angle;
  38098. layout.startAngle = startAngle + dir * idx * angle;
  38099. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  38100. }
  38101. });
  38102. }
  38103. else {
  38104. unitRadian = restAngle / valueSumLargerThanMinAngle;
  38105. currentAngle = startAngle;
  38106. data.each(valueDim, function (value, idx) {
  38107. if (!isNaN(value)) {
  38108. var layout = data.getItemLayout(idx);
  38109. var angle = layout.angle === minAngle
  38110. ? minAngle : value * unitRadian;
  38111. layout.startAngle = currentAngle;
  38112. layout.endAngle = currentAngle + dir * angle;
  38113. currentAngle += dir * angle;
  38114. }
  38115. });
  38116. }
  38117. }
  38118. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  38119. });
  38120. };
  38121. /*
  38122. * Licensed to the Apache Software Foundation (ASF) under one
  38123. * or more contributor license agreements. See the NOTICE file
  38124. * distributed with this work for additional information
  38125. * regarding copyright ownership. The ASF licenses this file
  38126. * to you under the Apache License, Version 2.0 (the
  38127. * "License"); you may not use this file except in compliance
  38128. * with the License. You may obtain a copy of the License at
  38129. *
  38130. * http://www.apache.org/licenses/LICENSE-2.0
  38131. *
  38132. * Unless required by applicable law or agreed to in writing,
  38133. * software distributed under the License is distributed on an
  38134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38135. * KIND, either express or implied. See the License for the
  38136. * specific language governing permissions and limitations
  38137. * under the License.
  38138. */
  38139. var dataFilter = function (seriesType) {
  38140. return {
  38141. seriesType: seriesType,
  38142. reset: function (seriesModel, ecModel) {
  38143. var legendModels = ecModel.findComponents({
  38144. mainType: 'legend'
  38145. });
  38146. if (!legendModels || !legendModels.length) {
  38147. return;
  38148. }
  38149. var data = seriesModel.getData();
  38150. data.filterSelf(function (idx) {
  38151. var name = data.getName(idx);
  38152. // If in any legend component the status is not selected.
  38153. for (var i = 0; i < legendModels.length; i++) {
  38154. if (!legendModels[i].isSelected(name)) {
  38155. return false;
  38156. }
  38157. }
  38158. return true;
  38159. });
  38160. }
  38161. };
  38162. };
  38163. /*
  38164. * Licensed to the Apache Software Foundation (ASF) under one
  38165. * or more contributor license agreements. See the NOTICE file
  38166. * distributed with this work for additional information
  38167. * regarding copyright ownership. The ASF licenses this file
  38168. * to you under the Apache License, Version 2.0 (the
  38169. * "License"); you may not use this file except in compliance
  38170. * with the License. You may obtain a copy of the License at
  38171. *
  38172. * http://www.apache.org/licenses/LICENSE-2.0
  38173. *
  38174. * Unless required by applicable law or agreed to in writing,
  38175. * software distributed under the License is distributed on an
  38176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38177. * KIND, either express or implied. See the License for the
  38178. * specific language governing permissions and limitations
  38179. * under the License.
  38180. */
  38181. createDataSelectAction('pie', [{
  38182. type: 'pieToggleSelect',
  38183. event: 'pieselectchanged',
  38184. method: 'toggleSelected'
  38185. }, {
  38186. type: 'pieSelect',
  38187. event: 'pieselected',
  38188. method: 'select'
  38189. }, {
  38190. type: 'pieUnSelect',
  38191. event: 'pieunselected',
  38192. method: 'unSelect'
  38193. }]);
  38194. registerVisual(dataColor('pie'));
  38195. registerLayout(curry(pieLayout, 'pie'));
  38196. registerProcessor(dataFilter('pie'));
  38197. /*
  38198. * Licensed to the Apache Software Foundation (ASF) under one
  38199. * or more contributor license agreements. See the NOTICE file
  38200. * distributed with this work for additional information
  38201. * regarding copyright ownership. The ASF licenses this file
  38202. * to you under the Apache License, Version 2.0 (the
  38203. * "License"); you may not use this file except in compliance
  38204. * with the License. You may obtain a copy of the License at
  38205. *
  38206. * http://www.apache.org/licenses/LICENSE-2.0
  38207. *
  38208. * Unless required by applicable law or agreed to in writing,
  38209. * software distributed under the License is distributed on an
  38210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38211. * KIND, either express or implied. See the License for the
  38212. * specific language governing permissions and limitations
  38213. * under the License.
  38214. */
  38215. exports.version = version;
  38216. exports.dependencies = dependencies;
  38217. exports.PRIORITY = PRIORITY;
  38218. exports.init = init;
  38219. exports.connect = connect;
  38220. exports.disConnect = disConnect;
  38221. exports.disconnect = disconnect;
  38222. exports.dispose = dispose;
  38223. exports.getInstanceByDom = getInstanceByDom;
  38224. exports.getInstanceById = getInstanceById;
  38225. exports.registerTheme = registerTheme;
  38226. exports.registerPreprocessor = registerPreprocessor;
  38227. exports.registerProcessor = registerProcessor;
  38228. exports.registerPostUpdate = registerPostUpdate;
  38229. exports.registerAction = registerAction;
  38230. exports.registerCoordinateSystem = registerCoordinateSystem;
  38231. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  38232. exports.registerLayout = registerLayout;
  38233. exports.registerVisual = registerVisual;
  38234. exports.registerLoading = registerLoading;
  38235. exports.extendComponentModel = extendComponentModel;
  38236. exports.extendComponentView = extendComponentView;
  38237. exports.extendSeriesModel = extendSeriesModel;
  38238. exports.extendChartView = extendChartView;
  38239. exports.setCanvasCreator = setCanvasCreator;
  38240. exports.registerMap = registerMap;
  38241. exports.getMap = getMap;
  38242. exports.dataTool = dataTool;
  38243. })));