echarts.simple.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324
  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. // Find if there is draggable in the ancestor
  1050. while (draggingTarget && !draggingTarget.draggable) {
  1051. draggingTarget = draggingTarget.parent;
  1052. }
  1053. if (draggingTarget) {
  1054. this._draggingTarget = draggingTarget;
  1055. draggingTarget.dragging = true;
  1056. this._x = e.offsetX;
  1057. this._y = e.offsetY;
  1058. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1059. }
  1060. },
  1061. _drag: function (e) {
  1062. var draggingTarget = this._draggingTarget;
  1063. if (draggingTarget) {
  1064. var x = e.offsetX;
  1065. var y = e.offsetY;
  1066. var dx = x - this._x;
  1067. var dy = y - this._y;
  1068. this._x = x;
  1069. this._y = y;
  1070. draggingTarget.drift(dx, dy, e);
  1071. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1072. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1073. var lastDropTarget = this._dropTarget;
  1074. this._dropTarget = dropTarget;
  1075. if (draggingTarget !== dropTarget) {
  1076. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1077. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1078. }
  1079. if (dropTarget && dropTarget !== lastDropTarget) {
  1080. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1081. }
  1082. }
  1083. }
  1084. },
  1085. _dragEnd: function (e) {
  1086. var draggingTarget = this._draggingTarget;
  1087. if (draggingTarget) {
  1088. draggingTarget.dragging = false;
  1089. }
  1090. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1091. if (this._dropTarget) {
  1092. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1093. }
  1094. this._draggingTarget = null;
  1095. this._dropTarget = null;
  1096. }
  1097. };
  1098. function param(target, e) {
  1099. return {target: target, topTarget: e && e.topTarget};
  1100. }
  1101. /**
  1102. * Event Mixin
  1103. * @module zrender/mixin/Eventful
  1104. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1105. * pissang (https://www.github.com/pissang)
  1106. */
  1107. var arrySlice = Array.prototype.slice;
  1108. /**
  1109. * Event dispatcher.
  1110. *
  1111. * @alias module:zrender/mixin/Eventful
  1112. * @constructor
  1113. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1114. * `eventProcessor.xxx` called.
  1115. * @param {Function} [eventProcessor.normalizeQuery]
  1116. * param: {string|Object} Raw query.
  1117. * return: {string|Object} Normalized query.
  1118. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1119. * if it returns `true`.
  1120. * param: {string} eventType
  1121. * param: {string|Object} query
  1122. * return: {boolean}
  1123. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1124. * param: {string} eventType
  1125. */
  1126. var Eventful = function (eventProcessor) {
  1127. this._$handlers = {};
  1128. this._$eventProcessor = eventProcessor;
  1129. };
  1130. Eventful.prototype = {
  1131. constructor: Eventful,
  1132. /**
  1133. * The handler can only be triggered once, then removed.
  1134. *
  1135. * @param {string} event The event name.
  1136. * @param {string|Object} [query] Condition used on event filter.
  1137. * @param {Function} handler The event handler.
  1138. * @param {Object} context
  1139. */
  1140. one: function (event, query, handler, context) {
  1141. return on(this, event, query, handler, context, true);
  1142. },
  1143. /**
  1144. * Bind a handler.
  1145. *
  1146. * @param {string} event The event name.
  1147. * @param {string|Object} [query] Condition used on event filter.
  1148. * @param {Function} handler The event handler.
  1149. * @param {Object} [context]
  1150. */
  1151. on: function (event, query, handler, context) {
  1152. return on(this, event, query, handler, context, false);
  1153. },
  1154. /**
  1155. * Whether any handler has bound.
  1156. *
  1157. * @param {string} event
  1158. * @return {boolean}
  1159. */
  1160. isSilent: function (event) {
  1161. var _h = this._$handlers;
  1162. return !_h[event] || !_h[event].length;
  1163. },
  1164. /**
  1165. * Unbind a event.
  1166. *
  1167. * @param {string} [event] The event name.
  1168. * If no `event` input, "off" all listeners.
  1169. * @param {Function} [handler] The event handler.
  1170. * If no `handler` input, "off" all listeners of the `event`.
  1171. */
  1172. off: function (event, handler) {
  1173. var _h = this._$handlers;
  1174. if (!event) {
  1175. this._$handlers = {};
  1176. return this;
  1177. }
  1178. if (handler) {
  1179. if (_h[event]) {
  1180. var newList = [];
  1181. for (var i = 0, l = _h[event].length; i < l; i++) {
  1182. if (_h[event][i].h !== handler) {
  1183. newList.push(_h[event][i]);
  1184. }
  1185. }
  1186. _h[event] = newList;
  1187. }
  1188. if (_h[event] && _h[event].length === 0) {
  1189. delete _h[event];
  1190. }
  1191. }
  1192. else {
  1193. delete _h[event];
  1194. }
  1195. return this;
  1196. },
  1197. /**
  1198. * Dispatch a event.
  1199. *
  1200. * @param {string} type The event name.
  1201. */
  1202. trigger: function (type) {
  1203. var _h = this._$handlers[type];
  1204. var eventProcessor = this._$eventProcessor;
  1205. if (_h) {
  1206. var args = arguments;
  1207. var argLen = args.length;
  1208. if (argLen > 3) {
  1209. args = arrySlice.call(args, 1);
  1210. }
  1211. var len = _h.length;
  1212. for (var i = 0; i < len;) {
  1213. var hItem = _h[i];
  1214. if (eventProcessor
  1215. && eventProcessor.filter
  1216. && hItem.query != null
  1217. && !eventProcessor.filter(type, hItem.query)
  1218. ) {
  1219. i++;
  1220. continue;
  1221. }
  1222. // Optimize advise from backbone
  1223. switch (argLen) {
  1224. case 1:
  1225. hItem.h.call(hItem.ctx);
  1226. break;
  1227. case 2:
  1228. hItem.h.call(hItem.ctx, args[1]);
  1229. break;
  1230. case 3:
  1231. hItem.h.call(hItem.ctx, args[1], args[2]);
  1232. break;
  1233. default:
  1234. // have more than 2 given arguments
  1235. hItem.h.apply(hItem.ctx, args);
  1236. break;
  1237. }
  1238. if (hItem.one) {
  1239. _h.splice(i, 1);
  1240. len--;
  1241. }
  1242. else {
  1243. i++;
  1244. }
  1245. }
  1246. }
  1247. eventProcessor && eventProcessor.afterTrigger
  1248. && eventProcessor.afterTrigger(type);
  1249. return this;
  1250. },
  1251. /**
  1252. * Dispatch a event with context, which is specified at the last parameter.
  1253. *
  1254. * @param {string} type The event name.
  1255. */
  1256. triggerWithContext: function (type) {
  1257. var _h = this._$handlers[type];
  1258. var eventProcessor = this._$eventProcessor;
  1259. if (_h) {
  1260. var args = arguments;
  1261. var argLen = args.length;
  1262. if (argLen > 4) {
  1263. args = arrySlice.call(args, 1, args.length - 1);
  1264. }
  1265. var ctx = args[args.length - 1];
  1266. var len = _h.length;
  1267. for (var i = 0; i < len;) {
  1268. var hItem = _h[i];
  1269. if (eventProcessor
  1270. && eventProcessor.filter
  1271. && hItem.query != null
  1272. && !eventProcessor.filter(type, hItem.query)
  1273. ) {
  1274. i++;
  1275. continue;
  1276. }
  1277. // Optimize advise from backbone
  1278. switch (argLen) {
  1279. case 1:
  1280. hItem.h.call(ctx);
  1281. break;
  1282. case 2:
  1283. hItem.h.call(ctx, args[1]);
  1284. break;
  1285. case 3:
  1286. hItem.h.call(ctx, args[1], args[2]);
  1287. break;
  1288. default:
  1289. // have more than 2 given arguments
  1290. hItem.h.apply(ctx, args);
  1291. break;
  1292. }
  1293. if (hItem.one) {
  1294. _h.splice(i, 1);
  1295. len--;
  1296. }
  1297. else {
  1298. i++;
  1299. }
  1300. }
  1301. }
  1302. eventProcessor && eventProcessor.afterTrigger
  1303. && eventProcessor.afterTrigger(type);
  1304. return this;
  1305. }
  1306. };
  1307. function normalizeQuery(host, query) {
  1308. var eventProcessor = host._$eventProcessor;
  1309. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1310. query = eventProcessor.normalizeQuery(query);
  1311. }
  1312. return query;
  1313. }
  1314. function on(eventful, event, query, handler, context, isOnce) {
  1315. var _h = eventful._$handlers;
  1316. if (typeof query === 'function') {
  1317. context = handler;
  1318. handler = query;
  1319. query = null;
  1320. }
  1321. if (!handler || !event) {
  1322. return eventful;
  1323. }
  1324. query = normalizeQuery(eventful, query);
  1325. if (!_h[event]) {
  1326. _h[event] = [];
  1327. }
  1328. for (var i = 0; i < _h[event].length; i++) {
  1329. if (_h[event][i].h === handler) {
  1330. return eventful;
  1331. }
  1332. }
  1333. var wrap = {
  1334. h: handler,
  1335. one: isOnce,
  1336. query: query,
  1337. ctx: context || eventful,
  1338. // FIXME
  1339. // Do not publish this feature util it is proved that it makes sense.
  1340. callAtLast: handler.zrEventfulCallAtLast
  1341. };
  1342. var lastIndex = _h[event].length - 1;
  1343. var lastWrap = _h[event][lastIndex];
  1344. (lastWrap && lastWrap.callAtLast)
  1345. ? _h[event].splice(lastIndex, 0, wrap)
  1346. : _h[event].push(wrap);
  1347. return eventful;
  1348. }
  1349. /**
  1350. * The algoritm is learnt from
  1351. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1352. * And we made some optimization for matrix inversion.
  1353. * Other similar approaches:
  1354. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1355. */
  1356. var LN2 = Math.log(2);
  1357. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1358. var cacheKey = rowMask + '-' + colMask;
  1359. var fullRank = rows.length;
  1360. if (detCache.hasOwnProperty(cacheKey)) {
  1361. return detCache[cacheKey];
  1362. }
  1363. if (rank === 1) {
  1364. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1365. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1366. return rows[rowStart][colStart];
  1367. }
  1368. var subRowMask = rowMask | (1 << rowStart);
  1369. var subRowStart = rowStart + 1;
  1370. while (rowMask & (1 << subRowStart)) {
  1371. subRowStart++;
  1372. }
  1373. var sum = 0;
  1374. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1375. var colTag = 1 << j;
  1376. if (!(colTag & colMask)) {
  1377. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1378. // det(subMatrix(0, j))
  1379. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1380. colLocalIdx++;
  1381. }
  1382. }
  1383. detCache[cacheKey] = sum;
  1384. return sum;
  1385. }
  1386. /**
  1387. * Usage:
  1388. * ```js
  1389. * var transformer = buildTransformer(
  1390. * [10, 44, 100, 44, 100, 300, 10, 300],
  1391. * [50, 54, 130, 14, 140, 330, 14, 220]
  1392. * );
  1393. * var out = [];
  1394. * transformer && transformer([11, 33], out);
  1395. * ```
  1396. *
  1397. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1398. *
  1399. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1400. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1401. * @return {Function} transformer If fail, return null/undefined.
  1402. */
  1403. function buildTransformer(src, dest) {
  1404. var mA = [
  1405. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1406. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1407. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1408. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1409. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1410. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1411. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1412. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1413. ];
  1414. var detCache = {};
  1415. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1416. if (det === 0) {
  1417. // can not make transformer when and only when
  1418. // any three of the markers are collinear.
  1419. return;
  1420. }
  1421. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1422. var vh = [];
  1423. for (var i = 0; i < 8; i++) {
  1424. for (var j = 0; j < 8; j++) {
  1425. vh[j] == null && (vh[j] = 0);
  1426. vh[j] += ((i + j) % 2 ? -1 : 1)
  1427. // det(subMatrix(i, j))
  1428. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1429. / det * dest[i];
  1430. }
  1431. }
  1432. return function (out, srcPointX, srcPointY) {
  1433. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1434. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1435. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1436. };
  1437. }
  1438. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1439. /**
  1440. * Transform "local coord" from `elFrom` to `elTarget`.
  1441. * "local coord": the coord based on the input `el`. The origin point is at
  1442. * the position of "left: 0; top: 0;" in the `el`.
  1443. *
  1444. * Support when CSS transform is used.
  1445. *
  1446. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1447. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1448. * to locate the element.
  1449. *
  1450. * For example, this code below positions a child of `document.body` on the event
  1451. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1452. * ```js
  1453. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1454. * if (!eqNaN(out[0])) {
  1455. * // Then locate the tip element on the event point.
  1456. * var tipEl = document.createElement('div');
  1457. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1458. * document.body.appendChild(tipEl);
  1459. * }
  1460. * ```
  1461. *
  1462. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1463. *
  1464. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1465. * If can not transform, `out` will not be modified but return `false`.
  1466. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1467. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1468. * @param {number} inX
  1469. * @param {number} inY
  1470. * @return {boolean} Whether transform successfully.
  1471. */
  1472. /**
  1473. * Transform between a "viewport coord" and a "local coord".
  1474. * "viewport coord": the coord based on the left-top corner of the viewport
  1475. * of the browser.
  1476. * "local coord": the coord based on the input `el`. The origin point is at
  1477. * the position of "left: 0; top: 0;" in the `el`.
  1478. *
  1479. * Support the case when CSS transform is used on el.
  1480. *
  1481. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1482. * it represents "local coord", otherwise "vireport coord".
  1483. * If can not transform, `out` will not be modified but return `false`.
  1484. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1485. * @param {number} inX If `inverse: false`,
  1486. * it represents "vireport coord", otherwise "local coord".
  1487. * @param {number} inY If `inverse: false`,
  1488. * it represents "vireport coord", otherwise "local coord".
  1489. * @param {boolean} [inverse=false]
  1490. * `true`: from "viewport coord" to "local coord".
  1491. * `false`: from "local coord" to "viewport coord".
  1492. * @return {boolean} Whether transform successfully.
  1493. */
  1494. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1495. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1496. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1497. var markers = prepareCoordMarkers(el, saved);
  1498. var transformer = preparePointerTransformer(markers, saved, inverse);
  1499. if (transformer) {
  1500. transformer(out, inX, inY);
  1501. return true;
  1502. }
  1503. }
  1504. return false;
  1505. }
  1506. function prepareCoordMarkers(el, saved) {
  1507. var markers = saved.markers;
  1508. if (markers) {
  1509. return markers;
  1510. }
  1511. markers = saved.markers = [];
  1512. var propLR = ['left', 'right'];
  1513. var propTB = ['top', 'bottom'];
  1514. for (var i = 0; i < 4; i++) {
  1515. var marker = document.createElement('div');
  1516. var stl = marker.style;
  1517. var idxLR = i % 2;
  1518. var idxTB = (i >> 1) % 2;
  1519. stl.cssText = [
  1520. 'position: absolute',
  1521. 'visibility: hidden',
  1522. 'padding: 0',
  1523. 'margin: 0',
  1524. 'border-width: 0',
  1525. 'user-select: none',
  1526. 'width:0',
  1527. 'height:0',
  1528. // 'width: 5px',
  1529. // 'height: 5px',
  1530. propLR[idxLR] + ':0',
  1531. propTB[idxTB] + ':0',
  1532. propLR[1 - idxLR] + ':auto',
  1533. propTB[1 - idxTB] + ':auto',
  1534. ''
  1535. ].join('!important;');
  1536. el.appendChild(marker);
  1537. markers.push(marker);
  1538. }
  1539. return markers;
  1540. }
  1541. function preparePointerTransformer(markers, saved, inverse) {
  1542. var transformerName = inverse ? 'invTrans' : 'trans';
  1543. var transformer = saved[transformerName];
  1544. var oldSrcCoords = saved.srcCoords;
  1545. var oldCoordTheSame = true;
  1546. var srcCoords = [];
  1547. var destCoords = [];
  1548. for (var i = 0; i < 4; i++) {
  1549. var rect = markers[i].getBoundingClientRect();
  1550. var ii = 2 * i;
  1551. var x = rect.left;
  1552. var y = rect.top;
  1553. srcCoords.push(x, y);
  1554. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1555. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1556. }
  1557. // Cache to avoid time consuming of `buildTransformer`.
  1558. return (oldCoordTheSame && transformer)
  1559. ? transformer
  1560. : (
  1561. saved.srcCoords = srcCoords,
  1562. saved[transformerName] = inverse
  1563. ? buildTransformer(destCoords, srcCoords)
  1564. : buildTransformer(srcCoords, destCoords)
  1565. );
  1566. }
  1567. function isCanvasEl(el) {
  1568. return el.nodeName.toUpperCase() === 'CANVAS';
  1569. }
  1570. /**
  1571. * Utilities for mouse or touch events.
  1572. */
  1573. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1574. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1575. var _calcOut = [];
  1576. /**
  1577. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1578. * the input `el`.
  1579. * CSS transform (2D & 3D) is supported.
  1580. *
  1581. * The strategy to fetch the coords:
  1582. * + If `calculate` is not set as `true`, users of this method should
  1583. * ensure that `el` is the same or the same size & location as `e.target`.
  1584. * Otherwise the result coords are probably not expected. Because we
  1585. * firstly try to get coords from e.offsetX/e.offsetY.
  1586. * + If `calculate` is set as `true`, the input `el` can be any element
  1587. * and we force to calculate the coords based on `el`.
  1588. * + The input `el` should be positionable (not position:static).
  1589. *
  1590. * The force `calculate` can be used in case like:
  1591. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1592. *
  1593. * @param {HTMLElement} el DOM element.
  1594. * @param {Event} e Mouse event or touch event.
  1595. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1596. * @param {boolean} [calculate=false] Whether to force calculate
  1597. * the coordinates but not use ones provided by browser.
  1598. */
  1599. function clientToLocal(el, e, out, calculate) {
  1600. out = out || {};
  1601. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1602. // to the padding edge of the target element. The only browser using this convention
  1603. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1604. // not support the properties.
  1605. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1606. // In zr painter.dom, padding edge equals to border edge.
  1607. if (calculate || !env$1.canvasSupported) {
  1608. calculateZrXY(el, e, out);
  1609. }
  1610. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1611. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1612. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1613. // zoom-factor, overflow / opacity layers, transforms ...)
  1614. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1615. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1616. // BTW3, In ff, offsetX/offsetY is always 0.
  1617. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1618. out.zrX = e.layerX;
  1619. out.zrY = e.layerY;
  1620. }
  1621. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1622. else if (e.offsetX != null) {
  1623. out.zrX = e.offsetX;
  1624. out.zrY = e.offsetY;
  1625. }
  1626. // For some other device, e.g., IOS safari.
  1627. else {
  1628. calculateZrXY(el, e, out);
  1629. }
  1630. return out;
  1631. }
  1632. function calculateZrXY(el, e, out) {
  1633. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1634. if (env$1.domSupported && el.getBoundingClientRect) {
  1635. var ex = e.clientX;
  1636. var ey = e.clientY;
  1637. if (isCanvasEl(el)) {
  1638. // Original approach, which do not support CSS transform.
  1639. // marker can not be locationed in a canvas container
  1640. // (getBoundingClientRect is always 0). We do not support
  1641. // that input a pre-created canvas to zr while using css
  1642. // transform in iOS.
  1643. var box = el.getBoundingClientRect();
  1644. out.zrX = ex - box.left;
  1645. out.zrY = ey - box.top;
  1646. return;
  1647. }
  1648. else {
  1649. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1650. out.zrX = _calcOut[0];
  1651. out.zrY = _calcOut[1];
  1652. return;
  1653. }
  1654. }
  1655. }
  1656. out.zrX = out.zrY = 0;
  1657. }
  1658. /**
  1659. * Find native event compat for legency IE.
  1660. * Should be called at the begining of a native event listener.
  1661. *
  1662. * @param {Event} [e] Mouse event or touch event or pointer event.
  1663. * For lagency IE, we use `window.event` is used.
  1664. * @return {Event} The native event.
  1665. */
  1666. function getNativeEvent(e) {
  1667. return e || window.event;
  1668. }
  1669. /**
  1670. * Normalize the coordinates of the input event.
  1671. *
  1672. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1673. * the input `el`.
  1674. * Get `e.zrDelta` if using mouse wheel.
  1675. * Get `e.which`, see the comment inside this function.
  1676. *
  1677. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1678. *
  1679. * Notice: see comments in `clientToLocal`. check the relationship
  1680. * between the result coords and the parameters `el` and `calculate`.
  1681. *
  1682. * @param {HTMLElement} el DOM element.
  1683. * @param {Event} [e] See `getNativeEvent`.
  1684. * @param {boolean} [calculate=false] Whether to force calculate
  1685. * the coordinates but not use ones provided by browser.
  1686. * @return {UIEvent} The normalized native UIEvent.
  1687. */
  1688. function normalizeEvent(el, e, calculate) {
  1689. e = getNativeEvent(e);
  1690. if (e.zrX != null) {
  1691. return e;
  1692. }
  1693. var eventType = e.type;
  1694. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1695. if (!isTouch) {
  1696. clientToLocal(el, e, e, calculate);
  1697. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1698. }
  1699. else {
  1700. var touch = eventType !== 'touchend'
  1701. ? e.targetTouches[0]
  1702. : e.changedTouches[0];
  1703. touch && clientToLocal(el, touch, e, calculate);
  1704. }
  1705. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1706. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1707. // If e.which has been defined, it may be readonly,
  1708. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1709. var button = e.button;
  1710. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1711. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1712. }
  1713. // [Caution]: `e.which` from browser is not always reliable. For example,
  1714. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1715. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1716. // `mousedown (pointerdown)` is the same as Chrome does.
  1717. return e;
  1718. }
  1719. /**
  1720. * @param {HTMLElement} el
  1721. * @param {string} name
  1722. * @param {Function} handler
  1723. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1724. * @param {boolean} [opt.capture=false]
  1725. * @param {boolean} [opt.passive=false]
  1726. */
  1727. function addEventListener(el, name, handler, opt) {
  1728. if (isDomLevel2) {
  1729. // Reproduct the console warning:
  1730. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1731. // Consider marking event handler as 'passive' to make the page more responsive.
  1732. // Just set console log level: verbose in chrome dev tool.
  1733. // then the warning log will be printed when addEventListener called.
  1734. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1735. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1736. // listener delegate all of the upper events of element. Some of those events need
  1737. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1738. // Before passive can be adopted, these issues should be considered:
  1739. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1740. // passive or not.
  1741. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1742. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1743. // compatibility should be handled.
  1744. // var opts = (env.passiveSupported && name === 'mousewheel')
  1745. // ? {passive: true}
  1746. // // By default, the third param of el.addEventListener is `capture: false`.
  1747. // : void 0;
  1748. // el.addEventListener(name, handler /* , opts */);
  1749. el.addEventListener(name, handler, opt);
  1750. }
  1751. else {
  1752. // For simplicity, do not implement `setCapture` for IE9-.
  1753. el.attachEvent('on' + name, handler);
  1754. }
  1755. }
  1756. /**
  1757. * Parameter are the same as `addEventListener`.
  1758. *
  1759. * Notice that if a listener is registered twice, one with capture and one without,
  1760. * remove each one separately. Removal of a capturing listener does not affect a
  1761. * non-capturing version of the same listener, and vice versa.
  1762. */
  1763. function removeEventListener(el, name, handler, opt) {
  1764. if (isDomLevel2) {
  1765. el.removeEventListener(name, handler, opt);
  1766. }
  1767. else {
  1768. el.detachEvent('on' + name, handler);
  1769. }
  1770. }
  1771. /**
  1772. * preventDefault and stopPropagation.
  1773. * Notice: do not use this method in zrender. It can only be
  1774. * used by upper applications if necessary.
  1775. *
  1776. * @param {Event} e A mouse or touch event.
  1777. */
  1778. var stop = isDomLevel2
  1779. ? function (e) {
  1780. e.preventDefault();
  1781. e.stopPropagation();
  1782. e.cancelBubble = true;
  1783. }
  1784. : function (e) {
  1785. e.returnValue = false;
  1786. e.cancelBubble = true;
  1787. };
  1788. /**
  1789. * This method only works for mouseup and mousedown. The functionality is restricted
  1790. * for fault tolerance, See the `e.which` compatibility above.
  1791. *
  1792. * @param {MouseEvent} e
  1793. * @return {boolean}
  1794. */
  1795. /**
  1796. * To be removed.
  1797. * @deprecated
  1798. */
  1799. /**
  1800. * Only implements needed gestures for mobile.
  1801. */
  1802. var GestureMgr = function () {
  1803. /**
  1804. * @private
  1805. * @type {Array.<Object>}
  1806. */
  1807. this._track = [];
  1808. };
  1809. GestureMgr.prototype = {
  1810. constructor: GestureMgr,
  1811. recognize: function (event, target, root) {
  1812. this._doTrack(event, target, root);
  1813. return this._recognize(event);
  1814. },
  1815. clear: function () {
  1816. this._track.length = 0;
  1817. return this;
  1818. },
  1819. _doTrack: function (event, target, root) {
  1820. var touches = event.touches;
  1821. if (!touches) {
  1822. return;
  1823. }
  1824. var trackItem = {
  1825. points: [],
  1826. touches: [],
  1827. target: target,
  1828. event: event
  1829. };
  1830. for (var i = 0, len = touches.length; i < len; i++) {
  1831. var touch = touches[i];
  1832. var pos = clientToLocal(root, touch, {});
  1833. trackItem.points.push([pos.zrX, pos.zrY]);
  1834. trackItem.touches.push(touch);
  1835. }
  1836. this._track.push(trackItem);
  1837. },
  1838. _recognize: function (event) {
  1839. for (var eventName in recognizers) {
  1840. if (recognizers.hasOwnProperty(eventName)) {
  1841. var gestureInfo = recognizers[eventName](this._track, event);
  1842. if (gestureInfo) {
  1843. return gestureInfo;
  1844. }
  1845. }
  1846. }
  1847. }
  1848. };
  1849. function dist$1(pointPair) {
  1850. var dx = pointPair[1][0] - pointPair[0][0];
  1851. var dy = pointPair[1][1] - pointPair[0][1];
  1852. return Math.sqrt(dx * dx + dy * dy);
  1853. }
  1854. function center(pointPair) {
  1855. return [
  1856. (pointPair[0][0] + pointPair[1][0]) / 2,
  1857. (pointPair[0][1] + pointPair[1][1]) / 2
  1858. ];
  1859. }
  1860. var recognizers = {
  1861. pinch: function (track, event) {
  1862. var trackLen = track.length;
  1863. if (!trackLen) {
  1864. return;
  1865. }
  1866. var pinchEnd = (track[trackLen - 1] || {}).points;
  1867. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1868. if (pinchPre
  1869. && pinchPre.length > 1
  1870. && pinchEnd
  1871. && pinchEnd.length > 1
  1872. ) {
  1873. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1874. !isFinite(pinchScale) && (pinchScale = 1);
  1875. event.pinchScale = pinchScale;
  1876. var pinchCenter = center(pinchEnd);
  1877. event.pinchX = pinchCenter[0];
  1878. event.pinchY = pinchCenter[1];
  1879. return {
  1880. type: 'pinch',
  1881. target: track[0].target,
  1882. event: event
  1883. };
  1884. }
  1885. }
  1886. // Only pinch currently.
  1887. };
  1888. /**
  1889. * [The interface between `Handler` and `HandlerProxy`]:
  1890. *
  1891. * The default `HandlerProxy` only support the common standard web environment
  1892. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1893. * But `HandlerProxy` can be replaced to support more non-standard environment
  1894. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1895. * not provided (like echarts-gl did).
  1896. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1897. * make break changes util inevitable. The interface include the public methods
  1898. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1899. * drives `Handler`.
  1900. */
  1901. /**
  1902. * [Drag outside]:
  1903. *
  1904. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1905. * zrender area when dragging. That is important for the improvement of the user experience
  1906. * when dragging something near the boundary without being terminated unexpectedly.
  1907. *
  1908. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1909. * to resolve this issue. But some drawbacks of it is described in
  1910. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1911. *
  1912. * Instead, we referenced the specifications:
  1913. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1914. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1915. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1916. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1917. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1918. *
  1919. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1920. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1921. * to fire until release the pointer. That is implemented by listen to those event on
  1922. * `document`.
  1923. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1924. * The touch event support this feature by default.
  1925. *
  1926. * Note:
  1927. * There might be some cases that the mouse event can not be
  1928. * received on `document`. For example,
  1929. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1930. * of zr dom throw Error .
  1931. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1932. * zr dom call `stopPropagation`.
  1933. * In these cases, the `mousemove` event might be keep triggered event
  1934. * if the mouse is released. We try to reduce the side-effect in those cases.
  1935. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1936. *
  1937. * Note:
  1938. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1939. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1940. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1941. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1942. * But they are needed to work when the pointer inside the zrender dom.
  1943. */
  1944. var SILENT = 'silent';
  1945. function makeEventPacket(eveType, targetInfo, event) {
  1946. return {
  1947. type: eveType,
  1948. event: event,
  1949. // target can only be an element that is not silent.
  1950. target: targetInfo.target,
  1951. // topTarget can be a silent element.
  1952. topTarget: targetInfo.topTarget,
  1953. cancelBubble: false,
  1954. offsetX: event.zrX,
  1955. offsetY: event.zrY,
  1956. gestureEvent: event.gestureEvent,
  1957. pinchX: event.pinchX,
  1958. pinchY: event.pinchY,
  1959. pinchScale: event.pinchScale,
  1960. wheelDelta: event.zrDelta,
  1961. zrByTouch: event.zrByTouch,
  1962. which: event.which,
  1963. stop: stopEvent
  1964. };
  1965. }
  1966. function stopEvent() {
  1967. stop(this.event);
  1968. }
  1969. function EmptyProxy() {}
  1970. EmptyProxy.prototype.dispose = function () {};
  1971. var handlerNames = [
  1972. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1973. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1974. ];
  1975. /**
  1976. * @alias module:zrender/Handler
  1977. * @constructor
  1978. * @extends module:zrender/mixin/Eventful
  1979. * @param {module:zrender/Storage} storage Storage instance.
  1980. * @param {module:zrender/Painter} painter Painter instance.
  1981. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1982. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1983. */
  1984. var Handler = function (storage, painter, proxy, painterRoot) {
  1985. Eventful.call(this);
  1986. this.storage = storage;
  1987. this.painter = painter;
  1988. this.painterRoot = painterRoot;
  1989. proxy = proxy || new EmptyProxy();
  1990. /**
  1991. * Proxy of event. can be Dom, WebGLSurface, etc.
  1992. */
  1993. this.proxy = null;
  1994. /**
  1995. * {target, topTarget, x, y}
  1996. * @private
  1997. * @type {Object}
  1998. */
  1999. this._hovered = {};
  2000. /**
  2001. * @private
  2002. * @type {Date}
  2003. */
  2004. this._lastTouchMoment;
  2005. /**
  2006. * @private
  2007. * @type {number}
  2008. */
  2009. this._lastX;
  2010. /**
  2011. * @private
  2012. * @type {number}
  2013. */
  2014. this._lastY;
  2015. /**
  2016. * @private
  2017. * @type {module:zrender/core/GestureMgr}
  2018. */
  2019. this._gestureMgr;
  2020. Draggable.call(this);
  2021. this.setHandlerProxy(proxy);
  2022. };
  2023. Handler.prototype = {
  2024. constructor: Handler,
  2025. setHandlerProxy: function (proxy) {
  2026. if (this.proxy) {
  2027. this.proxy.dispose();
  2028. }
  2029. if (proxy) {
  2030. each$1(handlerNames, function (name) {
  2031. proxy.on && proxy.on(name, this[name], this);
  2032. }, this);
  2033. // Attach handler
  2034. proxy.handler = this;
  2035. }
  2036. this.proxy = proxy;
  2037. },
  2038. mousemove: function (event) {
  2039. var x = event.zrX;
  2040. var y = event.zrY;
  2041. var isOutside = isOutsideBoundary(this, x, y);
  2042. var lastHovered = this._hovered;
  2043. var lastHoveredTarget = lastHovered.target;
  2044. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2045. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2046. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2047. // See #6198.
  2048. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2049. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2050. lastHoveredTarget = lastHovered.target;
  2051. }
  2052. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2053. var hoveredTarget = hovered.target;
  2054. var proxy = this.proxy;
  2055. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2056. // Mouse out on previous hovered element
  2057. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2058. this.dispatchToElement(lastHovered, 'mouseout', event);
  2059. }
  2060. // Mouse moving on one element
  2061. this.dispatchToElement(hovered, 'mousemove', event);
  2062. // Mouse over on a new element
  2063. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2064. this.dispatchToElement(hovered, 'mouseover', event);
  2065. }
  2066. },
  2067. mouseout: function (event) {
  2068. var eventControl = event.zrEventControl;
  2069. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2070. if (eventControl !== 'only_globalout') {
  2071. this.dispatchToElement(this._hovered, 'mouseout', event);
  2072. }
  2073. if (eventControl !== 'no_globalout') {
  2074. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2075. // the `globalout` should have been triggered. But currently not.
  2076. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2077. }
  2078. },
  2079. /**
  2080. * Resize
  2081. */
  2082. resize: function (event) {
  2083. this._hovered = {};
  2084. },
  2085. /**
  2086. * Dispatch event
  2087. * @param {string} eventName
  2088. * @param {event=} eventArgs
  2089. */
  2090. dispatch: function (eventName, eventArgs) {
  2091. var handler = this[eventName];
  2092. handler && handler.call(this, eventArgs);
  2093. },
  2094. /**
  2095. * Dispose
  2096. */
  2097. dispose: function () {
  2098. this.proxy.dispose();
  2099. this.storage =
  2100. this.proxy =
  2101. this.painter = null;
  2102. },
  2103. /**
  2104. * 设置默认的cursor style
  2105. * @param {string} [cursorStyle='default'] 例如 crosshair
  2106. */
  2107. setCursorStyle: function (cursorStyle) {
  2108. var proxy = this.proxy;
  2109. proxy.setCursor && proxy.setCursor(cursorStyle);
  2110. },
  2111. /**
  2112. * 事件分发代理
  2113. *
  2114. * @private
  2115. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2116. * @param {string} eventName 事件名称
  2117. * @param {Object} event 事件对象
  2118. */
  2119. dispatchToElement: function (targetInfo, eventName, event) {
  2120. targetInfo = targetInfo || {};
  2121. var el = targetInfo.target;
  2122. if (el && el.silent) {
  2123. return;
  2124. }
  2125. var eventHandler = 'on' + eventName;
  2126. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2127. while (el) {
  2128. el[eventHandler]
  2129. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2130. el.trigger(eventName, eventPacket);
  2131. el = el.parent;
  2132. if (eventPacket.cancelBubble) {
  2133. break;
  2134. }
  2135. }
  2136. if (!eventPacket.cancelBubble) {
  2137. // 冒泡到顶级 zrender 对象
  2138. this.trigger(eventName, eventPacket);
  2139. // 分发事件到用户自定义层
  2140. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2141. this.painter && this.painter.eachOtherLayer(function (layer) {
  2142. if (typeof (layer[eventHandler]) === 'function') {
  2143. layer[eventHandler].call(layer, eventPacket);
  2144. }
  2145. if (layer.trigger) {
  2146. layer.trigger(eventName, eventPacket);
  2147. }
  2148. });
  2149. }
  2150. },
  2151. /**
  2152. * @private
  2153. * @param {number} x
  2154. * @param {number} y
  2155. * @param {module:zrender/graphic/Displayable} exclude
  2156. * @return {model:zrender/Element}
  2157. * @method
  2158. */
  2159. findHover: function (x, y, exclude) {
  2160. var list = this.storage.getDisplayList();
  2161. var out = {x: x, y: y};
  2162. for (var i = list.length - 1; i >= 0; i--) {
  2163. var hoverCheckResult;
  2164. if (list[i] !== exclude
  2165. // getDisplayList may include ignored item in VML mode
  2166. && !list[i].ignore
  2167. && (hoverCheckResult = isHover(list[i], x, y))
  2168. ) {
  2169. !out.topTarget && (out.topTarget = list[i]);
  2170. if (hoverCheckResult !== SILENT) {
  2171. out.target = list[i];
  2172. break;
  2173. }
  2174. }
  2175. }
  2176. return out;
  2177. },
  2178. processGesture: function (event, stage) {
  2179. if (!this._gestureMgr) {
  2180. this._gestureMgr = new GestureMgr();
  2181. }
  2182. var gestureMgr = this._gestureMgr;
  2183. stage === 'start' && gestureMgr.clear();
  2184. var gestureInfo = gestureMgr.recognize(
  2185. event,
  2186. this.findHover(event.zrX, event.zrY, null).target,
  2187. this.proxy.dom
  2188. );
  2189. stage === 'end' && gestureMgr.clear();
  2190. // Do not do any preventDefault here. Upper application do that if necessary.
  2191. if (gestureInfo) {
  2192. var type = gestureInfo.type;
  2193. event.gestureEvent = type;
  2194. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2195. }
  2196. }
  2197. };
  2198. // Common handlers
  2199. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2200. Handler.prototype[name] = function (event) {
  2201. var x = event.zrX;
  2202. var y = event.zrY;
  2203. var isOutside = isOutsideBoundary(this, x, y);
  2204. var hovered;
  2205. var hoveredTarget;
  2206. if (name !== 'mouseup' || !isOutside) {
  2207. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2208. hovered = this.findHover(x, y);
  2209. hoveredTarget = hovered.target;
  2210. }
  2211. if (name === 'mousedown') {
  2212. this._downEl = hoveredTarget;
  2213. this._downPoint = [event.zrX, event.zrY];
  2214. // In case click triggered before mouseup
  2215. this._upEl = hoveredTarget;
  2216. }
  2217. else if (name === 'mouseup') {
  2218. this._upEl = hoveredTarget;
  2219. }
  2220. else if (name === 'click') {
  2221. if (this._downEl !== this._upEl
  2222. // Original click event is triggered on the whole canvas element,
  2223. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2224. // which should be filtered, otherwise it will bring trouble to
  2225. // pan and zoom.
  2226. || !this._downPoint
  2227. // Arbitrary value
  2228. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2229. ) {
  2230. return;
  2231. }
  2232. this._downPoint = null;
  2233. }
  2234. this.dispatchToElement(hovered, name, event);
  2235. };
  2236. });
  2237. function isHover(displayable, x, y) {
  2238. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2239. var el = displayable;
  2240. var isSilent;
  2241. while (el) {
  2242. // If clipped by ancestor.
  2243. // FIXME: If clipPath has neither stroke nor fill,
  2244. // el.clipPath.contain(x, y) will always return false.
  2245. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2246. return false;
  2247. }
  2248. if (el.silent) {
  2249. isSilent = true;
  2250. }
  2251. el = el.parent;
  2252. }
  2253. return isSilent ? SILENT : true;
  2254. }
  2255. return false;
  2256. }
  2257. /**
  2258. * See [Drag outside].
  2259. */
  2260. function isOutsideBoundary(handlerInstance, x, y) {
  2261. var painter = handlerInstance.painter;
  2262. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2263. }
  2264. mixin(Handler, Eventful);
  2265. mixin(Handler, Draggable);
  2266. /**
  2267. * 3x2矩阵操作类
  2268. * @exports zrender/tool/matrix
  2269. */
  2270. /* global Float32Array */
  2271. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2272. ? Array
  2273. : Float32Array;
  2274. /**
  2275. * Create a identity matrix.
  2276. * @return {Float32Array|Array.<number>}
  2277. */
  2278. function create$1() {
  2279. var out = new ArrayCtor$1(6);
  2280. identity(out);
  2281. return out;
  2282. }
  2283. /**
  2284. * 设置矩阵为单位矩阵
  2285. * @param {Float32Array|Array.<number>} out
  2286. */
  2287. function identity(out) {
  2288. out[0] = 1;
  2289. out[1] = 0;
  2290. out[2] = 0;
  2291. out[3] = 1;
  2292. out[4] = 0;
  2293. out[5] = 0;
  2294. return out;
  2295. }
  2296. /**
  2297. * 复制矩阵
  2298. * @param {Float32Array|Array.<number>} out
  2299. * @param {Float32Array|Array.<number>} m
  2300. */
  2301. function copy$1(out, m) {
  2302. out[0] = m[0];
  2303. out[1] = m[1];
  2304. out[2] = m[2];
  2305. out[3] = m[3];
  2306. out[4] = m[4];
  2307. out[5] = m[5];
  2308. return out;
  2309. }
  2310. /**
  2311. * 矩阵相乘
  2312. * @param {Float32Array|Array.<number>} out
  2313. * @param {Float32Array|Array.<number>} m1
  2314. * @param {Float32Array|Array.<number>} m2
  2315. */
  2316. function mul$1(out, m1, m2) {
  2317. // Consider matrix.mul(m, m2, m);
  2318. // where out is the same as m2.
  2319. // So use temp variable to escape error.
  2320. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2321. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2322. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2323. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2324. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2325. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2326. out[0] = out0;
  2327. out[1] = out1;
  2328. out[2] = out2;
  2329. out[3] = out3;
  2330. out[4] = out4;
  2331. out[5] = out5;
  2332. return out;
  2333. }
  2334. /**
  2335. * 平移变换
  2336. * @param {Float32Array|Array.<number>} out
  2337. * @param {Float32Array|Array.<number>} a
  2338. * @param {Float32Array|Array.<number>} v
  2339. */
  2340. function translate(out, a, v) {
  2341. out[0] = a[0];
  2342. out[1] = a[1];
  2343. out[2] = a[2];
  2344. out[3] = a[3];
  2345. out[4] = a[4] + v[0];
  2346. out[5] = a[5] + v[1];
  2347. return out;
  2348. }
  2349. /**
  2350. * 旋转变换
  2351. * @param {Float32Array|Array.<number>} out
  2352. * @param {Float32Array|Array.<number>} a
  2353. * @param {number} rad
  2354. */
  2355. function rotate(out, a, rad) {
  2356. var aa = a[0];
  2357. var ac = a[2];
  2358. var atx = a[4];
  2359. var ab = a[1];
  2360. var ad = a[3];
  2361. var aty = a[5];
  2362. var st = Math.sin(rad);
  2363. var ct = Math.cos(rad);
  2364. out[0] = aa * ct + ab * st;
  2365. out[1] = -aa * st + ab * ct;
  2366. out[2] = ac * ct + ad * st;
  2367. out[3] = -ac * st + ct * ad;
  2368. out[4] = ct * atx + st * aty;
  2369. out[5] = ct * aty - st * atx;
  2370. return out;
  2371. }
  2372. /**
  2373. * 缩放变换
  2374. * @param {Float32Array|Array.<number>} out
  2375. * @param {Float32Array|Array.<number>} a
  2376. * @param {Float32Array|Array.<number>} v
  2377. */
  2378. function scale$1(out, a, v) {
  2379. var vx = v[0];
  2380. var vy = v[1];
  2381. out[0] = a[0] * vx;
  2382. out[1] = a[1] * vy;
  2383. out[2] = a[2] * vx;
  2384. out[3] = a[3] * vy;
  2385. out[4] = a[4] * vx;
  2386. out[5] = a[5] * vy;
  2387. return out;
  2388. }
  2389. /**
  2390. * 求逆矩阵
  2391. * @param {Float32Array|Array.<number>} out
  2392. * @param {Float32Array|Array.<number>} a
  2393. */
  2394. function invert(out, a) {
  2395. var aa = a[0];
  2396. var ac = a[2];
  2397. var atx = a[4];
  2398. var ab = a[1];
  2399. var ad = a[3];
  2400. var aty = a[5];
  2401. var det = aa * ad - ab * ac;
  2402. if (!det) {
  2403. return null;
  2404. }
  2405. det = 1.0 / det;
  2406. out[0] = ad * det;
  2407. out[1] = -ab * det;
  2408. out[2] = -ac * det;
  2409. out[3] = aa * det;
  2410. out[4] = (ac * aty - ad * atx) * det;
  2411. out[5] = (ab * atx - aa * aty) * det;
  2412. return out;
  2413. }
  2414. /**
  2415. * Clone a new matrix.
  2416. * @param {Float32Array|Array.<number>} a
  2417. */
  2418. /**
  2419. * 提供变换扩展
  2420. * @module zrender/mixin/Transformable
  2421. * @author pissang (https://www.github.com/pissang)
  2422. */
  2423. var mIdentity = identity;
  2424. var EPSILON = 5e-5;
  2425. function isNotAroundZero(val) {
  2426. return val > EPSILON || val < -EPSILON;
  2427. }
  2428. /**
  2429. * @alias module:zrender/mixin/Transformable
  2430. * @constructor
  2431. */
  2432. var Transformable = function (opts) {
  2433. opts = opts || {};
  2434. // If there are no given position, rotation, scale
  2435. if (!opts.position) {
  2436. /**
  2437. * 平移
  2438. * @type {Array.<number>}
  2439. * @default [0, 0]
  2440. */
  2441. this.position = [0, 0];
  2442. }
  2443. if (opts.rotation == null) {
  2444. /**
  2445. * 旋转
  2446. * @type {Array.<number>}
  2447. * @default 0
  2448. */
  2449. this.rotation = 0;
  2450. }
  2451. if (!opts.scale) {
  2452. /**
  2453. * 缩放
  2454. * @type {Array.<number>}
  2455. * @default [1, 1]
  2456. */
  2457. this.scale = [1, 1];
  2458. }
  2459. /**
  2460. * 旋转和缩放的原点
  2461. * @type {Array.<number>}
  2462. * @default null
  2463. */
  2464. this.origin = this.origin || null;
  2465. };
  2466. var transformableProto = Transformable.prototype;
  2467. transformableProto.transform = null;
  2468. /**
  2469. * 判断是否需要有坐标变换
  2470. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2471. */
  2472. transformableProto.needLocalTransform = function () {
  2473. return isNotAroundZero(this.rotation)
  2474. || isNotAroundZero(this.position[0])
  2475. || isNotAroundZero(this.position[1])
  2476. || isNotAroundZero(this.scale[0] - 1)
  2477. || isNotAroundZero(this.scale[1] - 1);
  2478. };
  2479. var scaleTmp = [];
  2480. transformableProto.updateTransform = function () {
  2481. var parent = this.parent;
  2482. var parentHasTransform = parent && parent.transform;
  2483. var needLocalTransform = this.needLocalTransform();
  2484. var m = this.transform;
  2485. if (!(needLocalTransform || parentHasTransform)) {
  2486. m && mIdentity(m);
  2487. return;
  2488. }
  2489. m = m || create$1();
  2490. if (needLocalTransform) {
  2491. this.getLocalTransform(m);
  2492. }
  2493. else {
  2494. mIdentity(m);
  2495. }
  2496. // 应用父节点变换
  2497. if (parentHasTransform) {
  2498. if (needLocalTransform) {
  2499. mul$1(m, parent.transform, m);
  2500. }
  2501. else {
  2502. copy$1(m, parent.transform);
  2503. }
  2504. }
  2505. // 保存这个变换矩阵
  2506. this.transform = m;
  2507. var globalScaleRatio = this.globalScaleRatio;
  2508. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2509. this.getGlobalScale(scaleTmp);
  2510. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2511. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2512. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2513. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2514. m[0] *= sx;
  2515. m[1] *= sx;
  2516. m[2] *= sy;
  2517. m[3] *= sy;
  2518. }
  2519. this.invTransform = this.invTransform || create$1();
  2520. invert(this.invTransform, m);
  2521. };
  2522. transformableProto.getLocalTransform = function (m) {
  2523. return Transformable.getLocalTransform(this, m);
  2524. };
  2525. /**
  2526. * 将自己的transform应用到context上
  2527. * @param {CanvasRenderingContext2D} ctx
  2528. */
  2529. transformableProto.setTransform = function (ctx) {
  2530. var m = this.transform;
  2531. var dpr = ctx.dpr || 1;
  2532. if (m) {
  2533. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2534. }
  2535. else {
  2536. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2537. }
  2538. };
  2539. transformableProto.restoreTransform = function (ctx) {
  2540. var dpr = ctx.dpr || 1;
  2541. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2542. };
  2543. var tmpTransform = [];
  2544. var originTransform = create$1();
  2545. transformableProto.setLocalTransform = function (m) {
  2546. if (!m) {
  2547. // TODO return or set identity?
  2548. return;
  2549. }
  2550. var sx = m[0] * m[0] + m[1] * m[1];
  2551. var sy = m[2] * m[2] + m[3] * m[3];
  2552. var position = this.position;
  2553. var scale$$1 = this.scale;
  2554. if (isNotAroundZero(sx - 1)) {
  2555. sx = Math.sqrt(sx);
  2556. }
  2557. if (isNotAroundZero(sy - 1)) {
  2558. sy = Math.sqrt(sy);
  2559. }
  2560. if (m[0] < 0) {
  2561. sx = -sx;
  2562. }
  2563. if (m[3] < 0) {
  2564. sy = -sy;
  2565. }
  2566. position[0] = m[4];
  2567. position[1] = m[5];
  2568. scale$$1[0] = sx;
  2569. scale$$1[1] = sy;
  2570. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2571. };
  2572. /**
  2573. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2574. */
  2575. transformableProto.decomposeTransform = function () {
  2576. if (!this.transform) {
  2577. return;
  2578. }
  2579. var parent = this.parent;
  2580. var m = this.transform;
  2581. if (parent && parent.transform) {
  2582. // Get local transform and decompose them to position, scale, rotation
  2583. mul$1(tmpTransform, parent.invTransform, m);
  2584. m = tmpTransform;
  2585. }
  2586. var origin = this.origin;
  2587. if (origin && (origin[0] || origin[1])) {
  2588. originTransform[4] = origin[0];
  2589. originTransform[5] = origin[1];
  2590. mul$1(tmpTransform, m, originTransform);
  2591. tmpTransform[4] -= origin[0];
  2592. tmpTransform[5] -= origin[1];
  2593. m = tmpTransform;
  2594. }
  2595. this.setLocalTransform(m);
  2596. };
  2597. /**
  2598. * Get global scale
  2599. * @return {Array.<number>}
  2600. */
  2601. transformableProto.getGlobalScale = function (out) {
  2602. var m = this.transform;
  2603. out = out || [];
  2604. if (!m) {
  2605. out[0] = 1;
  2606. out[1] = 1;
  2607. return out;
  2608. }
  2609. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2610. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2611. if (m[0] < 0) {
  2612. out[0] = -out[0];
  2613. }
  2614. if (m[3] < 0) {
  2615. out[1] = -out[1];
  2616. }
  2617. return out;
  2618. };
  2619. /**
  2620. * 变换坐标位置到 shape 的局部坐标空间
  2621. * @method
  2622. * @param {number} x
  2623. * @param {number} y
  2624. * @return {Array.<number>}
  2625. */
  2626. transformableProto.transformCoordToLocal = function (x, y) {
  2627. var v2 = [x, y];
  2628. var invTransform = this.invTransform;
  2629. if (invTransform) {
  2630. applyTransform(v2, v2, invTransform);
  2631. }
  2632. return v2;
  2633. };
  2634. /**
  2635. * 变换局部坐标位置到全局坐标空间
  2636. * @method
  2637. * @param {number} x
  2638. * @param {number} y
  2639. * @return {Array.<number>}
  2640. */
  2641. transformableProto.transformCoordToGlobal = function (x, y) {
  2642. var v2 = [x, y];
  2643. var transform = this.transform;
  2644. if (transform) {
  2645. applyTransform(v2, v2, transform);
  2646. }
  2647. return v2;
  2648. };
  2649. /**
  2650. * @static
  2651. * @param {Object} target
  2652. * @param {Array.<number>} target.origin
  2653. * @param {number} target.rotation
  2654. * @param {Array.<number>} target.position
  2655. * @param {Array.<number>} [m]
  2656. */
  2657. Transformable.getLocalTransform = function (target, m) {
  2658. m = m || [];
  2659. mIdentity(m);
  2660. var origin = target.origin;
  2661. var scale$$1 = target.scale || [1, 1];
  2662. var rotation = target.rotation || 0;
  2663. var position = target.position || [0, 0];
  2664. if (origin) {
  2665. // Translate to origin
  2666. m[4] -= origin[0];
  2667. m[5] -= origin[1];
  2668. }
  2669. scale$1(m, m, scale$$1);
  2670. if (rotation) {
  2671. rotate(m, m, rotation);
  2672. }
  2673. if (origin) {
  2674. // Translate back from origin
  2675. m[4] += origin[0];
  2676. m[5] += origin[1];
  2677. }
  2678. m[4] += position[0];
  2679. m[5] += position[1];
  2680. return m;
  2681. };
  2682. /**
  2683. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2684. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2685. * @exports zrender/animation/easing
  2686. */
  2687. var easing = {
  2688. /**
  2689. * @param {number} k
  2690. * @return {number}
  2691. */
  2692. linear: function (k) {
  2693. return k;
  2694. },
  2695. /**
  2696. * @param {number} k
  2697. * @return {number}
  2698. */
  2699. quadraticIn: function (k) {
  2700. return k * k;
  2701. },
  2702. /**
  2703. * @param {number} k
  2704. * @return {number}
  2705. */
  2706. quadraticOut: function (k) {
  2707. return k * (2 - k);
  2708. },
  2709. /**
  2710. * @param {number} k
  2711. * @return {number}
  2712. */
  2713. quadraticInOut: function (k) {
  2714. if ((k *= 2) < 1) {
  2715. return 0.5 * k * k;
  2716. }
  2717. return -0.5 * (--k * (k - 2) - 1);
  2718. },
  2719. // 三次方的缓动(t^3)
  2720. /**
  2721. * @param {number} k
  2722. * @return {number}
  2723. */
  2724. cubicIn: function (k) {
  2725. return k * k * k;
  2726. },
  2727. /**
  2728. * @param {number} k
  2729. * @return {number}
  2730. */
  2731. cubicOut: function (k) {
  2732. return --k * k * k + 1;
  2733. },
  2734. /**
  2735. * @param {number} k
  2736. * @return {number}
  2737. */
  2738. cubicInOut: function (k) {
  2739. if ((k *= 2) < 1) {
  2740. return 0.5 * k * k * k;
  2741. }
  2742. return 0.5 * ((k -= 2) * k * k + 2);
  2743. },
  2744. // 四次方的缓动(t^4)
  2745. /**
  2746. * @param {number} k
  2747. * @return {number}
  2748. */
  2749. quarticIn: function (k) {
  2750. return k * k * k * k;
  2751. },
  2752. /**
  2753. * @param {number} k
  2754. * @return {number}
  2755. */
  2756. quarticOut: function (k) {
  2757. return 1 - (--k * k * k * k);
  2758. },
  2759. /**
  2760. * @param {number} k
  2761. * @return {number}
  2762. */
  2763. quarticInOut: function (k) {
  2764. if ((k *= 2) < 1) {
  2765. return 0.5 * k * k * k * k;
  2766. }
  2767. return -0.5 * ((k -= 2) * k * k * k - 2);
  2768. },
  2769. // 五次方的缓动(t^5)
  2770. /**
  2771. * @param {number} k
  2772. * @return {number}
  2773. */
  2774. quinticIn: function (k) {
  2775. return k * k * k * k * k;
  2776. },
  2777. /**
  2778. * @param {number} k
  2779. * @return {number}
  2780. */
  2781. quinticOut: function (k) {
  2782. return --k * k * k * k * k + 1;
  2783. },
  2784. /**
  2785. * @param {number} k
  2786. * @return {number}
  2787. */
  2788. quinticInOut: function (k) {
  2789. if ((k *= 2) < 1) {
  2790. return 0.5 * k * k * k * k * k;
  2791. }
  2792. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2793. },
  2794. // 正弦曲线的缓动(sin(t))
  2795. /**
  2796. * @param {number} k
  2797. * @return {number}
  2798. */
  2799. sinusoidalIn: function (k) {
  2800. return 1 - Math.cos(k * Math.PI / 2);
  2801. },
  2802. /**
  2803. * @param {number} k
  2804. * @return {number}
  2805. */
  2806. sinusoidalOut: function (k) {
  2807. return Math.sin(k * Math.PI / 2);
  2808. },
  2809. /**
  2810. * @param {number} k
  2811. * @return {number}
  2812. */
  2813. sinusoidalInOut: function (k) {
  2814. return 0.5 * (1 - Math.cos(Math.PI * k));
  2815. },
  2816. // 指数曲线的缓动(2^t)
  2817. /**
  2818. * @param {number} k
  2819. * @return {number}
  2820. */
  2821. exponentialIn: function (k) {
  2822. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2823. },
  2824. /**
  2825. * @param {number} k
  2826. * @return {number}
  2827. */
  2828. exponentialOut: function (k) {
  2829. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2830. },
  2831. /**
  2832. * @param {number} k
  2833. * @return {number}
  2834. */
  2835. exponentialInOut: function (k) {
  2836. if (k === 0) {
  2837. return 0;
  2838. }
  2839. if (k === 1) {
  2840. return 1;
  2841. }
  2842. if ((k *= 2) < 1) {
  2843. return 0.5 * Math.pow(1024, k - 1);
  2844. }
  2845. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2846. },
  2847. // 圆形曲线的缓动(sqrt(1-t^2))
  2848. /**
  2849. * @param {number} k
  2850. * @return {number}
  2851. */
  2852. circularIn: function (k) {
  2853. return 1 - Math.sqrt(1 - k * k);
  2854. },
  2855. /**
  2856. * @param {number} k
  2857. * @return {number}
  2858. */
  2859. circularOut: function (k) {
  2860. return Math.sqrt(1 - (--k * k));
  2861. },
  2862. /**
  2863. * @param {number} k
  2864. * @return {number}
  2865. */
  2866. circularInOut: function (k) {
  2867. if ((k *= 2) < 1) {
  2868. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2869. }
  2870. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2871. },
  2872. // 创建类似于弹簧在停止前来回振荡的动画
  2873. /**
  2874. * @param {number} k
  2875. * @return {number}
  2876. */
  2877. elasticIn: function (k) {
  2878. var s;
  2879. var a = 0.1;
  2880. var p = 0.4;
  2881. if (k === 0) {
  2882. return 0;
  2883. }
  2884. if (k === 1) {
  2885. return 1;
  2886. }
  2887. if (!a || a < 1) {
  2888. a = 1;
  2889. s = p / 4;
  2890. }
  2891. else {
  2892. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2893. }
  2894. return -(a * Math.pow(2, 10 * (k -= 1))
  2895. * Math.sin((k - s) * (2 * Math.PI) / p));
  2896. },
  2897. /**
  2898. * @param {number} k
  2899. * @return {number}
  2900. */
  2901. elasticOut: function (k) {
  2902. var s;
  2903. var a = 0.1;
  2904. var p = 0.4;
  2905. if (k === 0) {
  2906. return 0;
  2907. }
  2908. if (k === 1) {
  2909. return 1;
  2910. }
  2911. if (!a || a < 1) {
  2912. a = 1;
  2913. s = p / 4;
  2914. }
  2915. else {
  2916. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2917. }
  2918. return (a * Math.pow(2, -10 * k)
  2919. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2920. },
  2921. /**
  2922. * @param {number} k
  2923. * @return {number}
  2924. */
  2925. elasticInOut: function (k) {
  2926. var s;
  2927. var a = 0.1;
  2928. var p = 0.4;
  2929. if (k === 0) {
  2930. return 0;
  2931. }
  2932. if (k === 1) {
  2933. return 1;
  2934. }
  2935. if (!a || a < 1) {
  2936. a = 1;
  2937. s = p / 4;
  2938. }
  2939. else {
  2940. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2941. }
  2942. if ((k *= 2) < 1) {
  2943. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2944. * Math.sin((k - s) * (2 * Math.PI) / p));
  2945. }
  2946. return a * Math.pow(2, -10 * (k -= 1))
  2947. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2948. },
  2949. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2950. /**
  2951. * @param {number} k
  2952. * @return {number}
  2953. */
  2954. backIn: function (k) {
  2955. var s = 1.70158;
  2956. return k * k * ((s + 1) * k - s);
  2957. },
  2958. /**
  2959. * @param {number} k
  2960. * @return {number}
  2961. */
  2962. backOut: function (k) {
  2963. var s = 1.70158;
  2964. return --k * k * ((s + 1) * k + s) + 1;
  2965. },
  2966. /**
  2967. * @param {number} k
  2968. * @return {number}
  2969. */
  2970. backInOut: function (k) {
  2971. var s = 1.70158 * 1.525;
  2972. if ((k *= 2) < 1) {
  2973. return 0.5 * (k * k * ((s + 1) * k - s));
  2974. }
  2975. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2976. },
  2977. // 创建弹跳效果
  2978. /**
  2979. * @param {number} k
  2980. * @return {number}
  2981. */
  2982. bounceIn: function (k) {
  2983. return 1 - easing.bounceOut(1 - k);
  2984. },
  2985. /**
  2986. * @param {number} k
  2987. * @return {number}
  2988. */
  2989. bounceOut: function (k) {
  2990. if (k < (1 / 2.75)) {
  2991. return 7.5625 * k * k;
  2992. }
  2993. else if (k < (2 / 2.75)) {
  2994. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2995. }
  2996. else if (k < (2.5 / 2.75)) {
  2997. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2998. }
  2999. else {
  3000. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3001. }
  3002. },
  3003. /**
  3004. * @param {number} k
  3005. * @return {number}
  3006. */
  3007. bounceInOut: function (k) {
  3008. if (k < 0.5) {
  3009. return easing.bounceIn(k * 2) * 0.5;
  3010. }
  3011. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3012. }
  3013. };
  3014. /**
  3015. * 动画主控制器
  3016. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3017. * @config life(1000) 动画时长
  3018. * @config delay(0) 动画延迟时间
  3019. * @config loop(true)
  3020. * @config gap(0) 循环的间隔时间
  3021. * @config onframe
  3022. * @config easing(optional)
  3023. * @config ondestroy(optional)
  3024. * @config onrestart(optional)
  3025. *
  3026. * TODO pause
  3027. */
  3028. function Clip(options) {
  3029. this._target = options.target;
  3030. // 生命周期
  3031. this._life = options.life || 1000;
  3032. // 延时
  3033. this._delay = options.delay || 0;
  3034. // 开始时间
  3035. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3036. this._initialized = false;
  3037. // 是否循环
  3038. this.loop = options.loop == null ? false : options.loop;
  3039. this.gap = options.gap || 0;
  3040. this.easing = options.easing || 'Linear';
  3041. this.onframe = options.onframe;
  3042. this.ondestroy = options.ondestroy;
  3043. this.onrestart = options.onrestart;
  3044. this._pausedTime = 0;
  3045. this._paused = false;
  3046. }
  3047. Clip.prototype = {
  3048. constructor: Clip,
  3049. step: function (globalTime, deltaTime) {
  3050. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3051. // PENDING
  3052. if (!this._initialized) {
  3053. this._startTime = globalTime + this._delay;
  3054. this._initialized = true;
  3055. }
  3056. if (this._paused) {
  3057. this._pausedTime += deltaTime;
  3058. return;
  3059. }
  3060. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3061. // 还没开始
  3062. if (percent < 0) {
  3063. return;
  3064. }
  3065. percent = Math.min(percent, 1);
  3066. var easing$$1 = this.easing;
  3067. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3068. var schedule = typeof easingFunc === 'function'
  3069. ? easingFunc(percent)
  3070. : percent;
  3071. this.fire('frame', schedule);
  3072. // 结束
  3073. if (percent === 1) {
  3074. if (this.loop) {
  3075. this.restart(globalTime);
  3076. // 重新开始周期
  3077. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3078. return 'restart';
  3079. }
  3080. // 动画完成将这个控制器标识为待删除
  3081. // 在Animation.update中进行批量删除
  3082. this._needsRemove = true;
  3083. return 'destroy';
  3084. }
  3085. return null;
  3086. },
  3087. restart: function (globalTime) {
  3088. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3089. this._startTime = globalTime - remainder + this.gap;
  3090. this._pausedTime = 0;
  3091. this._needsRemove = false;
  3092. },
  3093. fire: function (eventType, arg) {
  3094. eventType = 'on' + eventType;
  3095. if (this[eventType]) {
  3096. this[eventType](this._target, arg);
  3097. }
  3098. },
  3099. pause: function () {
  3100. this._paused = true;
  3101. },
  3102. resume: function () {
  3103. this._paused = false;
  3104. }
  3105. };
  3106. // Simple LRU cache use doubly linked list
  3107. // @module zrender/core/LRU
  3108. /**
  3109. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3110. * @constructor
  3111. */
  3112. var LinkedList = function () {
  3113. /**
  3114. * @type {module:zrender/core/LRU~Entry}
  3115. */
  3116. this.head = null;
  3117. /**
  3118. * @type {module:zrender/core/LRU~Entry}
  3119. */
  3120. this.tail = null;
  3121. this._len = 0;
  3122. };
  3123. var linkedListProto = LinkedList.prototype;
  3124. /**
  3125. * Insert a new value at the tail
  3126. * @param {} val
  3127. * @return {module:zrender/core/LRU~Entry}
  3128. */
  3129. linkedListProto.insert = function (val) {
  3130. var entry = new Entry(val);
  3131. this.insertEntry(entry);
  3132. return entry;
  3133. };
  3134. /**
  3135. * Insert an entry at the tail
  3136. * @param {module:zrender/core/LRU~Entry} entry
  3137. */
  3138. linkedListProto.insertEntry = function (entry) {
  3139. if (!this.head) {
  3140. this.head = this.tail = entry;
  3141. }
  3142. else {
  3143. this.tail.next = entry;
  3144. entry.prev = this.tail;
  3145. entry.next = null;
  3146. this.tail = entry;
  3147. }
  3148. this._len++;
  3149. };
  3150. /**
  3151. * Remove entry.
  3152. * @param {module:zrender/core/LRU~Entry} entry
  3153. */
  3154. linkedListProto.remove = function (entry) {
  3155. var prev = entry.prev;
  3156. var next = entry.next;
  3157. if (prev) {
  3158. prev.next = next;
  3159. }
  3160. else {
  3161. // Is head
  3162. this.head = next;
  3163. }
  3164. if (next) {
  3165. next.prev = prev;
  3166. }
  3167. else {
  3168. // Is tail
  3169. this.tail = prev;
  3170. }
  3171. entry.next = entry.prev = null;
  3172. this._len--;
  3173. };
  3174. /**
  3175. * @return {number}
  3176. */
  3177. linkedListProto.len = function () {
  3178. return this._len;
  3179. };
  3180. /**
  3181. * Clear list
  3182. */
  3183. linkedListProto.clear = function () {
  3184. this.head = this.tail = null;
  3185. this._len = 0;
  3186. };
  3187. /**
  3188. * @constructor
  3189. * @param {} val
  3190. */
  3191. var Entry = function (val) {
  3192. /**
  3193. * @type {}
  3194. */
  3195. this.value = val;
  3196. /**
  3197. * @type {module:zrender/core/LRU~Entry}
  3198. */
  3199. this.next;
  3200. /**
  3201. * @type {module:zrender/core/LRU~Entry}
  3202. */
  3203. this.prev;
  3204. };
  3205. /**
  3206. * LRU Cache
  3207. * @constructor
  3208. * @alias module:zrender/core/LRU
  3209. */
  3210. var LRU = function (maxSize) {
  3211. this._list = new LinkedList();
  3212. this._map = {};
  3213. this._maxSize = maxSize || 10;
  3214. this._lastRemovedEntry = null;
  3215. };
  3216. var LRUProto = LRU.prototype;
  3217. /**
  3218. * @param {string} key
  3219. * @param {} value
  3220. * @return {} Removed value
  3221. */
  3222. LRUProto.put = function (key, value) {
  3223. var list = this._list;
  3224. var map = this._map;
  3225. var removed = null;
  3226. if (map[key] == null) {
  3227. var len = list.len();
  3228. // Reuse last removed entry
  3229. var entry = this._lastRemovedEntry;
  3230. if (len >= this._maxSize && len > 0) {
  3231. // Remove the least recently used
  3232. var leastUsedEntry = list.head;
  3233. list.remove(leastUsedEntry);
  3234. delete map[leastUsedEntry.key];
  3235. removed = leastUsedEntry.value;
  3236. this._lastRemovedEntry = leastUsedEntry;
  3237. }
  3238. if (entry) {
  3239. entry.value = value;
  3240. }
  3241. else {
  3242. entry = new Entry(value);
  3243. }
  3244. entry.key = key;
  3245. list.insertEntry(entry);
  3246. map[key] = entry;
  3247. }
  3248. return removed;
  3249. };
  3250. /**
  3251. * @param {string} key
  3252. * @return {}
  3253. */
  3254. LRUProto.get = function (key) {
  3255. var entry = this._map[key];
  3256. var list = this._list;
  3257. if (entry != null) {
  3258. // Put the latest used entry in the tail
  3259. if (entry !== list.tail) {
  3260. list.remove(entry);
  3261. list.insertEntry(entry);
  3262. }
  3263. return entry.value;
  3264. }
  3265. };
  3266. /**
  3267. * Clear the cache
  3268. */
  3269. LRUProto.clear = function () {
  3270. this._list.clear();
  3271. this._map = {};
  3272. };
  3273. var kCSSColorTable = {
  3274. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3275. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3276. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3277. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3278. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3279. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3280. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3281. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3282. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3283. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3284. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3285. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3286. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3287. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3288. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3289. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3290. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3291. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3292. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3293. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3294. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3295. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3296. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3297. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3298. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3299. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3300. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3301. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3302. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3303. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3304. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3305. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3306. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3307. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3308. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3309. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3310. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3311. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3312. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3313. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3314. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3315. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3316. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3317. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3318. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3319. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3320. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3321. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3322. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3323. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3324. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3325. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3326. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3327. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3328. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3329. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3330. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3331. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3332. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3333. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3334. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3335. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3336. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3337. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3338. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3339. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3340. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3341. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3342. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3343. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3344. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3345. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3346. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3347. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3348. };
  3349. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3350. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3351. return i < 0 ? 0 : i > 255 ? 255 : i;
  3352. }
  3353. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3354. return f < 0 ? 0 : f > 1 ? 1 : f;
  3355. }
  3356. function parseCssInt(str) { // int or percentage.
  3357. if (str.length && str.charAt(str.length - 1) === '%') {
  3358. return clampCssByte(parseFloat(str) / 100 * 255);
  3359. }
  3360. return clampCssByte(parseInt(str, 10));
  3361. }
  3362. function parseCssFloat(str) { // float or percentage.
  3363. if (str.length && str.charAt(str.length - 1) === '%') {
  3364. return clampCssFloat(parseFloat(str) / 100);
  3365. }
  3366. return clampCssFloat(parseFloat(str));
  3367. }
  3368. function cssHueToRgb(m1, m2, h) {
  3369. if (h < 0) {
  3370. h += 1;
  3371. }
  3372. else if (h > 1) {
  3373. h -= 1;
  3374. }
  3375. if (h * 6 < 1) {
  3376. return m1 + (m2 - m1) * h * 6;
  3377. }
  3378. if (h * 2 < 1) {
  3379. return m2;
  3380. }
  3381. if (h * 3 < 2) {
  3382. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3383. }
  3384. return m1;
  3385. }
  3386. function setRgba(out, r, g, b, a) {
  3387. out[0] = r;
  3388. out[1] = g;
  3389. out[2] = b;
  3390. out[3] = a;
  3391. return out;
  3392. }
  3393. function copyRgba(out, a) {
  3394. out[0] = a[0];
  3395. out[1] = a[1];
  3396. out[2] = a[2];
  3397. out[3] = a[3];
  3398. return out;
  3399. }
  3400. var colorCache = new LRU(20);
  3401. var lastRemovedArr = null;
  3402. function putToCache(colorStr, rgbaArr) {
  3403. // Reuse removed array
  3404. if (lastRemovedArr) {
  3405. copyRgba(lastRemovedArr, rgbaArr);
  3406. }
  3407. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3408. }
  3409. /**
  3410. * @param {string} colorStr
  3411. * @param {Array.<number>} out
  3412. * @return {Array.<number>}
  3413. * @memberOf module:zrender/util/color
  3414. */
  3415. function parse(colorStr, rgbaArr) {
  3416. if (!colorStr) {
  3417. return;
  3418. }
  3419. rgbaArr = rgbaArr || [];
  3420. var cached = colorCache.get(colorStr);
  3421. if (cached) {
  3422. return copyRgba(rgbaArr, cached);
  3423. }
  3424. // colorStr may be not string
  3425. colorStr = colorStr + '';
  3426. // Remove all whitespace, not compliant, but should just be more accepting.
  3427. var str = colorStr.replace(/ /g, '').toLowerCase();
  3428. // Color keywords (and transparent) lookup.
  3429. if (str in kCSSColorTable) {
  3430. copyRgba(rgbaArr, kCSSColorTable[str]);
  3431. putToCache(colorStr, rgbaArr);
  3432. return rgbaArr;
  3433. }
  3434. // #abc and #abc123 syntax.
  3435. if (str.charAt(0) === '#') {
  3436. if (str.length === 4) {
  3437. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3438. if (!(iv >= 0 && iv <= 0xfff)) {
  3439. setRgba(rgbaArr, 0, 0, 0, 1);
  3440. return; // Covers NaN.
  3441. }
  3442. setRgba(rgbaArr,
  3443. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3444. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3445. (iv & 0xf) | ((iv & 0xf) << 4),
  3446. 1
  3447. );
  3448. putToCache(colorStr, rgbaArr);
  3449. return rgbaArr;
  3450. }
  3451. else if (str.length === 7) {
  3452. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3453. if (!(iv >= 0 && iv <= 0xffffff)) {
  3454. setRgba(rgbaArr, 0, 0, 0, 1);
  3455. return; // Covers NaN.
  3456. }
  3457. setRgba(rgbaArr,
  3458. (iv & 0xff0000) >> 16,
  3459. (iv & 0xff00) >> 8,
  3460. iv & 0xff,
  3461. 1
  3462. );
  3463. putToCache(colorStr, rgbaArr);
  3464. return rgbaArr;
  3465. }
  3466. return;
  3467. }
  3468. var op = str.indexOf('(');
  3469. var ep = str.indexOf(')');
  3470. if (op !== -1 && ep + 1 === str.length) {
  3471. var fname = str.substr(0, op);
  3472. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3473. var alpha = 1; // To allow case fallthrough.
  3474. switch (fname) {
  3475. case 'rgba':
  3476. if (params.length !== 4) {
  3477. setRgba(rgbaArr, 0, 0, 0, 1);
  3478. return;
  3479. }
  3480. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3481. // Fall through.
  3482. case 'rgb':
  3483. if (params.length !== 3) {
  3484. setRgba(rgbaArr, 0, 0, 0, 1);
  3485. return;
  3486. }
  3487. setRgba(rgbaArr,
  3488. parseCssInt(params[0]),
  3489. parseCssInt(params[1]),
  3490. parseCssInt(params[2]),
  3491. alpha
  3492. );
  3493. putToCache(colorStr, rgbaArr);
  3494. return rgbaArr;
  3495. case 'hsla':
  3496. if (params.length !== 4) {
  3497. setRgba(rgbaArr, 0, 0, 0, 1);
  3498. return;
  3499. }
  3500. params[3] = parseCssFloat(params[3]);
  3501. hsla2rgba(params, rgbaArr);
  3502. putToCache(colorStr, rgbaArr);
  3503. return rgbaArr;
  3504. case 'hsl':
  3505. if (params.length !== 3) {
  3506. setRgba(rgbaArr, 0, 0, 0, 1);
  3507. return;
  3508. }
  3509. hsla2rgba(params, rgbaArr);
  3510. putToCache(colorStr, rgbaArr);
  3511. return rgbaArr;
  3512. default:
  3513. return;
  3514. }
  3515. }
  3516. setRgba(rgbaArr, 0, 0, 0, 1);
  3517. return;
  3518. }
  3519. /**
  3520. * @param {Array.<number>} hsla
  3521. * @param {Array.<number>} rgba
  3522. * @return {Array.<number>} rgba
  3523. */
  3524. function hsla2rgba(hsla, rgba) {
  3525. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3526. // NOTE(deanm): According to the CSS spec s/l should only be
  3527. // percentages, but we don't bother and let float or percentage.
  3528. var s = parseCssFloat(hsla[1]);
  3529. var l = parseCssFloat(hsla[2]);
  3530. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3531. var m1 = l * 2 - m2;
  3532. rgba = rgba || [];
  3533. setRgba(rgba,
  3534. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3535. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3536. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3537. 1
  3538. );
  3539. if (hsla.length === 4) {
  3540. rgba[3] = hsla[3];
  3541. }
  3542. return rgba;
  3543. }
  3544. /**
  3545. * @param {string} color
  3546. * @param {number} level
  3547. * @return {string}
  3548. * @memberOf module:zrender/util/color
  3549. */
  3550. function lift(color, level) {
  3551. var colorArr = parse(color);
  3552. if (colorArr) {
  3553. for (var i = 0; i < 3; i++) {
  3554. if (level < 0) {
  3555. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3556. }
  3557. else {
  3558. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3559. }
  3560. if (colorArr[i] > 255) {
  3561. colorArr[i] = 255;
  3562. }
  3563. else if (color[i] < 0) {
  3564. colorArr[i] = 0;
  3565. }
  3566. }
  3567. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3568. }
  3569. }
  3570. /**
  3571. * @param {string} color
  3572. * @return {string}
  3573. * @memberOf module:zrender/util/color
  3574. */
  3575. /**
  3576. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3577. * @param {number} normalizedValue A float between 0 and 1.
  3578. * @param {Array.<Array.<number>>} colors List of rgba color array
  3579. * @param {Array.<number>} [out] Mapped gba color array
  3580. * @return {Array.<number>} will be null/undefined if input illegal.
  3581. */
  3582. /**
  3583. * @deprecated
  3584. */
  3585. /**
  3586. * @param {number} normalizedValue A float between 0 and 1.
  3587. * @param {Array.<string>} colors Color list.
  3588. * @param {boolean=} fullOutput Default false.
  3589. * @return {(string|Object)} Result color. If fullOutput,
  3590. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3591. * @memberOf module:zrender/util/color
  3592. */
  3593. /**
  3594. * @deprecated
  3595. */
  3596. /**
  3597. * @param {string} color
  3598. * @param {number=} h 0 ~ 360, ignore when null.
  3599. * @param {number=} s 0 ~ 1, ignore when null.
  3600. * @param {number=} l 0 ~ 1, ignore when null.
  3601. * @return {string} Color string in rgba format.
  3602. * @memberOf module:zrender/util/color
  3603. */
  3604. /**
  3605. * @param {string} color
  3606. * @param {number=} alpha 0 ~ 1
  3607. * @return {string} Color string in rgba format.
  3608. * @memberOf module:zrender/util/color
  3609. */
  3610. /**
  3611. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3612. * @param {string} type 'rgba', 'hsva', ...
  3613. * @return {string} Result color. (If input illegal, return undefined).
  3614. */
  3615. function stringify(arrColor, type) {
  3616. if (!arrColor || !arrColor.length) {
  3617. return;
  3618. }
  3619. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3620. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3621. colorStr += ',' + arrColor[3];
  3622. }
  3623. return type + '(' + colorStr + ')';
  3624. }
  3625. /**
  3626. * @module echarts/animation/Animator
  3627. */
  3628. var arraySlice = Array.prototype.slice;
  3629. function defaultGetter(target, key) {
  3630. return target[key];
  3631. }
  3632. function defaultSetter(target, key, value) {
  3633. target[key] = value;
  3634. }
  3635. /**
  3636. * @param {number} p0
  3637. * @param {number} p1
  3638. * @param {number} percent
  3639. * @return {number}
  3640. */
  3641. function interpolateNumber(p0, p1, percent) {
  3642. return (p1 - p0) * percent + p0;
  3643. }
  3644. /**
  3645. * @param {string} p0
  3646. * @param {string} p1
  3647. * @param {number} percent
  3648. * @return {string}
  3649. */
  3650. function interpolateString(p0, p1, percent) {
  3651. return percent > 0.5 ? p1 : p0;
  3652. }
  3653. /**
  3654. * @param {Array} p0
  3655. * @param {Array} p1
  3656. * @param {number} percent
  3657. * @param {Array} out
  3658. * @param {number} arrDim
  3659. */
  3660. function interpolateArray(p0, p1, percent, out, arrDim) {
  3661. var len = p0.length;
  3662. if (arrDim === 1) {
  3663. for (var i = 0; i < len; i++) {
  3664. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3665. }
  3666. }
  3667. else {
  3668. var len2 = len && p0[0].length;
  3669. for (var i = 0; i < len; i++) {
  3670. for (var j = 0; j < len2; j++) {
  3671. out[i][j] = interpolateNumber(
  3672. p0[i][j], p1[i][j], percent
  3673. );
  3674. }
  3675. }
  3676. }
  3677. }
  3678. // arr0 is source array, arr1 is target array.
  3679. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3680. function fillArr(arr0, arr1, arrDim) {
  3681. var arr0Len = arr0.length;
  3682. var arr1Len = arr1.length;
  3683. if (arr0Len !== arr1Len) {
  3684. // FIXME Not work for TypedArray
  3685. var isPreviousLarger = arr0Len > arr1Len;
  3686. if (isPreviousLarger) {
  3687. // Cut the previous
  3688. arr0.length = arr1Len;
  3689. }
  3690. else {
  3691. // Fill the previous
  3692. for (var i = arr0Len; i < arr1Len; i++) {
  3693. arr0.push(
  3694. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3695. );
  3696. }
  3697. }
  3698. }
  3699. // Handling NaN value
  3700. var len2 = arr0[0] && arr0[0].length;
  3701. for (var i = 0; i < arr0.length; i++) {
  3702. if (arrDim === 1) {
  3703. if (isNaN(arr0[i])) {
  3704. arr0[i] = arr1[i];
  3705. }
  3706. }
  3707. else {
  3708. for (var j = 0; j < len2; j++) {
  3709. if (isNaN(arr0[i][j])) {
  3710. arr0[i][j] = arr1[i][j];
  3711. }
  3712. }
  3713. }
  3714. }
  3715. }
  3716. /**
  3717. * @param {Array} arr0
  3718. * @param {Array} arr1
  3719. * @param {number} arrDim
  3720. * @return {boolean}
  3721. */
  3722. function isArraySame(arr0, arr1, arrDim) {
  3723. if (arr0 === arr1) {
  3724. return true;
  3725. }
  3726. var len = arr0.length;
  3727. if (len !== arr1.length) {
  3728. return false;
  3729. }
  3730. if (arrDim === 1) {
  3731. for (var i = 0; i < len; i++) {
  3732. if (arr0[i] !== arr1[i]) {
  3733. return false;
  3734. }
  3735. }
  3736. }
  3737. else {
  3738. var len2 = arr0[0].length;
  3739. for (var i = 0; i < len; i++) {
  3740. for (var j = 0; j < len2; j++) {
  3741. if (arr0[i][j] !== arr1[i][j]) {
  3742. return false;
  3743. }
  3744. }
  3745. }
  3746. }
  3747. return true;
  3748. }
  3749. /**
  3750. * Catmull Rom interpolate array
  3751. * @param {Array} p0
  3752. * @param {Array} p1
  3753. * @param {Array} p2
  3754. * @param {Array} p3
  3755. * @param {number} t
  3756. * @param {number} t2
  3757. * @param {number} t3
  3758. * @param {Array} out
  3759. * @param {number} arrDim
  3760. */
  3761. function catmullRomInterpolateArray(
  3762. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3763. ) {
  3764. var len = p0.length;
  3765. if (arrDim === 1) {
  3766. for (var i = 0; i < len; i++) {
  3767. out[i] = catmullRomInterpolate(
  3768. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3769. );
  3770. }
  3771. }
  3772. else {
  3773. var len2 = p0[0].length;
  3774. for (var i = 0; i < len; i++) {
  3775. for (var j = 0; j < len2; j++) {
  3776. out[i][j] = catmullRomInterpolate(
  3777. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3778. t, t2, t3
  3779. );
  3780. }
  3781. }
  3782. }
  3783. }
  3784. /**
  3785. * Catmull Rom interpolate number
  3786. * @param {number} p0
  3787. * @param {number} p1
  3788. * @param {number} p2
  3789. * @param {number} p3
  3790. * @param {number} t
  3791. * @param {number} t2
  3792. * @param {number} t3
  3793. * @return {number}
  3794. */
  3795. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3796. var v0 = (p2 - p0) * 0.5;
  3797. var v1 = (p3 - p1) * 0.5;
  3798. return (2 * (p1 - p2) + v0 + v1) * t3
  3799. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3800. + v0 * t + p1;
  3801. }
  3802. function cloneValue(value) {
  3803. if (isArrayLike(value)) {
  3804. var len = value.length;
  3805. if (isArrayLike(value[0])) {
  3806. var ret = [];
  3807. for (var i = 0; i < len; i++) {
  3808. ret.push(arraySlice.call(value[i]));
  3809. }
  3810. return ret;
  3811. }
  3812. return arraySlice.call(value);
  3813. }
  3814. return value;
  3815. }
  3816. function rgba2String(rgba) {
  3817. rgba[0] = Math.floor(rgba[0]);
  3818. rgba[1] = Math.floor(rgba[1]);
  3819. rgba[2] = Math.floor(rgba[2]);
  3820. return 'rgba(' + rgba.join(',') + ')';
  3821. }
  3822. function getArrayDim(keyframes) {
  3823. var lastValue = keyframes[keyframes.length - 1].value;
  3824. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3825. }
  3826. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3827. var getter = animator._getter;
  3828. var setter = animator._setter;
  3829. var useSpline = easing === 'spline';
  3830. var trackLen = keyframes.length;
  3831. if (!trackLen) {
  3832. return;
  3833. }
  3834. // Guess data type
  3835. var firstVal = keyframes[0].value;
  3836. var isValueArray = isArrayLike(firstVal);
  3837. var isValueColor = false;
  3838. var isValueString = false;
  3839. // For vertices morphing
  3840. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3841. var trackMaxTime;
  3842. // Sort keyframe as ascending
  3843. keyframes.sort(function (a, b) {
  3844. return a.time - b.time;
  3845. });
  3846. trackMaxTime = keyframes[trackLen - 1].time;
  3847. // Percents of each keyframe
  3848. var kfPercents = [];
  3849. // Value of each keyframe
  3850. var kfValues = [];
  3851. var prevValue = keyframes[0].value;
  3852. var isAllValueEqual = true;
  3853. for (var i = 0; i < trackLen; i++) {
  3854. kfPercents.push(keyframes[i].time / trackMaxTime);
  3855. // Assume value is a color when it is a string
  3856. var value = keyframes[i].value;
  3857. // Check if value is equal, deep check if value is array
  3858. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3859. || (!isValueArray && value === prevValue))) {
  3860. isAllValueEqual = false;
  3861. }
  3862. prevValue = value;
  3863. // Try converting a string to a color array
  3864. if (typeof value === 'string') {
  3865. var colorArray = parse(value);
  3866. if (colorArray) {
  3867. value = colorArray;
  3868. isValueColor = true;
  3869. }
  3870. else {
  3871. isValueString = true;
  3872. }
  3873. }
  3874. kfValues.push(value);
  3875. }
  3876. if (!forceAnimate && isAllValueEqual) {
  3877. return;
  3878. }
  3879. var lastValue = kfValues[trackLen - 1];
  3880. // Polyfill array and NaN value
  3881. for (var i = 0; i < trackLen - 1; i++) {
  3882. if (isValueArray) {
  3883. fillArr(kfValues[i], lastValue, arrDim);
  3884. }
  3885. else {
  3886. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3887. kfValues[i] = lastValue;
  3888. }
  3889. }
  3890. }
  3891. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3892. // Cache the key of last frame to speed up when
  3893. // animation playback is sequency
  3894. var lastFrame = 0;
  3895. var lastFramePercent = 0;
  3896. var start;
  3897. var w;
  3898. var p0;
  3899. var p1;
  3900. var p2;
  3901. var p3;
  3902. if (isValueColor) {
  3903. var rgba = [0, 0, 0, 0];
  3904. }
  3905. var onframe = function (target, percent) {
  3906. // Find the range keyframes
  3907. // kf1-----kf2---------current--------kf3
  3908. // find kf2 and kf3 and do interpolation
  3909. var frame;
  3910. // In the easing function like elasticOut, percent may less than 0
  3911. if (percent < 0) {
  3912. frame = 0;
  3913. }
  3914. else if (percent < lastFramePercent) {
  3915. // Start from next key
  3916. // PENDING start from lastFrame ?
  3917. start = Math.min(lastFrame + 1, trackLen - 1);
  3918. for (frame = start; frame >= 0; frame--) {
  3919. if (kfPercents[frame] <= percent) {
  3920. break;
  3921. }
  3922. }
  3923. // PENDING really need to do this ?
  3924. frame = Math.min(frame, trackLen - 2);
  3925. }
  3926. else {
  3927. for (frame = lastFrame; frame < trackLen; frame++) {
  3928. if (kfPercents[frame] > percent) {
  3929. break;
  3930. }
  3931. }
  3932. frame = Math.min(frame - 1, trackLen - 2);
  3933. }
  3934. lastFrame = frame;
  3935. lastFramePercent = percent;
  3936. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3937. if (range === 0) {
  3938. return;
  3939. }
  3940. else {
  3941. w = (percent - kfPercents[frame]) / range;
  3942. }
  3943. if (useSpline) {
  3944. p1 = kfValues[frame];
  3945. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3946. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3947. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3948. if (isValueArray) {
  3949. catmullRomInterpolateArray(
  3950. p0, p1, p2, p3, w, w * w, w * w * w,
  3951. getter(target, propName),
  3952. arrDim
  3953. );
  3954. }
  3955. else {
  3956. var value;
  3957. if (isValueColor) {
  3958. value = catmullRomInterpolateArray(
  3959. p0, p1, p2, p3, w, w * w, w * w * w,
  3960. rgba, 1
  3961. );
  3962. value = rgba2String(rgba);
  3963. }
  3964. else if (isValueString) {
  3965. // String is step(0.5)
  3966. return interpolateString(p1, p2, w);
  3967. }
  3968. else {
  3969. value = catmullRomInterpolate(
  3970. p0, p1, p2, p3, w, w * w, w * w * w
  3971. );
  3972. }
  3973. setter(
  3974. target,
  3975. propName,
  3976. value
  3977. );
  3978. }
  3979. }
  3980. else {
  3981. if (isValueArray) {
  3982. interpolateArray(
  3983. kfValues[frame], kfValues[frame + 1], w,
  3984. getter(target, propName),
  3985. arrDim
  3986. );
  3987. }
  3988. else {
  3989. var value;
  3990. if (isValueColor) {
  3991. interpolateArray(
  3992. kfValues[frame], kfValues[frame + 1], w,
  3993. rgba, 1
  3994. );
  3995. value = rgba2String(rgba);
  3996. }
  3997. else if (isValueString) {
  3998. // String is step(0.5)
  3999. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4000. }
  4001. else {
  4002. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4003. }
  4004. setter(
  4005. target,
  4006. propName,
  4007. value
  4008. );
  4009. }
  4010. }
  4011. };
  4012. var clip = new Clip({
  4013. target: animator._target,
  4014. life: trackMaxTime,
  4015. loop: animator._loop,
  4016. delay: animator._delay,
  4017. onframe: onframe,
  4018. ondestroy: oneTrackDone
  4019. });
  4020. if (easing && easing !== 'spline') {
  4021. clip.easing = easing;
  4022. }
  4023. return clip;
  4024. }
  4025. /**
  4026. * @alias module:zrender/animation/Animator
  4027. * @constructor
  4028. * @param {Object} target
  4029. * @param {boolean} loop
  4030. * @param {Function} getter
  4031. * @param {Function} setter
  4032. */
  4033. var Animator = function (target, loop, getter, setter) {
  4034. this._tracks = {};
  4035. this._target = target;
  4036. this._loop = loop || false;
  4037. this._getter = getter || defaultGetter;
  4038. this._setter = setter || defaultSetter;
  4039. this._clipCount = 0;
  4040. this._delay = 0;
  4041. this._doneList = [];
  4042. this._onframeList = [];
  4043. this._clipList = [];
  4044. };
  4045. Animator.prototype = {
  4046. /**
  4047. * Set Animation keyframe
  4048. * @param {number} time 关键帧时间,单位是ms
  4049. * @param {Object} props 关键帧的属性值,key-value表示
  4050. * @return {module:zrender/animation/Animator}
  4051. */
  4052. when: function (time /* ms */, props) {
  4053. var tracks = this._tracks;
  4054. for (var propName in props) {
  4055. if (!props.hasOwnProperty(propName)) {
  4056. continue;
  4057. }
  4058. if (!tracks[propName]) {
  4059. tracks[propName] = [];
  4060. // Invalid value
  4061. var value = this._getter(this._target, propName);
  4062. if (value == null) {
  4063. // zrLog('Invalid property ' + propName);
  4064. continue;
  4065. }
  4066. // If time is 0
  4067. // Then props is given initialize value
  4068. // Else
  4069. // Initialize value from current prop value
  4070. if (time !== 0) {
  4071. tracks[propName].push({
  4072. time: 0,
  4073. value: cloneValue(value)
  4074. });
  4075. }
  4076. }
  4077. tracks[propName].push({
  4078. time: time,
  4079. value: props[propName]
  4080. });
  4081. }
  4082. return this;
  4083. },
  4084. /**
  4085. * 添加动画每一帧的回调函数
  4086. * @param {Function} callback
  4087. * @return {module:zrender/animation/Animator}
  4088. */
  4089. during: function (callback) {
  4090. this._onframeList.push(callback);
  4091. return this;
  4092. },
  4093. pause: function () {
  4094. for (var i = 0; i < this._clipList.length; i++) {
  4095. this._clipList[i].pause();
  4096. }
  4097. this._paused = true;
  4098. },
  4099. resume: function () {
  4100. for (var i = 0; i < this._clipList.length; i++) {
  4101. this._clipList[i].resume();
  4102. }
  4103. this._paused = false;
  4104. },
  4105. isPaused: function () {
  4106. return !!this._paused;
  4107. },
  4108. _doneCallback: function () {
  4109. // Clear all tracks
  4110. this._tracks = {};
  4111. // Clear all clips
  4112. this._clipList.length = 0;
  4113. var doneList = this._doneList;
  4114. var len = doneList.length;
  4115. for (var i = 0; i < len; i++) {
  4116. doneList[i].call(this);
  4117. }
  4118. },
  4119. /**
  4120. * Start the animation
  4121. * @param {string|Function} [easing]
  4122. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4123. * @param {boolean} forceAnimate
  4124. * @return {module:zrender/animation/Animator}
  4125. */
  4126. start: function (easing, forceAnimate) {
  4127. var self = this;
  4128. var clipCount = 0;
  4129. var oneTrackDone = function () {
  4130. clipCount--;
  4131. if (!clipCount) {
  4132. self._doneCallback();
  4133. }
  4134. };
  4135. var lastClip;
  4136. for (var propName in this._tracks) {
  4137. if (!this._tracks.hasOwnProperty(propName)) {
  4138. continue;
  4139. }
  4140. var clip = createTrackClip(
  4141. this, easing, oneTrackDone,
  4142. this._tracks[propName], propName, forceAnimate
  4143. );
  4144. if (clip) {
  4145. this._clipList.push(clip);
  4146. clipCount++;
  4147. // If start after added to animation
  4148. if (this.animation) {
  4149. this.animation.addClip(clip);
  4150. }
  4151. lastClip = clip;
  4152. }
  4153. }
  4154. // Add during callback on the last clip
  4155. if (lastClip) {
  4156. var oldOnFrame = lastClip.onframe;
  4157. lastClip.onframe = function (target, percent) {
  4158. oldOnFrame(target, percent);
  4159. for (var i = 0; i < self._onframeList.length; i++) {
  4160. self._onframeList[i](target, percent);
  4161. }
  4162. };
  4163. }
  4164. // This optimization will help the case that in the upper application
  4165. // the view may be refreshed frequently, where animation will be
  4166. // called repeatly but nothing changed.
  4167. if (!clipCount) {
  4168. this._doneCallback();
  4169. }
  4170. return this;
  4171. },
  4172. /**
  4173. * Stop animation
  4174. * @param {boolean} forwardToLast If move to last frame before stop
  4175. */
  4176. stop: function (forwardToLast) {
  4177. var clipList = this._clipList;
  4178. var animation = this.animation;
  4179. for (var i = 0; i < clipList.length; i++) {
  4180. var clip = clipList[i];
  4181. if (forwardToLast) {
  4182. // Move to last frame before stop
  4183. clip.onframe(this._target, 1);
  4184. }
  4185. animation && animation.removeClip(clip);
  4186. }
  4187. clipList.length = 0;
  4188. },
  4189. /**
  4190. * Set when animation delay starts
  4191. * @param {number} time 单位ms
  4192. * @return {module:zrender/animation/Animator}
  4193. */
  4194. delay: function (time) {
  4195. this._delay = time;
  4196. return this;
  4197. },
  4198. /**
  4199. * Add callback for animation end
  4200. * @param {Function} cb
  4201. * @return {module:zrender/animation/Animator}
  4202. */
  4203. done: function (cb) {
  4204. if (cb) {
  4205. this._doneList.push(cb);
  4206. }
  4207. return this;
  4208. },
  4209. /**
  4210. * @return {Array.<module:zrender/animation/Clip>}
  4211. */
  4212. getClips: function () {
  4213. return this._clipList;
  4214. }
  4215. };
  4216. var dpr = 1;
  4217. // If in browser environment
  4218. if (typeof window !== 'undefined') {
  4219. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4220. }
  4221. /**
  4222. * config默认配置项
  4223. * @exports zrender/config
  4224. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4225. */
  4226. /**
  4227. * Debug log mode:
  4228. * 0: Do nothing, for release.
  4229. * 1: console.error, for debug.
  4230. */
  4231. var debugMode = 0;
  4232. // retina 屏幕优化
  4233. var devicePixelRatio = dpr;
  4234. var logError = function () {
  4235. };
  4236. if (debugMode === 1) {
  4237. logError = console.error;
  4238. }
  4239. var logError$1 = logError;
  4240. /**
  4241. * @alias module:zrender/mixin/Animatable
  4242. * @constructor
  4243. */
  4244. var Animatable = function () {
  4245. /**
  4246. * @type {Array.<module:zrender/animation/Animator>}
  4247. * @readOnly
  4248. */
  4249. this.animators = [];
  4250. };
  4251. Animatable.prototype = {
  4252. constructor: Animatable,
  4253. /**
  4254. * 动画
  4255. *
  4256. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4257. * @param {boolean} [loop] Whether to loop animation.
  4258. * @return {module:zrender/animation/Animator}
  4259. * @example:
  4260. * el.animate('style', false)
  4261. * .when(1000, {x: 10} )
  4262. * .done(function(){ // Animation done })
  4263. * .start()
  4264. */
  4265. animate: function (path, loop) {
  4266. var target;
  4267. var animatingShape = false;
  4268. var el = this;
  4269. var zr = this.__zr;
  4270. if (path) {
  4271. var pathSplitted = path.split('.');
  4272. var prop = el;
  4273. // If animating shape
  4274. animatingShape = pathSplitted[0] === 'shape';
  4275. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4276. if (!prop) {
  4277. continue;
  4278. }
  4279. prop = prop[pathSplitted[i]];
  4280. }
  4281. if (prop) {
  4282. target = prop;
  4283. }
  4284. }
  4285. else {
  4286. target = el;
  4287. }
  4288. if (!target) {
  4289. logError$1(
  4290. 'Property "'
  4291. + path
  4292. + '" is not existed in element '
  4293. + el.id
  4294. );
  4295. return;
  4296. }
  4297. var animators = el.animators;
  4298. var animator = new Animator(target, loop);
  4299. animator.during(function (target) {
  4300. el.dirty(animatingShape);
  4301. })
  4302. .done(function () {
  4303. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4304. animators.splice(indexOf(animators, animator), 1);
  4305. });
  4306. animators.push(animator);
  4307. // If animate after added to the zrender
  4308. if (zr) {
  4309. zr.animation.addAnimator(animator);
  4310. }
  4311. return animator;
  4312. },
  4313. /**
  4314. * 停止动画
  4315. * @param {boolean} forwardToLast If move to last frame before stop
  4316. */
  4317. stopAnimation: function (forwardToLast) {
  4318. var animators = this.animators;
  4319. var len = animators.length;
  4320. for (var i = 0; i < len; i++) {
  4321. animators[i].stop(forwardToLast);
  4322. }
  4323. animators.length = 0;
  4324. return this;
  4325. },
  4326. /**
  4327. * Caution: this method will stop previous animation.
  4328. * So do not use this method to one element twice before
  4329. * animation starts, unless you know what you are doing.
  4330. * @param {Object} target
  4331. * @param {number} [time=500] Time in ms
  4332. * @param {string} [easing='linear']
  4333. * @param {number} [delay=0]
  4334. * @param {Function} [callback]
  4335. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4336. * immediently when target values are the same as current values.
  4337. *
  4338. * @example
  4339. * // Animate position
  4340. * el.animateTo({
  4341. * position: [10, 10]
  4342. * }, function () { // done })
  4343. *
  4344. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4345. * el.animateTo({
  4346. * shape: {
  4347. * width: 500
  4348. * },
  4349. * style: {
  4350. * fill: 'red'
  4351. * }
  4352. * position: [10, 10]
  4353. * }, 100, 100, 'cubicOut', function () { // done })
  4354. */
  4355. // TODO Return animation key
  4356. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4357. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4358. },
  4359. /**
  4360. * Animate from the target state to current state.
  4361. * The params and the return value are the same as `this.animateTo`.
  4362. */
  4363. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4364. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4365. }
  4366. };
  4367. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4368. // animateTo(target, time, easing, callback);
  4369. if (isString(delay)) {
  4370. callback = easing;
  4371. easing = delay;
  4372. delay = 0;
  4373. }
  4374. // animateTo(target, time, delay, callback);
  4375. else if (isFunction$1(easing)) {
  4376. callback = easing;
  4377. easing = 'linear';
  4378. delay = 0;
  4379. }
  4380. // animateTo(target, time, callback);
  4381. else if (isFunction$1(delay)) {
  4382. callback = delay;
  4383. delay = 0;
  4384. }
  4385. // animateTo(target, callback)
  4386. else if (isFunction$1(time)) {
  4387. callback = time;
  4388. time = 500;
  4389. }
  4390. // animateTo(target)
  4391. else if (!time) {
  4392. time = 500;
  4393. }
  4394. // Stop all previous animations
  4395. animatable.stopAnimation();
  4396. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4397. // Animators may be removed immediately after start
  4398. // if there is nothing to animate
  4399. var animators = animatable.animators.slice();
  4400. var count = animators.length;
  4401. function done() {
  4402. count--;
  4403. if (!count) {
  4404. callback && callback();
  4405. }
  4406. }
  4407. // No animators. This should be checked before animators[i].start(),
  4408. // because 'done' may be executed immediately if no need to animate.
  4409. if (!count) {
  4410. callback && callback();
  4411. }
  4412. // Start after all animators created
  4413. // Incase any animator is done immediately when all animation properties are not changed
  4414. for (var i = 0; i < animators.length; i++) {
  4415. animators[i]
  4416. .done(done)
  4417. .start(easing, forceAnimate);
  4418. }
  4419. }
  4420. /**
  4421. * @param {string} path=''
  4422. * @param {Object} source=animatable
  4423. * @param {Object} target
  4424. * @param {number} [time=500]
  4425. * @param {number} [delay=0]
  4426. * @param {boolean} [reverse] If `true`, animate
  4427. * from the `target` to current state.
  4428. *
  4429. * @example
  4430. * // Animate position
  4431. * el._animateToShallow({
  4432. * position: [10, 10]
  4433. * })
  4434. *
  4435. * // Animate shape, style and position in 100ms, delayed 100ms
  4436. * el._animateToShallow({
  4437. * shape: {
  4438. * width: 500
  4439. * },
  4440. * style: {
  4441. * fill: 'red'
  4442. * }
  4443. * position: [10, 10]
  4444. * }, 100, 100)
  4445. */
  4446. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4447. var objShallow = {};
  4448. var propertyCount = 0;
  4449. for (var name in target) {
  4450. if (!target.hasOwnProperty(name)) {
  4451. continue;
  4452. }
  4453. if (source[name] != null) {
  4454. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4455. animateToShallow(
  4456. animatable,
  4457. path ? path + '.' + name : name,
  4458. source[name],
  4459. target[name],
  4460. time,
  4461. delay,
  4462. reverse
  4463. );
  4464. }
  4465. else {
  4466. if (reverse) {
  4467. objShallow[name] = source[name];
  4468. setAttrByPath(animatable, path, name, target[name]);
  4469. }
  4470. else {
  4471. objShallow[name] = target[name];
  4472. }
  4473. propertyCount++;
  4474. }
  4475. }
  4476. else if (target[name] != null && !reverse) {
  4477. setAttrByPath(animatable, path, name, target[name]);
  4478. }
  4479. }
  4480. if (propertyCount > 0) {
  4481. animatable.animate(path, false)
  4482. .when(time == null ? 500 : time, objShallow)
  4483. .delay(delay || 0);
  4484. }
  4485. }
  4486. function setAttrByPath(el, path, name, value) {
  4487. // Attr directly if not has property
  4488. // FIXME, if some property not needed for element ?
  4489. if (!path) {
  4490. el.attr(name, value);
  4491. }
  4492. else {
  4493. // Only support set shape or style
  4494. var props = {};
  4495. props[path] = {};
  4496. props[path][name] = value;
  4497. el.attr(props);
  4498. }
  4499. }
  4500. /**
  4501. * @alias module:zrender/Element
  4502. * @constructor
  4503. * @extends {module:zrender/mixin/Animatable}
  4504. * @extends {module:zrender/mixin/Transformable}
  4505. * @extends {module:zrender/mixin/Eventful}
  4506. */
  4507. var Element = function (opts) { // jshint ignore:line
  4508. Transformable.call(this, opts);
  4509. Eventful.call(this, opts);
  4510. Animatable.call(this, opts);
  4511. /**
  4512. * 画布元素ID
  4513. * @type {string}
  4514. */
  4515. this.id = opts.id || guid();
  4516. };
  4517. Element.prototype = {
  4518. /**
  4519. * 元素类型
  4520. * Element type
  4521. * @type {string}
  4522. */
  4523. type: 'element',
  4524. /**
  4525. * 元素名字
  4526. * Element name
  4527. * @type {string}
  4528. */
  4529. name: '',
  4530. /**
  4531. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4532. * ZRender instance will be assigned when element is associated with zrender
  4533. * @name module:/zrender/Element#__zr
  4534. * @type {module:zrender/ZRender}
  4535. */
  4536. __zr: null,
  4537. /**
  4538. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4539. * If ignore drawing and events of the element object
  4540. * @name module:/zrender/Element#ignore
  4541. * @type {boolean}
  4542. * @default false
  4543. */
  4544. ignore: false,
  4545. /**
  4546. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4547. * 该路径会继承被裁减对象的变换
  4548. * @type {module:zrender/graphic/Path}
  4549. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4550. * @readOnly
  4551. */
  4552. clipPath: null,
  4553. /**
  4554. * 是否是 Group
  4555. * @type {boolean}
  4556. */
  4557. isGroup: false,
  4558. /**
  4559. * Drift element
  4560. * @param {number} dx dx on the global space
  4561. * @param {number} dy dy on the global space
  4562. */
  4563. drift: function (dx, dy) {
  4564. switch (this.draggable) {
  4565. case 'horizontal':
  4566. dy = 0;
  4567. break;
  4568. case 'vertical':
  4569. dx = 0;
  4570. break;
  4571. }
  4572. var m = this.transform;
  4573. if (!m) {
  4574. m = this.transform = [1, 0, 0, 1, 0, 0];
  4575. }
  4576. m[4] += dx;
  4577. m[5] += dy;
  4578. this.decomposeTransform();
  4579. this.dirty(false);
  4580. },
  4581. /**
  4582. * Hook before update
  4583. */
  4584. beforeUpdate: function () {},
  4585. /**
  4586. * Hook after update
  4587. */
  4588. afterUpdate: function () {},
  4589. /**
  4590. * Update each frame
  4591. */
  4592. update: function () {
  4593. this.updateTransform();
  4594. },
  4595. /**
  4596. * @param {Function} cb
  4597. * @param {} context
  4598. */
  4599. traverse: function (cb, context) {},
  4600. /**
  4601. * @protected
  4602. */
  4603. attrKV: function (key, value) {
  4604. if (key === 'position' || key === 'scale' || key === 'origin') {
  4605. // Copy the array
  4606. if (value) {
  4607. var target = this[key];
  4608. if (!target) {
  4609. target = this[key] = [];
  4610. }
  4611. target[0] = value[0];
  4612. target[1] = value[1];
  4613. }
  4614. }
  4615. else {
  4616. this[key] = value;
  4617. }
  4618. },
  4619. /**
  4620. * Hide the element
  4621. */
  4622. hide: function () {
  4623. this.ignore = true;
  4624. this.__zr && this.__zr.refresh();
  4625. },
  4626. /**
  4627. * Show the element
  4628. */
  4629. show: function () {
  4630. this.ignore = false;
  4631. this.__zr && this.__zr.refresh();
  4632. },
  4633. /**
  4634. * @param {string|Object} key
  4635. * @param {*} value
  4636. */
  4637. attr: function (key, value) {
  4638. if (typeof key === 'string') {
  4639. this.attrKV(key, value);
  4640. }
  4641. else if (isObject$1(key)) {
  4642. for (var name in key) {
  4643. if (key.hasOwnProperty(name)) {
  4644. this.attrKV(name, key[name]);
  4645. }
  4646. }
  4647. }
  4648. this.dirty(false);
  4649. return this;
  4650. },
  4651. /**
  4652. * @param {module:zrender/graphic/Path} clipPath
  4653. */
  4654. setClipPath: function (clipPath) {
  4655. var zr = this.__zr;
  4656. if (zr) {
  4657. clipPath.addSelfToZr(zr);
  4658. }
  4659. // Remove previous clip path
  4660. if (this.clipPath && this.clipPath !== clipPath) {
  4661. this.removeClipPath();
  4662. }
  4663. this.clipPath = clipPath;
  4664. clipPath.__zr = zr;
  4665. clipPath.__clipTarget = this;
  4666. this.dirty(false);
  4667. },
  4668. /**
  4669. */
  4670. removeClipPath: function () {
  4671. var clipPath = this.clipPath;
  4672. if (clipPath) {
  4673. if (clipPath.__zr) {
  4674. clipPath.removeSelfFromZr(clipPath.__zr);
  4675. }
  4676. clipPath.__zr = null;
  4677. clipPath.__clipTarget = null;
  4678. this.clipPath = null;
  4679. this.dirty(false);
  4680. }
  4681. },
  4682. /**
  4683. * Add self from zrender instance.
  4684. * Not recursively because it will be invoked when element added to storage.
  4685. * @param {module:zrender/ZRender} zr
  4686. */
  4687. addSelfToZr: function (zr) {
  4688. this.__zr = zr;
  4689. // 添加动画
  4690. var animators = this.animators;
  4691. if (animators) {
  4692. for (var i = 0; i < animators.length; i++) {
  4693. zr.animation.addAnimator(animators[i]);
  4694. }
  4695. }
  4696. if (this.clipPath) {
  4697. this.clipPath.addSelfToZr(zr);
  4698. }
  4699. },
  4700. /**
  4701. * Remove self from zrender instance.
  4702. * Not recursively because it will be invoked when element added to storage.
  4703. * @param {module:zrender/ZRender} zr
  4704. */
  4705. removeSelfFromZr: function (zr) {
  4706. this.__zr = null;
  4707. // 移除动画
  4708. var animators = this.animators;
  4709. if (animators) {
  4710. for (var i = 0; i < animators.length; i++) {
  4711. zr.animation.removeAnimator(animators[i]);
  4712. }
  4713. }
  4714. if (this.clipPath) {
  4715. this.clipPath.removeSelfFromZr(zr);
  4716. }
  4717. }
  4718. };
  4719. mixin(Element, Animatable);
  4720. mixin(Element, Transformable);
  4721. mixin(Element, Eventful);
  4722. /**
  4723. * @module echarts/core/BoundingRect
  4724. */
  4725. var v2ApplyTransform = applyTransform;
  4726. var mathMin = Math.min;
  4727. var mathMax = Math.max;
  4728. /**
  4729. * @alias module:echarts/core/BoundingRect
  4730. */
  4731. function BoundingRect(x, y, width, height) {
  4732. if (width < 0) {
  4733. x = x + width;
  4734. width = -width;
  4735. }
  4736. if (height < 0) {
  4737. y = y + height;
  4738. height = -height;
  4739. }
  4740. /**
  4741. * @type {number}
  4742. */
  4743. this.x = x;
  4744. /**
  4745. * @type {number}
  4746. */
  4747. this.y = y;
  4748. /**
  4749. * @type {number}
  4750. */
  4751. this.width = width;
  4752. /**
  4753. * @type {number}
  4754. */
  4755. this.height = height;
  4756. }
  4757. BoundingRect.prototype = {
  4758. constructor: BoundingRect,
  4759. /**
  4760. * @param {module:echarts/core/BoundingRect} other
  4761. */
  4762. union: function (other) {
  4763. var x = mathMin(other.x, this.x);
  4764. var y = mathMin(other.y, this.y);
  4765. this.width = mathMax(
  4766. other.x + other.width,
  4767. this.x + this.width
  4768. ) - x;
  4769. this.height = mathMax(
  4770. other.y + other.height,
  4771. this.y + this.height
  4772. ) - y;
  4773. this.x = x;
  4774. this.y = y;
  4775. },
  4776. /**
  4777. * @param {Array.<number>} m
  4778. * @methods
  4779. */
  4780. applyTransform: (function () {
  4781. var lt = [];
  4782. var rb = [];
  4783. var lb = [];
  4784. var rt = [];
  4785. return function (m) {
  4786. // In case usage like this
  4787. // el.getBoundingRect().applyTransform(el.transform)
  4788. // And element has no transform
  4789. if (!m) {
  4790. return;
  4791. }
  4792. lt[0] = lb[0] = this.x;
  4793. lt[1] = rt[1] = this.y;
  4794. rb[0] = rt[0] = this.x + this.width;
  4795. rb[1] = lb[1] = this.y + this.height;
  4796. v2ApplyTransform(lt, lt, m);
  4797. v2ApplyTransform(rb, rb, m);
  4798. v2ApplyTransform(lb, lb, m);
  4799. v2ApplyTransform(rt, rt, m);
  4800. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4801. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4802. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4803. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4804. this.width = maxX - this.x;
  4805. this.height = maxY - this.y;
  4806. };
  4807. })(),
  4808. /**
  4809. * Calculate matrix of transforming from self to target rect
  4810. * @param {module:zrender/core/BoundingRect} b
  4811. * @return {Array.<number>}
  4812. */
  4813. calculateTransform: function (b) {
  4814. var a = this;
  4815. var sx = b.width / a.width;
  4816. var sy = b.height / a.height;
  4817. var m = create$1();
  4818. // 矩阵右乘
  4819. translate(m, m, [-a.x, -a.y]);
  4820. scale$1(m, m, [sx, sy]);
  4821. translate(m, m, [b.x, b.y]);
  4822. return m;
  4823. },
  4824. /**
  4825. * @param {(module:echarts/core/BoundingRect|Object)} b
  4826. * @return {boolean}
  4827. */
  4828. intersect: function (b) {
  4829. if (!b) {
  4830. return false;
  4831. }
  4832. if (!(b instanceof BoundingRect)) {
  4833. // Normalize negative width/height.
  4834. b = BoundingRect.create(b);
  4835. }
  4836. var a = this;
  4837. var ax0 = a.x;
  4838. var ax1 = a.x + a.width;
  4839. var ay0 = a.y;
  4840. var ay1 = a.y + a.height;
  4841. var bx0 = b.x;
  4842. var bx1 = b.x + b.width;
  4843. var by0 = b.y;
  4844. var by1 = b.y + b.height;
  4845. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4846. },
  4847. contain: function (x, y) {
  4848. var rect = this;
  4849. return x >= rect.x
  4850. && x <= (rect.x + rect.width)
  4851. && y >= rect.y
  4852. && y <= (rect.y + rect.height);
  4853. },
  4854. /**
  4855. * @return {module:echarts/core/BoundingRect}
  4856. */
  4857. clone: function () {
  4858. return new BoundingRect(this.x, this.y, this.width, this.height);
  4859. },
  4860. /**
  4861. * Copy from another rect
  4862. */
  4863. copy: function (other) {
  4864. this.x = other.x;
  4865. this.y = other.y;
  4866. this.width = other.width;
  4867. this.height = other.height;
  4868. },
  4869. plain: function () {
  4870. return {
  4871. x: this.x,
  4872. y: this.y,
  4873. width: this.width,
  4874. height: this.height
  4875. };
  4876. }
  4877. };
  4878. /**
  4879. * @param {Object|module:zrender/core/BoundingRect} rect
  4880. * @param {number} rect.x
  4881. * @param {number} rect.y
  4882. * @param {number} rect.width
  4883. * @param {number} rect.height
  4884. * @return {module:zrender/core/BoundingRect}
  4885. */
  4886. BoundingRect.create = function (rect) {
  4887. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4888. };
  4889. /**
  4890. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4891. * @module zrender/graphic/Group
  4892. * @example
  4893. * var Group = require('zrender/container/Group');
  4894. * var Circle = require('zrender/graphic/shape/Circle');
  4895. * var g = new Group();
  4896. * g.position[0] = 100;
  4897. * g.position[1] = 100;
  4898. * g.add(new Circle({
  4899. * style: {
  4900. * x: 100,
  4901. * y: 100,
  4902. * r: 20,
  4903. * }
  4904. * }));
  4905. * zr.add(g);
  4906. */
  4907. /**
  4908. * @alias module:zrender/graphic/Group
  4909. * @constructor
  4910. * @extends module:zrender/mixin/Transformable
  4911. * @extends module:zrender/mixin/Eventful
  4912. */
  4913. var Group = function (opts) {
  4914. opts = opts || {};
  4915. Element.call(this, opts);
  4916. for (var key in opts) {
  4917. if (opts.hasOwnProperty(key)) {
  4918. this[key] = opts[key];
  4919. }
  4920. }
  4921. this._children = [];
  4922. this.__storage = null;
  4923. this.__dirty = true;
  4924. };
  4925. Group.prototype = {
  4926. constructor: Group,
  4927. isGroup: true,
  4928. /**
  4929. * @type {string}
  4930. */
  4931. type: 'group',
  4932. /**
  4933. * 所有子孙元素是否响应鼠标事件
  4934. * @name module:/zrender/container/Group#silent
  4935. * @type {boolean}
  4936. * @default false
  4937. */
  4938. silent: false,
  4939. /**
  4940. * @return {Array.<module:zrender/Element>}
  4941. */
  4942. children: function () {
  4943. return this._children.slice();
  4944. },
  4945. /**
  4946. * 获取指定 index 的儿子节点
  4947. * @param {number} idx
  4948. * @return {module:zrender/Element}
  4949. */
  4950. childAt: function (idx) {
  4951. return this._children[idx];
  4952. },
  4953. /**
  4954. * 获取指定名字的儿子节点
  4955. * @param {string} name
  4956. * @return {module:zrender/Element}
  4957. */
  4958. childOfName: function (name) {
  4959. var children = this._children;
  4960. for (var i = 0; i < children.length; i++) {
  4961. if (children[i].name === name) {
  4962. return children[i];
  4963. }
  4964. }
  4965. },
  4966. /**
  4967. * @return {number}
  4968. */
  4969. childCount: function () {
  4970. return this._children.length;
  4971. },
  4972. /**
  4973. * 添加子节点到最后
  4974. * @param {module:zrender/Element} child
  4975. */
  4976. add: function (child) {
  4977. if (child && child !== this && child.parent !== this) {
  4978. this._children.push(child);
  4979. this._doAdd(child);
  4980. }
  4981. return this;
  4982. },
  4983. /**
  4984. * 添加子节点在 nextSibling 之前
  4985. * @param {module:zrender/Element} child
  4986. * @param {module:zrender/Element} nextSibling
  4987. */
  4988. addBefore: function (child, nextSibling) {
  4989. if (child && child !== this && child.parent !== this
  4990. && nextSibling && nextSibling.parent === this) {
  4991. var children = this._children;
  4992. var idx = children.indexOf(nextSibling);
  4993. if (idx >= 0) {
  4994. children.splice(idx, 0, child);
  4995. this._doAdd(child);
  4996. }
  4997. }
  4998. return this;
  4999. },
  5000. _doAdd: function (child) {
  5001. if (child.parent) {
  5002. child.parent.remove(child);
  5003. }
  5004. child.parent = this;
  5005. var storage = this.__storage;
  5006. var zr = this.__zr;
  5007. if (storage && storage !== child.__storage) {
  5008. storage.addToStorage(child);
  5009. if (child instanceof Group) {
  5010. child.addChildrenToStorage(storage);
  5011. }
  5012. }
  5013. zr && zr.refresh();
  5014. },
  5015. /**
  5016. * 移除子节点
  5017. * @param {module:zrender/Element} child
  5018. */
  5019. remove: function (child) {
  5020. var zr = this.__zr;
  5021. var storage = this.__storage;
  5022. var children = this._children;
  5023. var idx = indexOf(children, child);
  5024. if (idx < 0) {
  5025. return this;
  5026. }
  5027. children.splice(idx, 1);
  5028. child.parent = null;
  5029. if (storage) {
  5030. storage.delFromStorage(child);
  5031. if (child instanceof Group) {
  5032. child.delChildrenFromStorage(storage);
  5033. }
  5034. }
  5035. zr && zr.refresh();
  5036. return this;
  5037. },
  5038. /**
  5039. * 移除所有子节点
  5040. */
  5041. removeAll: function () {
  5042. var children = this._children;
  5043. var storage = this.__storage;
  5044. var child;
  5045. var i;
  5046. for (i = 0; i < children.length; i++) {
  5047. child = children[i];
  5048. if (storage) {
  5049. storage.delFromStorage(child);
  5050. if (child instanceof Group) {
  5051. child.delChildrenFromStorage(storage);
  5052. }
  5053. }
  5054. child.parent = null;
  5055. }
  5056. children.length = 0;
  5057. return this;
  5058. },
  5059. /**
  5060. * 遍历所有子节点
  5061. * @param {Function} cb
  5062. * @param {} context
  5063. */
  5064. eachChild: function (cb, context) {
  5065. var children = this._children;
  5066. for (var i = 0; i < children.length; i++) {
  5067. var child = children[i];
  5068. cb.call(context, child, i);
  5069. }
  5070. return this;
  5071. },
  5072. /**
  5073. * 深度优先遍历所有子孙节点
  5074. * @param {Function} cb
  5075. * @param {} context
  5076. */
  5077. traverse: function (cb, context) {
  5078. for (var i = 0; i < this._children.length; i++) {
  5079. var child = this._children[i];
  5080. cb.call(context, child);
  5081. if (child.type === 'group') {
  5082. child.traverse(cb, context);
  5083. }
  5084. }
  5085. return this;
  5086. },
  5087. addChildrenToStorage: function (storage) {
  5088. for (var i = 0; i < this._children.length; i++) {
  5089. var child = this._children[i];
  5090. storage.addToStorage(child);
  5091. if (child instanceof Group) {
  5092. child.addChildrenToStorage(storage);
  5093. }
  5094. }
  5095. },
  5096. delChildrenFromStorage: function (storage) {
  5097. for (var i = 0; i < this._children.length; i++) {
  5098. var child = this._children[i];
  5099. storage.delFromStorage(child);
  5100. if (child instanceof Group) {
  5101. child.delChildrenFromStorage(storage);
  5102. }
  5103. }
  5104. },
  5105. dirty: function () {
  5106. this.__dirty = true;
  5107. this.__zr && this.__zr.refresh();
  5108. return this;
  5109. },
  5110. /**
  5111. * @return {module:zrender/core/BoundingRect}
  5112. */
  5113. getBoundingRect: function (includeChildren) {
  5114. // TODO Caching
  5115. var rect = null;
  5116. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5117. var children = includeChildren || this._children;
  5118. var tmpMat = [];
  5119. for (var i = 0; i < children.length; i++) {
  5120. var child = children[i];
  5121. if (child.ignore || child.invisible) {
  5122. continue;
  5123. }
  5124. var childRect = child.getBoundingRect();
  5125. var transform = child.getLocalTransform(tmpMat);
  5126. // TODO
  5127. // The boundingRect cacluated by transforming original
  5128. // rect may be bigger than the actual bundingRect when rotation
  5129. // is used. (Consider a circle rotated aginst its center, where
  5130. // the actual boundingRect should be the same as that not be
  5131. // rotated.) But we can not find better approach to calculate
  5132. // actual boundingRect yet, considering performance.
  5133. if (transform) {
  5134. tmpRect.copy(childRect);
  5135. tmpRect.applyTransform(transform);
  5136. rect = rect || tmpRect.clone();
  5137. rect.union(tmpRect);
  5138. }
  5139. else {
  5140. rect = rect || childRect.clone();
  5141. rect.union(childRect);
  5142. }
  5143. }
  5144. return rect || tmpRect;
  5145. }
  5146. };
  5147. inherits(Group, Element);
  5148. // https://github.com/mziccard/node-timsort
  5149. var DEFAULT_MIN_MERGE = 32;
  5150. var DEFAULT_MIN_GALLOPING = 7;
  5151. function minRunLength(n) {
  5152. var r = 0;
  5153. while (n >= DEFAULT_MIN_MERGE) {
  5154. r |= n & 1;
  5155. n >>= 1;
  5156. }
  5157. return n + r;
  5158. }
  5159. function makeAscendingRun(array, lo, hi, compare) {
  5160. var runHi = lo + 1;
  5161. if (runHi === hi) {
  5162. return 1;
  5163. }
  5164. if (compare(array[runHi++], array[lo]) < 0) {
  5165. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5166. runHi++;
  5167. }
  5168. reverseRun(array, lo, runHi);
  5169. }
  5170. else {
  5171. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5172. runHi++;
  5173. }
  5174. }
  5175. return runHi - lo;
  5176. }
  5177. function reverseRun(array, lo, hi) {
  5178. hi--;
  5179. while (lo < hi) {
  5180. var t = array[lo];
  5181. array[lo++] = array[hi];
  5182. array[hi--] = t;
  5183. }
  5184. }
  5185. function binaryInsertionSort(array, lo, hi, start, compare) {
  5186. if (start === lo) {
  5187. start++;
  5188. }
  5189. for (; start < hi; start++) {
  5190. var pivot = array[start];
  5191. var left = lo;
  5192. var right = start;
  5193. var mid;
  5194. while (left < right) {
  5195. mid = left + right >>> 1;
  5196. if (compare(pivot, array[mid]) < 0) {
  5197. right = mid;
  5198. }
  5199. else {
  5200. left = mid + 1;
  5201. }
  5202. }
  5203. var n = start - left;
  5204. switch (n) {
  5205. case 3:
  5206. array[left + 3] = array[left + 2];
  5207. case 2:
  5208. array[left + 2] = array[left + 1];
  5209. case 1:
  5210. array[left + 1] = array[left];
  5211. break;
  5212. default:
  5213. while (n > 0) {
  5214. array[left + n] = array[left + n - 1];
  5215. n--;
  5216. }
  5217. }
  5218. array[left] = pivot;
  5219. }
  5220. }
  5221. function gallopLeft(value, array, start, length, hint, compare) {
  5222. var lastOffset = 0;
  5223. var maxOffset = 0;
  5224. var offset = 1;
  5225. if (compare(value, array[start + hint]) > 0) {
  5226. maxOffset = length - hint;
  5227. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5228. lastOffset = offset;
  5229. offset = (offset << 1) + 1;
  5230. if (offset <= 0) {
  5231. offset = maxOffset;
  5232. }
  5233. }
  5234. if (offset > maxOffset) {
  5235. offset = maxOffset;
  5236. }
  5237. lastOffset += hint;
  5238. offset += hint;
  5239. }
  5240. else {
  5241. maxOffset = hint + 1;
  5242. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5243. lastOffset = offset;
  5244. offset = (offset << 1) + 1;
  5245. if (offset <= 0) {
  5246. offset = maxOffset;
  5247. }
  5248. }
  5249. if (offset > maxOffset) {
  5250. offset = maxOffset;
  5251. }
  5252. var tmp = lastOffset;
  5253. lastOffset = hint - offset;
  5254. offset = hint - tmp;
  5255. }
  5256. lastOffset++;
  5257. while (lastOffset < offset) {
  5258. var m = lastOffset + (offset - lastOffset >>> 1);
  5259. if (compare(value, array[start + m]) > 0) {
  5260. lastOffset = m + 1;
  5261. }
  5262. else {
  5263. offset = m;
  5264. }
  5265. }
  5266. return offset;
  5267. }
  5268. function gallopRight(value, array, start, length, hint, compare) {
  5269. var lastOffset = 0;
  5270. var maxOffset = 0;
  5271. var offset = 1;
  5272. if (compare(value, array[start + hint]) < 0) {
  5273. maxOffset = hint + 1;
  5274. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5275. lastOffset = offset;
  5276. offset = (offset << 1) + 1;
  5277. if (offset <= 0) {
  5278. offset = maxOffset;
  5279. }
  5280. }
  5281. if (offset > maxOffset) {
  5282. offset = maxOffset;
  5283. }
  5284. var tmp = lastOffset;
  5285. lastOffset = hint - offset;
  5286. offset = hint - tmp;
  5287. }
  5288. else {
  5289. maxOffset = length - hint;
  5290. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5291. lastOffset = offset;
  5292. offset = (offset << 1) + 1;
  5293. if (offset <= 0) {
  5294. offset = maxOffset;
  5295. }
  5296. }
  5297. if (offset > maxOffset) {
  5298. offset = maxOffset;
  5299. }
  5300. lastOffset += hint;
  5301. offset += hint;
  5302. }
  5303. lastOffset++;
  5304. while (lastOffset < offset) {
  5305. var m = lastOffset + (offset - lastOffset >>> 1);
  5306. if (compare(value, array[start + m]) < 0) {
  5307. offset = m;
  5308. }
  5309. else {
  5310. lastOffset = m + 1;
  5311. }
  5312. }
  5313. return offset;
  5314. }
  5315. function TimSort(array, compare) {
  5316. var minGallop = DEFAULT_MIN_GALLOPING;
  5317. var runStart;
  5318. var runLength;
  5319. var stackSize = 0;
  5320. var tmp = [];
  5321. runStart = [];
  5322. runLength = [];
  5323. function pushRun(_runStart, _runLength) {
  5324. runStart[stackSize] = _runStart;
  5325. runLength[stackSize] = _runLength;
  5326. stackSize += 1;
  5327. }
  5328. function mergeRuns() {
  5329. while (stackSize > 1) {
  5330. var n = stackSize - 2;
  5331. if (
  5332. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5333. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5334. ) {
  5335. if (runLength[n - 1] < runLength[n + 1]) {
  5336. n--;
  5337. }
  5338. }
  5339. else if (runLength[n] > runLength[n + 1]) {
  5340. break;
  5341. }
  5342. mergeAt(n);
  5343. }
  5344. }
  5345. function forceMergeRuns() {
  5346. while (stackSize > 1) {
  5347. var n = stackSize - 2;
  5348. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5349. n--;
  5350. }
  5351. mergeAt(n);
  5352. }
  5353. }
  5354. function mergeAt(i) {
  5355. var start1 = runStart[i];
  5356. var length1 = runLength[i];
  5357. var start2 = runStart[i + 1];
  5358. var length2 = runLength[i + 1];
  5359. runLength[i] = length1 + length2;
  5360. if (i === stackSize - 3) {
  5361. runStart[i + 1] = runStart[i + 2];
  5362. runLength[i + 1] = runLength[i + 2];
  5363. }
  5364. stackSize--;
  5365. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5366. start1 += k;
  5367. length1 -= k;
  5368. if (length1 === 0) {
  5369. return;
  5370. }
  5371. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5372. if (length2 === 0) {
  5373. return;
  5374. }
  5375. if (length1 <= length2) {
  5376. mergeLow(start1, length1, start2, length2);
  5377. }
  5378. else {
  5379. mergeHigh(start1, length1, start2, length2);
  5380. }
  5381. }
  5382. function mergeLow(start1, length1, start2, length2) {
  5383. var i = 0;
  5384. for (i = 0; i < length1; i++) {
  5385. tmp[i] = array[start1 + i];
  5386. }
  5387. var cursor1 = 0;
  5388. var cursor2 = start2;
  5389. var dest = start1;
  5390. array[dest++] = array[cursor2++];
  5391. if (--length2 === 0) {
  5392. for (i = 0; i < length1; i++) {
  5393. array[dest + i] = tmp[cursor1 + i];
  5394. }
  5395. return;
  5396. }
  5397. if (length1 === 1) {
  5398. for (i = 0; i < length2; i++) {
  5399. array[dest + i] = array[cursor2 + i];
  5400. }
  5401. array[dest + length2] = tmp[cursor1];
  5402. return;
  5403. }
  5404. var _minGallop = minGallop;
  5405. var count1;
  5406. var count2;
  5407. var exit;
  5408. while (1) {
  5409. count1 = 0;
  5410. count2 = 0;
  5411. exit = false;
  5412. do {
  5413. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5414. array[dest++] = array[cursor2++];
  5415. count2++;
  5416. count1 = 0;
  5417. if (--length2 === 0) {
  5418. exit = true;
  5419. break;
  5420. }
  5421. }
  5422. else {
  5423. array[dest++] = tmp[cursor1++];
  5424. count1++;
  5425. count2 = 0;
  5426. if (--length1 === 1) {
  5427. exit = true;
  5428. break;
  5429. }
  5430. }
  5431. } while ((count1 | count2) < _minGallop);
  5432. if (exit) {
  5433. break;
  5434. }
  5435. do {
  5436. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5437. if (count1 !== 0) {
  5438. for (i = 0; i < count1; i++) {
  5439. array[dest + i] = tmp[cursor1 + i];
  5440. }
  5441. dest += count1;
  5442. cursor1 += count1;
  5443. length1 -= count1;
  5444. if (length1 <= 1) {
  5445. exit = true;
  5446. break;
  5447. }
  5448. }
  5449. array[dest++] = array[cursor2++];
  5450. if (--length2 === 0) {
  5451. exit = true;
  5452. break;
  5453. }
  5454. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5455. if (count2 !== 0) {
  5456. for (i = 0; i < count2; i++) {
  5457. array[dest + i] = array[cursor2 + i];
  5458. }
  5459. dest += count2;
  5460. cursor2 += count2;
  5461. length2 -= count2;
  5462. if (length2 === 0) {
  5463. exit = true;
  5464. break;
  5465. }
  5466. }
  5467. array[dest++] = tmp[cursor1++];
  5468. if (--length1 === 1) {
  5469. exit = true;
  5470. break;
  5471. }
  5472. _minGallop--;
  5473. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5474. if (exit) {
  5475. break;
  5476. }
  5477. if (_minGallop < 0) {
  5478. _minGallop = 0;
  5479. }
  5480. _minGallop += 2;
  5481. }
  5482. minGallop = _minGallop;
  5483. minGallop < 1 && (minGallop = 1);
  5484. if (length1 === 1) {
  5485. for (i = 0; i < length2; i++) {
  5486. array[dest + i] = array[cursor2 + i];
  5487. }
  5488. array[dest + length2] = tmp[cursor1];
  5489. }
  5490. else if (length1 === 0) {
  5491. throw new Error();
  5492. // throw new Error('mergeLow preconditions were not respected');
  5493. }
  5494. else {
  5495. for (i = 0; i < length1; i++) {
  5496. array[dest + i] = tmp[cursor1 + i];
  5497. }
  5498. }
  5499. }
  5500. function mergeHigh(start1, length1, start2, length2) {
  5501. var i = 0;
  5502. for (i = 0; i < length2; i++) {
  5503. tmp[i] = array[start2 + i];
  5504. }
  5505. var cursor1 = start1 + length1 - 1;
  5506. var cursor2 = length2 - 1;
  5507. var dest = start2 + length2 - 1;
  5508. var customCursor = 0;
  5509. var customDest = 0;
  5510. array[dest--] = array[cursor1--];
  5511. if (--length1 === 0) {
  5512. customCursor = dest - (length2 - 1);
  5513. for (i = 0; i < length2; i++) {
  5514. array[customCursor + i] = tmp[i];
  5515. }
  5516. return;
  5517. }
  5518. if (length2 === 1) {
  5519. dest -= length1;
  5520. cursor1 -= length1;
  5521. customDest = dest + 1;
  5522. customCursor = cursor1 + 1;
  5523. for (i = length1 - 1; i >= 0; i--) {
  5524. array[customDest + i] = array[customCursor + i];
  5525. }
  5526. array[dest] = tmp[cursor2];
  5527. return;
  5528. }
  5529. var _minGallop = minGallop;
  5530. while (true) {
  5531. var count1 = 0;
  5532. var count2 = 0;
  5533. var exit = false;
  5534. do {
  5535. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5536. array[dest--] = array[cursor1--];
  5537. count1++;
  5538. count2 = 0;
  5539. if (--length1 === 0) {
  5540. exit = true;
  5541. break;
  5542. }
  5543. }
  5544. else {
  5545. array[dest--] = tmp[cursor2--];
  5546. count2++;
  5547. count1 = 0;
  5548. if (--length2 === 1) {
  5549. exit = true;
  5550. break;
  5551. }
  5552. }
  5553. } while ((count1 | count2) < _minGallop);
  5554. if (exit) {
  5555. break;
  5556. }
  5557. do {
  5558. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5559. if (count1 !== 0) {
  5560. dest -= count1;
  5561. cursor1 -= count1;
  5562. length1 -= count1;
  5563. customDest = dest + 1;
  5564. customCursor = cursor1 + 1;
  5565. for (i = count1 - 1; i >= 0; i--) {
  5566. array[customDest + i] = array[customCursor + i];
  5567. }
  5568. if (length1 === 0) {
  5569. exit = true;
  5570. break;
  5571. }
  5572. }
  5573. array[dest--] = tmp[cursor2--];
  5574. if (--length2 === 1) {
  5575. exit = true;
  5576. break;
  5577. }
  5578. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5579. if (count2 !== 0) {
  5580. dest -= count2;
  5581. cursor2 -= count2;
  5582. length2 -= count2;
  5583. customDest = dest + 1;
  5584. customCursor = cursor2 + 1;
  5585. for (i = 0; i < count2; i++) {
  5586. array[customDest + i] = tmp[customCursor + i];
  5587. }
  5588. if (length2 <= 1) {
  5589. exit = true;
  5590. break;
  5591. }
  5592. }
  5593. array[dest--] = array[cursor1--];
  5594. if (--length1 === 0) {
  5595. exit = true;
  5596. break;
  5597. }
  5598. _minGallop--;
  5599. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5600. if (exit) {
  5601. break;
  5602. }
  5603. if (_minGallop < 0) {
  5604. _minGallop = 0;
  5605. }
  5606. _minGallop += 2;
  5607. }
  5608. minGallop = _minGallop;
  5609. if (minGallop < 1) {
  5610. minGallop = 1;
  5611. }
  5612. if (length2 === 1) {
  5613. dest -= length1;
  5614. cursor1 -= length1;
  5615. customDest = dest + 1;
  5616. customCursor = cursor1 + 1;
  5617. for (i = length1 - 1; i >= 0; i--) {
  5618. array[customDest + i] = array[customCursor + i];
  5619. }
  5620. array[dest] = tmp[cursor2];
  5621. }
  5622. else if (length2 === 0) {
  5623. throw new Error();
  5624. // throw new Error('mergeHigh preconditions were not respected');
  5625. }
  5626. else {
  5627. customCursor = dest - (length2 - 1);
  5628. for (i = 0; i < length2; i++) {
  5629. array[customCursor + i] = tmp[i];
  5630. }
  5631. }
  5632. }
  5633. this.mergeRuns = mergeRuns;
  5634. this.forceMergeRuns = forceMergeRuns;
  5635. this.pushRun = pushRun;
  5636. }
  5637. function sort(array, compare, lo, hi) {
  5638. if (!lo) {
  5639. lo = 0;
  5640. }
  5641. if (!hi) {
  5642. hi = array.length;
  5643. }
  5644. var remaining = hi - lo;
  5645. if (remaining < 2) {
  5646. return;
  5647. }
  5648. var runLength = 0;
  5649. if (remaining < DEFAULT_MIN_MERGE) {
  5650. runLength = makeAscendingRun(array, lo, hi, compare);
  5651. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5652. return;
  5653. }
  5654. var ts = new TimSort(array, compare);
  5655. var minRun = minRunLength(remaining);
  5656. do {
  5657. runLength = makeAscendingRun(array, lo, hi, compare);
  5658. if (runLength < minRun) {
  5659. var force = remaining;
  5660. if (force > minRun) {
  5661. force = minRun;
  5662. }
  5663. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5664. runLength = force;
  5665. }
  5666. ts.pushRun(lo, runLength);
  5667. ts.mergeRuns();
  5668. remaining -= runLength;
  5669. lo += runLength;
  5670. } while (remaining !== 0);
  5671. ts.forceMergeRuns();
  5672. }
  5673. // Use timsort because in most case elements are partially sorted
  5674. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5675. function shapeCompareFunc(a, b) {
  5676. if (a.zlevel === b.zlevel) {
  5677. if (a.z === b.z) {
  5678. // if (a.z2 === b.z2) {
  5679. // // FIXME Slow has renderidx compare
  5680. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5681. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5682. // return a.__renderidx - b.__renderidx;
  5683. // }
  5684. return a.z2 - b.z2;
  5685. }
  5686. return a.z - b.z;
  5687. }
  5688. return a.zlevel - b.zlevel;
  5689. }
  5690. /**
  5691. * 内容仓库 (M)
  5692. * @alias module:zrender/Storage
  5693. * @constructor
  5694. */
  5695. var Storage = function () { // jshint ignore:line
  5696. this._roots = [];
  5697. this._displayList = [];
  5698. this._displayListLen = 0;
  5699. };
  5700. Storage.prototype = {
  5701. constructor: Storage,
  5702. /**
  5703. * @param {Function} cb
  5704. *
  5705. */
  5706. traverse: function (cb, context) {
  5707. for (var i = 0; i < this._roots.length; i++) {
  5708. this._roots[i].traverse(cb, context);
  5709. }
  5710. },
  5711. /**
  5712. * 返回所有图形的绘制队列
  5713. * @param {boolean} [update=false] 是否在返回前更新该数组
  5714. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5715. *
  5716. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5717. * @return {Array.<module:zrender/graphic/Displayable>}
  5718. */
  5719. getDisplayList: function (update, includeIgnore) {
  5720. includeIgnore = includeIgnore || false;
  5721. if (update) {
  5722. this.updateDisplayList(includeIgnore);
  5723. }
  5724. return this._displayList;
  5725. },
  5726. /**
  5727. * 更新图形的绘制队列。
  5728. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5729. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5730. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5731. */
  5732. updateDisplayList: function (includeIgnore) {
  5733. this._displayListLen = 0;
  5734. var roots = this._roots;
  5735. var displayList = this._displayList;
  5736. for (var i = 0, len = roots.length; i < len; i++) {
  5737. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5738. }
  5739. displayList.length = this._displayListLen;
  5740. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5741. },
  5742. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5743. if (el.ignore && !includeIgnore) {
  5744. return;
  5745. }
  5746. el.beforeUpdate();
  5747. if (el.__dirty) {
  5748. el.update();
  5749. }
  5750. el.afterUpdate();
  5751. var userSetClipPath = el.clipPath;
  5752. if (userSetClipPath) {
  5753. // FIXME 效率影响
  5754. if (clipPaths) {
  5755. clipPaths = clipPaths.slice();
  5756. }
  5757. else {
  5758. clipPaths = [];
  5759. }
  5760. var currentClipPath = userSetClipPath;
  5761. var parentClipPath = el;
  5762. // Recursively add clip path
  5763. while (currentClipPath) {
  5764. // clipPath 的变换是基于使用这个 clipPath 的元素
  5765. currentClipPath.parent = parentClipPath;
  5766. currentClipPath.updateTransform();
  5767. clipPaths.push(currentClipPath);
  5768. parentClipPath = currentClipPath;
  5769. currentClipPath = currentClipPath.clipPath;
  5770. }
  5771. }
  5772. if (el.isGroup) {
  5773. var children = el._children;
  5774. for (var i = 0; i < children.length; i++) {
  5775. var child = children[i];
  5776. // Force to mark as dirty if group is dirty
  5777. // FIXME __dirtyPath ?
  5778. if (el.__dirty) {
  5779. child.__dirty = true;
  5780. }
  5781. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5782. }
  5783. // Mark group clean here
  5784. el.__dirty = false;
  5785. }
  5786. else {
  5787. el.__clipPaths = clipPaths;
  5788. this._displayList[this._displayListLen++] = el;
  5789. }
  5790. },
  5791. /**
  5792. * 添加图形(Shape)或者组(Group)到根节点
  5793. * @param {module:zrender/Element} el
  5794. */
  5795. addRoot: function (el) {
  5796. if (el.__storage === this) {
  5797. return;
  5798. }
  5799. if (el instanceof Group) {
  5800. el.addChildrenToStorage(this);
  5801. }
  5802. this.addToStorage(el);
  5803. this._roots.push(el);
  5804. },
  5805. /**
  5806. * 删除指定的图形(Shape)或者组(Group)
  5807. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5808. */
  5809. delRoot: function (el) {
  5810. if (el == null) {
  5811. // 不指定el清空
  5812. for (var i = 0; i < this._roots.length; i++) {
  5813. var root = this._roots[i];
  5814. if (root instanceof Group) {
  5815. root.delChildrenFromStorage(this);
  5816. }
  5817. }
  5818. this._roots = [];
  5819. this._displayList = [];
  5820. this._displayListLen = 0;
  5821. return;
  5822. }
  5823. if (el instanceof Array) {
  5824. for (var i = 0, l = el.length; i < l; i++) {
  5825. this.delRoot(el[i]);
  5826. }
  5827. return;
  5828. }
  5829. var idx = indexOf(this._roots, el);
  5830. if (idx >= 0) {
  5831. this.delFromStorage(el);
  5832. this._roots.splice(idx, 1);
  5833. if (el instanceof Group) {
  5834. el.delChildrenFromStorage(this);
  5835. }
  5836. }
  5837. },
  5838. addToStorage: function (el) {
  5839. if (el) {
  5840. el.__storage = this;
  5841. el.dirty(false);
  5842. }
  5843. return this;
  5844. },
  5845. delFromStorage: function (el) {
  5846. if (el) {
  5847. el.__storage = null;
  5848. }
  5849. return this;
  5850. },
  5851. /**
  5852. * 清空并且释放Storage
  5853. */
  5854. dispose: function () {
  5855. this._renderList =
  5856. this._roots = null;
  5857. },
  5858. displayableSortFunc: shapeCompareFunc
  5859. };
  5860. var SHADOW_PROPS = {
  5861. 'shadowBlur': 1,
  5862. 'shadowOffsetX': 1,
  5863. 'shadowOffsetY': 1,
  5864. 'textShadowBlur': 1,
  5865. 'textShadowOffsetX': 1,
  5866. 'textShadowOffsetY': 1,
  5867. 'textBoxShadowBlur': 1,
  5868. 'textBoxShadowOffsetX': 1,
  5869. 'textBoxShadowOffsetY': 1
  5870. };
  5871. var fixShadow = function (ctx, propName, value) {
  5872. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5873. return value *= ctx.dpr;
  5874. }
  5875. return value;
  5876. };
  5877. var ContextCachedBy = {
  5878. NONE: 0,
  5879. STYLE_BIND: 1,
  5880. PLAIN_TEXT: 2
  5881. };
  5882. // Avoid confused with 0/false.
  5883. var WILL_BE_RESTORED = 9;
  5884. var STYLE_COMMON_PROPS = [
  5885. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5886. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5887. ];
  5888. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5889. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5890. var Style = function (opts) {
  5891. this.extendFrom(opts, false);
  5892. };
  5893. function createLinearGradient(ctx, obj, rect) {
  5894. var x = obj.x == null ? 0 : obj.x;
  5895. var x2 = obj.x2 == null ? 1 : obj.x2;
  5896. var y = obj.y == null ? 0 : obj.y;
  5897. var y2 = obj.y2 == null ? 0 : obj.y2;
  5898. if (!obj.global) {
  5899. x = x * rect.width + rect.x;
  5900. x2 = x2 * rect.width + rect.x;
  5901. y = y * rect.height + rect.y;
  5902. y2 = y2 * rect.height + rect.y;
  5903. }
  5904. // Fix NaN when rect is Infinity
  5905. x = isNaN(x) ? 0 : x;
  5906. x2 = isNaN(x2) ? 1 : x2;
  5907. y = isNaN(y) ? 0 : y;
  5908. y2 = isNaN(y2) ? 0 : y2;
  5909. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5910. return canvasGradient;
  5911. }
  5912. function createRadialGradient(ctx, obj, rect) {
  5913. var width = rect.width;
  5914. var height = rect.height;
  5915. var min = Math.min(width, height);
  5916. var x = obj.x == null ? 0.5 : obj.x;
  5917. var y = obj.y == null ? 0.5 : obj.y;
  5918. var r = obj.r == null ? 0.5 : obj.r;
  5919. if (!obj.global) {
  5920. x = x * width + rect.x;
  5921. y = y * height + rect.y;
  5922. r = r * min;
  5923. }
  5924. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5925. return canvasGradient;
  5926. }
  5927. Style.prototype = {
  5928. constructor: Style,
  5929. /**
  5930. * @type {string}
  5931. */
  5932. fill: '#000',
  5933. /**
  5934. * @type {string}
  5935. */
  5936. stroke: null,
  5937. /**
  5938. * @type {number}
  5939. */
  5940. opacity: 1,
  5941. /**
  5942. * @type {number}
  5943. */
  5944. fillOpacity: null,
  5945. /**
  5946. * @type {number}
  5947. */
  5948. strokeOpacity: null,
  5949. /**
  5950. * `true` is not supported.
  5951. * `false`/`null`/`undefined` are the same.
  5952. * `false` is used to remove lineDash in some
  5953. * case that `null`/`undefined` can not be set.
  5954. * (e.g., emphasis.lineStyle in echarts)
  5955. * @type {Array.<number>|boolean}
  5956. */
  5957. lineDash: null,
  5958. /**
  5959. * @type {number}
  5960. */
  5961. lineDashOffset: 0,
  5962. /**
  5963. * @type {number}
  5964. */
  5965. shadowBlur: 0,
  5966. /**
  5967. * @type {number}
  5968. */
  5969. shadowOffsetX: 0,
  5970. /**
  5971. * @type {number}
  5972. */
  5973. shadowOffsetY: 0,
  5974. /**
  5975. * @type {number}
  5976. */
  5977. lineWidth: 1,
  5978. /**
  5979. * If stroke ignore scale
  5980. * @type {Boolean}
  5981. */
  5982. strokeNoScale: false,
  5983. // Bounding rect text configuration
  5984. // Not affected by element transform
  5985. /**
  5986. * @type {string}
  5987. */
  5988. text: null,
  5989. /**
  5990. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5991. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5992. * So do not visit it directly in upper application (like echarts),
  5993. * but use `contain/text#makeFont` instead.
  5994. * @type {string}
  5995. */
  5996. font: null,
  5997. /**
  5998. * The same as font. Use font please.
  5999. * @deprecated
  6000. * @type {string}
  6001. */
  6002. textFont: null,
  6003. /**
  6004. * It helps merging respectively, rather than parsing an entire font string.
  6005. * @type {string}
  6006. */
  6007. fontStyle: null,
  6008. /**
  6009. * It helps merging respectively, rather than parsing an entire font string.
  6010. * @type {string}
  6011. */
  6012. fontWeight: null,
  6013. /**
  6014. * It helps merging respectively, rather than parsing an entire font string.
  6015. * Should be 12 but not '12px'.
  6016. * @type {number}
  6017. */
  6018. fontSize: null,
  6019. /**
  6020. * It helps merging respectively, rather than parsing an entire font string.
  6021. * @type {string}
  6022. */
  6023. fontFamily: null,
  6024. /**
  6025. * Reserved for special functinality, like 'hr'.
  6026. * @type {string}
  6027. */
  6028. textTag: null,
  6029. /**
  6030. * @type {string}
  6031. */
  6032. textFill: '#000',
  6033. /**
  6034. * @type {string}
  6035. */
  6036. textStroke: null,
  6037. /**
  6038. * @type {number}
  6039. */
  6040. textWidth: null,
  6041. /**
  6042. * Only for textBackground.
  6043. * @type {number}
  6044. */
  6045. textHeight: null,
  6046. /**
  6047. * textStroke may be set as some color as a default
  6048. * value in upper applicaion, where the default value
  6049. * of textStrokeWidth should be 0 to make sure that
  6050. * user can choose to do not use text stroke.
  6051. * @type {number}
  6052. */
  6053. textStrokeWidth: 0,
  6054. /**
  6055. * @type {number}
  6056. */
  6057. textLineHeight: null,
  6058. /**
  6059. * 'inside', 'left', 'right', 'top', 'bottom'
  6060. * [x, y]
  6061. * Based on x, y of rect.
  6062. * @type {string|Array.<number>}
  6063. * @default 'inside'
  6064. */
  6065. textPosition: 'inside',
  6066. /**
  6067. * If not specified, use the boundingRect of a `displayable`.
  6068. * @type {Object}
  6069. */
  6070. textRect: null,
  6071. /**
  6072. * [x, y]
  6073. * @type {Array.<number>}
  6074. */
  6075. textOffset: null,
  6076. /**
  6077. * @type {string}
  6078. */
  6079. textAlign: null,
  6080. /**
  6081. * @type {string}
  6082. */
  6083. textVerticalAlign: null,
  6084. /**
  6085. * @type {number}
  6086. */
  6087. textDistance: 5,
  6088. /**
  6089. * @type {string}
  6090. */
  6091. textShadowColor: 'transparent',
  6092. /**
  6093. * @type {number}
  6094. */
  6095. textShadowBlur: 0,
  6096. /**
  6097. * @type {number}
  6098. */
  6099. textShadowOffsetX: 0,
  6100. /**
  6101. * @type {number}
  6102. */
  6103. textShadowOffsetY: 0,
  6104. /**
  6105. * @type {string}
  6106. */
  6107. textBoxShadowColor: 'transparent',
  6108. /**
  6109. * @type {number}
  6110. */
  6111. textBoxShadowBlur: 0,
  6112. /**
  6113. * @type {number}
  6114. */
  6115. textBoxShadowOffsetX: 0,
  6116. /**
  6117. * @type {number}
  6118. */
  6119. textBoxShadowOffsetY: 0,
  6120. /**
  6121. * Whether transform text.
  6122. * Only available in Path and Image element,
  6123. * where the text is called as `RectText`.
  6124. * @type {boolean}
  6125. */
  6126. transformText: false,
  6127. /**
  6128. * Text rotate around position of Path or Image.
  6129. * The origin of the rotation can be specified by `textOrigin`.
  6130. * Only available in Path and Image element,
  6131. * where the text is called as `RectText`.
  6132. */
  6133. textRotation: 0,
  6134. /**
  6135. * Text origin of text rotation.
  6136. * Useful in the case like label rotation of circular symbol.
  6137. * Only available in Path and Image element, where the text is called
  6138. * as `RectText` and the element is called as "host element".
  6139. * The value can be:
  6140. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6141. * base on the left-top corner of the rect of its host element.
  6142. * + If specified as a string `center`, it is the center of the rect of
  6143. * its host element.
  6144. * + By default, this origin is the `textPosition`.
  6145. * @type {string|Array.<number>}
  6146. */
  6147. textOrigin: null,
  6148. /**
  6149. * @type {string}
  6150. */
  6151. textBackgroundColor: null,
  6152. /**
  6153. * @type {string}
  6154. */
  6155. textBorderColor: null,
  6156. /**
  6157. * @type {number}
  6158. */
  6159. textBorderWidth: 0,
  6160. /**
  6161. * @type {number}
  6162. */
  6163. textBorderRadius: 0,
  6164. /**
  6165. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6166. * @type {number|Array.<number>}
  6167. */
  6168. textPadding: null,
  6169. /**
  6170. * Text styles for rich text.
  6171. * @type {Object}
  6172. */
  6173. rich: null,
  6174. /**
  6175. * {outerWidth, outerHeight, ellipsis, placeholder}
  6176. * @type {Object}
  6177. */
  6178. truncate: null,
  6179. /**
  6180. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6181. * @type {string}
  6182. */
  6183. blend: null,
  6184. /**
  6185. * @param {CanvasRenderingContext2D} ctx
  6186. */
  6187. bind: function (ctx, el, prevEl) {
  6188. var style = this;
  6189. var prevStyle = prevEl && prevEl.style;
  6190. // If no prevStyle, it means first draw.
  6191. // Only apply cache if the last time cachced by this function.
  6192. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6193. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6194. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6195. var prop = STYLE_COMMON_PROPS[i];
  6196. var styleName = prop[0];
  6197. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6198. // FIXME Invalid property value will cause style leak from previous element.
  6199. ctx[styleName] =
  6200. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6201. }
  6202. }
  6203. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6204. ctx.fillStyle = style.fill;
  6205. }
  6206. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6207. ctx.strokeStyle = style.stroke;
  6208. }
  6209. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6210. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6211. }
  6212. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6213. ctx.globalCompositeOperation = style.blend || 'source-over';
  6214. }
  6215. if (this.hasStroke()) {
  6216. var lineWidth = style.lineWidth;
  6217. ctx.lineWidth = lineWidth / (
  6218. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6219. );
  6220. }
  6221. },
  6222. hasFill: function () {
  6223. var fill = this.fill;
  6224. return fill != null && fill !== 'none';
  6225. },
  6226. hasStroke: function () {
  6227. var stroke = this.stroke;
  6228. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6229. },
  6230. /**
  6231. * Extend from other style
  6232. * @param {zrender/graphic/Style} otherStyle
  6233. * @param {boolean} overwrite true: overwrirte any way.
  6234. * false: overwrite only when !target.hasOwnProperty
  6235. * others: overwrite when property is not null/undefined.
  6236. */
  6237. extendFrom: function (otherStyle, overwrite) {
  6238. if (otherStyle) {
  6239. for (var name in otherStyle) {
  6240. if (otherStyle.hasOwnProperty(name)
  6241. && (overwrite === true
  6242. || (
  6243. overwrite === false
  6244. ? !this.hasOwnProperty(name)
  6245. : otherStyle[name] != null
  6246. )
  6247. )
  6248. ) {
  6249. this[name] = otherStyle[name];
  6250. }
  6251. }
  6252. }
  6253. },
  6254. /**
  6255. * Batch setting style with a given object
  6256. * @param {Object|string} obj
  6257. * @param {*} [obj]
  6258. */
  6259. set: function (obj, value) {
  6260. if (typeof obj === 'string') {
  6261. this[obj] = value;
  6262. }
  6263. else {
  6264. this.extendFrom(obj, true);
  6265. }
  6266. },
  6267. /**
  6268. * Clone
  6269. * @return {zrender/graphic/Style} [description]
  6270. */
  6271. clone: function () {
  6272. var newStyle = new this.constructor();
  6273. newStyle.extendFrom(this, true);
  6274. return newStyle;
  6275. },
  6276. getGradient: function (ctx, obj, rect) {
  6277. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6278. var canvasGradient = method(ctx, obj, rect);
  6279. var colorStops = obj.colorStops;
  6280. for (var i = 0; i < colorStops.length; i++) {
  6281. canvasGradient.addColorStop(
  6282. colorStops[i].offset, colorStops[i].color
  6283. );
  6284. }
  6285. return canvasGradient;
  6286. }
  6287. };
  6288. var styleProto = Style.prototype;
  6289. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6290. var prop = STYLE_COMMON_PROPS[i];
  6291. if (!(prop[0] in styleProto)) {
  6292. styleProto[prop[0]] = prop[1];
  6293. }
  6294. }
  6295. // Provide for others
  6296. Style.getGradient = styleProto.getGradient;
  6297. var Pattern = function (image, repeat) {
  6298. // Should do nothing more in this constructor. Because gradient can be
  6299. // declard by `color: {image: ...}`, where this constructor will not be called.
  6300. this.image = image;
  6301. this.repeat = repeat;
  6302. // Can be cloned
  6303. this.type = 'pattern';
  6304. };
  6305. Pattern.prototype.getCanvasPattern = function (ctx) {
  6306. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6307. };
  6308. /**
  6309. * @module zrender/Layer
  6310. * @author pissang(https://www.github.com/pissang)
  6311. */
  6312. function returnFalse() {
  6313. return false;
  6314. }
  6315. /**
  6316. * 创建dom
  6317. *
  6318. * @inner
  6319. * @param {string} id dom id 待用
  6320. * @param {Painter} painter painter instance
  6321. * @param {number} number
  6322. */
  6323. function createDom(id, painter, dpr) {
  6324. var newDom = createCanvas();
  6325. var width = painter.getWidth();
  6326. var height = painter.getHeight();
  6327. var newDomStyle = newDom.style;
  6328. if (newDomStyle) { // In node or some other non-browser environment
  6329. newDomStyle.position = 'absolute';
  6330. newDomStyle.left = 0;
  6331. newDomStyle.top = 0;
  6332. newDomStyle.width = width + 'px';
  6333. newDomStyle.height = height + 'px';
  6334. newDom.setAttribute('data-zr-dom-id', id);
  6335. }
  6336. newDom.width = width * dpr;
  6337. newDom.height = height * dpr;
  6338. return newDom;
  6339. }
  6340. /**
  6341. * @alias module:zrender/Layer
  6342. * @constructor
  6343. * @extends module:zrender/mixin/Transformable
  6344. * @param {string} id
  6345. * @param {module:zrender/Painter} painter
  6346. * @param {number} [dpr]
  6347. */
  6348. var Layer = function (id, painter, dpr) {
  6349. var dom;
  6350. dpr = dpr || devicePixelRatio;
  6351. if (typeof id === 'string') {
  6352. dom = createDom(id, painter, dpr);
  6353. }
  6354. // Not using isDom because in node it will return false
  6355. else if (isObject$1(id)) {
  6356. dom = id;
  6357. id = dom.id;
  6358. }
  6359. this.id = id;
  6360. this.dom = dom;
  6361. var domStyle = dom.style;
  6362. if (domStyle) { // Not in node
  6363. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6364. domStyle['-webkit-user-select'] = 'none';
  6365. domStyle['user-select'] = 'none';
  6366. domStyle['-webkit-touch-callout'] = 'none';
  6367. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6368. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6369. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6370. domStyle['border-width'] = 0;
  6371. }
  6372. this.domBack = null;
  6373. this.ctxBack = null;
  6374. this.painter = painter;
  6375. this.config = null;
  6376. // Configs
  6377. /**
  6378. * 每次清空画布的颜色
  6379. * @type {string}
  6380. * @default 0
  6381. */
  6382. this.clearColor = 0;
  6383. /**
  6384. * 是否开启动态模糊
  6385. * @type {boolean}
  6386. * @default false
  6387. */
  6388. this.motionBlur = false;
  6389. /**
  6390. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6391. * @type {number}
  6392. * @default 0.7
  6393. */
  6394. this.lastFrameAlpha = 0.7;
  6395. /**
  6396. * Layer dpr
  6397. * @type {number}
  6398. */
  6399. this.dpr = dpr;
  6400. };
  6401. Layer.prototype = {
  6402. constructor: Layer,
  6403. __dirty: true,
  6404. __used: false,
  6405. __drawIndex: 0,
  6406. __startIndex: 0,
  6407. __endIndex: 0,
  6408. incremental: false,
  6409. getElementCount: function () {
  6410. return this.__endIndex - this.__startIndex;
  6411. },
  6412. initContext: function () {
  6413. this.ctx = this.dom.getContext('2d');
  6414. this.ctx.dpr = this.dpr;
  6415. },
  6416. createBackBuffer: function () {
  6417. var dpr = this.dpr;
  6418. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6419. this.ctxBack = this.domBack.getContext('2d');
  6420. if (dpr !== 1) {
  6421. this.ctxBack.scale(dpr, dpr);
  6422. }
  6423. },
  6424. /**
  6425. * @param {number} width
  6426. * @param {number} height
  6427. */
  6428. resize: function (width, height) {
  6429. var dpr = this.dpr;
  6430. var dom = this.dom;
  6431. var domStyle = dom.style;
  6432. var domBack = this.domBack;
  6433. if (domStyle) {
  6434. domStyle.width = width + 'px';
  6435. domStyle.height = height + 'px';
  6436. }
  6437. dom.width = width * dpr;
  6438. dom.height = height * dpr;
  6439. if (domBack) {
  6440. domBack.width = width * dpr;
  6441. domBack.height = height * dpr;
  6442. if (dpr !== 1) {
  6443. this.ctxBack.scale(dpr, dpr);
  6444. }
  6445. }
  6446. },
  6447. /**
  6448. * 清空该层画布
  6449. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6450. * @param {Color} [clearColor]
  6451. */
  6452. clear: function (clearAll, clearColor) {
  6453. var dom = this.dom;
  6454. var ctx = this.ctx;
  6455. var width = dom.width;
  6456. var height = dom.height;
  6457. var clearColor = clearColor || this.clearColor;
  6458. var haveMotionBLur = this.motionBlur && !clearAll;
  6459. var lastFrameAlpha = this.lastFrameAlpha;
  6460. var dpr = this.dpr;
  6461. if (haveMotionBLur) {
  6462. if (!this.domBack) {
  6463. this.createBackBuffer();
  6464. }
  6465. this.ctxBack.globalCompositeOperation = 'copy';
  6466. this.ctxBack.drawImage(
  6467. dom, 0, 0,
  6468. width / dpr,
  6469. height / dpr
  6470. );
  6471. }
  6472. ctx.clearRect(0, 0, width, height);
  6473. if (clearColor && clearColor !== 'transparent') {
  6474. var clearColorGradientOrPattern;
  6475. // Gradient
  6476. if (clearColor.colorStops) {
  6477. // Cache canvas gradient
  6478. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6479. x: 0,
  6480. y: 0,
  6481. width: width,
  6482. height: height
  6483. });
  6484. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6485. }
  6486. // Pattern
  6487. else if (clearColor.image) {
  6488. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6489. }
  6490. ctx.save();
  6491. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6492. ctx.fillRect(0, 0, width, height);
  6493. ctx.restore();
  6494. }
  6495. if (haveMotionBLur) {
  6496. var domBack = this.domBack;
  6497. ctx.save();
  6498. ctx.globalAlpha = lastFrameAlpha;
  6499. ctx.drawImage(domBack, 0, 0, width, height);
  6500. ctx.restore();
  6501. }
  6502. }
  6503. };
  6504. var requestAnimationFrame = (
  6505. typeof window !== 'undefined'
  6506. && (
  6507. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6508. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6509. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6510. || window.mozRequestAnimationFrame
  6511. || window.webkitRequestAnimationFrame
  6512. )
  6513. ) || function (func) {
  6514. setTimeout(func, 16);
  6515. };
  6516. var globalImageCache = new LRU(50);
  6517. /**
  6518. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6519. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6520. */
  6521. function findExistImage(newImageOrSrc) {
  6522. if (typeof newImageOrSrc === 'string') {
  6523. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6524. return cachedImgObj && cachedImgObj.image;
  6525. }
  6526. else {
  6527. return newImageOrSrc;
  6528. }
  6529. }
  6530. /**
  6531. * Caution: User should cache loaded images, but not just count on LRU.
  6532. * Consider if required images more than LRU size, will dead loop occur?
  6533. *
  6534. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6535. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6536. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6537. * @param {Function} [cb] params: (image, cbPayload)
  6538. * @param {Object} [cbPayload] Payload on cb calling.
  6539. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6540. */
  6541. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6542. if (!newImageOrSrc) {
  6543. return image;
  6544. }
  6545. else if (typeof newImageOrSrc === 'string') {
  6546. // Image should not be loaded repeatly.
  6547. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6548. return image;
  6549. }
  6550. // Only when there is no existent image or existent image src
  6551. // is different, this method is responsible for load.
  6552. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6553. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6554. if (cachedImgObj) {
  6555. image = cachedImgObj.image;
  6556. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6557. }
  6558. else {
  6559. image = new Image();
  6560. image.onload = image.onerror = imageOnLoad;
  6561. globalImageCache.put(
  6562. newImageOrSrc,
  6563. image.__cachedImgObj = {
  6564. image: image,
  6565. pending: [pendingWrap]
  6566. }
  6567. );
  6568. image.src = image.__zrImageSrc = newImageOrSrc;
  6569. }
  6570. return image;
  6571. }
  6572. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6573. else {
  6574. return newImageOrSrc;
  6575. }
  6576. }
  6577. function imageOnLoad() {
  6578. var cachedImgObj = this.__cachedImgObj;
  6579. this.onload = this.onerror = this.__cachedImgObj = null;
  6580. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6581. var pendingWrap = cachedImgObj.pending[i];
  6582. var cb = pendingWrap.cb;
  6583. cb && cb(this, pendingWrap.cbPayload);
  6584. pendingWrap.hostEl.dirty();
  6585. }
  6586. cachedImgObj.pending.length = 0;
  6587. }
  6588. function isImageReady(image) {
  6589. return image && image.width && image.height;
  6590. }
  6591. var textWidthCache = {};
  6592. var textWidthCacheCounter = 0;
  6593. var TEXT_CACHE_MAX = 5000;
  6594. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6595. var DEFAULT_FONT$1 = '12px sans-serif';
  6596. // Avoid assign to an exported variable, for transforming to cjs.
  6597. var methods$1 = {};
  6598. /**
  6599. * @public
  6600. * @param {string} text
  6601. * @param {string} font
  6602. * @return {number} width
  6603. */
  6604. function getWidth(text, font) {
  6605. font = font || DEFAULT_FONT$1;
  6606. var key = text + ':' + font;
  6607. if (textWidthCache[key]) {
  6608. return textWidthCache[key];
  6609. }
  6610. var textLines = (text + '').split('\n');
  6611. var width = 0;
  6612. for (var i = 0, l = textLines.length; i < l; i++) {
  6613. // textContain.measureText may be overrided in SVG or VML
  6614. width = Math.max(measureText(textLines[i], font).width, width);
  6615. }
  6616. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6617. textWidthCacheCounter = 0;
  6618. textWidthCache = {};
  6619. }
  6620. textWidthCacheCounter++;
  6621. textWidthCache[key] = width;
  6622. return width;
  6623. }
  6624. /**
  6625. * @public
  6626. * @param {string} text
  6627. * @param {string} font
  6628. * @param {string} [textAlign='left']
  6629. * @param {string} [textVerticalAlign='top']
  6630. * @param {Array.<number>} [textPadding]
  6631. * @param {Object} [rich]
  6632. * @param {Object} [truncate]
  6633. * @return {Object} {x, y, width, height, lineHeight}
  6634. */
  6635. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6636. return rich
  6637. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6638. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6639. }
  6640. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6641. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6642. var outerWidth = getWidth(text, font);
  6643. if (textPadding) {
  6644. outerWidth += textPadding[1] + textPadding[3];
  6645. }
  6646. var outerHeight = contentBlock.outerHeight;
  6647. var x = adjustTextX(0, outerWidth, textAlign);
  6648. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6649. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6650. rect.lineHeight = contentBlock.lineHeight;
  6651. return rect;
  6652. }
  6653. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6654. var contentBlock = parseRichText(text, {
  6655. rich: rich,
  6656. truncate: truncate,
  6657. font: font,
  6658. textAlign: textAlign,
  6659. textPadding: textPadding,
  6660. textLineHeight: textLineHeight
  6661. });
  6662. var outerWidth = contentBlock.outerWidth;
  6663. var outerHeight = contentBlock.outerHeight;
  6664. var x = adjustTextX(0, outerWidth, textAlign);
  6665. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6666. return new BoundingRect(x, y, outerWidth, outerHeight);
  6667. }
  6668. /**
  6669. * @public
  6670. * @param {number} x
  6671. * @param {number} width
  6672. * @param {string} [textAlign='left']
  6673. * @return {number} Adjusted x.
  6674. */
  6675. function adjustTextX(x, width, textAlign) {
  6676. // FIXME Right to left language
  6677. if (textAlign === 'right') {
  6678. x -= width;
  6679. }
  6680. else if (textAlign === 'center') {
  6681. x -= width / 2;
  6682. }
  6683. return x;
  6684. }
  6685. /**
  6686. * @public
  6687. * @param {number} y
  6688. * @param {number} height
  6689. * @param {string} [textVerticalAlign='top']
  6690. * @return {number} Adjusted y.
  6691. */
  6692. function adjustTextY(y, height, textVerticalAlign) {
  6693. if (textVerticalAlign === 'middle') {
  6694. y -= height / 2;
  6695. }
  6696. else if (textVerticalAlign === 'bottom') {
  6697. y -= height;
  6698. }
  6699. return y;
  6700. }
  6701. /**
  6702. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6703. * @public
  6704. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6705. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6706. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6707. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6708. */
  6709. function calculateTextPosition(out, style, rect) {
  6710. var textPosition = style.textPosition;
  6711. var distance = style.textDistance;
  6712. var x = rect.x;
  6713. var y = rect.y;
  6714. distance = distance || 0;
  6715. var height = rect.height;
  6716. var width = rect.width;
  6717. var halfHeight = height / 2;
  6718. var textAlign = 'left';
  6719. var textVerticalAlign = 'top';
  6720. switch (textPosition) {
  6721. case 'left':
  6722. x -= distance;
  6723. y += halfHeight;
  6724. textAlign = 'right';
  6725. textVerticalAlign = 'middle';
  6726. break;
  6727. case 'right':
  6728. x += distance + width;
  6729. y += halfHeight;
  6730. textVerticalAlign = 'middle';
  6731. break;
  6732. case 'top':
  6733. x += width / 2;
  6734. y -= distance;
  6735. textAlign = 'center';
  6736. textVerticalAlign = 'bottom';
  6737. break;
  6738. case 'bottom':
  6739. x += width / 2;
  6740. y += height + distance;
  6741. textAlign = 'center';
  6742. break;
  6743. case 'inside':
  6744. x += width / 2;
  6745. y += halfHeight;
  6746. textAlign = 'center';
  6747. textVerticalAlign = 'middle';
  6748. break;
  6749. case 'insideLeft':
  6750. x += distance;
  6751. y += halfHeight;
  6752. textVerticalAlign = 'middle';
  6753. break;
  6754. case 'insideRight':
  6755. x += width - distance;
  6756. y += halfHeight;
  6757. textAlign = 'right';
  6758. textVerticalAlign = 'middle';
  6759. break;
  6760. case 'insideTop':
  6761. x += width / 2;
  6762. y += distance;
  6763. textAlign = 'center';
  6764. break;
  6765. case 'insideBottom':
  6766. x += width / 2;
  6767. y += height - distance;
  6768. textAlign = 'center';
  6769. textVerticalAlign = 'bottom';
  6770. break;
  6771. case 'insideTopLeft':
  6772. x += distance;
  6773. y += distance;
  6774. break;
  6775. case 'insideTopRight':
  6776. x += width - distance;
  6777. y += distance;
  6778. textAlign = 'right';
  6779. break;
  6780. case 'insideBottomLeft':
  6781. x += distance;
  6782. y += height - distance;
  6783. textVerticalAlign = 'bottom';
  6784. break;
  6785. case 'insideBottomRight':
  6786. x += width - distance;
  6787. y += height - distance;
  6788. textAlign = 'right';
  6789. textVerticalAlign = 'bottom';
  6790. break;
  6791. }
  6792. out = out || {};
  6793. out.x = x;
  6794. out.y = y;
  6795. out.textAlign = textAlign;
  6796. out.textVerticalAlign = textVerticalAlign;
  6797. return out;
  6798. }
  6799. /**
  6800. * To be removed. But still do not remove in case that some one has imported it.
  6801. * @deprecated
  6802. * @public
  6803. * @param {stirng} textPosition
  6804. * @param {Object} rect {x, y, width, height}
  6805. * @param {number} distance
  6806. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6807. */
  6808. /**
  6809. * Show ellipsis if overflow.
  6810. *
  6811. * @public
  6812. * @param {string} text
  6813. * @param {string} containerWidth
  6814. * @param {string} font
  6815. * @param {number} [ellipsis='...']
  6816. * @param {Object} [options]
  6817. * @param {number} [options.maxIterations=3]
  6818. * @param {number} [options.minChar=0] If truncate result are less
  6819. * then minChar, ellipsis will not show, which is
  6820. * better for user hint in some cases.
  6821. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6822. * @return {string}
  6823. */
  6824. function truncateText(text, containerWidth, font, ellipsis, options) {
  6825. if (!containerWidth) {
  6826. return '';
  6827. }
  6828. var textLines = (text + '').split('\n');
  6829. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6830. // FIXME
  6831. // It is not appropriate that every line has '...' when truncate multiple lines.
  6832. for (var i = 0, len = textLines.length; i < len; i++) {
  6833. textLines[i] = truncateSingleLine(textLines[i], options);
  6834. }
  6835. return textLines.join('\n');
  6836. }
  6837. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6838. options = extend({}, options);
  6839. options.font = font;
  6840. var ellipsis = retrieve2(ellipsis, '...');
  6841. options.maxIterations = retrieve2(options.maxIterations, 2);
  6842. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6843. // FIXME
  6844. // Other languages?
  6845. options.cnCharWidth = getWidth('国', font);
  6846. // FIXME
  6847. // Consider proportional font?
  6848. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6849. options.placeholder = retrieve2(options.placeholder, '');
  6850. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6851. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6852. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6853. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6854. contentWidth -= ascCharWidth;
  6855. }
  6856. var ellipsisWidth = getWidth(ellipsis, font);
  6857. if (ellipsisWidth > contentWidth) {
  6858. ellipsis = '';
  6859. ellipsisWidth = 0;
  6860. }
  6861. contentWidth = containerWidth - ellipsisWidth;
  6862. options.ellipsis = ellipsis;
  6863. options.ellipsisWidth = ellipsisWidth;
  6864. options.contentWidth = contentWidth;
  6865. options.containerWidth = containerWidth;
  6866. return options;
  6867. }
  6868. function truncateSingleLine(textLine, options) {
  6869. var containerWidth = options.containerWidth;
  6870. var font = options.font;
  6871. var contentWidth = options.contentWidth;
  6872. if (!containerWidth) {
  6873. return '';
  6874. }
  6875. var lineWidth = getWidth(textLine, font);
  6876. if (lineWidth <= containerWidth) {
  6877. return textLine;
  6878. }
  6879. for (var j = 0; ; j++) {
  6880. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6881. textLine += options.ellipsis;
  6882. break;
  6883. }
  6884. var subLength = j === 0
  6885. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6886. : lineWidth > 0
  6887. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6888. : 0;
  6889. textLine = textLine.substr(0, subLength);
  6890. lineWidth = getWidth(textLine, font);
  6891. }
  6892. if (textLine === '') {
  6893. textLine = options.placeholder;
  6894. }
  6895. return textLine;
  6896. }
  6897. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6898. var width = 0;
  6899. var i = 0;
  6900. for (var len = text.length; i < len && width < contentWidth; i++) {
  6901. var charCode = text.charCodeAt(i);
  6902. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6903. }
  6904. return i;
  6905. }
  6906. /**
  6907. * @public
  6908. * @param {string} font
  6909. * @return {number} line height
  6910. */
  6911. function getLineHeight(font) {
  6912. // FIXME A rough approach.
  6913. return getWidth('国', font);
  6914. }
  6915. /**
  6916. * @public
  6917. * @param {string} text
  6918. * @param {string} font
  6919. * @return {Object} width
  6920. */
  6921. function measureText(text, font) {
  6922. return methods$1.measureText(text, font);
  6923. }
  6924. // Avoid assign to an exported variable, for transforming to cjs.
  6925. methods$1.measureText = function (text, font) {
  6926. var ctx = getContext();
  6927. ctx.font = font || DEFAULT_FONT$1;
  6928. return ctx.measureText(text);
  6929. };
  6930. /**
  6931. * @public
  6932. * @param {string} text
  6933. * @param {string} font
  6934. * @param {Object} [truncate]
  6935. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  6936. * Notice: for performance, do not calculate outerWidth util needed.
  6937. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  6938. * Thus we can simply comparing the `input` text to determin whether the result changed,
  6939. * without travel the result `lines`.
  6940. */
  6941. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6942. text != null && (text += '');
  6943. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6944. var lines = text ? text.split('\n') : [];
  6945. var height = lines.length * lineHeight;
  6946. var outerHeight = height;
  6947. var canCacheByTextString = true;
  6948. if (padding) {
  6949. outerHeight += padding[0] + padding[2];
  6950. }
  6951. if (text && truncate) {
  6952. canCacheByTextString = false;
  6953. var truncOuterHeight = truncate.outerHeight;
  6954. var truncOuterWidth = truncate.outerWidth;
  6955. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6956. text = '';
  6957. lines = [];
  6958. }
  6959. else if (truncOuterWidth != null) {
  6960. var options = prepareTruncateOptions(
  6961. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6962. font,
  6963. truncate.ellipsis,
  6964. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6965. );
  6966. // FIXME
  6967. // It is not appropriate that every line has '...' when truncate multiple lines.
  6968. for (var i = 0, len = lines.length; i < len; i++) {
  6969. lines[i] = truncateSingleLine(lines[i], options);
  6970. }
  6971. }
  6972. }
  6973. return {
  6974. lines: lines,
  6975. height: height,
  6976. outerHeight: outerHeight,
  6977. lineHeight: lineHeight,
  6978. canCacheByTextString: canCacheByTextString
  6979. };
  6980. }
  6981. /**
  6982. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6983. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6984. *
  6985. * @public
  6986. * @param {string} text
  6987. * @param {Object} style
  6988. * @return {Object} block
  6989. * {
  6990. * width,
  6991. * height,
  6992. * lines: [{
  6993. * lineHeight,
  6994. * width,
  6995. * tokens: [[{
  6996. * styleName,
  6997. * text,
  6998. * width, // include textPadding
  6999. * height, // include textPadding
  7000. * textWidth, // pure text width
  7001. * textHeight, // pure text height
  7002. * lineHeihgt,
  7003. * font,
  7004. * textAlign,
  7005. * textVerticalAlign
  7006. * }], [...], ...]
  7007. * }, ...]
  7008. * }
  7009. * If styleName is undefined, it is plain text.
  7010. */
  7011. function parseRichText(text, style) {
  7012. var contentBlock = {lines: [], width: 0, height: 0};
  7013. text != null && (text += '');
  7014. if (!text) {
  7015. return contentBlock;
  7016. }
  7017. var lastIndex = STYLE_REG.lastIndex = 0;
  7018. var result;
  7019. while ((result = STYLE_REG.exec(text)) != null) {
  7020. var matchedIndex = result.index;
  7021. if (matchedIndex > lastIndex) {
  7022. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7023. }
  7024. pushTokens(contentBlock, result[2], result[1]);
  7025. lastIndex = STYLE_REG.lastIndex;
  7026. }
  7027. if (lastIndex < text.length) {
  7028. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7029. }
  7030. var lines = contentBlock.lines;
  7031. var contentHeight = 0;
  7032. var contentWidth = 0;
  7033. // For `textWidth: 100%`
  7034. var pendingList = [];
  7035. var stlPadding = style.textPadding;
  7036. var truncate = style.truncate;
  7037. var truncateWidth = truncate && truncate.outerWidth;
  7038. var truncateHeight = truncate && truncate.outerHeight;
  7039. if (stlPadding) {
  7040. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7041. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7042. }
  7043. // Calculate layout info of tokens.
  7044. for (var i = 0; i < lines.length; i++) {
  7045. var line = lines[i];
  7046. var lineHeight = 0;
  7047. var lineWidth = 0;
  7048. for (var j = 0; j < line.tokens.length; j++) {
  7049. var token = line.tokens[j];
  7050. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7051. // textPadding should not inherit from style.
  7052. var textPadding = token.textPadding = tokenStyle.textPadding;
  7053. // textFont has been asigned to font by `normalizeStyle`.
  7054. var font = token.font = tokenStyle.font || style.font;
  7055. // textHeight can be used when textVerticalAlign is specified in token.
  7056. var tokenHeight = token.textHeight = retrieve2(
  7057. // textHeight should not be inherited, consider it can be specified
  7058. // as box height of the block.
  7059. tokenStyle.textHeight, getLineHeight(font)
  7060. );
  7061. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7062. token.height = tokenHeight;
  7063. token.lineHeight = retrieve3(
  7064. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7065. );
  7066. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7067. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7068. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7069. return {lines: [], width: 0, height: 0};
  7070. }
  7071. token.textWidth = getWidth(token.text, font);
  7072. var tokenWidth = tokenStyle.textWidth;
  7073. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7074. // Percent width, can be `100%`, can be used in drawing separate
  7075. // line when box width is needed to be auto.
  7076. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7077. token.percentWidth = tokenWidth;
  7078. pendingList.push(token);
  7079. tokenWidth = 0;
  7080. // Do not truncate in this case, because there is no user case
  7081. // and it is too complicated.
  7082. }
  7083. else {
  7084. if (tokenWidthNotSpecified) {
  7085. tokenWidth = token.textWidth;
  7086. // FIXME: If image is not loaded and textWidth is not specified, calling
  7087. // `getBoundingRect()` will not get correct result.
  7088. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7089. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7090. // Use cases:
  7091. // (1) If image is not loaded, it will be loaded at render phase and call
  7092. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7093. // image, and then the right size will be calculated here at the next tick.
  7094. // See `graphic/helper/text.js`.
  7095. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7096. // use `imageHelper.findExistImage` to find cached image.
  7097. // `imageHelper.findExistImage` will always be called here before
  7098. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7099. // which ensures that image will not be rendered before correct size calcualted.
  7100. if (bgImg) {
  7101. bgImg = findExistImage(bgImg);
  7102. if (isImageReady(bgImg)) {
  7103. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7104. }
  7105. }
  7106. }
  7107. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7108. tokenWidth += paddingW;
  7109. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7110. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7111. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7112. token.text = '';
  7113. token.textWidth = tokenWidth = 0;
  7114. }
  7115. else {
  7116. token.text = truncateText(
  7117. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7118. {minChar: truncate.minChar}
  7119. );
  7120. token.textWidth = getWidth(token.text, font);
  7121. tokenWidth = token.textWidth + paddingW;
  7122. }
  7123. }
  7124. }
  7125. lineWidth += (token.width = tokenWidth);
  7126. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7127. }
  7128. line.width = lineWidth;
  7129. line.lineHeight = lineHeight;
  7130. contentHeight += lineHeight;
  7131. contentWidth = Math.max(contentWidth, lineWidth);
  7132. }
  7133. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7134. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7135. if (stlPadding) {
  7136. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7137. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7138. }
  7139. for (var i = 0; i < pendingList.length; i++) {
  7140. var token = pendingList[i];
  7141. var percentWidth = token.percentWidth;
  7142. // Should not base on outerWidth, because token can not be placed out of padding.
  7143. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7144. }
  7145. return contentBlock;
  7146. }
  7147. function pushTokens(block, str, styleName) {
  7148. var isEmptyStr = str === '';
  7149. var strs = str.split('\n');
  7150. var lines = block.lines;
  7151. for (var i = 0; i < strs.length; i++) {
  7152. var text = strs[i];
  7153. var token = {
  7154. styleName: styleName,
  7155. text: text,
  7156. isLineHolder: !text && !isEmptyStr
  7157. };
  7158. // The first token should be appended to the last line.
  7159. if (!i) {
  7160. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7161. // Consider cases:
  7162. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7163. // (which is a placeholder) should be replaced by new token.
  7164. // (2) A image backage, where token likes {a|}.
  7165. // (3) A redundant '' will affect textAlign in line.
  7166. // (4) tokens with the same tplName should not be merged, because
  7167. // they should be displayed in different box (with border and padding).
  7168. var tokensLen = tokens.length;
  7169. (tokensLen === 1 && tokens[0].isLineHolder)
  7170. ? (tokens[0] = token)
  7171. // Consider text is '', only insert when it is the "lineHolder" or
  7172. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7173. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7174. }
  7175. // Other tokens always start a new line.
  7176. else {
  7177. // If there is '', insert it as a placeholder.
  7178. lines.push({tokens: [token]});
  7179. }
  7180. }
  7181. }
  7182. function makeFont(style) {
  7183. // FIXME in node-canvas fontWeight is before fontStyle
  7184. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7185. var font = (style.fontSize || style.fontFamily) && [
  7186. style.fontStyle,
  7187. style.fontWeight,
  7188. (style.fontSize || 12) + 'px',
  7189. // If font properties are defined, `fontFamily` should not be ignored.
  7190. style.fontFamily || 'sans-serif'
  7191. ].join(' ');
  7192. return font && trim(font) || style.textFont || style.font;
  7193. }
  7194. /**
  7195. * @param {Object} ctx
  7196. * @param {Object} shape
  7197. * @param {number} shape.x
  7198. * @param {number} shape.y
  7199. * @param {number} shape.width
  7200. * @param {number} shape.height
  7201. * @param {number} shape.r
  7202. */
  7203. function buildPath(ctx, shape) {
  7204. var x = shape.x;
  7205. var y = shape.y;
  7206. var width = shape.width;
  7207. var height = shape.height;
  7208. var r = shape.r;
  7209. var r1;
  7210. var r2;
  7211. var r3;
  7212. var r4;
  7213. // Convert width and height to positive for better borderRadius
  7214. if (width < 0) {
  7215. x = x + width;
  7216. width = -width;
  7217. }
  7218. if (height < 0) {
  7219. y = y + height;
  7220. height = -height;
  7221. }
  7222. if (typeof r === 'number') {
  7223. r1 = r2 = r3 = r4 = r;
  7224. }
  7225. else if (r instanceof Array) {
  7226. if (r.length === 1) {
  7227. r1 = r2 = r3 = r4 = r[0];
  7228. }
  7229. else if (r.length === 2) {
  7230. r1 = r3 = r[0];
  7231. r2 = r4 = r[1];
  7232. }
  7233. else if (r.length === 3) {
  7234. r1 = r[0];
  7235. r2 = r4 = r[1];
  7236. r3 = r[2];
  7237. }
  7238. else {
  7239. r1 = r[0];
  7240. r2 = r[1];
  7241. r3 = r[2];
  7242. r4 = r[3];
  7243. }
  7244. }
  7245. else {
  7246. r1 = r2 = r3 = r4 = 0;
  7247. }
  7248. var total;
  7249. if (r1 + r2 > width) {
  7250. total = r1 + r2;
  7251. r1 *= width / total;
  7252. r2 *= width / total;
  7253. }
  7254. if (r3 + r4 > width) {
  7255. total = r3 + r4;
  7256. r3 *= width / total;
  7257. r4 *= width / total;
  7258. }
  7259. if (r2 + r3 > height) {
  7260. total = r2 + r3;
  7261. r2 *= height / total;
  7262. r3 *= height / total;
  7263. }
  7264. if (r1 + r4 > height) {
  7265. total = r1 + r4;
  7266. r1 *= height / total;
  7267. r4 *= height / total;
  7268. }
  7269. ctx.moveTo(x + r1, y);
  7270. ctx.lineTo(x + width - r2, y);
  7271. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7272. ctx.lineTo(x + width, y + height - r3);
  7273. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7274. ctx.lineTo(x + r4, y + height);
  7275. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7276. ctx.lineTo(x, y + r1);
  7277. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7278. }
  7279. var DEFAULT_FONT = DEFAULT_FONT$1;
  7280. // TODO: Have not support 'start', 'end' yet.
  7281. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7282. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7283. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7284. // the default value of shadowColor is `'transparent'`.
  7285. var SHADOW_STYLE_COMMON_PROPS = [
  7286. ['textShadowBlur', 'shadowBlur', 0],
  7287. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7288. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7289. ['textShadowColor', 'shadowColor', 'transparent']
  7290. ];
  7291. var _tmpTextPositionResult = {};
  7292. var _tmpBoxPositionResult = {};
  7293. /**
  7294. * @param {module:zrender/graphic/Style} style
  7295. * @return {module:zrender/graphic/Style} The input style.
  7296. */
  7297. function normalizeTextStyle(style) {
  7298. normalizeStyle(style);
  7299. each$1(style.rich, normalizeStyle);
  7300. return style;
  7301. }
  7302. function normalizeStyle(style) {
  7303. if (style) {
  7304. style.font = makeFont(style);
  7305. var textAlign = style.textAlign;
  7306. textAlign === 'middle' && (textAlign = 'center');
  7307. style.textAlign = (
  7308. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7309. ) ? textAlign : 'left';
  7310. // Compatible with textBaseline.
  7311. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7312. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7313. style.textVerticalAlign = (
  7314. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7315. ) ? textVerticalAlign : 'top';
  7316. var textPadding = style.textPadding;
  7317. if (textPadding) {
  7318. style.textPadding = normalizeCssArray(style.textPadding);
  7319. }
  7320. }
  7321. }
  7322. /**
  7323. * @param {CanvasRenderingContext2D} ctx
  7324. * @param {string} text
  7325. * @param {module:zrender/graphic/Style} style
  7326. * @param {Object|boolean} [rect] {x, y, width, height}
  7327. * If set false, rect text is not used.
  7328. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7329. */
  7330. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7331. style.rich
  7332. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7333. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7334. }
  7335. // Avoid setting to ctx according to prevEl if possible for
  7336. // performance in scenarios of large amount text.
  7337. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7338. 'use strict';
  7339. var needDrawBg = needDrawBackground(style);
  7340. var prevStyle;
  7341. var checkCache = false;
  7342. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7343. // Only take and check cache for `Text` el, but not RectText.
  7344. if (prevEl !== WILL_BE_RESTORED) {
  7345. if (prevEl) {
  7346. prevStyle = prevEl.style;
  7347. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7348. }
  7349. // Prevent from using cache in `Style::bind`, because of the case:
  7350. // ctx property is modified by other properties than `Style::bind`
  7351. // used, and Style::bind is called next.
  7352. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7353. }
  7354. // Since this will be restored, prevent from using these props to check cache in the next
  7355. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7356. else if (cachedByMe) {
  7357. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7358. }
  7359. var styleFont = style.font || DEFAULT_FONT;
  7360. // PENDING
  7361. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7362. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7363. // But layer save/restore needed to be considered.
  7364. // if (styleFont !== ctx.__fontCache) {
  7365. // ctx.font = styleFont;
  7366. // if (prevEl !== WILL_BE_RESTORED) {
  7367. // ctx.__fontCache = styleFont;
  7368. // }
  7369. // }
  7370. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7371. ctx.font = styleFont;
  7372. }
  7373. // Use the final font from context-2d, because the final
  7374. // font might not be the style.font when it is illegal.
  7375. // But get `ctx.font` might be time consuming.
  7376. var computedFont = hostEl.__computedFont;
  7377. if (hostEl.__styleFont !== styleFont) {
  7378. hostEl.__styleFont = styleFont;
  7379. computedFont = hostEl.__computedFont = ctx.font;
  7380. }
  7381. var textPadding = style.textPadding;
  7382. var textLineHeight = style.textLineHeight;
  7383. var contentBlock = hostEl.__textCotentBlock;
  7384. if (!contentBlock || hostEl.__dirtyText) {
  7385. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7386. text, computedFont, textPadding, textLineHeight, style.truncate
  7387. );
  7388. }
  7389. var outerHeight = contentBlock.outerHeight;
  7390. var textLines = contentBlock.lines;
  7391. var lineHeight = contentBlock.lineHeight;
  7392. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7393. var baseX = boxPos.baseX;
  7394. var baseY = boxPos.baseY;
  7395. var textAlign = boxPos.textAlign || 'left';
  7396. var textVerticalAlign = boxPos.textVerticalAlign;
  7397. // Origin of textRotation should be the base point of text drawing.
  7398. applyTextRotation(ctx, style, rect, baseX, baseY);
  7399. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7400. var textX = baseX;
  7401. var textY = boxY;
  7402. if (needDrawBg || textPadding) {
  7403. // Consider performance, do not call getTextWidth util necessary.
  7404. var textWidth = getWidth(text, computedFont);
  7405. var outerWidth = textWidth;
  7406. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7407. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7408. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7409. if (textPadding) {
  7410. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7411. textY += textPadding[0];
  7412. }
  7413. }
  7414. // Always set textAlign and textBase line, because it is difficute to calculate
  7415. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7416. // font set happened.
  7417. ctx.textAlign = textAlign;
  7418. // Force baseline to be "middle". Otherwise, if using "top", the
  7419. // text will offset downward a little bit in font "Microsoft YaHei".
  7420. ctx.textBaseline = 'middle';
  7421. // Set text opacity
  7422. ctx.globalAlpha = style.opacity || 1;
  7423. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7424. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7425. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7426. var styleProp = propItem[0];
  7427. var ctxProp = propItem[1];
  7428. var val = style[styleProp];
  7429. if (!checkCache || val !== prevStyle[styleProp]) {
  7430. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7431. }
  7432. }
  7433. // `textBaseline` is set as 'middle'.
  7434. textY += lineHeight / 2;
  7435. var textStrokeWidth = style.textStrokeWidth;
  7436. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7437. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7438. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7439. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7440. var textFill = getFill(style.textFill);
  7441. if (textStroke) {
  7442. if (strokeWidthChanged) {
  7443. ctx.lineWidth = textStrokeWidth;
  7444. }
  7445. if (strokeChanged) {
  7446. ctx.strokeStyle = textStroke;
  7447. }
  7448. }
  7449. if (textFill) {
  7450. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7451. ctx.fillStyle = textFill;
  7452. }
  7453. }
  7454. // Optimize simply, in most cases only one line exists.
  7455. if (textLines.length === 1) {
  7456. // Fill after stroke so the outline will not cover the main part.
  7457. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7458. textFill && ctx.fillText(textLines[0], textX, textY);
  7459. }
  7460. else {
  7461. for (var i = 0; i < textLines.length; i++) {
  7462. // Fill after stroke so the outline will not cover the main part.
  7463. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7464. textFill && ctx.fillText(textLines[i], textX, textY);
  7465. textY += lineHeight;
  7466. }
  7467. }
  7468. }
  7469. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7470. // Do not do cache for rich text because of the complexity.
  7471. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7472. if (prevEl !== WILL_BE_RESTORED) {
  7473. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7474. }
  7475. var contentBlock = hostEl.__textCotentBlock;
  7476. if (!contentBlock || hostEl.__dirtyText) {
  7477. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7478. }
  7479. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7480. }
  7481. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7482. var contentWidth = contentBlock.width;
  7483. var outerWidth = contentBlock.outerWidth;
  7484. var outerHeight = contentBlock.outerHeight;
  7485. var textPadding = style.textPadding;
  7486. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7487. var baseX = boxPos.baseX;
  7488. var baseY = boxPos.baseY;
  7489. var textAlign = boxPos.textAlign;
  7490. var textVerticalAlign = boxPos.textVerticalAlign;
  7491. // Origin of textRotation should be the base point of text drawing.
  7492. applyTextRotation(ctx, style, rect, baseX, baseY);
  7493. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7494. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7495. var xLeft = boxX;
  7496. var lineTop = boxY;
  7497. if (textPadding) {
  7498. xLeft += textPadding[3];
  7499. lineTop += textPadding[0];
  7500. }
  7501. var xRight = xLeft + contentWidth;
  7502. needDrawBackground(style) && drawBackground(
  7503. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7504. );
  7505. for (var i = 0; i < contentBlock.lines.length; i++) {
  7506. var line = contentBlock.lines[i];
  7507. var tokens = line.tokens;
  7508. var tokenCount = tokens.length;
  7509. var lineHeight = line.lineHeight;
  7510. var usedWidth = line.width;
  7511. var leftIndex = 0;
  7512. var lineXLeft = xLeft;
  7513. var lineXRight = xRight;
  7514. var rightIndex = tokenCount - 1;
  7515. var token;
  7516. while (
  7517. leftIndex < tokenCount
  7518. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7519. ) {
  7520. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7521. usedWidth -= token.width;
  7522. lineXLeft += token.width;
  7523. leftIndex++;
  7524. }
  7525. while (
  7526. rightIndex >= 0
  7527. && (token = tokens[rightIndex], token.textAlign === 'right')
  7528. ) {
  7529. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7530. usedWidth -= token.width;
  7531. lineXRight -= token.width;
  7532. rightIndex--;
  7533. }
  7534. // The other tokens are placed as textAlign 'center' if there is enough space.
  7535. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7536. while (leftIndex <= rightIndex) {
  7537. token = tokens[leftIndex];
  7538. // Consider width specified by user, use 'center' rather than 'left'.
  7539. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7540. lineXLeft += token.width;
  7541. leftIndex++;
  7542. }
  7543. lineTop += lineHeight;
  7544. }
  7545. }
  7546. function applyTextRotation(ctx, style, rect, x, y) {
  7547. // textRotation only apply in RectText.
  7548. if (rect && style.textRotation) {
  7549. var origin = style.textOrigin;
  7550. if (origin === 'center') {
  7551. x = rect.width / 2 + rect.x;
  7552. y = rect.height / 2 + rect.y;
  7553. }
  7554. else if (origin) {
  7555. x = origin[0] + rect.x;
  7556. y = origin[1] + rect.y;
  7557. }
  7558. ctx.translate(x, y);
  7559. // Positive: anticlockwise
  7560. ctx.rotate(-style.textRotation);
  7561. ctx.translate(-x, -y);
  7562. }
  7563. }
  7564. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7565. var tokenStyle = style.rich[token.styleName] || {};
  7566. tokenStyle.text = token.text;
  7567. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7568. // the bias of "Microsoft YaHei".
  7569. var textVerticalAlign = token.textVerticalAlign;
  7570. var y = lineTop + lineHeight / 2;
  7571. if (textVerticalAlign === 'top') {
  7572. y = lineTop + token.height / 2;
  7573. }
  7574. else if (textVerticalAlign === 'bottom') {
  7575. y = lineTop + lineHeight - token.height / 2;
  7576. }
  7577. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7578. hostEl,
  7579. ctx,
  7580. tokenStyle,
  7581. textAlign === 'right'
  7582. ? x - token.width
  7583. : textAlign === 'center'
  7584. ? x - token.width / 2
  7585. : x,
  7586. y - token.height / 2,
  7587. token.width,
  7588. token.height
  7589. );
  7590. var textPadding = token.textPadding;
  7591. if (textPadding) {
  7592. x = getTextXForPadding(x, textAlign, textPadding);
  7593. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7594. }
  7595. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7596. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7597. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7598. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7599. setCtx(ctx, 'textAlign', textAlign);
  7600. // Force baseline to be "middle". Otherwise, if using "top", the
  7601. // text will offset downward a little bit in font "Microsoft YaHei".
  7602. setCtx(ctx, 'textBaseline', 'middle');
  7603. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7604. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7605. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7606. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7607. // Fill after stroke so the outline will not cover the main part.
  7608. if (textStroke) {
  7609. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7610. setCtx(ctx, 'strokeStyle', textStroke);
  7611. ctx.strokeText(token.text, x, y);
  7612. }
  7613. if (textFill) {
  7614. setCtx(ctx, 'fillStyle', textFill);
  7615. ctx.fillText(token.text, x, y);
  7616. }
  7617. }
  7618. function needDrawBackground(style) {
  7619. return !!(
  7620. style.textBackgroundColor
  7621. || (style.textBorderWidth && style.textBorderColor)
  7622. );
  7623. }
  7624. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7625. // shape: {x, y, width, height}
  7626. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7627. var textBackgroundColor = style.textBackgroundColor;
  7628. var textBorderWidth = style.textBorderWidth;
  7629. var textBorderColor = style.textBorderColor;
  7630. var isPlainBg = isString(textBackgroundColor);
  7631. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7632. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7633. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7634. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7635. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7636. ctx.beginPath();
  7637. var textBorderRadius = style.textBorderRadius;
  7638. if (!textBorderRadius) {
  7639. ctx.rect(x, y, width, height);
  7640. }
  7641. else {
  7642. buildPath(ctx, {
  7643. x: x, y: y, width: width, height: height, r: textBorderRadius
  7644. });
  7645. }
  7646. ctx.closePath();
  7647. }
  7648. if (isPlainBg) {
  7649. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7650. if (style.fillOpacity != null) {
  7651. var originalGlobalAlpha = ctx.globalAlpha;
  7652. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7653. ctx.fill();
  7654. ctx.globalAlpha = originalGlobalAlpha;
  7655. }
  7656. else {
  7657. ctx.fill();
  7658. }
  7659. }
  7660. else if (isObject$1(textBackgroundColor)) {
  7661. var image = textBackgroundColor.image;
  7662. image = createOrUpdateImage(
  7663. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7664. );
  7665. if (image && isImageReady(image)) {
  7666. ctx.drawImage(image, x, y, width, height);
  7667. }
  7668. }
  7669. if (textBorderWidth && textBorderColor) {
  7670. setCtx(ctx, 'lineWidth', textBorderWidth);
  7671. setCtx(ctx, 'strokeStyle', textBorderColor);
  7672. if (style.strokeOpacity != null) {
  7673. var originalGlobalAlpha = ctx.globalAlpha;
  7674. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7675. ctx.stroke();
  7676. ctx.globalAlpha = originalGlobalAlpha;
  7677. }
  7678. else {
  7679. ctx.stroke();
  7680. }
  7681. }
  7682. }
  7683. function onBgImageLoaded(image, textBackgroundColor) {
  7684. // Replace image, so that `contain/text.js#parseRichText`
  7685. // will get correct result in next tick.
  7686. textBackgroundColor.image = image;
  7687. }
  7688. function getBoxPosition(out, hostEl, style, rect) {
  7689. var baseX = style.x || 0;
  7690. var baseY = style.y || 0;
  7691. var textAlign = style.textAlign;
  7692. var textVerticalAlign = style.textVerticalAlign;
  7693. // Text position represented by coord
  7694. if (rect) {
  7695. var textPosition = style.textPosition;
  7696. if (textPosition instanceof Array) {
  7697. // Percent
  7698. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7699. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7700. }
  7701. else {
  7702. var res = (hostEl && hostEl.calculateTextPosition)
  7703. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7704. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7705. baseX = res.x;
  7706. baseY = res.y;
  7707. // Default align and baseline when has textPosition
  7708. textAlign = textAlign || res.textAlign;
  7709. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7710. }
  7711. // textOffset is only support in RectText, otherwise
  7712. // we have to adjust boundingRect for textOffset.
  7713. var textOffset = style.textOffset;
  7714. if (textOffset) {
  7715. baseX += textOffset[0];
  7716. baseY += textOffset[1];
  7717. }
  7718. }
  7719. out = out || {};
  7720. out.baseX = baseX;
  7721. out.baseY = baseY;
  7722. out.textAlign = textAlign;
  7723. out.textVerticalAlign = textVerticalAlign;
  7724. return out;
  7725. }
  7726. function setCtx(ctx, prop, value) {
  7727. ctx[prop] = fixShadow(ctx, prop, value);
  7728. return ctx[prop];
  7729. }
  7730. /**
  7731. * @param {string} [stroke] If specified, do not check style.textStroke.
  7732. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7733. * @param {number} style
  7734. */
  7735. function getStroke(stroke, lineWidth) {
  7736. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7737. ? null
  7738. // TODO pattern and gradient?
  7739. : (stroke.image || stroke.colorStops)
  7740. ? '#000'
  7741. : stroke;
  7742. }
  7743. function getFill(fill) {
  7744. return (fill == null || fill === 'none')
  7745. ? null
  7746. // TODO pattern and gradient?
  7747. : (fill.image || fill.colorStops)
  7748. ? '#000'
  7749. : fill;
  7750. }
  7751. function parsePercent(value, maxValue) {
  7752. if (typeof value === 'string') {
  7753. if (value.lastIndexOf('%') >= 0) {
  7754. return parseFloat(value) / 100 * maxValue;
  7755. }
  7756. return parseFloat(value);
  7757. }
  7758. return value;
  7759. }
  7760. function getTextXForPadding(x, textAlign, textPadding) {
  7761. return textAlign === 'right'
  7762. ? (x - textPadding[1])
  7763. : textAlign === 'center'
  7764. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7765. : (x + textPadding[3]);
  7766. }
  7767. /**
  7768. * @param {string} text
  7769. * @param {module:zrender/Style} style
  7770. * @return {boolean}
  7771. */
  7772. function needDrawText(text, style) {
  7773. return text != null
  7774. && (text
  7775. || style.textBackgroundColor
  7776. || (style.textBorderWidth && style.textBorderColor)
  7777. || style.textPadding
  7778. );
  7779. }
  7780. /**
  7781. * Mixin for drawing text in a element bounding rect
  7782. * @module zrender/mixin/RectText
  7783. */
  7784. var tmpRect$1 = new BoundingRect();
  7785. var RectText = function () {};
  7786. RectText.prototype = {
  7787. constructor: RectText,
  7788. /**
  7789. * Draw text in a rect with specified position.
  7790. * @param {CanvasRenderingContext2D} ctx
  7791. * @param {Object} rect Displayable rect
  7792. */
  7793. drawRectText: function (ctx, rect) {
  7794. var style = this.style;
  7795. rect = style.textRect || rect;
  7796. // Optimize, avoid normalize every time.
  7797. this.__dirty && normalizeTextStyle(style, true);
  7798. var text = style.text;
  7799. // Convert to string
  7800. text != null && (text += '');
  7801. if (!needDrawText(text, style)) {
  7802. return;
  7803. }
  7804. // FIXME
  7805. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7806. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7807. // text propably break the cache for its host elements.
  7808. ctx.save();
  7809. // Transform rect to view space
  7810. var transform = this.transform;
  7811. if (!style.transformText) {
  7812. if (transform) {
  7813. tmpRect$1.copy(rect);
  7814. tmpRect$1.applyTransform(transform);
  7815. rect = tmpRect$1;
  7816. }
  7817. }
  7818. else {
  7819. this.setTransform(ctx);
  7820. }
  7821. // transformText and textRotation can not be used at the same time.
  7822. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7823. ctx.restore();
  7824. }
  7825. };
  7826. /**
  7827. * Base class of all displayable graphic objects
  7828. * @module zrender/graphic/Displayable
  7829. */
  7830. /**
  7831. * @alias module:zrender/graphic/Displayable
  7832. * @extends module:zrender/Element
  7833. * @extends module:zrender/graphic/mixin/RectText
  7834. */
  7835. function Displayable(opts) {
  7836. opts = opts || {};
  7837. Element.call(this, opts);
  7838. // Extend properties
  7839. for (var name in opts) {
  7840. if (
  7841. opts.hasOwnProperty(name)
  7842. && name !== 'style'
  7843. ) {
  7844. this[name] = opts[name];
  7845. }
  7846. }
  7847. /**
  7848. * @type {module:zrender/graphic/Style}
  7849. */
  7850. this.style = new Style(opts.style, this);
  7851. this._rect = null;
  7852. // Shapes for cascade clipping.
  7853. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  7854. // because it is easy to only using null to check whether clipPaths changed.
  7855. this.__clipPaths = null;
  7856. // FIXME Stateful must be mixined after style is setted
  7857. // Stateful.call(this, opts);
  7858. }
  7859. Displayable.prototype = {
  7860. constructor: Displayable,
  7861. type: 'displayable',
  7862. /**
  7863. * Dirty flag. From which painter will determine if this displayable object needs brush.
  7864. * @name module:zrender/graphic/Displayable#__dirty
  7865. * @type {boolean}
  7866. */
  7867. __dirty: true,
  7868. /**
  7869. * Whether the displayable object is visible. when it is true, the displayable object
  7870. * is not drawn, but the mouse event can still trigger the object.
  7871. * @name module:/zrender/graphic/Displayable#invisible
  7872. * @type {boolean}
  7873. * @default false
  7874. */
  7875. invisible: false,
  7876. /**
  7877. * @name module:/zrender/graphic/Displayable#z
  7878. * @type {number}
  7879. * @default 0
  7880. */
  7881. z: 0,
  7882. /**
  7883. * @name module:/zrender/graphic/Displayable#z
  7884. * @type {number}
  7885. * @default 0
  7886. */
  7887. z2: 0,
  7888. /**
  7889. * The z level determines the displayable object can be drawn in which layer canvas.
  7890. * @name module:/zrender/graphic/Displayable#zlevel
  7891. * @type {number}
  7892. * @default 0
  7893. */
  7894. zlevel: 0,
  7895. /**
  7896. * Whether it can be dragged.
  7897. * @name module:/zrender/graphic/Displayable#draggable
  7898. * @type {boolean}
  7899. * @default false
  7900. */
  7901. draggable: false,
  7902. /**
  7903. * Whether is it dragging.
  7904. * @name module:/zrender/graphic/Displayable#draggable
  7905. * @type {boolean}
  7906. * @default false
  7907. */
  7908. dragging: false,
  7909. /**
  7910. * Whether to respond to mouse events.
  7911. * @name module:/zrender/graphic/Displayable#silent
  7912. * @type {boolean}
  7913. * @default false
  7914. */
  7915. silent: false,
  7916. /**
  7917. * If enable culling
  7918. * @type {boolean}
  7919. * @default false
  7920. */
  7921. culling: false,
  7922. /**
  7923. * Mouse cursor when hovered
  7924. * @name module:/zrender/graphic/Displayable#cursor
  7925. * @type {string}
  7926. */
  7927. cursor: 'pointer',
  7928. /**
  7929. * If hover area is bounding rect
  7930. * @name module:/zrender/graphic/Displayable#rectHover
  7931. * @type {string}
  7932. */
  7933. rectHover: false,
  7934. /**
  7935. * Render the element progressively when the value >= 0,
  7936. * usefull for large data.
  7937. * @type {boolean}
  7938. */
  7939. progressive: false,
  7940. /**
  7941. * @type {boolean}
  7942. */
  7943. incremental: false,
  7944. /**
  7945. * Scale ratio for global scale.
  7946. * @type {boolean}
  7947. */
  7948. globalScaleRatio: 1,
  7949. beforeBrush: function (ctx) {},
  7950. afterBrush: function (ctx) {},
  7951. /**
  7952. * Graphic drawing method.
  7953. * @param {CanvasRenderingContext2D} ctx
  7954. */
  7955. // Interface
  7956. brush: function (ctx, prevEl) {},
  7957. /**
  7958. * Get the minimum bounding box.
  7959. * @return {module:zrender/core/BoundingRect}
  7960. */
  7961. // Interface
  7962. getBoundingRect: function () {},
  7963. /**
  7964. * If displayable element contain coord x, y
  7965. * @param {number} x
  7966. * @param {number} y
  7967. * @return {boolean}
  7968. */
  7969. contain: function (x, y) {
  7970. return this.rectContain(x, y);
  7971. },
  7972. /**
  7973. * @param {Function} cb
  7974. * @param {} context
  7975. */
  7976. traverse: function (cb, context) {
  7977. cb.call(context, this);
  7978. },
  7979. /**
  7980. * If bounding rect of element contain coord x, y
  7981. * @param {number} x
  7982. * @param {number} y
  7983. * @return {boolean}
  7984. */
  7985. rectContain: function (x, y) {
  7986. var coord = this.transformCoordToLocal(x, y);
  7987. var rect = this.getBoundingRect();
  7988. return rect.contain(coord[0], coord[1]);
  7989. },
  7990. /**
  7991. * Mark displayable element dirty and refresh next frame
  7992. */
  7993. dirty: function () {
  7994. this.__dirty = this.__dirtyText = true;
  7995. this._rect = null;
  7996. this.__zr && this.__zr.refresh();
  7997. },
  7998. /**
  7999. * If displayable object binded any event
  8000. * @return {boolean}
  8001. */
  8002. // TODO, events bound by bind
  8003. // isSilent: function () {
  8004. // return !(
  8005. // this.hoverable || this.draggable
  8006. // || this.onmousemove || this.onmouseover || this.onmouseout
  8007. // || this.onmousedown || this.onmouseup || this.onclick
  8008. // || this.ondragenter || this.ondragover || this.ondragleave
  8009. // || this.ondrop
  8010. // );
  8011. // },
  8012. /**
  8013. * Alias for animate('style')
  8014. * @param {boolean} loop
  8015. */
  8016. animateStyle: function (loop) {
  8017. return this.animate('style', loop);
  8018. },
  8019. attrKV: function (key, value) {
  8020. if (key !== 'style') {
  8021. Element.prototype.attrKV.call(this, key, value);
  8022. }
  8023. else {
  8024. this.style.set(value);
  8025. }
  8026. },
  8027. /**
  8028. * @param {Object|string} key
  8029. * @param {*} value
  8030. */
  8031. setStyle: function (key, value) {
  8032. this.style.set(key, value);
  8033. this.dirty(false);
  8034. return this;
  8035. },
  8036. /**
  8037. * Use given style object
  8038. * @param {Object} obj
  8039. */
  8040. useStyle: function (obj) {
  8041. this.style = new Style(obj, this);
  8042. this.dirty(false);
  8043. return this;
  8044. },
  8045. /**
  8046. * The string value of `textPosition` needs to be calculated to a real postion.
  8047. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8048. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8049. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8050. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8051. * for those shapes. It will be called if the `style.textPosition` is a string.
  8052. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8053. * be responsible for creating one.
  8054. * @param {module:zrender/graphic/Style} style
  8055. * @param {Object} rect {x, y, width, height}
  8056. * @return {Obejct} out The same as the input out.
  8057. * {
  8058. * x: number. mandatory.
  8059. * y: number. mandatory.
  8060. * textAlign: string. optional. use style.textAlign by default.
  8061. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8062. * }
  8063. */
  8064. calculateTextPosition: null
  8065. };
  8066. inherits(Displayable, Element);
  8067. mixin(Displayable, RectText);
  8068. /**
  8069. * @alias zrender/graphic/Image
  8070. * @extends module:zrender/graphic/Displayable
  8071. * @constructor
  8072. * @param {Object} opts
  8073. */
  8074. function ZImage(opts) {
  8075. Displayable.call(this, opts);
  8076. }
  8077. ZImage.prototype = {
  8078. constructor: ZImage,
  8079. type: 'image',
  8080. brush: function (ctx, prevEl) {
  8081. var style = this.style;
  8082. var src = style.image;
  8083. // Must bind each time
  8084. style.bind(ctx, this, prevEl);
  8085. var image = this._image = createOrUpdateImage(
  8086. src,
  8087. this._image,
  8088. this,
  8089. this.onload
  8090. );
  8091. if (!image || !isImageReady(image)) {
  8092. return;
  8093. }
  8094. // 图片已经加载完成
  8095. // if (image.nodeName.toUpperCase() == 'IMG') {
  8096. // if (!image.complete) {
  8097. // return;
  8098. // }
  8099. // }
  8100. // Else is canvas
  8101. var x = style.x || 0;
  8102. var y = style.y || 0;
  8103. var width = style.width;
  8104. var height = style.height;
  8105. var aspect = image.width / image.height;
  8106. if (width == null && height != null) {
  8107. // Keep image/height ratio
  8108. width = height * aspect;
  8109. }
  8110. else if (height == null && width != null) {
  8111. height = width / aspect;
  8112. }
  8113. else if (width == null && height == null) {
  8114. width = image.width;
  8115. height = image.height;
  8116. }
  8117. // 设置transform
  8118. this.setTransform(ctx);
  8119. if (style.sWidth && style.sHeight) {
  8120. var sx = style.sx || 0;
  8121. var sy = style.sy || 0;
  8122. ctx.drawImage(
  8123. image,
  8124. sx, sy, style.sWidth, style.sHeight,
  8125. x, y, width, height
  8126. );
  8127. }
  8128. else if (style.sx && style.sy) {
  8129. var sx = style.sx;
  8130. var sy = style.sy;
  8131. var sWidth = width - sx;
  8132. var sHeight = height - sy;
  8133. ctx.drawImage(
  8134. image,
  8135. sx, sy, sWidth, sHeight,
  8136. x, y, width, height
  8137. );
  8138. }
  8139. else {
  8140. ctx.drawImage(image, x, y, width, height);
  8141. }
  8142. // Draw rect text
  8143. if (style.text != null) {
  8144. // Only restore transform when needs draw text.
  8145. this.restoreTransform(ctx);
  8146. this.drawRectText(ctx, this.getBoundingRect());
  8147. }
  8148. },
  8149. getBoundingRect: function () {
  8150. var style = this.style;
  8151. if (!this._rect) {
  8152. this._rect = new BoundingRect(
  8153. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8154. );
  8155. }
  8156. return this._rect;
  8157. }
  8158. };
  8159. inherits(ZImage, Displayable);
  8160. var HOVER_LAYER_ZLEVEL = 1e5;
  8161. var CANVAS_ZLEVEL = 314159;
  8162. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8163. var INCREMENTAL_INC = 0.001;
  8164. function parseInt10(val) {
  8165. return parseInt(val, 10);
  8166. }
  8167. function isLayerValid(layer) {
  8168. if (!layer) {
  8169. return false;
  8170. }
  8171. if (layer.__builtin__) {
  8172. return true;
  8173. }
  8174. if (typeof (layer.resize) !== 'function'
  8175. || typeof (layer.refresh) !== 'function'
  8176. ) {
  8177. return false;
  8178. }
  8179. return true;
  8180. }
  8181. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8182. var viewRect = new BoundingRect(0, 0, 0, 0);
  8183. function isDisplayableCulled(el, width, height) {
  8184. tmpRect.copy(el.getBoundingRect());
  8185. if (el.transform) {
  8186. tmpRect.applyTransform(el.transform);
  8187. }
  8188. viewRect.width = width;
  8189. viewRect.height = height;
  8190. return !tmpRect.intersect(viewRect);
  8191. }
  8192. function isClipPathChanged(clipPaths, prevClipPaths) {
  8193. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8194. if (clipPaths === prevClipPaths) {
  8195. return false;
  8196. }
  8197. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8198. return true;
  8199. }
  8200. for (var i = 0; i < clipPaths.length; i++) {
  8201. if (clipPaths[i] !== prevClipPaths[i]) {
  8202. return true;
  8203. }
  8204. }
  8205. return false;
  8206. }
  8207. function doClip(clipPaths, ctx) {
  8208. for (var i = 0; i < clipPaths.length; i++) {
  8209. var clipPath = clipPaths[i];
  8210. clipPath.setTransform(ctx);
  8211. ctx.beginPath();
  8212. clipPath.buildPath(ctx, clipPath.shape);
  8213. ctx.clip();
  8214. // Transform back
  8215. clipPath.restoreTransform(ctx);
  8216. }
  8217. }
  8218. function createRoot(width, height) {
  8219. var domRoot = document.createElement('div');
  8220. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8221. domRoot.style.cssText = [
  8222. 'position:relative',
  8223. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8224. // dom does not act as expected) when some of the parent dom has
  8225. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8226. // the canvas is not at the top part of the page.
  8227. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8228. // this `overflow:hidden` to avoid the bug.
  8229. // 'overflow:hidden',
  8230. 'width:' + width + 'px',
  8231. 'height:' + height + 'px',
  8232. 'padding:0',
  8233. 'margin:0',
  8234. 'border-width:0'
  8235. ].join(';') + ';';
  8236. return domRoot;
  8237. }
  8238. /**
  8239. * @alias module:zrender/Painter
  8240. * @constructor
  8241. * @param {HTMLElement} root 绘图容器
  8242. * @param {module:zrender/Storage} storage
  8243. * @param {Object} opts
  8244. */
  8245. var Painter = function (root, storage, opts) {
  8246. this.type = 'canvas';
  8247. // In node environment using node-canvas
  8248. var singleCanvas = !root.nodeName // In node ?
  8249. || root.nodeName.toUpperCase() === 'CANVAS';
  8250. this._opts = opts = extend({}, opts || {});
  8251. /**
  8252. * @type {number}
  8253. */
  8254. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8255. /**
  8256. * @type {boolean}
  8257. * @private
  8258. */
  8259. this._singleCanvas = singleCanvas;
  8260. /**
  8261. * 绘图容器
  8262. * @type {HTMLElement}
  8263. */
  8264. this.root = root;
  8265. var rootStyle = root.style;
  8266. if (rootStyle) {
  8267. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8268. rootStyle['-webkit-user-select'] =
  8269. rootStyle['user-select'] =
  8270. rootStyle['-webkit-touch-callout'] = 'none';
  8271. root.innerHTML = '';
  8272. }
  8273. /**
  8274. * @type {module:zrender/Storage}
  8275. */
  8276. this.storage = storage;
  8277. /**
  8278. * @type {Array.<number>}
  8279. * @private
  8280. */
  8281. var zlevelList = this._zlevelList = [];
  8282. /**
  8283. * @type {Object.<string, module:zrender/Layer>}
  8284. * @private
  8285. */
  8286. var layers = this._layers = {};
  8287. /**
  8288. * @type {Object.<string, Object>}
  8289. * @private
  8290. */
  8291. this._layerConfig = {};
  8292. /**
  8293. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8294. */
  8295. this._needsManuallyCompositing = false;
  8296. if (!singleCanvas) {
  8297. this._width = this._getSize(0);
  8298. this._height = this._getSize(1);
  8299. var domRoot = this._domRoot = createRoot(
  8300. this._width, this._height
  8301. );
  8302. root.appendChild(domRoot);
  8303. }
  8304. else {
  8305. var width = root.width;
  8306. var height = root.height;
  8307. if (opts.width != null) {
  8308. width = opts.width;
  8309. }
  8310. if (opts.height != null) {
  8311. height = opts.height;
  8312. }
  8313. this.dpr = opts.devicePixelRatio || 1;
  8314. // Use canvas width and height directly
  8315. root.width = width * this.dpr;
  8316. root.height = height * this.dpr;
  8317. this._width = width;
  8318. this._height = height;
  8319. // Create layer if only one given canvas
  8320. // Device can be specified to create a high dpi image.
  8321. var mainLayer = new Layer(root, this, this.dpr);
  8322. mainLayer.__builtin__ = true;
  8323. mainLayer.initContext();
  8324. // FIXME Use canvas width and height
  8325. // mainLayer.resize(width, height);
  8326. layers[CANVAS_ZLEVEL] = mainLayer;
  8327. mainLayer.zlevel = CANVAS_ZLEVEL;
  8328. // Not use common zlevel.
  8329. zlevelList.push(CANVAS_ZLEVEL);
  8330. this._domRoot = root;
  8331. }
  8332. /**
  8333. * @type {module:zrender/Layer}
  8334. * @private
  8335. */
  8336. this._hoverlayer = null;
  8337. this._hoverElements = [];
  8338. };
  8339. Painter.prototype = {
  8340. constructor: Painter,
  8341. getType: function () {
  8342. return 'canvas';
  8343. },
  8344. /**
  8345. * If painter use a single canvas
  8346. * @return {boolean}
  8347. */
  8348. isSingleCanvas: function () {
  8349. return this._singleCanvas;
  8350. },
  8351. /**
  8352. * @return {HTMLDivElement}
  8353. */
  8354. getViewportRoot: function () {
  8355. return this._domRoot;
  8356. },
  8357. getViewportRootOffset: function () {
  8358. var viewportRoot = this.getViewportRoot();
  8359. if (viewportRoot) {
  8360. return {
  8361. offsetLeft: viewportRoot.offsetLeft || 0,
  8362. offsetTop: viewportRoot.offsetTop || 0
  8363. };
  8364. }
  8365. },
  8366. /**
  8367. * 刷新
  8368. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8369. */
  8370. refresh: function (paintAll) {
  8371. var list = this.storage.getDisplayList(true);
  8372. var zlevelList = this._zlevelList;
  8373. this._redrawId = Math.random();
  8374. this._paintList(list, paintAll, this._redrawId);
  8375. // Paint custum layers
  8376. for (var i = 0; i < zlevelList.length; i++) {
  8377. var z = zlevelList[i];
  8378. var layer = this._layers[z];
  8379. if (!layer.__builtin__ && layer.refresh) {
  8380. var clearColor = i === 0 ? this._backgroundColor : null;
  8381. layer.refresh(clearColor);
  8382. }
  8383. }
  8384. this.refreshHover();
  8385. return this;
  8386. },
  8387. addHover: function (el, hoverStyle) {
  8388. if (el.__hoverMir) {
  8389. return;
  8390. }
  8391. var elMirror = new el.constructor({
  8392. style: el.style,
  8393. shape: el.shape,
  8394. z: el.z,
  8395. z2: el.z2,
  8396. silent: el.silent
  8397. });
  8398. elMirror.__from = el;
  8399. el.__hoverMir = elMirror;
  8400. hoverStyle && elMirror.setStyle(hoverStyle);
  8401. this._hoverElements.push(elMirror);
  8402. return elMirror;
  8403. },
  8404. removeHover: function (el) {
  8405. var elMirror = el.__hoverMir;
  8406. var hoverElements = this._hoverElements;
  8407. var idx = indexOf(hoverElements, elMirror);
  8408. if (idx >= 0) {
  8409. hoverElements.splice(idx, 1);
  8410. }
  8411. el.__hoverMir = null;
  8412. },
  8413. clearHover: function (el) {
  8414. var hoverElements = this._hoverElements;
  8415. for (var i = 0; i < hoverElements.length; i++) {
  8416. var from = hoverElements[i].__from;
  8417. if (from) {
  8418. from.__hoverMir = null;
  8419. }
  8420. }
  8421. hoverElements.length = 0;
  8422. },
  8423. refreshHover: function () {
  8424. var hoverElements = this._hoverElements;
  8425. var len = hoverElements.length;
  8426. var hoverLayer = this._hoverlayer;
  8427. hoverLayer && hoverLayer.clear();
  8428. if (!len) {
  8429. return;
  8430. }
  8431. sort(hoverElements, this.storage.displayableSortFunc);
  8432. // Use a extream large zlevel
  8433. // FIXME?
  8434. if (!hoverLayer) {
  8435. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8436. }
  8437. var scope = {};
  8438. hoverLayer.ctx.save();
  8439. for (var i = 0; i < len;) {
  8440. var el = hoverElements[i];
  8441. var originalEl = el.__from;
  8442. // Original el is removed
  8443. // PENDING
  8444. if (!(originalEl && originalEl.__zr)) {
  8445. hoverElements.splice(i, 1);
  8446. originalEl.__hoverMir = null;
  8447. len--;
  8448. continue;
  8449. }
  8450. i++;
  8451. // Use transform
  8452. // FIXME style and shape ?
  8453. if (!originalEl.invisible) {
  8454. el.transform = originalEl.transform;
  8455. el.invTransform = originalEl.invTransform;
  8456. el.__clipPaths = originalEl.__clipPaths;
  8457. // el.
  8458. this._doPaintEl(el, hoverLayer, true, scope);
  8459. }
  8460. }
  8461. hoverLayer.ctx.restore();
  8462. },
  8463. getHoverLayer: function () {
  8464. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8465. },
  8466. _paintList: function (list, paintAll, redrawId) {
  8467. if (this._redrawId !== redrawId) {
  8468. return;
  8469. }
  8470. paintAll = paintAll || false;
  8471. this._updateLayerStatus(list);
  8472. var finished = this._doPaintList(list, paintAll);
  8473. if (this._needsManuallyCompositing) {
  8474. this._compositeManually();
  8475. }
  8476. if (!finished) {
  8477. var self = this;
  8478. requestAnimationFrame(function () {
  8479. self._paintList(list, paintAll, redrawId);
  8480. });
  8481. }
  8482. },
  8483. _compositeManually: function () {
  8484. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8485. var width = this._domRoot.width;
  8486. var height = this._domRoot.height;
  8487. ctx.clearRect(0, 0, width, height);
  8488. // PENDING, If only builtin layer?
  8489. this.eachBuiltinLayer(function (layer) {
  8490. if (layer.virtual) {
  8491. ctx.drawImage(layer.dom, 0, 0, width, height);
  8492. }
  8493. });
  8494. },
  8495. _doPaintList: function (list, paintAll) {
  8496. var layerList = [];
  8497. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8498. var zlevel = this._zlevelList[zi];
  8499. var layer = this._layers[zlevel];
  8500. if (layer.__builtin__
  8501. && layer !== this._hoverlayer
  8502. && (layer.__dirty || paintAll)
  8503. ) {
  8504. layerList.push(layer);
  8505. }
  8506. }
  8507. var finished = true;
  8508. for (var k = 0; k < layerList.length; k++) {
  8509. var layer = layerList[k];
  8510. var ctx = layer.ctx;
  8511. var scope = {};
  8512. ctx.save();
  8513. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8514. var useTimer = !paintAll && layer.incremental && Date.now;
  8515. var startTime = useTimer && Date.now();
  8516. var clearColor = layer.zlevel === this._zlevelList[0]
  8517. ? this._backgroundColor : null;
  8518. // All elements in this layer are cleared.
  8519. if (layer.__startIndex === layer.__endIndex) {
  8520. layer.clear(false, clearColor);
  8521. }
  8522. else if (start === layer.__startIndex) {
  8523. var firstEl = list[start];
  8524. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8525. layer.clear(false, clearColor);
  8526. }
  8527. }
  8528. if (start === -1) {
  8529. console.error('For some unknown reason. drawIndex is -1');
  8530. start = layer.__startIndex;
  8531. }
  8532. for (var i = start; i < layer.__endIndex; i++) {
  8533. var el = list[i];
  8534. this._doPaintEl(el, layer, paintAll, scope);
  8535. el.__dirty = el.__dirtyText = false;
  8536. if (useTimer) {
  8537. // Date.now can be executed in 13,025,305 ops/second.
  8538. var dTime = Date.now() - startTime;
  8539. // Give 15 millisecond to draw.
  8540. // The rest elements will be drawn in the next frame.
  8541. if (dTime > 15) {
  8542. break;
  8543. }
  8544. }
  8545. }
  8546. layer.__drawIndex = i;
  8547. if (layer.__drawIndex < layer.__endIndex) {
  8548. finished = false;
  8549. }
  8550. if (scope.prevElClipPaths) {
  8551. // Needs restore the state. If last drawn element is in the clipping area.
  8552. ctx.restore();
  8553. }
  8554. ctx.restore();
  8555. }
  8556. if (env$1.wxa) {
  8557. // Flush for weixin application
  8558. each$1(this._layers, function (layer) {
  8559. if (layer && layer.ctx && layer.ctx.draw) {
  8560. layer.ctx.draw();
  8561. }
  8562. });
  8563. }
  8564. return finished;
  8565. },
  8566. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8567. var ctx = currentLayer.ctx;
  8568. var m = el.transform;
  8569. if (
  8570. (currentLayer.__dirty || forcePaint)
  8571. // Ignore invisible element
  8572. && !el.invisible
  8573. // Ignore transparent element
  8574. && el.style.opacity !== 0
  8575. // Ignore scale 0 element, in some environment like node-canvas
  8576. // Draw a scale 0 element can cause all following draw wrong
  8577. // And setTransform with scale 0 will cause set back transform failed.
  8578. && !(m && !m[0] && !m[3])
  8579. // Ignore culled element
  8580. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8581. ) {
  8582. var clipPaths = el.__clipPaths;
  8583. var prevElClipPaths = scope.prevElClipPaths;
  8584. // Optimize when clipping on group with several elements
  8585. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8586. // If has previous clipping state, restore from it
  8587. if (prevElClipPaths) {
  8588. ctx.restore();
  8589. scope.prevElClipPaths = null;
  8590. // Reset prevEl since context has been restored
  8591. scope.prevEl = null;
  8592. }
  8593. // New clipping state
  8594. if (clipPaths) {
  8595. ctx.save();
  8596. doClip(clipPaths, ctx);
  8597. scope.prevElClipPaths = clipPaths;
  8598. }
  8599. }
  8600. el.beforeBrush && el.beforeBrush(ctx);
  8601. el.brush(ctx, scope.prevEl || null);
  8602. scope.prevEl = el;
  8603. el.afterBrush && el.afterBrush(ctx);
  8604. }
  8605. },
  8606. /**
  8607. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8608. * @param {number} zlevel
  8609. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8610. * @return {module:zrender/Layer}
  8611. */
  8612. getLayer: function (zlevel, virtual) {
  8613. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8614. zlevel = CANVAS_ZLEVEL;
  8615. }
  8616. var layer = this._layers[zlevel];
  8617. if (!layer) {
  8618. // Create a new layer
  8619. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8620. layer.zlevel = zlevel;
  8621. layer.__builtin__ = true;
  8622. if (this._layerConfig[zlevel]) {
  8623. merge(layer, this._layerConfig[zlevel], true);
  8624. }
  8625. if (virtual) {
  8626. layer.virtual = virtual;
  8627. }
  8628. this.insertLayer(zlevel, layer);
  8629. // Context is created after dom inserted to document
  8630. // Or excanvas will get 0px clientWidth and clientHeight
  8631. layer.initContext();
  8632. }
  8633. return layer;
  8634. },
  8635. insertLayer: function (zlevel, layer) {
  8636. var layersMap = this._layers;
  8637. var zlevelList = this._zlevelList;
  8638. var len = zlevelList.length;
  8639. var prevLayer = null;
  8640. var i = -1;
  8641. var domRoot = this._domRoot;
  8642. if (layersMap[zlevel]) {
  8643. logError$1('ZLevel ' + zlevel + ' has been used already');
  8644. return;
  8645. }
  8646. // Check if is a valid layer
  8647. if (!isLayerValid(layer)) {
  8648. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8649. return;
  8650. }
  8651. if (len > 0 && zlevel > zlevelList[0]) {
  8652. for (i = 0; i < len - 1; i++) {
  8653. if (
  8654. zlevelList[i] < zlevel
  8655. && zlevelList[i + 1] > zlevel
  8656. ) {
  8657. break;
  8658. }
  8659. }
  8660. prevLayer = layersMap[zlevelList[i]];
  8661. }
  8662. zlevelList.splice(i + 1, 0, zlevel);
  8663. layersMap[zlevel] = layer;
  8664. // Vitual layer will not directly show on the screen.
  8665. // (It can be a WebGL layer and assigned to a ZImage element)
  8666. // But it still under management of zrender.
  8667. if (!layer.virtual) {
  8668. if (prevLayer) {
  8669. var prevDom = prevLayer.dom;
  8670. if (prevDom.nextSibling) {
  8671. domRoot.insertBefore(
  8672. layer.dom,
  8673. prevDom.nextSibling
  8674. );
  8675. }
  8676. else {
  8677. domRoot.appendChild(layer.dom);
  8678. }
  8679. }
  8680. else {
  8681. if (domRoot.firstChild) {
  8682. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8683. }
  8684. else {
  8685. domRoot.appendChild(layer.dom);
  8686. }
  8687. }
  8688. }
  8689. },
  8690. // Iterate each layer
  8691. eachLayer: function (cb, context) {
  8692. var zlevelList = this._zlevelList;
  8693. var z;
  8694. var i;
  8695. for (i = 0; i < zlevelList.length; i++) {
  8696. z = zlevelList[i];
  8697. cb.call(context, this._layers[z], z);
  8698. }
  8699. },
  8700. // Iterate each buildin layer
  8701. eachBuiltinLayer: function (cb, context) {
  8702. var zlevelList = this._zlevelList;
  8703. var layer;
  8704. var z;
  8705. var i;
  8706. for (i = 0; i < zlevelList.length; i++) {
  8707. z = zlevelList[i];
  8708. layer = this._layers[z];
  8709. if (layer.__builtin__) {
  8710. cb.call(context, layer, z);
  8711. }
  8712. }
  8713. },
  8714. // Iterate each other layer except buildin layer
  8715. eachOtherLayer: function (cb, context) {
  8716. var zlevelList = this._zlevelList;
  8717. var layer;
  8718. var z;
  8719. var i;
  8720. for (i = 0; i < zlevelList.length; i++) {
  8721. z = zlevelList[i];
  8722. layer = this._layers[z];
  8723. if (!layer.__builtin__) {
  8724. cb.call(context, layer, z);
  8725. }
  8726. }
  8727. },
  8728. /**
  8729. * 获取所有已创建的层
  8730. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8731. */
  8732. getLayers: function () {
  8733. return this._layers;
  8734. },
  8735. _updateLayerStatus: function (list) {
  8736. this.eachBuiltinLayer(function (layer, z) {
  8737. layer.__dirty = layer.__used = false;
  8738. });
  8739. function updatePrevLayer(idx) {
  8740. if (prevLayer) {
  8741. if (prevLayer.__endIndex !== idx) {
  8742. prevLayer.__dirty = true;
  8743. }
  8744. prevLayer.__endIndex = idx;
  8745. }
  8746. }
  8747. if (this._singleCanvas) {
  8748. for (var i = 1; i < list.length; i++) {
  8749. var el = list[i];
  8750. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8751. this._needsManuallyCompositing = true;
  8752. break;
  8753. }
  8754. }
  8755. }
  8756. var prevLayer = null;
  8757. var incrementalLayerCount = 0;
  8758. for (var i = 0; i < list.length; i++) {
  8759. var el = list[i];
  8760. var zlevel = el.zlevel;
  8761. var layer;
  8762. // PENDING If change one incremental element style ?
  8763. // TODO Where there are non-incremental elements between incremental elements.
  8764. if (el.incremental) {
  8765. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8766. layer.incremental = true;
  8767. incrementalLayerCount = 1;
  8768. }
  8769. else {
  8770. layer = this.getLayer(
  8771. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8772. this._needsManuallyCompositing
  8773. );
  8774. }
  8775. if (!layer.__builtin__) {
  8776. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8777. }
  8778. if (layer !== prevLayer) {
  8779. layer.__used = true;
  8780. if (layer.__startIndex !== i) {
  8781. layer.__dirty = true;
  8782. }
  8783. layer.__startIndex = i;
  8784. if (!layer.incremental) {
  8785. layer.__drawIndex = i;
  8786. }
  8787. else {
  8788. // Mark layer draw index needs to update.
  8789. layer.__drawIndex = -1;
  8790. }
  8791. updatePrevLayer(i);
  8792. prevLayer = layer;
  8793. }
  8794. if (el.__dirty) {
  8795. layer.__dirty = true;
  8796. if (layer.incremental && layer.__drawIndex < 0) {
  8797. // Start draw from the first dirty element.
  8798. layer.__drawIndex = i;
  8799. }
  8800. }
  8801. }
  8802. updatePrevLayer(i);
  8803. this.eachBuiltinLayer(function (layer, z) {
  8804. // Used in last frame but not in this frame. Needs clear
  8805. if (!layer.__used && layer.getElementCount() > 0) {
  8806. layer.__dirty = true;
  8807. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8808. }
  8809. // For incremental layer. In case start index changed and no elements are dirty.
  8810. if (layer.__dirty && layer.__drawIndex < 0) {
  8811. layer.__drawIndex = layer.__startIndex;
  8812. }
  8813. });
  8814. },
  8815. /**
  8816. * 清除hover层外所有内容
  8817. */
  8818. clear: function () {
  8819. this.eachBuiltinLayer(this._clearLayer);
  8820. return this;
  8821. },
  8822. _clearLayer: function (layer) {
  8823. layer.clear();
  8824. },
  8825. setBackgroundColor: function (backgroundColor) {
  8826. this._backgroundColor = backgroundColor;
  8827. },
  8828. /**
  8829. * 修改指定zlevel的绘制参数
  8830. *
  8831. * @param {string} zlevel
  8832. * @param {Object} config 配置对象
  8833. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8834. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8835. * @param {number} [config.lastFrameAlpha=0.7]
  8836. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8837. */
  8838. configLayer: function (zlevel, config) {
  8839. if (config) {
  8840. var layerConfig = this._layerConfig;
  8841. if (!layerConfig[zlevel]) {
  8842. layerConfig[zlevel] = config;
  8843. }
  8844. else {
  8845. merge(layerConfig[zlevel], config, true);
  8846. }
  8847. for (var i = 0; i < this._zlevelList.length; i++) {
  8848. var _zlevel = this._zlevelList[i];
  8849. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8850. var layer = this._layers[_zlevel];
  8851. merge(layer, layerConfig[zlevel], true);
  8852. }
  8853. }
  8854. }
  8855. },
  8856. /**
  8857. * 删除指定层
  8858. * @param {number} zlevel 层所在的zlevel
  8859. */
  8860. delLayer: function (zlevel) {
  8861. var layers = this._layers;
  8862. var zlevelList = this._zlevelList;
  8863. var layer = layers[zlevel];
  8864. if (!layer) {
  8865. return;
  8866. }
  8867. layer.dom.parentNode.removeChild(layer.dom);
  8868. delete layers[zlevel];
  8869. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8870. },
  8871. /**
  8872. * 区域大小变化后重绘
  8873. */
  8874. resize: function (width, height) {
  8875. if (!this._domRoot.style) { // Maybe in node or worker
  8876. if (width == null || height == null) {
  8877. return;
  8878. }
  8879. this._width = width;
  8880. this._height = height;
  8881. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8882. }
  8883. else {
  8884. var domRoot = this._domRoot;
  8885. // FIXME Why ?
  8886. domRoot.style.display = 'none';
  8887. // Save input w/h
  8888. var opts = this._opts;
  8889. width != null && (opts.width = width);
  8890. height != null && (opts.height = height);
  8891. width = this._getSize(0);
  8892. height = this._getSize(1);
  8893. domRoot.style.display = '';
  8894. // 优化没有实际改变的resize
  8895. if (this._width !== width || height !== this._height) {
  8896. domRoot.style.width = width + 'px';
  8897. domRoot.style.height = height + 'px';
  8898. for (var id in this._layers) {
  8899. if (this._layers.hasOwnProperty(id)) {
  8900. this._layers[id].resize(width, height);
  8901. }
  8902. }
  8903. each$1(this._progressiveLayers, function (layer) {
  8904. layer.resize(width, height);
  8905. });
  8906. this.refresh(true);
  8907. }
  8908. this._width = width;
  8909. this._height = height;
  8910. }
  8911. return this;
  8912. },
  8913. /**
  8914. * 清除单独的一个层
  8915. * @param {number} zlevel
  8916. */
  8917. clearLayer: function (zlevel) {
  8918. var layer = this._layers[zlevel];
  8919. if (layer) {
  8920. layer.clear();
  8921. }
  8922. },
  8923. /**
  8924. * 释放
  8925. */
  8926. dispose: function () {
  8927. this.root.innerHTML = '';
  8928. this.root =
  8929. this.storage =
  8930. this._domRoot =
  8931. this._layers = null;
  8932. },
  8933. /**
  8934. * Get canvas which has all thing rendered
  8935. * @param {Object} opts
  8936. * @param {string} [opts.backgroundColor]
  8937. * @param {number} [opts.pixelRatio]
  8938. */
  8939. getRenderedCanvas: function (opts) {
  8940. opts = opts || {};
  8941. if (this._singleCanvas && !this._compositeManually) {
  8942. return this._layers[CANVAS_ZLEVEL].dom;
  8943. }
  8944. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8945. imageLayer.initContext();
  8946. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8947. if (opts.pixelRatio <= this.dpr) {
  8948. this.refresh();
  8949. var width = imageLayer.dom.width;
  8950. var height = imageLayer.dom.height;
  8951. var ctx = imageLayer.ctx;
  8952. this.eachLayer(function (layer) {
  8953. if (layer.__builtin__) {
  8954. ctx.drawImage(layer.dom, 0, 0, width, height);
  8955. }
  8956. else if (layer.renderToCanvas) {
  8957. imageLayer.ctx.save();
  8958. layer.renderToCanvas(imageLayer.ctx);
  8959. imageLayer.ctx.restore();
  8960. }
  8961. });
  8962. }
  8963. else {
  8964. // PENDING, echarts-gl and incremental rendering.
  8965. var scope = {};
  8966. var displayList = this.storage.getDisplayList(true);
  8967. for (var i = 0; i < displayList.length; i++) {
  8968. var el = displayList[i];
  8969. this._doPaintEl(el, imageLayer, true, scope);
  8970. }
  8971. }
  8972. return imageLayer.dom;
  8973. },
  8974. /**
  8975. * 获取绘图区域宽度
  8976. */
  8977. getWidth: function () {
  8978. return this._width;
  8979. },
  8980. /**
  8981. * 获取绘图区域高度
  8982. */
  8983. getHeight: function () {
  8984. return this._height;
  8985. },
  8986. _getSize: function (whIdx) {
  8987. var opts = this._opts;
  8988. var wh = ['width', 'height'][whIdx];
  8989. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8990. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8991. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8992. if (opts[wh] != null && opts[wh] !== 'auto') {
  8993. return parseFloat(opts[wh]);
  8994. }
  8995. var root = this.root;
  8996. // IE8 does not support getComputedStyle, but it use VML.
  8997. var stl = document.defaultView.getComputedStyle(root);
  8998. return (
  8999. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9000. - (parseInt10(stl[plt]) || 0)
  9001. - (parseInt10(stl[prb]) || 0)
  9002. ) | 0;
  9003. },
  9004. pathToImage: function (path, dpr) {
  9005. dpr = dpr || this.dpr;
  9006. var canvas = document.createElement('canvas');
  9007. var ctx = canvas.getContext('2d');
  9008. var rect = path.getBoundingRect();
  9009. var style = path.style;
  9010. var shadowBlurSize = style.shadowBlur * dpr;
  9011. var shadowOffsetX = style.shadowOffsetX * dpr;
  9012. var shadowOffsetY = style.shadowOffsetY * dpr;
  9013. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9014. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9015. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9016. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9017. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9018. var width = rect.width + leftMargin + rightMargin;
  9019. var height = rect.height + topMargin + bottomMargin;
  9020. canvas.width = width * dpr;
  9021. canvas.height = height * dpr;
  9022. ctx.scale(dpr, dpr);
  9023. ctx.clearRect(0, 0, width, height);
  9024. ctx.dpr = dpr;
  9025. var pathTransform = {
  9026. position: path.position,
  9027. rotation: path.rotation,
  9028. scale: path.scale
  9029. };
  9030. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9031. path.rotation = 0;
  9032. path.scale = [1, 1];
  9033. path.updateTransform();
  9034. if (path) {
  9035. path.brush(ctx);
  9036. }
  9037. var ImageShape = ZImage;
  9038. var imgShape = new ImageShape({
  9039. style: {
  9040. x: 0,
  9041. y: 0,
  9042. image: canvas
  9043. }
  9044. });
  9045. if (pathTransform.position != null) {
  9046. imgShape.position = path.position = pathTransform.position;
  9047. }
  9048. if (pathTransform.rotation != null) {
  9049. imgShape.rotation = path.rotation = pathTransform.rotation;
  9050. }
  9051. if (pathTransform.scale != null) {
  9052. imgShape.scale = path.scale = pathTransform.scale;
  9053. }
  9054. return imgShape;
  9055. }
  9056. };
  9057. /**
  9058. * Animation main class, dispatch and manage all animation controllers
  9059. *
  9060. * @module zrender/animation/Animation
  9061. * @author pissang(https://github.com/pissang)
  9062. */
  9063. // TODO Additive animation
  9064. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9065. // https://developer.apple.com/videos/wwdc2014/#236
  9066. /**
  9067. * @typedef {Object} IZRenderStage
  9068. * @property {Function} update
  9069. */
  9070. /**
  9071. * @alias module:zrender/animation/Animation
  9072. * @constructor
  9073. * @param {Object} [options]
  9074. * @param {Function} [options.onframe]
  9075. * @param {IZRenderStage} [options.stage]
  9076. * @example
  9077. * var animation = new Animation();
  9078. * var obj = {
  9079. * x: 100,
  9080. * y: 100
  9081. * };
  9082. * animation.animate(node.position)
  9083. * .when(1000, {
  9084. * x: 500,
  9085. * y: 500
  9086. * })
  9087. * .when(2000, {
  9088. * x: 100,
  9089. * y: 100
  9090. * })
  9091. * .start('spline');
  9092. */
  9093. var Animation = function (options) {
  9094. options = options || {};
  9095. this.stage = options.stage || {};
  9096. this.onframe = options.onframe || function () {};
  9097. // private properties
  9098. this._clips = [];
  9099. this._running = false;
  9100. this._time;
  9101. this._pausedTime;
  9102. this._pauseStart;
  9103. this._paused = false;
  9104. Eventful.call(this);
  9105. };
  9106. Animation.prototype = {
  9107. constructor: Animation,
  9108. /**
  9109. * Add clip
  9110. * @param {module:zrender/animation/Clip} clip
  9111. */
  9112. addClip: function (clip) {
  9113. this._clips.push(clip);
  9114. },
  9115. /**
  9116. * Add animator
  9117. * @param {module:zrender/animation/Animator} animator
  9118. */
  9119. addAnimator: function (animator) {
  9120. animator.animation = this;
  9121. var clips = animator.getClips();
  9122. for (var i = 0; i < clips.length; i++) {
  9123. this.addClip(clips[i]);
  9124. }
  9125. },
  9126. /**
  9127. * Delete animation clip
  9128. * @param {module:zrender/animation/Clip} clip
  9129. */
  9130. removeClip: function (clip) {
  9131. var idx = indexOf(this._clips, clip);
  9132. if (idx >= 0) {
  9133. this._clips.splice(idx, 1);
  9134. }
  9135. },
  9136. /**
  9137. * Delete animation clip
  9138. * @param {module:zrender/animation/Animator} animator
  9139. */
  9140. removeAnimator: function (animator) {
  9141. var clips = animator.getClips();
  9142. for (var i = 0; i < clips.length; i++) {
  9143. this.removeClip(clips[i]);
  9144. }
  9145. animator.animation = null;
  9146. },
  9147. _update: function () {
  9148. var time = new Date().getTime() - this._pausedTime;
  9149. var delta = time - this._time;
  9150. var clips = this._clips;
  9151. var len = clips.length;
  9152. var deferredEvents = [];
  9153. var deferredClips = [];
  9154. for (var i = 0; i < len; i++) {
  9155. var clip = clips[i];
  9156. var e = clip.step(time, delta);
  9157. // Throw out the events need to be called after
  9158. // stage.update, like destroy
  9159. if (e) {
  9160. deferredEvents.push(e);
  9161. deferredClips.push(clip);
  9162. }
  9163. }
  9164. // Remove the finished clip
  9165. for (var i = 0; i < len;) {
  9166. if (clips[i]._needsRemove) {
  9167. clips[i] = clips[len - 1];
  9168. clips.pop();
  9169. len--;
  9170. }
  9171. else {
  9172. i++;
  9173. }
  9174. }
  9175. len = deferredEvents.length;
  9176. for (var i = 0; i < len; i++) {
  9177. deferredClips[i].fire(deferredEvents[i]);
  9178. }
  9179. this._time = time;
  9180. this.onframe(delta);
  9181. // 'frame' should be triggered before stage, because upper application
  9182. // depends on the sequence (e.g., echarts-stream and finish
  9183. // event judge)
  9184. this.trigger('frame', delta);
  9185. if (this.stage.update) {
  9186. this.stage.update();
  9187. }
  9188. },
  9189. _startLoop: function () {
  9190. var self = this;
  9191. this._running = true;
  9192. function step() {
  9193. if (self._running) {
  9194. requestAnimationFrame(step);
  9195. !self._paused && self._update();
  9196. }
  9197. }
  9198. requestAnimationFrame(step);
  9199. },
  9200. /**
  9201. * Start animation.
  9202. */
  9203. start: function () {
  9204. this._time = new Date().getTime();
  9205. this._pausedTime = 0;
  9206. this._startLoop();
  9207. },
  9208. /**
  9209. * Stop animation.
  9210. */
  9211. stop: function () {
  9212. this._running = false;
  9213. },
  9214. /**
  9215. * Pause animation.
  9216. */
  9217. pause: function () {
  9218. if (!this._paused) {
  9219. this._pauseStart = new Date().getTime();
  9220. this._paused = true;
  9221. }
  9222. },
  9223. /**
  9224. * Resume animation.
  9225. */
  9226. resume: function () {
  9227. if (this._paused) {
  9228. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9229. this._paused = false;
  9230. }
  9231. },
  9232. /**
  9233. * Clear animation.
  9234. */
  9235. clear: function () {
  9236. this._clips = [];
  9237. },
  9238. /**
  9239. * Whether animation finished.
  9240. */
  9241. isFinished: function () {
  9242. return !this._clips.length;
  9243. },
  9244. /**
  9245. * Creat animator for a target, whose props can be animated.
  9246. *
  9247. * @param {Object} target
  9248. * @param {Object} options
  9249. * @param {boolean} [options.loop=false] Whether loop animation.
  9250. * @param {Function} [options.getter=null] Get value from target.
  9251. * @param {Function} [options.setter=null] Set value to target.
  9252. * @return {module:zrender/animation/Animation~Animator}
  9253. */
  9254. // TODO Gap
  9255. animate: function (target, options) {
  9256. options = options || {};
  9257. var animator = new Animator(
  9258. target,
  9259. options.loop,
  9260. options.getter,
  9261. options.setter
  9262. );
  9263. this.addAnimator(animator);
  9264. return animator;
  9265. }
  9266. };
  9267. mixin(Animation, Eventful);
  9268. /* global document */
  9269. var TOUCH_CLICK_DELAY = 300;
  9270. var globalEventSupported = env$1.domSupported;
  9271. var localNativeListenerNames = (function () {
  9272. var mouseHandlerNames = [
  9273. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9274. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9275. ];
  9276. var touchHandlerNames = [
  9277. 'touchstart', 'touchend', 'touchmove'
  9278. ];
  9279. var pointerEventNameMap = {
  9280. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9281. };
  9282. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9283. var nm = name.replace('mouse', 'pointer');
  9284. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9285. });
  9286. return {
  9287. mouse: mouseHandlerNames,
  9288. touch: touchHandlerNames,
  9289. pointer: pointerHandlerNames
  9290. };
  9291. })();
  9292. var globalNativeListenerNames = {
  9293. mouse: ['mousemove', 'mouseup'],
  9294. pointer: ['pointermove', 'pointerup']
  9295. };
  9296. function eventNameFix(name) {
  9297. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9298. }
  9299. function isPointerFromTouch(event) {
  9300. var pointerType = event.pointerType;
  9301. return pointerType === 'pen' || pointerType === 'touch';
  9302. }
  9303. // function useMSGuesture(handlerProxy, event) {
  9304. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9305. // }
  9306. // function onMSGestureChange(proxy, event) {
  9307. // if (event.translationX || event.translationY) {
  9308. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9309. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9310. // }
  9311. // if (event.scale !== 1) {
  9312. // event.pinchX = event.offsetX;
  9313. // event.pinchY = event.offsetY;
  9314. // event.pinchScale = event.scale;
  9315. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9316. // }
  9317. // }
  9318. /**
  9319. * Prevent mouse event from being dispatched after Touch Events action
  9320. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9321. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9322. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9323. * Result: Blocking Mouse Events for 700ms.
  9324. *
  9325. * @param {DOMHandlerScope} scope
  9326. */
  9327. function setTouchTimer(scope) {
  9328. scope.touching = true;
  9329. if (scope.touchTimer != null) {
  9330. clearTimeout(scope.touchTimer);
  9331. scope.touchTimer = null;
  9332. }
  9333. scope.touchTimer = setTimeout(function () {
  9334. scope.touching = false;
  9335. scope.touchTimer = null;
  9336. }, 700);
  9337. }
  9338. // Mark touch, which is useful in distinguish touch and
  9339. // mouse event in upper applicatoin.
  9340. function markTouch(event) {
  9341. event && (event.zrByTouch = true);
  9342. }
  9343. // function markTriggeredFromLocal(event) {
  9344. // event && (event.__zrIsFromLocal = true);
  9345. // }
  9346. // function isTriggeredFromLocal(instance, event) {
  9347. // return !!(event && event.__zrIsFromLocal);
  9348. // }
  9349. function normalizeGlobalEvent(instance, event) {
  9350. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9351. // handlers of the upper applications. Set `true` to force calculate them.
  9352. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9353. }
  9354. /**
  9355. * Detect whether the given el is in `painterRoot`.
  9356. */
  9357. function isLocalEl(instance, el) {
  9358. var elTmp = el;
  9359. var isLocal = false;
  9360. while (elTmp && elTmp.nodeType !== 9
  9361. && !(
  9362. isLocal = elTmp.domBelongToZr
  9363. || (elTmp !== el && elTmp === instance.painterRoot)
  9364. )
  9365. ) {
  9366. elTmp = elTmp.parentNode;
  9367. }
  9368. return isLocal;
  9369. }
  9370. /**
  9371. * Make a fake event but not change the original event,
  9372. * becuase the global event probably be used by other
  9373. * listeners not belonging to zrender.
  9374. * @class
  9375. */
  9376. function FakeGlobalEvent(instance, event) {
  9377. this.type = event.type;
  9378. this.target = this.currentTarget = instance.dom;
  9379. this.pointerType = event.pointerType;
  9380. // Necessray for the force calculation of zrX, zrY
  9381. this.clientX = event.clientX;
  9382. this.clientY = event.clientY;
  9383. // Because we do not mount global listeners to touch events,
  9384. // we do not copy `targetTouches` and `changedTouches` here.
  9385. }
  9386. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9387. // we make the default methods on the event do nothing,
  9388. // otherwise it is dangerous. See more details in
  9389. // [Drag outside] in `Handler.js`.
  9390. fakeGlobalEventProto.stopPropagation =
  9391. fakeGlobalEventProto.stopImmediatePropagation =
  9392. fakeGlobalEventProto.preventDefault = noop;
  9393. /**
  9394. * Local DOM Handlers
  9395. * @this {HandlerProxy}
  9396. */
  9397. var localDOMHandlers = {
  9398. mousedown: function (event) {
  9399. event = normalizeEvent(this.dom, event);
  9400. this._mayPointerCapture = [event.zrX, event.zrY];
  9401. this.trigger('mousedown', event);
  9402. },
  9403. mousemove: function (event) {
  9404. event = normalizeEvent(this.dom, event);
  9405. var downPoint = this._mayPointerCapture;
  9406. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9407. togglePointerCapture(this, true);
  9408. }
  9409. this.trigger('mousemove', event);
  9410. },
  9411. mouseup: function (event) {
  9412. event = normalizeEvent(this.dom, event);
  9413. togglePointerCapture(this, false);
  9414. this.trigger('mouseup', event);
  9415. },
  9416. mouseout: function (event) {
  9417. event = normalizeEvent(this.dom, event);
  9418. // Similarly to the browser did on `document` and touch event,
  9419. // `globalout` will be delayed to final pointer cature release.
  9420. if (this._pointerCapturing) {
  9421. event.zrEventControl = 'no_globalout';
  9422. }
  9423. // There might be some doms created by upper layer application
  9424. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9425. // dom created by echarts), where 'globalout' event should not
  9426. // be triggered when mouse enters these doms. (But 'mouseout'
  9427. // should be triggered at the original hovered element as usual).
  9428. var element = event.toElement || event.relatedTarget;
  9429. event.zrIsToLocalDOM = isLocalEl(this, element);
  9430. this.trigger('mouseout', event);
  9431. },
  9432. touchstart: function (event) {
  9433. // Default mouse behaviour should not be disabled here.
  9434. // For example, page may needs to be slided.
  9435. event = normalizeEvent(this.dom, event);
  9436. markTouch(event);
  9437. this._lastTouchMoment = new Date();
  9438. this.handler.processGesture(event, 'start');
  9439. // For consistent event listener for both touch device and mouse device,
  9440. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9441. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9442. // `mousedown`.
  9443. localDOMHandlers.mousemove.call(this, event);
  9444. localDOMHandlers.mousedown.call(this, event);
  9445. },
  9446. touchmove: function (event) {
  9447. event = normalizeEvent(this.dom, event);
  9448. markTouch(event);
  9449. this.handler.processGesture(event, 'change');
  9450. // Mouse move should always be triggered no matter whether
  9451. // there is gestrue event, because mouse move and pinch may
  9452. // be used at the same time.
  9453. localDOMHandlers.mousemove.call(this, event);
  9454. },
  9455. touchend: function (event) {
  9456. event = normalizeEvent(this.dom, event);
  9457. markTouch(event);
  9458. this.handler.processGesture(event, 'end');
  9459. localDOMHandlers.mouseup.call(this, event);
  9460. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9461. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9462. // we can conveniently implement "hover style" in both PC and touch device just
  9463. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9464. // to remove "hover style" on an element, without any additional code for
  9465. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9466. // style" will remain for user view)
  9467. // click event should always be triggered no matter whether
  9468. // there is gestrue event. System click can not be prevented.
  9469. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9470. localDOMHandlers.click.call(this, event);
  9471. }
  9472. },
  9473. pointerdown: function (event) {
  9474. localDOMHandlers.mousedown.call(this, event);
  9475. // if (useMSGuesture(this, event)) {
  9476. // this._msGesture.addPointer(event.pointerId);
  9477. // }
  9478. },
  9479. pointermove: function (event) {
  9480. // FIXME
  9481. // pointermove is so sensitive that it always triggered when
  9482. // tap(click) on touch screen, which affect some judgement in
  9483. // upper application. So, we dont support mousemove on MS touch
  9484. // device yet.
  9485. if (!isPointerFromTouch(event)) {
  9486. localDOMHandlers.mousemove.call(this, event);
  9487. }
  9488. },
  9489. pointerup: function (event) {
  9490. localDOMHandlers.mouseup.call(this, event);
  9491. },
  9492. pointerout: function (event) {
  9493. // pointerout will be triggered when tap on touch screen
  9494. // (IE11+/Edge on MS Surface) after click event triggered,
  9495. // which is inconsistent with the mousout behavior we defined
  9496. // in touchend. So we unify them.
  9497. // (check localDOMHandlers.touchend for detailed explanation)
  9498. if (!isPointerFromTouch(event)) {
  9499. localDOMHandlers.mouseout.call(this, event);
  9500. }
  9501. }
  9502. };
  9503. /**
  9504. * Othere DOM UI Event handlers for zr dom.
  9505. * @this {HandlerProxy}
  9506. */
  9507. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9508. localDOMHandlers[name] = function (event) {
  9509. event = normalizeEvent(this.dom, event);
  9510. this.trigger(name, event);
  9511. };
  9512. });
  9513. /**
  9514. * DOM UI Event handlers for global page.
  9515. *
  9516. * [Caution]:
  9517. * those handlers should both support in capture phase and bubble phase!
  9518. *
  9519. * @this {HandlerProxy}
  9520. */
  9521. var globalDOMHandlers = {
  9522. pointermove: function (event) {
  9523. // FIXME
  9524. // pointermove is so sensitive that it always triggered when
  9525. // tap(click) on touch screen, which affect some judgement in
  9526. // upper application. So, we dont support mousemove on MS touch
  9527. // device yet.
  9528. if (!isPointerFromTouch(event)) {
  9529. globalDOMHandlers.mousemove.call(this, event);
  9530. }
  9531. },
  9532. pointerup: function (event) {
  9533. globalDOMHandlers.mouseup.call(this, event);
  9534. },
  9535. mousemove: function (event) {
  9536. this.trigger('mousemove', event);
  9537. },
  9538. mouseup: function (event) {
  9539. var pointerCaptureReleasing = this._pointerCapturing;
  9540. togglePointerCapture(this, false);
  9541. this.trigger('mouseup', event);
  9542. if (pointerCaptureReleasing) {
  9543. event.zrEventControl = 'only_globalout';
  9544. this.trigger('mouseout', event);
  9545. }
  9546. }
  9547. };
  9548. /**
  9549. * @param {HandlerProxy} instance
  9550. * @param {DOMHandlerScope} scope
  9551. */
  9552. function mountLocalDOMEventListeners(instance, scope) {
  9553. var domHandlers = scope.domHandlers;
  9554. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9555. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9556. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9557. // at the same time.
  9558. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9559. // screen, which do not occurs in pointer event.
  9560. // So we use pointer event to both detect touch gesture and mouse behavior.
  9561. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9562. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9563. // markTriggeredFromLocal(event);
  9564. domHandlers[nativeEventName].call(instance, event);
  9565. });
  9566. });
  9567. // FIXME
  9568. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9569. // which does not prevent defuault behavior occasionally (which may cause view port
  9570. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9571. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9572. // touch screen. And we only support click behavior on MS touch screen now.
  9573. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9574. // We dont support touch on IE on win7.
  9575. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9576. // if (typeof MSGesture === 'function') {
  9577. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9578. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9579. // }
  9580. }
  9581. else {
  9582. if (env$1.touchEventsSupported) {
  9583. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9584. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9585. // markTriggeredFromLocal(event);
  9586. domHandlers[nativeEventName].call(instance, event);
  9587. setTouchTimer(scope);
  9588. });
  9589. });
  9590. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9591. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9592. }
  9593. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9594. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9595. // mouse event can not be handle in those devices.
  9596. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9597. // mouseevent after touch event triggered, see `setTouchTimer`.
  9598. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9599. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9600. event = getNativeEvent(event);
  9601. if (!scope.touching) {
  9602. // markTriggeredFromLocal(event);
  9603. domHandlers[nativeEventName].call(instance, event);
  9604. }
  9605. });
  9606. });
  9607. }
  9608. }
  9609. /**
  9610. * @param {HandlerProxy} instance
  9611. * @param {DOMHandlerScope} scope
  9612. */
  9613. function mountGlobalDOMEventListeners(instance, scope) {
  9614. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9615. if (env$1.pointerEventsSupported) {
  9616. each$1(globalNativeListenerNames.pointer, mount);
  9617. }
  9618. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9619. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9620. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9621. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9622. else if (!env$1.touchEventsSupported) {
  9623. each$1(globalNativeListenerNames.mouse, mount);
  9624. }
  9625. function mount(nativeEventName) {
  9626. function nativeEventListener(event) {
  9627. event = getNativeEvent(event);
  9628. // See the reason in [Drag outside] in `Handler.js`
  9629. // This checking supports both `useCapture` or not.
  9630. // PENDING: if there is performance issue in some devices,
  9631. // we probably can not use `useCapture` and change a easier
  9632. // to judes whether local (mark).
  9633. if (!isLocalEl(instance, event.target)) {
  9634. event = normalizeGlobalEvent(instance, event);
  9635. scope.domHandlers[nativeEventName].call(instance, event);
  9636. }
  9637. }
  9638. mountSingleDOMEventListener(
  9639. scope, nativeEventName, nativeEventListener,
  9640. {capture: true} // See [Drag Outside] in `Handler.js`
  9641. );
  9642. }
  9643. }
  9644. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9645. scope.mounted[nativeEventName] = listener;
  9646. scope.listenerOpts[nativeEventName] = opt;
  9647. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9648. }
  9649. function unmountDOMEventListeners(scope) {
  9650. var mounted = scope.mounted;
  9651. for (var nativeEventName in mounted) {
  9652. if (mounted.hasOwnProperty(nativeEventName)) {
  9653. removeEventListener(
  9654. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9655. scope.listenerOpts[nativeEventName]
  9656. );
  9657. }
  9658. }
  9659. scope.mounted = {};
  9660. }
  9661. /**
  9662. * See [Drag Outside] in `Handler.js`.
  9663. * @implement
  9664. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9665. * `true`: start to capture pointer if it is not capturing.
  9666. * `false`: end the capture if it is capturing.
  9667. */
  9668. function togglePointerCapture(instance, isPointerCapturing) {
  9669. instance._mayPointerCapture = null;
  9670. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9671. instance._pointerCapturing = isPointerCapturing;
  9672. var globalHandlerScope = instance._globalHandlerScope;
  9673. isPointerCapturing
  9674. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9675. : unmountDOMEventListeners(globalHandlerScope);
  9676. }
  9677. }
  9678. /**
  9679. * @inner
  9680. * @class
  9681. */
  9682. function DOMHandlerScope(domTarget, domHandlers) {
  9683. this.domTarget = domTarget;
  9684. this.domHandlers = domHandlers;
  9685. // Key: eventName, value: mounted handler funcitons.
  9686. // Used for unmount.
  9687. this.mounted = {};
  9688. this.listenerOpts = {};
  9689. this.touchTimer = null;
  9690. this.touching = false;
  9691. }
  9692. /**
  9693. * @public
  9694. * @class
  9695. */
  9696. function HandlerDomProxy(dom, painterRoot) {
  9697. Eventful.call(this);
  9698. this.dom = dom;
  9699. this.painterRoot = painterRoot;
  9700. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9701. if (globalEventSupported) {
  9702. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9703. }
  9704. /**
  9705. * @type {boolean}
  9706. */
  9707. this._pointerCapturing = false;
  9708. /**
  9709. * @type {Array.<number>} [x, y] or null.
  9710. */
  9711. this._mayPointerCapture = null;
  9712. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9713. }
  9714. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9715. handlerDomProxyProto.dispose = function () {
  9716. unmountDOMEventListeners(this._localHandlerScope);
  9717. if (globalEventSupported) {
  9718. unmountDOMEventListeners(this._globalHandlerScope);
  9719. }
  9720. };
  9721. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9722. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9723. };
  9724. mixin(HandlerDomProxy, Eventful);
  9725. /*!
  9726. * ZRender, a high performance 2d drawing library.
  9727. *
  9728. * Copyright (c) 2013, Baidu Inc.
  9729. * All rights reserved.
  9730. *
  9731. * LICENSE
  9732. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9733. */
  9734. var useVML = !env$1.canvasSupported;
  9735. var painterCtors = {
  9736. canvas: Painter
  9737. };
  9738. /**
  9739. * @type {string}
  9740. */
  9741. var version$1 = '4.3.0';
  9742. /**
  9743. * Initializing a zrender instance
  9744. * @param {HTMLElement} dom
  9745. * @param {Object} [opts]
  9746. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9747. * @param {number} [opts.devicePixelRatio]
  9748. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9749. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9750. * @return {module:zrender/ZRender}
  9751. */
  9752. function init$1(dom, opts) {
  9753. var zr = new ZRender(guid(), dom, opts);
  9754. return zr;
  9755. }
  9756. /**
  9757. * Dispose zrender instance
  9758. * @param {module:zrender/ZRender} zr
  9759. */
  9760. /**
  9761. * Get zrender instance by id
  9762. * @param {string} id zrender instance id
  9763. * @return {module:zrender/ZRender}
  9764. */
  9765. /**
  9766. * @module zrender/ZRender
  9767. */
  9768. /**
  9769. * @constructor
  9770. * @alias module:zrender/ZRender
  9771. * @param {string} id
  9772. * @param {HTMLElement} dom
  9773. * @param {Object} opts
  9774. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9775. * @param {number} [opts.devicePixelRatio]
  9776. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9777. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9778. */
  9779. var ZRender = function (id, dom, opts) {
  9780. opts = opts || {};
  9781. /**
  9782. * @type {HTMLDomElement}
  9783. */
  9784. this.dom = dom;
  9785. /**
  9786. * @type {string}
  9787. */
  9788. this.id = id;
  9789. var self = this;
  9790. var storage = new Storage();
  9791. var rendererType = opts.renderer;
  9792. // TODO WebGL
  9793. if (useVML) {
  9794. if (!painterCtors.vml) {
  9795. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9796. }
  9797. rendererType = 'vml';
  9798. }
  9799. else if (!rendererType || !painterCtors[rendererType]) {
  9800. rendererType = 'canvas';
  9801. }
  9802. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9803. this.storage = storage;
  9804. this.painter = painter;
  9805. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  9806. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9807. /**
  9808. * @type {module:zrender/animation/Animation}
  9809. */
  9810. this.animation = new Animation({
  9811. stage: {
  9812. update: bind(this.flush, this)
  9813. }
  9814. });
  9815. this.animation.start();
  9816. /**
  9817. * @type {boolean}
  9818. * @private
  9819. */
  9820. this._needsRefresh;
  9821. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9822. // FIXME 有点ugly
  9823. var oldDelFromStorage = storage.delFromStorage;
  9824. var oldAddToStorage = storage.addToStorage;
  9825. storage.delFromStorage = function (el) {
  9826. oldDelFromStorage.call(storage, el);
  9827. el && el.removeSelfFromZr(self);
  9828. };
  9829. storage.addToStorage = function (el) {
  9830. oldAddToStorage.call(storage, el);
  9831. el.addSelfToZr(self);
  9832. };
  9833. };
  9834. ZRender.prototype = {
  9835. constructor: ZRender,
  9836. /**
  9837. * 获取实例唯一标识
  9838. * @return {string}
  9839. */
  9840. getId: function () {
  9841. return this.id;
  9842. },
  9843. /**
  9844. * 添加元素
  9845. * @param {module:zrender/Element} el
  9846. */
  9847. add: function (el) {
  9848. this.storage.addRoot(el);
  9849. this._needsRefresh = true;
  9850. },
  9851. /**
  9852. * 删除元素
  9853. * @param {module:zrender/Element} el
  9854. */
  9855. remove: function (el) {
  9856. this.storage.delRoot(el);
  9857. this._needsRefresh = true;
  9858. },
  9859. /**
  9860. * Change configuration of layer
  9861. * @param {string} zLevel
  9862. * @param {Object} config
  9863. * @param {string} [config.clearColor=0] Clear color
  9864. * @param {string} [config.motionBlur=false] If enable motion blur
  9865. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9866. */
  9867. configLayer: function (zLevel, config) {
  9868. if (this.painter.configLayer) {
  9869. this.painter.configLayer(zLevel, config);
  9870. }
  9871. this._needsRefresh = true;
  9872. },
  9873. /**
  9874. * Set background color
  9875. * @param {string} backgroundColor
  9876. */
  9877. setBackgroundColor: function (backgroundColor) {
  9878. if (this.painter.setBackgroundColor) {
  9879. this.painter.setBackgroundColor(backgroundColor);
  9880. }
  9881. this._needsRefresh = true;
  9882. },
  9883. /**
  9884. * Repaint the canvas immediately
  9885. */
  9886. refreshImmediately: function () {
  9887. // var start = new Date();
  9888. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9889. // Or it will cause zrender refreshes again and again.
  9890. this._needsRefresh = this._needsRefreshHover = false;
  9891. this.painter.refresh();
  9892. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  9893. this._needsRefresh = this._needsRefreshHover = false;
  9894. // var end = new Date();
  9895. // var log = document.getElementById('log');
  9896. // if (log) {
  9897. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9898. // }
  9899. },
  9900. /**
  9901. * Mark and repaint the canvas in the next frame of browser
  9902. */
  9903. refresh: function () {
  9904. this._needsRefresh = true;
  9905. },
  9906. /**
  9907. * Perform all refresh
  9908. */
  9909. flush: function () {
  9910. var triggerRendered;
  9911. if (this._needsRefresh) {
  9912. triggerRendered = true;
  9913. this.refreshImmediately();
  9914. }
  9915. if (this._needsRefreshHover) {
  9916. triggerRendered = true;
  9917. this.refreshHoverImmediately();
  9918. }
  9919. triggerRendered && this.trigger('rendered');
  9920. },
  9921. /**
  9922. * Add element to hover layer
  9923. * @param {module:zrender/Element} el
  9924. * @param {Object} style
  9925. */
  9926. addHover: function (el, style) {
  9927. if (this.painter.addHover) {
  9928. var elMirror = this.painter.addHover(el, style);
  9929. this.refreshHover();
  9930. return elMirror;
  9931. }
  9932. },
  9933. /**
  9934. * Add element from hover layer
  9935. * @param {module:zrender/Element} el
  9936. */
  9937. removeHover: function (el) {
  9938. if (this.painter.removeHover) {
  9939. this.painter.removeHover(el);
  9940. this.refreshHover();
  9941. }
  9942. },
  9943. /**
  9944. * Clear all hover elements in hover layer
  9945. * @param {module:zrender/Element} el
  9946. */
  9947. clearHover: function () {
  9948. if (this.painter.clearHover) {
  9949. this.painter.clearHover();
  9950. this.refreshHover();
  9951. }
  9952. },
  9953. /**
  9954. * Refresh hover in next frame
  9955. */
  9956. refreshHover: function () {
  9957. this._needsRefreshHover = true;
  9958. },
  9959. /**
  9960. * Refresh hover immediately
  9961. */
  9962. refreshHoverImmediately: function () {
  9963. this._needsRefreshHover = false;
  9964. this.painter.refreshHover && this.painter.refreshHover();
  9965. },
  9966. /**
  9967. * Resize the canvas.
  9968. * Should be invoked when container size is changed
  9969. * @param {Object} [opts]
  9970. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9971. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9972. */
  9973. resize: function (opts) {
  9974. opts = opts || {};
  9975. this.painter.resize(opts.width, opts.height);
  9976. this.handler.resize();
  9977. },
  9978. /**
  9979. * Stop and clear all animation immediately
  9980. */
  9981. clearAnimation: function () {
  9982. this.animation.clear();
  9983. },
  9984. /**
  9985. * Get container width
  9986. */
  9987. getWidth: function () {
  9988. return this.painter.getWidth();
  9989. },
  9990. /**
  9991. * Get container height
  9992. */
  9993. getHeight: function () {
  9994. return this.painter.getHeight();
  9995. },
  9996. /**
  9997. * Export the canvas as Base64 URL
  9998. * @param {string} type
  9999. * @param {string} [backgroundColor='#fff']
  10000. * @return {string} Base64 URL
  10001. */
  10002. // toDataURL: function(type, backgroundColor) {
  10003. // return this.painter.getRenderedCanvas({
  10004. // backgroundColor: backgroundColor
  10005. // }).toDataURL(type);
  10006. // },
  10007. /**
  10008. * Converting a path to image.
  10009. * It has much better performance of drawing image rather than drawing a vector path.
  10010. * @param {module:zrender/graphic/Path} e
  10011. * @param {number} width
  10012. * @param {number} height
  10013. */
  10014. pathToImage: function (e, dpr) {
  10015. return this.painter.pathToImage(e, dpr);
  10016. },
  10017. /**
  10018. * Set default cursor
  10019. * @param {string} [cursorStyle='default'] 例如 crosshair
  10020. */
  10021. setCursorStyle: function (cursorStyle) {
  10022. this.handler.setCursorStyle(cursorStyle);
  10023. },
  10024. /**
  10025. * Find hovered element
  10026. * @param {number} x
  10027. * @param {number} y
  10028. * @return {Object} {target, topTarget}
  10029. */
  10030. findHover: function (x, y) {
  10031. return this.handler.findHover(x, y);
  10032. },
  10033. /**
  10034. * Bind event
  10035. *
  10036. * @param {string} eventName Event name
  10037. * @param {Function} eventHandler Handler function
  10038. * @param {Object} [context] Context object
  10039. */
  10040. on: function (eventName, eventHandler, context) {
  10041. this.handler.on(eventName, eventHandler, context);
  10042. },
  10043. /**
  10044. * Unbind event
  10045. * @param {string} eventName Event name
  10046. * @param {Function} [eventHandler] Handler function
  10047. */
  10048. off: function (eventName, eventHandler) {
  10049. this.handler.off(eventName, eventHandler);
  10050. },
  10051. /**
  10052. * Trigger event manually
  10053. *
  10054. * @param {string} eventName Event name
  10055. * @param {event=} event Event object
  10056. */
  10057. trigger: function (eventName, event) {
  10058. this.handler.trigger(eventName, event);
  10059. },
  10060. /**
  10061. * Clear all objects and the canvas.
  10062. */
  10063. clear: function () {
  10064. this.storage.delRoot();
  10065. this.painter.clear();
  10066. },
  10067. /**
  10068. * Dispose self.
  10069. */
  10070. dispose: function () {
  10071. this.animation.stop();
  10072. this.clear();
  10073. this.storage.dispose();
  10074. this.painter.dispose();
  10075. this.handler.dispose();
  10076. this.animation =
  10077. this.storage =
  10078. this.painter =
  10079. this.handler = null;
  10080. }
  10081. };
  10082. /*
  10083. * Licensed to the Apache Software Foundation (ASF) under one
  10084. * or more contributor license agreements. See the NOTICE file
  10085. * distributed with this work for additional information
  10086. * regarding copyright ownership. The ASF licenses this file
  10087. * to you under the Apache License, Version 2.0 (the
  10088. * "License"); you may not use this file except in compliance
  10089. * with the License. You may obtain a copy of the License at
  10090. *
  10091. * http://www.apache.org/licenses/LICENSE-2.0
  10092. *
  10093. * Unless required by applicable law or agreed to in writing,
  10094. * software distributed under the License is distributed on an
  10095. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10096. * KIND, either express or implied. See the License for the
  10097. * specific language governing permissions and limitations
  10098. * under the License.
  10099. */
  10100. var each$2 = each$1;
  10101. var isObject$2 = isObject$1;
  10102. var isArray$1 = isArray;
  10103. /**
  10104. * Make the name displayable. But we should
  10105. * make sure it is not duplicated with user
  10106. * specified name, so use '\0';
  10107. */
  10108. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10109. /**
  10110. * If value is not array, then translate it to array.
  10111. * @param {*} value
  10112. * @return {Array} [value] or value
  10113. */
  10114. function normalizeToArray(value) {
  10115. return value instanceof Array
  10116. ? value
  10117. : value == null
  10118. ? []
  10119. : [value];
  10120. }
  10121. /**
  10122. * Sync default option between normal and emphasis like `position` and `show`
  10123. * In case some one will write code like
  10124. * label: {
  10125. * show: false,
  10126. * position: 'outside',
  10127. * fontSize: 18
  10128. * },
  10129. * emphasis: {
  10130. * label: { show: true }
  10131. * }
  10132. * @param {Object} opt
  10133. * @param {string} key
  10134. * @param {Array.<string>} subOpts
  10135. */
  10136. function defaultEmphasis(opt, key, subOpts) {
  10137. // Caution: performance sensitive.
  10138. if (opt) {
  10139. opt[key] = opt[key] || {};
  10140. opt.emphasis = opt.emphasis || {};
  10141. opt.emphasis[key] = opt.emphasis[key] || {};
  10142. // Default emphasis option from normal
  10143. for (var i = 0, len = subOpts.length; i < len; i++) {
  10144. var subOptName = subOpts[i];
  10145. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10146. && opt[key].hasOwnProperty(subOptName)
  10147. ) {
  10148. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10149. }
  10150. }
  10151. }
  10152. }
  10153. var TEXT_STYLE_OPTIONS = [
  10154. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10155. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10156. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10157. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10158. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10159. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10160. ];
  10161. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10162. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10163. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10164. // // FIXME: deprecated, check and remove it.
  10165. // 'textStyle'
  10166. // ]);
  10167. /**
  10168. * The method do not ensure performance.
  10169. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10170. * This helper method retieves value from data.
  10171. * @param {string|number|Date|Array|Object} dataItem
  10172. * @return {number|string|Date|Array.<number|string|Date>}
  10173. */
  10174. function getDataItemValue(dataItem) {
  10175. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10176. ? dataItem.value : dataItem;
  10177. }
  10178. /**
  10179. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10180. * This helper method determine if dataItem has extra option besides value
  10181. * @param {string|number|Date|Array|Object} dataItem
  10182. */
  10183. function isDataItemOption(dataItem) {
  10184. return isObject$2(dataItem)
  10185. && !(dataItem instanceof Array);
  10186. // // markLine data can be array
  10187. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10188. }
  10189. /**
  10190. * Mapping to exists for merge.
  10191. *
  10192. * @public
  10193. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10194. * @param {Object|Array.<Object>} newCptOptions
  10195. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10196. * index of which is the same as exists.
  10197. */
  10198. function mappingToExists(exists, newCptOptions) {
  10199. // Mapping by the order by original option (but not order of
  10200. // new option) in merge mode. Because we should ensure
  10201. // some specified index (like xAxisIndex) is consistent with
  10202. // original option, which is easy to understand, espatially in
  10203. // media query. And in most case, merge option is used to
  10204. // update partial option but not be expected to change order.
  10205. newCptOptions = (newCptOptions || []).slice();
  10206. var result = map(exists || [], function (obj, index) {
  10207. return {exist: obj};
  10208. });
  10209. // Mapping by id or name if specified.
  10210. each$2(newCptOptions, function (cptOption, index) {
  10211. if (!isObject$2(cptOption)) {
  10212. return;
  10213. }
  10214. // id has highest priority.
  10215. for (var i = 0; i < result.length; i++) {
  10216. if (!result[i].option // Consider name: two map to one.
  10217. && cptOption.id != null
  10218. && result[i].exist.id === cptOption.id + ''
  10219. ) {
  10220. result[i].option = cptOption;
  10221. newCptOptions[index] = null;
  10222. return;
  10223. }
  10224. }
  10225. for (var i = 0; i < result.length; i++) {
  10226. var exist = result[i].exist;
  10227. if (!result[i].option // Consider name: two map to one.
  10228. // Can not match when both ids exist but different.
  10229. && (exist.id == null || cptOption.id == null)
  10230. && cptOption.name != null
  10231. && !isIdInner(cptOption)
  10232. && !isIdInner(exist)
  10233. && exist.name === cptOption.name + ''
  10234. ) {
  10235. result[i].option = cptOption;
  10236. newCptOptions[index] = null;
  10237. return;
  10238. }
  10239. }
  10240. });
  10241. // Otherwise mapping by index.
  10242. each$2(newCptOptions, function (cptOption, index) {
  10243. if (!isObject$2(cptOption)) {
  10244. return;
  10245. }
  10246. var i = 0;
  10247. for (; i < result.length; i++) {
  10248. var exist = result[i].exist;
  10249. if (!result[i].option
  10250. // Existing model that already has id should be able to
  10251. // mapped to (because after mapping performed model may
  10252. // be assigned with a id, whish should not affect next
  10253. // mapping), except those has inner id.
  10254. && !isIdInner(exist)
  10255. // Caution:
  10256. // Do not overwrite id. But name can be overwritten,
  10257. // because axis use name as 'show label text'.
  10258. // 'exist' always has id and name and we dont
  10259. // need to check it.
  10260. && cptOption.id == null
  10261. ) {
  10262. result[i].option = cptOption;
  10263. break;
  10264. }
  10265. }
  10266. if (i >= result.length) {
  10267. result.push({option: cptOption});
  10268. }
  10269. });
  10270. return result;
  10271. }
  10272. /**
  10273. * Make id and name for mapping result (result of mappingToExists)
  10274. * into `keyInfo` field.
  10275. *
  10276. * @public
  10277. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10278. * which order is the same as exists.
  10279. * @return {Array.<Object>} The input.
  10280. */
  10281. function makeIdAndName(mapResult) {
  10282. // We use this id to hash component models and view instances
  10283. // in echarts. id can be specified by user, or auto generated.
  10284. // The id generation rule ensures new view instance are able
  10285. // to mapped to old instance when setOption are called in
  10286. // no-merge mode. So we generate model id by name and plus
  10287. // type in view id.
  10288. // name can be duplicated among components, which is convenient
  10289. // to specify multi components (like series) by one name.
  10290. // Ensure that each id is distinct.
  10291. var idMap = createHashMap();
  10292. each$2(mapResult, function (item, index) {
  10293. var existCpt = item.exist;
  10294. existCpt && idMap.set(existCpt.id, item);
  10295. });
  10296. each$2(mapResult, function (item, index) {
  10297. var opt = item.option;
  10298. assert$1(
  10299. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10300. 'id duplicates: ' + (opt && opt.id)
  10301. );
  10302. opt && opt.id != null && idMap.set(opt.id, item);
  10303. !item.keyInfo && (item.keyInfo = {});
  10304. });
  10305. // Make name and id.
  10306. each$2(mapResult, function (item, index) {
  10307. var existCpt = item.exist;
  10308. var opt = item.option;
  10309. var keyInfo = item.keyInfo;
  10310. if (!isObject$2(opt)) {
  10311. return;
  10312. }
  10313. // name can be overwitten. Consider case: axis.name = '20km'.
  10314. // But id generated by name will not be changed, which affect
  10315. // only in that case: setOption with 'not merge mode' and view
  10316. // instance will be recreated, which can be accepted.
  10317. keyInfo.name = opt.name != null
  10318. ? opt.name + ''
  10319. : existCpt
  10320. ? existCpt.name
  10321. // Avoid diffferent series has the same name,
  10322. // because name may be used like in color pallet.
  10323. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10324. if (existCpt) {
  10325. keyInfo.id = existCpt.id;
  10326. }
  10327. else if (opt.id != null) {
  10328. keyInfo.id = opt.id + '';
  10329. }
  10330. else {
  10331. // Consider this situatoin:
  10332. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10333. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10334. // Series with the same name between optionA and optionB
  10335. // should be mapped.
  10336. var idNum = 0;
  10337. do {
  10338. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10339. }
  10340. while (idMap.get(keyInfo.id));
  10341. }
  10342. idMap.set(keyInfo.id, item);
  10343. });
  10344. }
  10345. function isNameSpecified(componentModel) {
  10346. var name = componentModel.name;
  10347. // Is specified when `indexOf` get -1 or > 0.
  10348. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10349. }
  10350. /**
  10351. * @public
  10352. * @param {Object} cptOption
  10353. * @return {boolean}
  10354. */
  10355. function isIdInner(cptOption) {
  10356. return isObject$2(cptOption)
  10357. && cptOption.id
  10358. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10359. }
  10360. /**
  10361. * A helper for removing duplicate items between batchA and batchB,
  10362. * and in themselves, and categorize by series.
  10363. *
  10364. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10365. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10366. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10367. */
  10368. /**
  10369. * @param {module:echarts/data/List} data
  10370. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10371. * each of which can be Array or primary type.
  10372. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10373. */
  10374. function queryDataIndex(data, payload) {
  10375. if (payload.dataIndexInside != null) {
  10376. return payload.dataIndexInside;
  10377. }
  10378. else if (payload.dataIndex != null) {
  10379. return isArray(payload.dataIndex)
  10380. ? map(payload.dataIndex, function (value) {
  10381. return data.indexOfRawIndex(value);
  10382. })
  10383. : data.indexOfRawIndex(payload.dataIndex);
  10384. }
  10385. else if (payload.name != null) {
  10386. return isArray(payload.name)
  10387. ? map(payload.name, function (value) {
  10388. return data.indexOfName(value);
  10389. })
  10390. : data.indexOfName(payload.name);
  10391. }
  10392. }
  10393. /**
  10394. * Enable property storage to any host object.
  10395. * Notice: Serialization is not supported.
  10396. *
  10397. * For example:
  10398. * var inner = zrUitl.makeInner();
  10399. *
  10400. * function some1(hostObj) {
  10401. * inner(hostObj).someProperty = 1212;
  10402. * ...
  10403. * }
  10404. * function some2() {
  10405. * var fields = inner(this);
  10406. * fields.someProperty1 = 1212;
  10407. * fields.someProperty2 = 'xx';
  10408. * ...
  10409. * }
  10410. *
  10411. * @return {Function}
  10412. */
  10413. function makeInner() {
  10414. // Consider different scope by es module import.
  10415. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10416. return function (hostObj) {
  10417. return hostObj[key] || (hostObj[key] = {});
  10418. };
  10419. }
  10420. var innerUniqueIndex = 0;
  10421. /**
  10422. * @param {module:echarts/model/Global} ecModel
  10423. * @param {string|Object} finder
  10424. * If string, e.g., 'geo', means {geoIndex: 0}.
  10425. * If Object, could contain some of these properties below:
  10426. * {
  10427. * seriesIndex, seriesId, seriesName,
  10428. * geoIndex, geoId, geoName,
  10429. * bmapIndex, bmapId, bmapName,
  10430. * xAxisIndex, xAxisId, xAxisName,
  10431. * yAxisIndex, yAxisId, yAxisName,
  10432. * gridIndex, gridId, gridName,
  10433. * ... (can be extended)
  10434. * }
  10435. * Each properties can be number|string|Array.<number>|Array.<string>
  10436. * For example, a finder could be
  10437. * {
  10438. * seriesIndex: 3,
  10439. * geoId: ['aa', 'cc'],
  10440. * gridName: ['xx', 'rr']
  10441. * }
  10442. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10443. * If nothing or null/undefined specified, return nothing.
  10444. * @param {Object} [opt]
  10445. * @param {string} [opt.defaultMainType]
  10446. * @param {Array.<string>} [opt.includeMainTypes]
  10447. * @return {Object} result like:
  10448. * {
  10449. * seriesModels: [seriesModel1, seriesModel2],
  10450. * seriesModel: seriesModel1, // The first model
  10451. * geoModels: [geoModel1, geoModel2],
  10452. * geoModel: geoModel1, // The first model
  10453. * ...
  10454. * }
  10455. */
  10456. function parseFinder(ecModel, finder, opt) {
  10457. if (isString(finder)) {
  10458. var obj = {};
  10459. obj[finder + 'Index'] = 0;
  10460. finder = obj;
  10461. }
  10462. var defaultMainType = opt && opt.defaultMainType;
  10463. if (defaultMainType
  10464. && !has(finder, defaultMainType + 'Index')
  10465. && !has(finder, defaultMainType + 'Id')
  10466. && !has(finder, defaultMainType + 'Name')
  10467. ) {
  10468. finder[defaultMainType + 'Index'] = 0;
  10469. }
  10470. var result = {};
  10471. each$2(finder, function (value, key) {
  10472. var value = finder[key];
  10473. // Exclude 'dataIndex' and other illgal keys.
  10474. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10475. result[key] = value;
  10476. return;
  10477. }
  10478. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10479. var mainType = parsedKey[1];
  10480. var queryType = (parsedKey[2] || '').toLowerCase();
  10481. if (!mainType
  10482. || !queryType
  10483. || value == null
  10484. || (queryType === 'index' && value === 'none')
  10485. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10486. ) {
  10487. return;
  10488. }
  10489. var queryParam = {mainType: mainType};
  10490. if (queryType !== 'index' || value !== 'all') {
  10491. queryParam[queryType] = value;
  10492. }
  10493. var models = ecModel.queryComponents(queryParam);
  10494. result[mainType + 'Models'] = models;
  10495. result[mainType + 'Model'] = models[0];
  10496. });
  10497. return result;
  10498. }
  10499. function has(obj, prop) {
  10500. return obj && obj.hasOwnProperty(prop);
  10501. }
  10502. function setAttribute(dom, key, value) {
  10503. dom.setAttribute
  10504. ? dom.setAttribute(key, value)
  10505. : (dom[key] = value);
  10506. }
  10507. function getAttribute(dom, key) {
  10508. return dom.getAttribute
  10509. ? dom.getAttribute(key)
  10510. : dom[key];
  10511. }
  10512. function getTooltipRenderMode(renderModeOption) {
  10513. if (renderModeOption === 'auto') {
  10514. // Using html when `document` exists, use richText otherwise
  10515. return env$1.domSupported ? 'html' : 'richText';
  10516. }
  10517. else {
  10518. return renderModeOption || 'html';
  10519. }
  10520. }
  10521. /**
  10522. * Group a list by key.
  10523. *
  10524. * @param {Array} array
  10525. * @param {Function} getKey
  10526. * param {*} Array item
  10527. * return {string} key
  10528. * @return {Object} Result
  10529. * {Array}: keys,
  10530. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10531. */
  10532. /*
  10533. * Licensed to the Apache Software Foundation (ASF) under one
  10534. * or more contributor license agreements. See the NOTICE file
  10535. * distributed with this work for additional information
  10536. * regarding copyright ownership. The ASF licenses this file
  10537. * to you under the Apache License, Version 2.0 (the
  10538. * "License"); you may not use this file except in compliance
  10539. * with the License. You may obtain a copy of the License at
  10540. *
  10541. * http://www.apache.org/licenses/LICENSE-2.0
  10542. *
  10543. * Unless required by applicable law or agreed to in writing,
  10544. * software distributed under the License is distributed on an
  10545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10546. * KIND, either express or implied. See the License for the
  10547. * specific language governing permissions and limitations
  10548. * under the License.
  10549. */
  10550. var TYPE_DELIMITER = '.';
  10551. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10552. /**
  10553. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10554. * @public
  10555. */
  10556. function parseClassType$1(componentType) {
  10557. var ret = {main: '', sub: ''};
  10558. if (componentType) {
  10559. componentType = componentType.split(TYPE_DELIMITER);
  10560. ret.main = componentType[0] || '';
  10561. ret.sub = componentType[1] || '';
  10562. }
  10563. return ret;
  10564. }
  10565. /**
  10566. * @public
  10567. */
  10568. function checkClassType(componentType) {
  10569. assert$1(
  10570. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10571. 'componentType "' + componentType + '" illegal'
  10572. );
  10573. }
  10574. /**
  10575. * @public
  10576. */
  10577. function enableClassExtend(RootClass, mandatoryMethods) {
  10578. RootClass.$constructor = RootClass;
  10579. RootClass.extend = function (proto) {
  10580. if (__DEV__) {
  10581. each$1(mandatoryMethods, function (method) {
  10582. if (!proto[method]) {
  10583. console.warn(
  10584. 'Method `' + method + '` should be implemented'
  10585. + (proto.type ? ' in ' + proto.type : '') + '.'
  10586. );
  10587. }
  10588. });
  10589. }
  10590. var superClass = this;
  10591. var ExtendedClass = function () {
  10592. if (!proto.$constructor) {
  10593. superClass.apply(this, arguments);
  10594. }
  10595. else {
  10596. proto.$constructor.apply(this, arguments);
  10597. }
  10598. };
  10599. extend(ExtendedClass.prototype, proto);
  10600. ExtendedClass.extend = this.extend;
  10601. ExtendedClass.superCall = superCall;
  10602. ExtendedClass.superApply = superApply;
  10603. inherits(ExtendedClass, this);
  10604. ExtendedClass.superClass = superClass;
  10605. return ExtendedClass;
  10606. };
  10607. }
  10608. var classBase = 0;
  10609. /**
  10610. * Can not use instanceof, consider different scope by
  10611. * cross domain or es module import in ec extensions.
  10612. * Mount a method "isInstance()" to Clz.
  10613. */
  10614. function enableClassCheck(Clz) {
  10615. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10616. Clz.prototype[classAttr] = true;
  10617. if (__DEV__) {
  10618. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10619. }
  10620. Clz.isInstance = function (obj) {
  10621. return !!(obj && obj[classAttr]);
  10622. };
  10623. }
  10624. // superCall should have class info, which can not be fetch from 'this'.
  10625. // Consider this case:
  10626. // class A has method f,
  10627. // class B inherits class A, overrides method f, f call superApply('f'),
  10628. // class C inherits class B, do not overrides method f,
  10629. // then when method of class C is called, dead loop occured.
  10630. function superCall(context, methodName) {
  10631. var args = slice(arguments, 2);
  10632. return this.superClass.prototype[methodName].apply(context, args);
  10633. }
  10634. function superApply(context, methodName, args) {
  10635. return this.superClass.prototype[methodName].apply(context, args);
  10636. }
  10637. /**
  10638. * @param {Object} entity
  10639. * @param {Object} options
  10640. * @param {boolean} [options.registerWhenExtend]
  10641. * @public
  10642. */
  10643. function enableClassManagement(entity, options) {
  10644. options = options || {};
  10645. /**
  10646. * Component model classes
  10647. * key: componentType,
  10648. * value:
  10649. * componentClass, when componentType is 'xxx'
  10650. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10651. * @type {Object}
  10652. */
  10653. var storage = {};
  10654. entity.registerClass = function (Clazz, componentType) {
  10655. if (componentType) {
  10656. checkClassType(componentType);
  10657. componentType = parseClassType$1(componentType);
  10658. if (!componentType.sub) {
  10659. if (__DEV__) {
  10660. if (storage[componentType.main]) {
  10661. console.warn(componentType.main + ' exists.');
  10662. }
  10663. }
  10664. storage[componentType.main] = Clazz;
  10665. }
  10666. else if (componentType.sub !== IS_CONTAINER) {
  10667. var container = makeContainer(componentType);
  10668. container[componentType.sub] = Clazz;
  10669. }
  10670. }
  10671. return Clazz;
  10672. };
  10673. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10674. var Clazz = storage[componentMainType];
  10675. if (Clazz && Clazz[IS_CONTAINER]) {
  10676. Clazz = subType ? Clazz[subType] : null;
  10677. }
  10678. if (throwWhenNotFound && !Clazz) {
  10679. throw new Error(
  10680. !subType
  10681. ? componentMainType + '.' + 'type should be specified.'
  10682. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10683. );
  10684. }
  10685. return Clazz;
  10686. };
  10687. entity.getClassesByMainType = function (componentType) {
  10688. componentType = parseClassType$1(componentType);
  10689. var result = [];
  10690. var obj = storage[componentType.main];
  10691. if (obj && obj[IS_CONTAINER]) {
  10692. each$1(obj, function (o, type) {
  10693. type !== IS_CONTAINER && result.push(o);
  10694. });
  10695. }
  10696. else {
  10697. result.push(obj);
  10698. }
  10699. return result;
  10700. };
  10701. entity.hasClass = function (componentType) {
  10702. // Just consider componentType.main.
  10703. componentType = parseClassType$1(componentType);
  10704. return !!storage[componentType.main];
  10705. };
  10706. /**
  10707. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10708. */
  10709. entity.getAllClassMainTypes = function () {
  10710. var types = [];
  10711. each$1(storage, function (obj, type) {
  10712. types.push(type);
  10713. });
  10714. return types;
  10715. };
  10716. /**
  10717. * If a main type is container and has sub types
  10718. * @param {string} mainType
  10719. * @return {boolean}
  10720. */
  10721. entity.hasSubTypes = function (componentType) {
  10722. componentType = parseClassType$1(componentType);
  10723. var obj = storage[componentType.main];
  10724. return obj && obj[IS_CONTAINER];
  10725. };
  10726. entity.parseClassType = parseClassType$1;
  10727. function makeContainer(componentType) {
  10728. var container = storage[componentType.main];
  10729. if (!container || !container[IS_CONTAINER]) {
  10730. container = storage[componentType.main] = {};
  10731. container[IS_CONTAINER] = true;
  10732. }
  10733. return container;
  10734. }
  10735. if (options.registerWhenExtend) {
  10736. var originalExtend = entity.extend;
  10737. if (originalExtend) {
  10738. entity.extend = function (proto) {
  10739. var ExtendedClass = originalExtend.call(this, proto);
  10740. return entity.registerClass(ExtendedClass, proto.type);
  10741. };
  10742. }
  10743. }
  10744. return entity;
  10745. }
  10746. /**
  10747. * @param {string|Array.<string>} properties
  10748. */
  10749. /*
  10750. * Licensed to the Apache Software Foundation (ASF) under one
  10751. * or more contributor license agreements. See the NOTICE file
  10752. * distributed with this work for additional information
  10753. * regarding copyright ownership. The ASF licenses this file
  10754. * to you under the Apache License, Version 2.0 (the
  10755. * "License"); you may not use this file except in compliance
  10756. * with the License. You may obtain a copy of the License at
  10757. *
  10758. * http://www.apache.org/licenses/LICENSE-2.0
  10759. *
  10760. * Unless required by applicable law or agreed to in writing,
  10761. * software distributed under the License is distributed on an
  10762. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10763. * KIND, either express or implied. See the License for the
  10764. * specific language governing permissions and limitations
  10765. * under the License.
  10766. */
  10767. // TODO Parse shadow style
  10768. // TODO Only shallow path support
  10769. var makeStyleMapper = function (properties) {
  10770. // Normalize
  10771. for (var i = 0; i < properties.length; i++) {
  10772. if (!properties[i][1]) {
  10773. properties[i][1] = properties[i][0];
  10774. }
  10775. }
  10776. return function (model, excludes, includes) {
  10777. var style = {};
  10778. for (var i = 0; i < properties.length; i++) {
  10779. var propName = properties[i][1];
  10780. if ((excludes && indexOf(excludes, propName) >= 0)
  10781. || (includes && indexOf(includes, propName) < 0)
  10782. ) {
  10783. continue;
  10784. }
  10785. var val = model.getShallow(propName);
  10786. if (val != null) {
  10787. style[properties[i][0]] = val;
  10788. }
  10789. }
  10790. return style;
  10791. };
  10792. };
  10793. /*
  10794. * Licensed to the Apache Software Foundation (ASF) under one
  10795. * or more contributor license agreements. See the NOTICE file
  10796. * distributed with this work for additional information
  10797. * regarding copyright ownership. The ASF licenses this file
  10798. * to you under the Apache License, Version 2.0 (the
  10799. * "License"); you may not use this file except in compliance
  10800. * with the License. You may obtain a copy of the License at
  10801. *
  10802. * http://www.apache.org/licenses/LICENSE-2.0
  10803. *
  10804. * Unless required by applicable law or agreed to in writing,
  10805. * software distributed under the License is distributed on an
  10806. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10807. * KIND, either express or implied. See the License for the
  10808. * specific language governing permissions and limitations
  10809. * under the License.
  10810. */
  10811. var getLineStyle = makeStyleMapper(
  10812. [
  10813. ['lineWidth', 'width'],
  10814. ['stroke', 'color'],
  10815. ['opacity'],
  10816. ['shadowBlur'],
  10817. ['shadowOffsetX'],
  10818. ['shadowOffsetY'],
  10819. ['shadowColor']
  10820. ]
  10821. );
  10822. var lineStyleMixin = {
  10823. getLineStyle: function (excludes) {
  10824. var style = getLineStyle(this, excludes);
  10825. // Always set lineDash whether dashed, otherwise we can not
  10826. // erase the previous style when assigning to el.style.
  10827. style.lineDash = this.getLineDash(style.lineWidth);
  10828. return style;
  10829. },
  10830. getLineDash: function (lineWidth) {
  10831. if (lineWidth == null) {
  10832. lineWidth = 1;
  10833. }
  10834. var lineType = this.get('type');
  10835. var dotSize = Math.max(lineWidth, 2);
  10836. var dashSize = lineWidth * 4;
  10837. return (lineType === 'solid' || lineType == null)
  10838. // Use `false` but not `null` for the solid line here, because `null` might be
  10839. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  10840. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  10841. // `lineDash` gotten form the latter one is not able to erase that from the former
  10842. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  10843. ? false
  10844. : lineType === 'dashed'
  10845. ? [dashSize, dashSize]
  10846. : [dotSize, dotSize];
  10847. }
  10848. };
  10849. /*
  10850. * Licensed to the Apache Software Foundation (ASF) under one
  10851. * or more contributor license agreements. See the NOTICE file
  10852. * distributed with this work for additional information
  10853. * regarding copyright ownership. The ASF licenses this file
  10854. * to you under the Apache License, Version 2.0 (the
  10855. * "License"); you may not use this file except in compliance
  10856. * with the License. You may obtain a copy of the License at
  10857. *
  10858. * http://www.apache.org/licenses/LICENSE-2.0
  10859. *
  10860. * Unless required by applicable law or agreed to in writing,
  10861. * software distributed under the License is distributed on an
  10862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10863. * KIND, either express or implied. See the License for the
  10864. * specific language governing permissions and limitations
  10865. * under the License.
  10866. */
  10867. var getAreaStyle = makeStyleMapper(
  10868. [
  10869. ['fill', 'color'],
  10870. ['shadowBlur'],
  10871. ['shadowOffsetX'],
  10872. ['shadowOffsetY'],
  10873. ['opacity'],
  10874. ['shadowColor']
  10875. ]
  10876. );
  10877. var areaStyleMixin = {
  10878. getAreaStyle: function (excludes, includes) {
  10879. return getAreaStyle(this, excludes, includes);
  10880. }
  10881. };
  10882. /**
  10883. * 曲线辅助模块
  10884. * @module zrender/core/curve
  10885. * @author pissang(https://www.github.com/pissang)
  10886. */
  10887. var mathPow = Math.pow;
  10888. var mathSqrt$2 = Math.sqrt;
  10889. var EPSILON$1 = 1e-8;
  10890. var EPSILON_NUMERIC = 1e-4;
  10891. var THREE_SQRT = mathSqrt$2(3);
  10892. var ONE_THIRD = 1 / 3;
  10893. // 临时变量
  10894. var _v0 = create();
  10895. var _v1 = create();
  10896. var _v2 = create();
  10897. function isAroundZero(val) {
  10898. return val > -EPSILON$1 && val < EPSILON$1;
  10899. }
  10900. function isNotAroundZero$1(val) {
  10901. return val > EPSILON$1 || val < -EPSILON$1;
  10902. }
  10903. /**
  10904. * 计算三次贝塞尔值
  10905. * @memberOf module:zrender/core/curve
  10906. * @param {number} p0
  10907. * @param {number} p1
  10908. * @param {number} p2
  10909. * @param {number} p3
  10910. * @param {number} t
  10911. * @return {number}
  10912. */
  10913. function cubicAt(p0, p1, p2, p3, t) {
  10914. var onet = 1 - t;
  10915. return onet * onet * (onet * p0 + 3 * t * p1)
  10916. + t * t * (t * p3 + 3 * onet * p2);
  10917. }
  10918. /**
  10919. * 计算三次贝塞尔导数值
  10920. * @memberOf module:zrender/core/curve
  10921. * @param {number} p0
  10922. * @param {number} p1
  10923. * @param {number} p2
  10924. * @param {number} p3
  10925. * @param {number} t
  10926. * @return {number}
  10927. */
  10928. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10929. var onet = 1 - t;
  10930. return 3 * (
  10931. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10932. + (p3 - p2) * t * t
  10933. );
  10934. }
  10935. /**
  10936. * 计算三次贝塞尔方程根,使用盛金公式
  10937. * @memberOf module:zrender/core/curve
  10938. * @param {number} p0
  10939. * @param {number} p1
  10940. * @param {number} p2
  10941. * @param {number} p3
  10942. * @param {number} val
  10943. * @param {Array.<number>} roots
  10944. * @return {number} 有效根数目
  10945. */
  10946. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10947. // Evaluate roots of cubic functions
  10948. var a = p3 + 3 * (p1 - p2) - p0;
  10949. var b = 3 * (p2 - p1 * 2 + p0);
  10950. var c = 3 * (p1 - p0);
  10951. var d = p0 - val;
  10952. var A = b * b - 3 * a * c;
  10953. var B = b * c - 9 * a * d;
  10954. var C = c * c - 3 * b * d;
  10955. var n = 0;
  10956. if (isAroundZero(A) && isAroundZero(B)) {
  10957. if (isAroundZero(b)) {
  10958. roots[0] = 0;
  10959. }
  10960. else {
  10961. var t1 = -c / b; //t1, t2, t3, b is not zero
  10962. if (t1 >= 0 && t1 <= 1) {
  10963. roots[n++] = t1;
  10964. }
  10965. }
  10966. }
  10967. else {
  10968. var disc = B * B - 4 * A * C;
  10969. if (isAroundZero(disc)) {
  10970. var K = B / A;
  10971. var t1 = -b / a + K; // t1, a is not zero
  10972. var t2 = -K / 2; // t2, t3
  10973. if (t1 >= 0 && t1 <= 1) {
  10974. roots[n++] = t1;
  10975. }
  10976. if (t2 >= 0 && t2 <= 1) {
  10977. roots[n++] = t2;
  10978. }
  10979. }
  10980. else if (disc > 0) {
  10981. var discSqrt = mathSqrt$2(disc);
  10982. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10983. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10984. if (Y1 < 0) {
  10985. Y1 = -mathPow(-Y1, ONE_THIRD);
  10986. }
  10987. else {
  10988. Y1 = mathPow(Y1, ONE_THIRD);
  10989. }
  10990. if (Y2 < 0) {
  10991. Y2 = -mathPow(-Y2, ONE_THIRD);
  10992. }
  10993. else {
  10994. Y2 = mathPow(Y2, ONE_THIRD);
  10995. }
  10996. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10997. if (t1 >= 0 && t1 <= 1) {
  10998. roots[n++] = t1;
  10999. }
  11000. }
  11001. else {
  11002. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  11003. var theta = Math.acos(T) / 3;
  11004. var ASqrt = mathSqrt$2(A);
  11005. var tmp = Math.cos(theta);
  11006. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  11007. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  11008. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  11009. if (t1 >= 0 && t1 <= 1) {
  11010. roots[n++] = t1;
  11011. }
  11012. if (t2 >= 0 && t2 <= 1) {
  11013. roots[n++] = t2;
  11014. }
  11015. if (t3 >= 0 && t3 <= 1) {
  11016. roots[n++] = t3;
  11017. }
  11018. }
  11019. }
  11020. return n;
  11021. }
  11022. /**
  11023. * 计算三次贝塞尔方程极限值的位置
  11024. * @memberOf module:zrender/core/curve
  11025. * @param {number} p0
  11026. * @param {number} p1
  11027. * @param {number} p2
  11028. * @param {number} p3
  11029. * @param {Array.<number>} extrema
  11030. * @return {number} 有效数目
  11031. */
  11032. function cubicExtrema(p0, p1, p2, p3, extrema) {
  11033. var b = 6 * p2 - 12 * p1 + 6 * p0;
  11034. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  11035. var c = 3 * p1 - 3 * p0;
  11036. var n = 0;
  11037. if (isAroundZero(a)) {
  11038. if (isNotAroundZero$1(b)) {
  11039. var t1 = -c / b;
  11040. if (t1 >= 0 && t1 <= 1) {
  11041. extrema[n++] = t1;
  11042. }
  11043. }
  11044. }
  11045. else {
  11046. var disc = b * b - 4 * a * c;
  11047. if (isAroundZero(disc)) {
  11048. extrema[0] = -b / (2 * a);
  11049. }
  11050. else if (disc > 0) {
  11051. var discSqrt = mathSqrt$2(disc);
  11052. var t1 = (-b + discSqrt) / (2 * a);
  11053. var t2 = (-b - discSqrt) / (2 * a);
  11054. if (t1 >= 0 && t1 <= 1) {
  11055. extrema[n++] = t1;
  11056. }
  11057. if (t2 >= 0 && t2 <= 1) {
  11058. extrema[n++] = t2;
  11059. }
  11060. }
  11061. }
  11062. return n;
  11063. }
  11064. /**
  11065. * 细分三次贝塞尔曲线
  11066. * @memberOf module:zrender/core/curve
  11067. * @param {number} p0
  11068. * @param {number} p1
  11069. * @param {number} p2
  11070. * @param {number} p3
  11071. * @param {number} t
  11072. * @param {Array.<number>} out
  11073. */
  11074. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  11075. var p01 = (p1 - p0) * t + p0;
  11076. var p12 = (p2 - p1) * t + p1;
  11077. var p23 = (p3 - p2) * t + p2;
  11078. var p012 = (p12 - p01) * t + p01;
  11079. var p123 = (p23 - p12) * t + p12;
  11080. var p0123 = (p123 - p012) * t + p012;
  11081. // Seg0
  11082. out[0] = p0;
  11083. out[1] = p01;
  11084. out[2] = p012;
  11085. out[3] = p0123;
  11086. // Seg1
  11087. out[4] = p0123;
  11088. out[5] = p123;
  11089. out[6] = p23;
  11090. out[7] = p3;
  11091. }
  11092. /**
  11093. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11094. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11095. * @param {number} x0
  11096. * @param {number} y0
  11097. * @param {number} x1
  11098. * @param {number} y1
  11099. * @param {number} x2
  11100. * @param {number} y2
  11101. * @param {number} x3
  11102. * @param {number} y3
  11103. * @param {number} x
  11104. * @param {number} y
  11105. * @param {Array.<number>} [out] 投射点
  11106. * @return {number}
  11107. */
  11108. function cubicProjectPoint(
  11109. x0, y0, x1, y1, x2, y2, x3, y3,
  11110. x, y, out
  11111. ) {
  11112. // http://pomax.github.io/bezierinfo/#projections
  11113. var t;
  11114. var interval = 0.005;
  11115. var d = Infinity;
  11116. var prev;
  11117. var next;
  11118. var d1;
  11119. var d2;
  11120. _v0[0] = x;
  11121. _v0[1] = y;
  11122. // 先粗略估计一下可能的最小距离的 t 值
  11123. // PENDING
  11124. for (var _t = 0; _t < 1; _t += 0.05) {
  11125. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11126. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11127. d1 = distSquare(_v0, _v1);
  11128. if (d1 < d) {
  11129. t = _t;
  11130. d = d1;
  11131. }
  11132. }
  11133. d = Infinity;
  11134. // At most 32 iteration
  11135. for (var i = 0; i < 32; i++) {
  11136. if (interval < EPSILON_NUMERIC) {
  11137. break;
  11138. }
  11139. prev = t - interval;
  11140. next = t + interval;
  11141. // t - interval
  11142. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11143. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11144. d1 = distSquare(_v1, _v0);
  11145. if (prev >= 0 && d1 < d) {
  11146. t = prev;
  11147. d = d1;
  11148. }
  11149. else {
  11150. // t + interval
  11151. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11152. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11153. d2 = distSquare(_v2, _v0);
  11154. if (next <= 1 && d2 < d) {
  11155. t = next;
  11156. d = d2;
  11157. }
  11158. else {
  11159. interval *= 0.5;
  11160. }
  11161. }
  11162. }
  11163. // t
  11164. if (out) {
  11165. out[0] = cubicAt(x0, x1, x2, x3, t);
  11166. out[1] = cubicAt(y0, y1, y2, y3, t);
  11167. }
  11168. // console.log(interval, i);
  11169. return mathSqrt$2(d);
  11170. }
  11171. /**
  11172. * 计算二次方贝塞尔值
  11173. * @param {number} p0
  11174. * @param {number} p1
  11175. * @param {number} p2
  11176. * @param {number} t
  11177. * @return {number}
  11178. */
  11179. function quadraticAt(p0, p1, p2, t) {
  11180. var onet = 1 - t;
  11181. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11182. }
  11183. /**
  11184. * 计算二次方贝塞尔导数值
  11185. * @param {number} p0
  11186. * @param {number} p1
  11187. * @param {number} p2
  11188. * @param {number} t
  11189. * @return {number}
  11190. */
  11191. function quadraticDerivativeAt(p0, p1, p2, t) {
  11192. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11193. }
  11194. /**
  11195. * 计算二次方贝塞尔方程根
  11196. * @param {number} p0
  11197. * @param {number} p1
  11198. * @param {number} p2
  11199. * @param {number} t
  11200. * @param {Array.<number>} roots
  11201. * @return {number} 有效根数目
  11202. */
  11203. function quadraticRootAt(p0, p1, p2, val, roots) {
  11204. var a = p0 - 2 * p1 + p2;
  11205. var b = 2 * (p1 - p0);
  11206. var c = p0 - val;
  11207. var n = 0;
  11208. if (isAroundZero(a)) {
  11209. if (isNotAroundZero$1(b)) {
  11210. var t1 = -c / b;
  11211. if (t1 >= 0 && t1 <= 1) {
  11212. roots[n++] = t1;
  11213. }
  11214. }
  11215. }
  11216. else {
  11217. var disc = b * b - 4 * a * c;
  11218. if (isAroundZero(disc)) {
  11219. var t1 = -b / (2 * a);
  11220. if (t1 >= 0 && t1 <= 1) {
  11221. roots[n++] = t1;
  11222. }
  11223. }
  11224. else if (disc > 0) {
  11225. var discSqrt = mathSqrt$2(disc);
  11226. var t1 = (-b + discSqrt) / (2 * a);
  11227. var t2 = (-b - discSqrt) / (2 * a);
  11228. if (t1 >= 0 && t1 <= 1) {
  11229. roots[n++] = t1;
  11230. }
  11231. if (t2 >= 0 && t2 <= 1) {
  11232. roots[n++] = t2;
  11233. }
  11234. }
  11235. }
  11236. return n;
  11237. }
  11238. /**
  11239. * 计算二次贝塞尔方程极限值
  11240. * @memberOf module:zrender/core/curve
  11241. * @param {number} p0
  11242. * @param {number} p1
  11243. * @param {number} p2
  11244. * @return {number}
  11245. */
  11246. function quadraticExtremum(p0, p1, p2) {
  11247. var divider = p0 + p2 - 2 * p1;
  11248. if (divider === 0) {
  11249. // p1 is center of p0 and p2
  11250. return 0.5;
  11251. }
  11252. else {
  11253. return (p0 - p1) / divider;
  11254. }
  11255. }
  11256. /**
  11257. * 细分二次贝塞尔曲线
  11258. * @memberOf module:zrender/core/curve
  11259. * @param {number} p0
  11260. * @param {number} p1
  11261. * @param {number} p2
  11262. * @param {number} t
  11263. * @param {Array.<number>} out
  11264. */
  11265. function quadraticSubdivide(p0, p1, p2, t, out) {
  11266. var p01 = (p1 - p0) * t + p0;
  11267. var p12 = (p2 - p1) * t + p1;
  11268. var p012 = (p12 - p01) * t + p01;
  11269. // Seg0
  11270. out[0] = p0;
  11271. out[1] = p01;
  11272. out[2] = p012;
  11273. // Seg1
  11274. out[3] = p012;
  11275. out[4] = p12;
  11276. out[5] = p2;
  11277. }
  11278. /**
  11279. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11280. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11281. * @param {number} x0
  11282. * @param {number} y0
  11283. * @param {number} x1
  11284. * @param {number} y1
  11285. * @param {number} x2
  11286. * @param {number} y2
  11287. * @param {number} x
  11288. * @param {number} y
  11289. * @param {Array.<number>} out 投射点
  11290. * @return {number}
  11291. */
  11292. function quadraticProjectPoint(
  11293. x0, y0, x1, y1, x2, y2,
  11294. x, y, out
  11295. ) {
  11296. // http://pomax.github.io/bezierinfo/#projections
  11297. var t;
  11298. var interval = 0.005;
  11299. var d = Infinity;
  11300. _v0[0] = x;
  11301. _v0[1] = y;
  11302. // 先粗略估计一下可能的最小距离的 t 值
  11303. // PENDING
  11304. for (var _t = 0; _t < 1; _t += 0.05) {
  11305. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11306. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11307. var d1 = distSquare(_v0, _v1);
  11308. if (d1 < d) {
  11309. t = _t;
  11310. d = d1;
  11311. }
  11312. }
  11313. d = Infinity;
  11314. // At most 32 iteration
  11315. for (var i = 0; i < 32; i++) {
  11316. if (interval < EPSILON_NUMERIC) {
  11317. break;
  11318. }
  11319. var prev = t - interval;
  11320. var next = t + interval;
  11321. // t - interval
  11322. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11323. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11324. var d1 = distSquare(_v1, _v0);
  11325. if (prev >= 0 && d1 < d) {
  11326. t = prev;
  11327. d = d1;
  11328. }
  11329. else {
  11330. // t + interval
  11331. _v2[0] = quadraticAt(x0, x1, x2, next);
  11332. _v2[1] = quadraticAt(y0, y1, y2, next);
  11333. var d2 = distSquare(_v2, _v0);
  11334. if (next <= 1 && d2 < d) {
  11335. t = next;
  11336. d = d2;
  11337. }
  11338. else {
  11339. interval *= 0.5;
  11340. }
  11341. }
  11342. }
  11343. // t
  11344. if (out) {
  11345. out[0] = quadraticAt(x0, x1, x2, t);
  11346. out[1] = quadraticAt(y0, y1, y2, t);
  11347. }
  11348. // console.log(interval, i);
  11349. return mathSqrt$2(d);
  11350. }
  11351. /**
  11352. * @author Yi Shen(https://github.com/pissang)
  11353. */
  11354. var mathMin$3 = Math.min;
  11355. var mathMax$3 = Math.max;
  11356. var mathSin$2 = Math.sin;
  11357. var mathCos$2 = Math.cos;
  11358. var PI2 = Math.PI * 2;
  11359. var start = create();
  11360. var end = create();
  11361. var extremity = create();
  11362. /**
  11363. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11364. * @module zrender/core/bbox
  11365. * @param {Array<Object>} points 顶点数组
  11366. * @param {number} min
  11367. * @param {number} max
  11368. */
  11369. /**
  11370. * @memberOf module:zrender/core/bbox
  11371. * @param {number} x0
  11372. * @param {number} y0
  11373. * @param {number} x1
  11374. * @param {number} y1
  11375. * @param {Array.<number>} min
  11376. * @param {Array.<number>} max
  11377. */
  11378. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11379. min$$1[0] = mathMin$3(x0, x1);
  11380. min$$1[1] = mathMin$3(y0, y1);
  11381. max$$1[0] = mathMax$3(x0, x1);
  11382. max$$1[1] = mathMax$3(y0, y1);
  11383. }
  11384. var xDim = [];
  11385. var yDim = [];
  11386. /**
  11387. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11388. * @memberOf module:zrender/core/bbox
  11389. * @param {number} x0
  11390. * @param {number} y0
  11391. * @param {number} x1
  11392. * @param {number} y1
  11393. * @param {number} x2
  11394. * @param {number} y2
  11395. * @param {number} x3
  11396. * @param {number} y3
  11397. * @param {Array.<number>} min
  11398. * @param {Array.<number>} max
  11399. */
  11400. function fromCubic(
  11401. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11402. ) {
  11403. var cubicExtrema$$1 = cubicExtrema;
  11404. var cubicAt$$1 = cubicAt;
  11405. var i;
  11406. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11407. min$$1[0] = Infinity;
  11408. min$$1[1] = Infinity;
  11409. max$$1[0] = -Infinity;
  11410. max$$1[1] = -Infinity;
  11411. for (i = 0; i < n; i++) {
  11412. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11413. min$$1[0] = mathMin$3(x, min$$1[0]);
  11414. max$$1[0] = mathMax$3(x, max$$1[0]);
  11415. }
  11416. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11417. for (i = 0; i < n; i++) {
  11418. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11419. min$$1[1] = mathMin$3(y, min$$1[1]);
  11420. max$$1[1] = mathMax$3(y, max$$1[1]);
  11421. }
  11422. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11423. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11424. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11425. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11426. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11427. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11428. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11429. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11430. }
  11431. /**
  11432. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11433. * @memberOf module:zrender/core/bbox
  11434. * @param {number} x0
  11435. * @param {number} y0
  11436. * @param {number} x1
  11437. * @param {number} y1
  11438. * @param {number} x2
  11439. * @param {number} y2
  11440. * @param {Array.<number>} min
  11441. * @param {Array.<number>} max
  11442. */
  11443. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11444. var quadraticExtremum$$1 = quadraticExtremum;
  11445. var quadraticAt$$1 = quadraticAt;
  11446. // Find extremities, where derivative in x dim or y dim is zero
  11447. var tx =
  11448. mathMax$3(
  11449. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11450. );
  11451. var ty =
  11452. mathMax$3(
  11453. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11454. );
  11455. var x = quadraticAt$$1(x0, x1, x2, tx);
  11456. var y = quadraticAt$$1(y0, y1, y2, ty);
  11457. min$$1[0] = mathMin$3(x0, x2, x);
  11458. min$$1[1] = mathMin$3(y0, y2, y);
  11459. max$$1[0] = mathMax$3(x0, x2, x);
  11460. max$$1[1] = mathMax$3(y0, y2, y);
  11461. }
  11462. /**
  11463. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11464. * @method
  11465. * @memberOf module:zrender/core/bbox
  11466. * @param {number} x
  11467. * @param {number} y
  11468. * @param {number} rx
  11469. * @param {number} ry
  11470. * @param {number} startAngle
  11471. * @param {number} endAngle
  11472. * @param {number} anticlockwise
  11473. * @param {Array.<number>} min
  11474. * @param {Array.<number>} max
  11475. */
  11476. function fromArc(
  11477. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11478. ) {
  11479. var vec2Min = min;
  11480. var vec2Max = max;
  11481. var diff = Math.abs(startAngle - endAngle);
  11482. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11483. // Is a circle
  11484. min$$1[0] = x - rx;
  11485. min$$1[1] = y - ry;
  11486. max$$1[0] = x + rx;
  11487. max$$1[1] = y + ry;
  11488. return;
  11489. }
  11490. start[0] = mathCos$2(startAngle) * rx + x;
  11491. start[1] = mathSin$2(startAngle) * ry + y;
  11492. end[0] = mathCos$2(endAngle) * rx + x;
  11493. end[1] = mathSin$2(endAngle) * ry + y;
  11494. vec2Min(min$$1, start, end);
  11495. vec2Max(max$$1, start, end);
  11496. // Thresh to [0, Math.PI * 2]
  11497. startAngle = startAngle % (PI2);
  11498. if (startAngle < 0) {
  11499. startAngle = startAngle + PI2;
  11500. }
  11501. endAngle = endAngle % (PI2);
  11502. if (endAngle < 0) {
  11503. endAngle = endAngle + PI2;
  11504. }
  11505. if (startAngle > endAngle && !anticlockwise) {
  11506. endAngle += PI2;
  11507. }
  11508. else if (startAngle < endAngle && anticlockwise) {
  11509. startAngle += PI2;
  11510. }
  11511. if (anticlockwise) {
  11512. var tmp = endAngle;
  11513. endAngle = startAngle;
  11514. startAngle = tmp;
  11515. }
  11516. // var number = 0;
  11517. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11518. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11519. if (angle > startAngle) {
  11520. extremity[0] = mathCos$2(angle) * rx + x;
  11521. extremity[1] = mathSin$2(angle) * ry + y;
  11522. vec2Min(min$$1, extremity, min$$1);
  11523. vec2Max(max$$1, extremity, max$$1);
  11524. }
  11525. }
  11526. }
  11527. /**
  11528. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11529. * 可以用于 isInsidePath 判断以及获取boundingRect
  11530. *
  11531. * @module zrender/core/PathProxy
  11532. * @author Yi Shen (http://www.github.com/pissang)
  11533. */
  11534. // TODO getTotalLength, getPointAtLength
  11535. /* global Float32Array */
  11536. var CMD = {
  11537. M: 1,
  11538. L: 2,
  11539. C: 3,
  11540. Q: 4,
  11541. A: 5,
  11542. Z: 6,
  11543. // Rect
  11544. R: 7
  11545. };
  11546. // var CMD_MEM_SIZE = {
  11547. // M: 3,
  11548. // L: 3,
  11549. // C: 7,
  11550. // Q: 5,
  11551. // A: 9,
  11552. // R: 5,
  11553. // Z: 1
  11554. // };
  11555. var min$1 = [];
  11556. var max$1 = [];
  11557. var min2 = [];
  11558. var max2 = [];
  11559. var mathMin$2 = Math.min;
  11560. var mathMax$2 = Math.max;
  11561. var mathCos$1 = Math.cos;
  11562. var mathSin$1 = Math.sin;
  11563. var mathSqrt$1 = Math.sqrt;
  11564. var mathAbs = Math.abs;
  11565. var hasTypedArray = typeof Float32Array !== 'undefined';
  11566. /**
  11567. * @alias module:zrender/core/PathProxy
  11568. * @constructor
  11569. */
  11570. var PathProxy = function (notSaveData) {
  11571. this._saveData = !(notSaveData || false);
  11572. if (this._saveData) {
  11573. /**
  11574. * Path data. Stored as flat array
  11575. * @type {Array.<Object>}
  11576. */
  11577. this.data = [];
  11578. }
  11579. this._ctx = null;
  11580. };
  11581. /**
  11582. * 快速计算Path包围盒(并不是最小包围盒)
  11583. * @return {Object}
  11584. */
  11585. PathProxy.prototype = {
  11586. constructor: PathProxy,
  11587. _xi: 0,
  11588. _yi: 0,
  11589. _x0: 0,
  11590. _y0: 0,
  11591. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11592. _ux: 0,
  11593. _uy: 0,
  11594. _len: 0,
  11595. _lineDash: null,
  11596. _dashOffset: 0,
  11597. _dashIdx: 0,
  11598. _dashSum: 0,
  11599. /**
  11600. * @readOnly
  11601. */
  11602. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11603. // Compat. Previously there is no segmentIgnoreThreshold.
  11604. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11605. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11606. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11607. },
  11608. getContext: function () {
  11609. return this._ctx;
  11610. },
  11611. /**
  11612. * @param {CanvasRenderingContext2D} ctx
  11613. * @return {module:zrender/core/PathProxy}
  11614. */
  11615. beginPath: function (ctx) {
  11616. this._ctx = ctx;
  11617. ctx && ctx.beginPath();
  11618. ctx && (this.dpr = ctx.dpr);
  11619. // Reset
  11620. if (this._saveData) {
  11621. this._len = 0;
  11622. }
  11623. if (this._lineDash) {
  11624. this._lineDash = null;
  11625. this._dashOffset = 0;
  11626. }
  11627. return this;
  11628. },
  11629. /**
  11630. * @param {number} x
  11631. * @param {number} y
  11632. * @return {module:zrender/core/PathProxy}
  11633. */
  11634. moveTo: function (x, y) {
  11635. this.addData(CMD.M, x, y);
  11636. this._ctx && this._ctx.moveTo(x, y);
  11637. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11638. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11639. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11640. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11641. this._x0 = x;
  11642. this._y0 = y;
  11643. this._xi = x;
  11644. this._yi = y;
  11645. return this;
  11646. },
  11647. /**
  11648. * @param {number} x
  11649. * @param {number} y
  11650. * @return {module:zrender/core/PathProxy}
  11651. */
  11652. lineTo: function (x, y) {
  11653. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11654. || mathAbs(y - this._yi) > this._uy
  11655. // Force draw the first segment
  11656. || this._len < 5;
  11657. this.addData(CMD.L, x, y);
  11658. if (this._ctx && exceedUnit) {
  11659. this._needsDash() ? this._dashedLineTo(x, y)
  11660. : this._ctx.lineTo(x, y);
  11661. }
  11662. if (exceedUnit) {
  11663. this._xi = x;
  11664. this._yi = y;
  11665. }
  11666. return this;
  11667. },
  11668. /**
  11669. * @param {number} x1
  11670. * @param {number} y1
  11671. * @param {number} x2
  11672. * @param {number} y2
  11673. * @param {number} x3
  11674. * @param {number} y3
  11675. * @return {module:zrender/core/PathProxy}
  11676. */
  11677. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11678. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11679. if (this._ctx) {
  11680. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11681. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11682. }
  11683. this._xi = x3;
  11684. this._yi = y3;
  11685. return this;
  11686. },
  11687. /**
  11688. * @param {number} x1
  11689. * @param {number} y1
  11690. * @param {number} x2
  11691. * @param {number} y2
  11692. * @return {module:zrender/core/PathProxy}
  11693. */
  11694. quadraticCurveTo: function (x1, y1, x2, y2) {
  11695. this.addData(CMD.Q, x1, y1, x2, y2);
  11696. if (this._ctx) {
  11697. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11698. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11699. }
  11700. this._xi = x2;
  11701. this._yi = y2;
  11702. return this;
  11703. },
  11704. /**
  11705. * @param {number} cx
  11706. * @param {number} cy
  11707. * @param {number} r
  11708. * @param {number} startAngle
  11709. * @param {number} endAngle
  11710. * @param {boolean} anticlockwise
  11711. * @return {module:zrender/core/PathProxy}
  11712. */
  11713. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11714. this.addData(
  11715. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11716. );
  11717. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11718. this._xi = mathCos$1(endAngle) * r + cx;
  11719. this._yi = mathSin$1(endAngle) * r + cy;
  11720. return this;
  11721. },
  11722. // TODO
  11723. arcTo: function (x1, y1, x2, y2, radius) {
  11724. if (this._ctx) {
  11725. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11726. }
  11727. return this;
  11728. },
  11729. // TODO
  11730. rect: function (x, y, w, h) {
  11731. this._ctx && this._ctx.rect(x, y, w, h);
  11732. this.addData(CMD.R, x, y, w, h);
  11733. return this;
  11734. },
  11735. /**
  11736. * @return {module:zrender/core/PathProxy}
  11737. */
  11738. closePath: function () {
  11739. this.addData(CMD.Z);
  11740. var ctx = this._ctx;
  11741. var x0 = this._x0;
  11742. var y0 = this._y0;
  11743. if (ctx) {
  11744. this._needsDash() && this._dashedLineTo(x0, y0);
  11745. ctx.closePath();
  11746. }
  11747. this._xi = x0;
  11748. this._yi = y0;
  11749. return this;
  11750. },
  11751. /**
  11752. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11753. * stroke 同样
  11754. * @param {CanvasRenderingContext2D} ctx
  11755. * @return {module:zrender/core/PathProxy}
  11756. */
  11757. fill: function (ctx) {
  11758. ctx && ctx.fill();
  11759. this.toStatic();
  11760. },
  11761. /**
  11762. * @param {CanvasRenderingContext2D} ctx
  11763. * @return {module:zrender/core/PathProxy}
  11764. */
  11765. stroke: function (ctx) {
  11766. ctx && ctx.stroke();
  11767. this.toStatic();
  11768. },
  11769. /**
  11770. * 必须在其它绘制命令前调用
  11771. * Must be invoked before all other path drawing methods
  11772. * @return {module:zrender/core/PathProxy}
  11773. */
  11774. setLineDash: function (lineDash) {
  11775. if (lineDash instanceof Array) {
  11776. this._lineDash = lineDash;
  11777. this._dashIdx = 0;
  11778. var lineDashSum = 0;
  11779. for (var i = 0; i < lineDash.length; i++) {
  11780. lineDashSum += lineDash[i];
  11781. }
  11782. this._dashSum = lineDashSum;
  11783. }
  11784. return this;
  11785. },
  11786. /**
  11787. * 必须在其它绘制命令前调用
  11788. * Must be invoked before all other path drawing methods
  11789. * @return {module:zrender/core/PathProxy}
  11790. */
  11791. setLineDashOffset: function (offset) {
  11792. this._dashOffset = offset;
  11793. return this;
  11794. },
  11795. /**
  11796. *
  11797. * @return {boolean}
  11798. */
  11799. len: function () {
  11800. return this._len;
  11801. },
  11802. /**
  11803. * 直接设置 Path 数据
  11804. */
  11805. setData: function (data) {
  11806. var len$$1 = data.length;
  11807. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11808. this.data = new Float32Array(len$$1);
  11809. }
  11810. for (var i = 0; i < len$$1; i++) {
  11811. this.data[i] = data[i];
  11812. }
  11813. this._len = len$$1;
  11814. },
  11815. /**
  11816. * 添加子路径
  11817. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11818. */
  11819. appendPath: function (path) {
  11820. if (!(path instanceof Array)) {
  11821. path = [path];
  11822. }
  11823. var len$$1 = path.length;
  11824. var appendSize = 0;
  11825. var offset = this._len;
  11826. for (var i = 0; i < len$$1; i++) {
  11827. appendSize += path[i].len();
  11828. }
  11829. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11830. this.data = new Float32Array(offset + appendSize);
  11831. }
  11832. for (var i = 0; i < len$$1; i++) {
  11833. var appendPathData = path[i].data;
  11834. for (var k = 0; k < appendPathData.length; k++) {
  11835. this.data[offset++] = appendPathData[k];
  11836. }
  11837. }
  11838. this._len = offset;
  11839. },
  11840. /**
  11841. * 填充 Path 数据。
  11842. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11843. */
  11844. addData: function (cmd) {
  11845. if (!this._saveData) {
  11846. return;
  11847. }
  11848. var data = this.data;
  11849. if (this._len + arguments.length > data.length) {
  11850. // 因为之前的数组已经转换成静态的 Float32Array
  11851. // 所以不够用时需要扩展一个新的动态数组
  11852. this._expandData();
  11853. data = this.data;
  11854. }
  11855. for (var i = 0; i < arguments.length; i++) {
  11856. data[this._len++] = arguments[i];
  11857. }
  11858. this._prevCmd = cmd;
  11859. },
  11860. _expandData: function () {
  11861. // Only if data is Float32Array
  11862. if (!(this.data instanceof Array)) {
  11863. var newData = [];
  11864. for (var i = 0; i < this._len; i++) {
  11865. newData[i] = this.data[i];
  11866. }
  11867. this.data = newData;
  11868. }
  11869. },
  11870. /**
  11871. * If needs js implemented dashed line
  11872. * @return {boolean}
  11873. * @private
  11874. */
  11875. _needsDash: function () {
  11876. return this._lineDash;
  11877. },
  11878. _dashedLineTo: function (x1, y1) {
  11879. var dashSum = this._dashSum;
  11880. var offset = this._dashOffset;
  11881. var lineDash = this._lineDash;
  11882. var ctx = this._ctx;
  11883. var x0 = this._xi;
  11884. var y0 = this._yi;
  11885. var dx = x1 - x0;
  11886. var dy = y1 - y0;
  11887. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11888. var x = x0;
  11889. var y = y0;
  11890. var dash;
  11891. var nDash = lineDash.length;
  11892. var idx;
  11893. dx /= dist$$1;
  11894. dy /= dist$$1;
  11895. if (offset < 0) {
  11896. // Convert to positive offset
  11897. offset = dashSum + offset;
  11898. }
  11899. offset %= dashSum;
  11900. x -= offset * dx;
  11901. y -= offset * dy;
  11902. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11903. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11904. idx = this._dashIdx;
  11905. dash = lineDash[idx];
  11906. x += dx * dash;
  11907. y += dy * dash;
  11908. this._dashIdx = (idx + 1) % nDash;
  11909. // Skip positive offset
  11910. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11911. continue;
  11912. }
  11913. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11914. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11915. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11916. );
  11917. }
  11918. // Offset for next lineTo
  11919. dx = x - x1;
  11920. dy = y - y1;
  11921. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11922. },
  11923. // Not accurate dashed line to
  11924. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11925. var dashSum = this._dashSum;
  11926. var offset = this._dashOffset;
  11927. var lineDash = this._lineDash;
  11928. var ctx = this._ctx;
  11929. var x0 = this._xi;
  11930. var y0 = this._yi;
  11931. var t;
  11932. var dx;
  11933. var dy;
  11934. var cubicAt$$1 = cubicAt;
  11935. var bezierLen = 0;
  11936. var idx = this._dashIdx;
  11937. var nDash = lineDash.length;
  11938. var x;
  11939. var y;
  11940. var tmpLen = 0;
  11941. if (offset < 0) {
  11942. // Convert to positive offset
  11943. offset = dashSum + offset;
  11944. }
  11945. offset %= dashSum;
  11946. // Bezier approx length
  11947. for (t = 0; t < 1; t += 0.1) {
  11948. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11949. - cubicAt$$1(x0, x1, x2, x3, t);
  11950. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11951. - cubicAt$$1(y0, y1, y2, y3, t);
  11952. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11953. }
  11954. // Find idx after add offset
  11955. for (; idx < nDash; idx++) {
  11956. tmpLen += lineDash[idx];
  11957. if (tmpLen > offset) {
  11958. break;
  11959. }
  11960. }
  11961. t = (tmpLen - offset) / bezierLen;
  11962. while (t <= 1) {
  11963. x = cubicAt$$1(x0, x1, x2, x3, t);
  11964. y = cubicAt$$1(y0, y1, y2, y3, t);
  11965. // Use line to approximate dashed bezier
  11966. // Bad result if dash is long
  11967. idx % 2 ? ctx.moveTo(x, y)
  11968. : ctx.lineTo(x, y);
  11969. t += lineDash[idx] / bezierLen;
  11970. idx = (idx + 1) % nDash;
  11971. }
  11972. // Finish the last segment and calculate the new offset
  11973. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11974. dx = x3 - x;
  11975. dy = y3 - y;
  11976. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11977. },
  11978. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11979. // Convert quadratic to cubic using degree elevation
  11980. var x3 = x2;
  11981. var y3 = y2;
  11982. x2 = (x2 + 2 * x1) / 3;
  11983. y2 = (y2 + 2 * y1) / 3;
  11984. x1 = (this._xi + 2 * x1) / 3;
  11985. y1 = (this._yi + 2 * y1) / 3;
  11986. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11987. },
  11988. /**
  11989. * 转成静态的 Float32Array 减少堆内存占用
  11990. * Convert dynamic array to static Float32Array
  11991. */
  11992. toStatic: function () {
  11993. var data = this.data;
  11994. if (data instanceof Array) {
  11995. data.length = this._len;
  11996. if (hasTypedArray) {
  11997. this.data = new Float32Array(data);
  11998. }
  11999. }
  12000. },
  12001. /**
  12002. * @return {module:zrender/core/BoundingRect}
  12003. */
  12004. getBoundingRect: function () {
  12005. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  12006. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  12007. var data = this.data;
  12008. var xi = 0;
  12009. var yi = 0;
  12010. var x0 = 0;
  12011. var y0 = 0;
  12012. for (var i = 0; i < data.length;) {
  12013. var cmd = data[i++];
  12014. if (i === 1) {
  12015. // 如果第一个命令是 L, C, Q
  12016. // 则 previous point 同绘制命令的第一个 point
  12017. //
  12018. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12019. xi = data[i];
  12020. yi = data[i + 1];
  12021. x0 = xi;
  12022. y0 = yi;
  12023. }
  12024. switch (cmd) {
  12025. case CMD.M:
  12026. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12027. // 在 closePath 的时候使用
  12028. x0 = data[i++];
  12029. y0 = data[i++];
  12030. xi = x0;
  12031. yi = y0;
  12032. min2[0] = x0;
  12033. min2[1] = y0;
  12034. max2[0] = x0;
  12035. max2[1] = y0;
  12036. break;
  12037. case CMD.L:
  12038. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  12039. xi = data[i++];
  12040. yi = data[i++];
  12041. break;
  12042. case CMD.C:
  12043. fromCubic(
  12044. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12045. min2, max2
  12046. );
  12047. xi = data[i++];
  12048. yi = data[i++];
  12049. break;
  12050. case CMD.Q:
  12051. fromQuadratic(
  12052. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  12053. min2, max2
  12054. );
  12055. xi = data[i++];
  12056. yi = data[i++];
  12057. break;
  12058. case CMD.A:
  12059. // TODO Arc 判断的开销比较大
  12060. var cx = data[i++];
  12061. var cy = data[i++];
  12062. var rx = data[i++];
  12063. var ry = data[i++];
  12064. var startAngle = data[i++];
  12065. var endAngle = data[i++] + startAngle;
  12066. // TODO Arc 旋转
  12067. i += 1;
  12068. var anticlockwise = 1 - data[i++];
  12069. if (i === 1) {
  12070. // 直接使用 arc 命令
  12071. // 第一个命令起点还未定义
  12072. x0 = mathCos$1(startAngle) * rx + cx;
  12073. y0 = mathSin$1(startAngle) * ry + cy;
  12074. }
  12075. fromArc(
  12076. cx, cy, rx, ry, startAngle, endAngle,
  12077. anticlockwise, min2, max2
  12078. );
  12079. xi = mathCos$1(endAngle) * rx + cx;
  12080. yi = mathSin$1(endAngle) * ry + cy;
  12081. break;
  12082. case CMD.R:
  12083. x0 = xi = data[i++];
  12084. y0 = yi = data[i++];
  12085. var width = data[i++];
  12086. var height = data[i++];
  12087. // Use fromLine
  12088. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12089. break;
  12090. case CMD.Z:
  12091. xi = x0;
  12092. yi = y0;
  12093. break;
  12094. }
  12095. // Union
  12096. min(min$1, min$1, min2);
  12097. max(max$1, max$1, max2);
  12098. }
  12099. // No data
  12100. if (i === 0) {
  12101. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12102. }
  12103. return new BoundingRect(
  12104. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12105. );
  12106. },
  12107. /**
  12108. * Rebuild path from current data
  12109. * Rebuild path will not consider javascript implemented line dash.
  12110. * @param {CanvasRenderingContext2D} ctx
  12111. */
  12112. rebuildPath: function (ctx) {
  12113. var d = this.data;
  12114. var x0;
  12115. var y0;
  12116. var xi;
  12117. var yi;
  12118. var x;
  12119. var y;
  12120. var ux = this._ux;
  12121. var uy = this._uy;
  12122. var len$$1 = this._len;
  12123. for (var i = 0; i < len$$1;) {
  12124. var cmd = d[i++];
  12125. if (i === 1) {
  12126. // 如果第一个命令是 L, C, Q
  12127. // 则 previous point 同绘制命令的第一个 point
  12128. //
  12129. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12130. xi = d[i];
  12131. yi = d[i + 1];
  12132. x0 = xi;
  12133. y0 = yi;
  12134. }
  12135. switch (cmd) {
  12136. case CMD.M:
  12137. x0 = xi = d[i++];
  12138. y0 = yi = d[i++];
  12139. ctx.moveTo(xi, yi);
  12140. break;
  12141. case CMD.L:
  12142. x = d[i++];
  12143. y = d[i++];
  12144. // Not draw too small seg between
  12145. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12146. ctx.lineTo(x, y);
  12147. xi = x;
  12148. yi = y;
  12149. }
  12150. break;
  12151. case CMD.C:
  12152. ctx.bezierCurveTo(
  12153. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12154. );
  12155. xi = d[i - 2];
  12156. yi = d[i - 1];
  12157. break;
  12158. case CMD.Q:
  12159. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12160. xi = d[i - 2];
  12161. yi = d[i - 1];
  12162. break;
  12163. case CMD.A:
  12164. var cx = d[i++];
  12165. var cy = d[i++];
  12166. var rx = d[i++];
  12167. var ry = d[i++];
  12168. var theta = d[i++];
  12169. var dTheta = d[i++];
  12170. var psi = d[i++];
  12171. var fs = d[i++];
  12172. var r = (rx > ry) ? rx : ry;
  12173. var scaleX = (rx > ry) ? 1 : rx / ry;
  12174. var scaleY = (rx > ry) ? ry / rx : 1;
  12175. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12176. var endAngle = theta + dTheta;
  12177. if (isEllipse) {
  12178. ctx.translate(cx, cy);
  12179. ctx.rotate(psi);
  12180. ctx.scale(scaleX, scaleY);
  12181. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12182. ctx.scale(1 / scaleX, 1 / scaleY);
  12183. ctx.rotate(-psi);
  12184. ctx.translate(-cx, -cy);
  12185. }
  12186. else {
  12187. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12188. }
  12189. if (i === 1) {
  12190. // 直接使用 arc 命令
  12191. // 第一个命令起点还未定义
  12192. x0 = mathCos$1(theta) * rx + cx;
  12193. y0 = mathSin$1(theta) * ry + cy;
  12194. }
  12195. xi = mathCos$1(endAngle) * rx + cx;
  12196. yi = mathSin$1(endAngle) * ry + cy;
  12197. break;
  12198. case CMD.R:
  12199. x0 = xi = d[i];
  12200. y0 = yi = d[i + 1];
  12201. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12202. break;
  12203. case CMD.Z:
  12204. ctx.closePath();
  12205. xi = x0;
  12206. yi = y0;
  12207. }
  12208. }
  12209. }
  12210. };
  12211. PathProxy.CMD = CMD;
  12212. /**
  12213. * 线段包含判断
  12214. * @param {number} x0
  12215. * @param {number} y0
  12216. * @param {number} x1
  12217. * @param {number} y1
  12218. * @param {number} lineWidth
  12219. * @param {number} x
  12220. * @param {number} y
  12221. * @return {boolean}
  12222. */
  12223. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12224. if (lineWidth === 0) {
  12225. return false;
  12226. }
  12227. var _l = lineWidth;
  12228. var _a = 0;
  12229. var _b = x0;
  12230. // Quick reject
  12231. if (
  12232. (y > y0 + _l && y > y1 + _l)
  12233. || (y < y0 - _l && y < y1 - _l)
  12234. || (x > x0 + _l && x > x1 + _l)
  12235. || (x < x0 - _l && x < x1 - _l)
  12236. ) {
  12237. return false;
  12238. }
  12239. if (x0 !== x1) {
  12240. _a = (y0 - y1) / (x0 - x1);
  12241. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12242. }
  12243. else {
  12244. return Math.abs(x - x0) <= _l / 2;
  12245. }
  12246. var tmp = _a * x - y + _b;
  12247. var _s = tmp * tmp / (_a * _a + 1);
  12248. return _s <= _l / 2 * _l / 2;
  12249. }
  12250. /**
  12251. * 三次贝塞尔曲线描边包含判断
  12252. * @param {number} x0
  12253. * @param {number} y0
  12254. * @param {number} x1
  12255. * @param {number} y1
  12256. * @param {number} x2
  12257. * @param {number} y2
  12258. * @param {number} x3
  12259. * @param {number} y3
  12260. * @param {number} lineWidth
  12261. * @param {number} x
  12262. * @param {number} y
  12263. * @return {boolean}
  12264. */
  12265. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12266. if (lineWidth === 0) {
  12267. return false;
  12268. }
  12269. var _l = lineWidth;
  12270. // Quick reject
  12271. if (
  12272. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12273. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12274. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12275. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12276. ) {
  12277. return false;
  12278. }
  12279. var d = cubicProjectPoint(
  12280. x0, y0, x1, y1, x2, y2, x3, y3,
  12281. x, y, null
  12282. );
  12283. return d <= _l / 2;
  12284. }
  12285. /**
  12286. * 二次贝塞尔曲线描边包含判断
  12287. * @param {number} x0
  12288. * @param {number} y0
  12289. * @param {number} x1
  12290. * @param {number} y1
  12291. * @param {number} x2
  12292. * @param {number} y2
  12293. * @param {number} lineWidth
  12294. * @param {number} x
  12295. * @param {number} y
  12296. * @return {boolean}
  12297. */
  12298. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12299. if (lineWidth === 0) {
  12300. return false;
  12301. }
  12302. var _l = lineWidth;
  12303. // Quick reject
  12304. if (
  12305. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12306. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12307. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12308. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12309. ) {
  12310. return false;
  12311. }
  12312. var d = quadraticProjectPoint(
  12313. x0, y0, x1, y1, x2, y2,
  12314. x, y, null
  12315. );
  12316. return d <= _l / 2;
  12317. }
  12318. var PI2$3 = Math.PI * 2;
  12319. function normalizeRadian(angle) {
  12320. angle %= PI2$3;
  12321. if (angle < 0) {
  12322. angle += PI2$3;
  12323. }
  12324. return angle;
  12325. }
  12326. var PI2$2 = Math.PI * 2;
  12327. /**
  12328. * 圆弧描边包含判断
  12329. * @param {number} cx
  12330. * @param {number} cy
  12331. * @param {number} r
  12332. * @param {number} startAngle
  12333. * @param {number} endAngle
  12334. * @param {boolean} anticlockwise
  12335. * @param {number} lineWidth
  12336. * @param {number} x
  12337. * @param {number} y
  12338. * @return {Boolean}
  12339. */
  12340. function containStroke$4(
  12341. cx, cy, r, startAngle, endAngle, anticlockwise,
  12342. lineWidth, x, y
  12343. ) {
  12344. if (lineWidth === 0) {
  12345. return false;
  12346. }
  12347. var _l = lineWidth;
  12348. x -= cx;
  12349. y -= cy;
  12350. var d = Math.sqrt(x * x + y * y);
  12351. if ((d - _l > r) || (d + _l < r)) {
  12352. return false;
  12353. }
  12354. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12355. // Is a circle
  12356. return true;
  12357. }
  12358. if (anticlockwise) {
  12359. var tmp = startAngle;
  12360. startAngle = normalizeRadian(endAngle);
  12361. endAngle = normalizeRadian(tmp);
  12362. }
  12363. else {
  12364. startAngle = normalizeRadian(startAngle);
  12365. endAngle = normalizeRadian(endAngle);
  12366. }
  12367. if (startAngle > endAngle) {
  12368. endAngle += PI2$2;
  12369. }
  12370. var angle = Math.atan2(y, x);
  12371. if (angle < 0) {
  12372. angle += PI2$2;
  12373. }
  12374. return (angle >= startAngle && angle <= endAngle)
  12375. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12376. }
  12377. function windingLine(x0, y0, x1, y1, x, y) {
  12378. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12379. return 0;
  12380. }
  12381. // Ignore horizontal line
  12382. if (y1 === y0) {
  12383. return 0;
  12384. }
  12385. var dir = y1 < y0 ? 1 : -1;
  12386. var t = (y - y0) / (y1 - y0);
  12387. // Avoid winding error when intersection point is the connect point of two line of polygon
  12388. if (t === 1 || t === 0) {
  12389. dir = y1 < y0 ? 0.5 : -0.5;
  12390. }
  12391. var x_ = t * (x1 - x0) + x0;
  12392. // If (x, y) on the line, considered as "contain".
  12393. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12394. }
  12395. var CMD$1 = PathProxy.CMD;
  12396. var PI2$1 = Math.PI * 2;
  12397. var EPSILON$2 = 1e-4;
  12398. function isAroundEqual(a, b) {
  12399. return Math.abs(a - b) < EPSILON$2;
  12400. }
  12401. // 临时数组
  12402. var roots = [-1, -1, -1];
  12403. var extrema = [-1, -1];
  12404. function swapExtrema() {
  12405. var tmp = extrema[0];
  12406. extrema[0] = extrema[1];
  12407. extrema[1] = tmp;
  12408. }
  12409. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12410. // Quick reject
  12411. if (
  12412. (y > y0 && y > y1 && y > y2 && y > y3)
  12413. || (y < y0 && y < y1 && y < y2 && y < y3)
  12414. ) {
  12415. return 0;
  12416. }
  12417. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12418. if (nRoots === 0) {
  12419. return 0;
  12420. }
  12421. else {
  12422. var w = 0;
  12423. var nExtrema = -1;
  12424. var y0_;
  12425. var y1_;
  12426. for (var i = 0; i < nRoots; i++) {
  12427. var t = roots[i];
  12428. // Avoid winding error when intersection point is the connect point of two line of polygon
  12429. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12430. var x_ = cubicAt(x0, x1, x2, x3, t);
  12431. if (x_ < x) { // Quick reject
  12432. continue;
  12433. }
  12434. if (nExtrema < 0) {
  12435. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12436. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12437. swapExtrema();
  12438. }
  12439. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12440. if (nExtrema > 1) {
  12441. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12442. }
  12443. }
  12444. if (nExtrema === 2) {
  12445. // 分成三段单调函数
  12446. if (t < extrema[0]) {
  12447. w += y0_ < y0 ? unit : -unit;
  12448. }
  12449. else if (t < extrema[1]) {
  12450. w += y1_ < y0_ ? unit : -unit;
  12451. }
  12452. else {
  12453. w += y3 < y1_ ? unit : -unit;
  12454. }
  12455. }
  12456. else {
  12457. // 分成两段单调函数
  12458. if (t < extrema[0]) {
  12459. w += y0_ < y0 ? unit : -unit;
  12460. }
  12461. else {
  12462. w += y3 < y0_ ? unit : -unit;
  12463. }
  12464. }
  12465. }
  12466. return w;
  12467. }
  12468. }
  12469. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12470. // Quick reject
  12471. if (
  12472. (y > y0 && y > y1 && y > y2)
  12473. || (y < y0 && y < y1 && y < y2)
  12474. ) {
  12475. return 0;
  12476. }
  12477. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12478. if (nRoots === 0) {
  12479. return 0;
  12480. }
  12481. else {
  12482. var t = quadraticExtremum(y0, y1, y2);
  12483. if (t >= 0 && t <= 1) {
  12484. var w = 0;
  12485. var y_ = quadraticAt(y0, y1, y2, t);
  12486. for (var i = 0; i < nRoots; i++) {
  12487. // Remove one endpoint.
  12488. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12489. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12490. if (x_ < x) { // Quick reject
  12491. continue;
  12492. }
  12493. if (roots[i] < t) {
  12494. w += y_ < y0 ? unit : -unit;
  12495. }
  12496. else {
  12497. w += y2 < y_ ? unit : -unit;
  12498. }
  12499. }
  12500. return w;
  12501. }
  12502. else {
  12503. // Remove one endpoint.
  12504. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12505. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12506. if (x_ < x) { // Quick reject
  12507. return 0;
  12508. }
  12509. return y2 < y0 ? unit : -unit;
  12510. }
  12511. }
  12512. }
  12513. // TODO
  12514. // Arc 旋转
  12515. function windingArc(
  12516. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12517. ) {
  12518. y -= cy;
  12519. if (y > r || y < -r) {
  12520. return 0;
  12521. }
  12522. var tmp = Math.sqrt(r * r - y * y);
  12523. roots[0] = -tmp;
  12524. roots[1] = tmp;
  12525. var diff = Math.abs(startAngle - endAngle);
  12526. if (diff < 1e-4) {
  12527. return 0;
  12528. }
  12529. if (diff % PI2$1 < 1e-4) {
  12530. // Is a circle
  12531. startAngle = 0;
  12532. endAngle = PI2$1;
  12533. var dir = anticlockwise ? 1 : -1;
  12534. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12535. return dir;
  12536. }
  12537. else {
  12538. return 0;
  12539. }
  12540. }
  12541. if (anticlockwise) {
  12542. var tmp = startAngle;
  12543. startAngle = normalizeRadian(endAngle);
  12544. endAngle = normalizeRadian(tmp);
  12545. }
  12546. else {
  12547. startAngle = normalizeRadian(startAngle);
  12548. endAngle = normalizeRadian(endAngle);
  12549. }
  12550. if (startAngle > endAngle) {
  12551. endAngle += PI2$1;
  12552. }
  12553. var w = 0;
  12554. for (var i = 0; i < 2; i++) {
  12555. var x_ = roots[i];
  12556. if (x_ + cx > x) {
  12557. var angle = Math.atan2(y, x_);
  12558. var dir = anticlockwise ? 1 : -1;
  12559. if (angle < 0) {
  12560. angle = PI2$1 + angle;
  12561. }
  12562. if (
  12563. (angle >= startAngle && angle <= endAngle)
  12564. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12565. ) {
  12566. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12567. dir = -dir;
  12568. }
  12569. w += dir;
  12570. }
  12571. }
  12572. }
  12573. return w;
  12574. }
  12575. function containPath(data, lineWidth, isStroke, x, y) {
  12576. var w = 0;
  12577. var xi = 0;
  12578. var yi = 0;
  12579. var x0 = 0;
  12580. var y0 = 0;
  12581. for (var i = 0; i < data.length;) {
  12582. var cmd = data[i++];
  12583. // Begin a new subpath
  12584. if (cmd === CMD$1.M && i > 1) {
  12585. // Close previous subpath
  12586. if (!isStroke) {
  12587. w += windingLine(xi, yi, x0, y0, x, y);
  12588. }
  12589. // 如果被任何一个 subpath 包含
  12590. // if (w !== 0) {
  12591. // return true;
  12592. // }
  12593. }
  12594. if (i === 1) {
  12595. // 如果第一个命令是 L, C, Q
  12596. // 则 previous point 同绘制命令的第一个 point
  12597. //
  12598. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12599. xi = data[i];
  12600. yi = data[i + 1];
  12601. x0 = xi;
  12602. y0 = yi;
  12603. }
  12604. switch (cmd) {
  12605. case CMD$1.M:
  12606. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12607. // 在 closePath 的时候使用
  12608. x0 = data[i++];
  12609. y0 = data[i++];
  12610. xi = x0;
  12611. yi = y0;
  12612. break;
  12613. case CMD$1.L:
  12614. if (isStroke) {
  12615. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12616. return true;
  12617. }
  12618. }
  12619. else {
  12620. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12621. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12622. }
  12623. xi = data[i++];
  12624. yi = data[i++];
  12625. break;
  12626. case CMD$1.C:
  12627. if (isStroke) {
  12628. if (containStroke$2(xi, yi,
  12629. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12630. lineWidth, x, y
  12631. )) {
  12632. return true;
  12633. }
  12634. }
  12635. else {
  12636. w += windingCubic(
  12637. xi, yi,
  12638. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12639. x, y
  12640. ) || 0;
  12641. }
  12642. xi = data[i++];
  12643. yi = data[i++];
  12644. break;
  12645. case CMD$1.Q:
  12646. if (isStroke) {
  12647. if (containStroke$3(xi, yi,
  12648. data[i++], data[i++], data[i], data[i + 1],
  12649. lineWidth, x, y
  12650. )) {
  12651. return true;
  12652. }
  12653. }
  12654. else {
  12655. w += windingQuadratic(
  12656. xi, yi,
  12657. data[i++], data[i++], data[i], data[i + 1],
  12658. x, y
  12659. ) || 0;
  12660. }
  12661. xi = data[i++];
  12662. yi = data[i++];
  12663. break;
  12664. case CMD$1.A:
  12665. // TODO Arc 判断的开销比较大
  12666. var cx = data[i++];
  12667. var cy = data[i++];
  12668. var rx = data[i++];
  12669. var ry = data[i++];
  12670. var theta = data[i++];
  12671. var dTheta = data[i++];
  12672. // TODO Arc 旋转
  12673. i += 1;
  12674. var anticlockwise = 1 - data[i++];
  12675. var x1 = Math.cos(theta) * rx + cx;
  12676. var y1 = Math.sin(theta) * ry + cy;
  12677. // 不是直接使用 arc 命令
  12678. if (i > 1) {
  12679. w += windingLine(xi, yi, x1, y1, x, y);
  12680. }
  12681. else {
  12682. // 第一个命令起点还未定义
  12683. x0 = x1;
  12684. y0 = y1;
  12685. }
  12686. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12687. var _x = (x - cx) * ry / rx + cx;
  12688. if (isStroke) {
  12689. if (containStroke$4(
  12690. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12691. lineWidth, _x, y
  12692. )) {
  12693. return true;
  12694. }
  12695. }
  12696. else {
  12697. w += windingArc(
  12698. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12699. _x, y
  12700. );
  12701. }
  12702. xi = Math.cos(theta + dTheta) * rx + cx;
  12703. yi = Math.sin(theta + dTheta) * ry + cy;
  12704. break;
  12705. case CMD$1.R:
  12706. x0 = xi = data[i++];
  12707. y0 = yi = data[i++];
  12708. var width = data[i++];
  12709. var height = data[i++];
  12710. var x1 = x0 + width;
  12711. var y1 = y0 + height;
  12712. if (isStroke) {
  12713. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12714. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12715. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12716. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12717. ) {
  12718. return true;
  12719. }
  12720. }
  12721. else {
  12722. // FIXME Clockwise ?
  12723. w += windingLine(x1, y0, x1, y1, x, y);
  12724. w += windingLine(x0, y1, x0, y0, x, y);
  12725. }
  12726. break;
  12727. case CMD$1.Z:
  12728. if (isStroke) {
  12729. if (containStroke$1(
  12730. xi, yi, x0, y0, lineWidth, x, y
  12731. )) {
  12732. return true;
  12733. }
  12734. }
  12735. else {
  12736. // Close a subpath
  12737. w += windingLine(xi, yi, x0, y0, x, y);
  12738. // 如果被任何一个 subpath 包含
  12739. // FIXME subpaths may overlap
  12740. // if (w !== 0) {
  12741. // return true;
  12742. // }
  12743. }
  12744. xi = x0;
  12745. yi = y0;
  12746. break;
  12747. }
  12748. }
  12749. if (!isStroke && !isAroundEqual(yi, y0)) {
  12750. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12751. }
  12752. return w !== 0;
  12753. }
  12754. function contain(pathData, x, y) {
  12755. return containPath(pathData, 0, false, x, y);
  12756. }
  12757. function containStroke(pathData, lineWidth, x, y) {
  12758. return containPath(pathData, lineWidth, true, x, y);
  12759. }
  12760. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12761. var abs = Math.abs;
  12762. var pathProxyForDraw = new PathProxy(true);
  12763. /**
  12764. * @alias module:zrender/graphic/Path
  12765. * @extends module:zrender/graphic/Displayable
  12766. * @constructor
  12767. * @param {Object} opts
  12768. */
  12769. function Path(opts) {
  12770. Displayable.call(this, opts);
  12771. /**
  12772. * @type {module:zrender/core/PathProxy}
  12773. * @readOnly
  12774. */
  12775. this.path = null;
  12776. }
  12777. Path.prototype = {
  12778. constructor: Path,
  12779. type: 'path',
  12780. __dirtyPath: true,
  12781. strokeContainThreshold: 5,
  12782. // This item default to be false. But in map series in echarts,
  12783. // in order to improve performance, it should be set to true,
  12784. // so the shorty segment won't draw.
  12785. segmentIgnoreThreshold: 0,
  12786. /**
  12787. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12788. * @type {boolean}
  12789. */
  12790. subPixelOptimize: false,
  12791. brush: function (ctx, prevEl) {
  12792. var style = this.style;
  12793. var path = this.path || pathProxyForDraw;
  12794. var hasStroke = style.hasStroke();
  12795. var hasFill = style.hasFill();
  12796. var fill = style.fill;
  12797. var stroke = style.stroke;
  12798. var hasFillGradient = hasFill && !!(fill.colorStops);
  12799. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12800. var hasFillPattern = hasFill && !!(fill.image);
  12801. var hasStrokePattern = hasStroke && !!(stroke.image);
  12802. style.bind(ctx, this, prevEl);
  12803. this.setTransform(ctx);
  12804. if (this.__dirty) {
  12805. var rect;
  12806. // Update gradient because bounding rect may changed
  12807. if (hasFillGradient) {
  12808. rect = rect || this.getBoundingRect();
  12809. this._fillGradient = style.getGradient(ctx, fill, rect);
  12810. }
  12811. if (hasStrokeGradient) {
  12812. rect = rect || this.getBoundingRect();
  12813. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12814. }
  12815. }
  12816. // Use the gradient or pattern
  12817. if (hasFillGradient) {
  12818. // PENDING If may have affect the state
  12819. ctx.fillStyle = this._fillGradient;
  12820. }
  12821. else if (hasFillPattern) {
  12822. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12823. }
  12824. if (hasStrokeGradient) {
  12825. ctx.strokeStyle = this._strokeGradient;
  12826. }
  12827. else if (hasStrokePattern) {
  12828. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12829. }
  12830. var lineDash = style.lineDash;
  12831. var lineDashOffset = style.lineDashOffset;
  12832. var ctxLineDash = !!ctx.setLineDash;
  12833. // Update path sx, sy
  12834. var scale = this.getGlobalScale();
  12835. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  12836. // Proxy context
  12837. // Rebuild path in following 2 cases
  12838. // 1. Path is dirty
  12839. // 2. Path needs javascript implemented lineDash stroking.
  12840. // In this case, lineDash information will not be saved in PathProxy
  12841. if (this.__dirtyPath
  12842. || (lineDash && !ctxLineDash && hasStroke)
  12843. ) {
  12844. path.beginPath(ctx);
  12845. // Setting line dash before build path
  12846. if (lineDash && !ctxLineDash) {
  12847. path.setLineDash(lineDash);
  12848. path.setLineDashOffset(lineDashOffset);
  12849. }
  12850. this.buildPath(path, this.shape, false);
  12851. // Clear path dirty flag
  12852. if (this.path) {
  12853. this.__dirtyPath = false;
  12854. }
  12855. }
  12856. else {
  12857. // Replay path building
  12858. ctx.beginPath();
  12859. this.path.rebuildPath(ctx);
  12860. }
  12861. if (hasFill) {
  12862. if (style.fillOpacity != null) {
  12863. var originalGlobalAlpha = ctx.globalAlpha;
  12864. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12865. path.fill(ctx);
  12866. ctx.globalAlpha = originalGlobalAlpha;
  12867. }
  12868. else {
  12869. path.fill(ctx);
  12870. }
  12871. }
  12872. if (lineDash && ctxLineDash) {
  12873. ctx.setLineDash(lineDash);
  12874. ctx.lineDashOffset = lineDashOffset;
  12875. }
  12876. if (hasStroke) {
  12877. if (style.strokeOpacity != null) {
  12878. var originalGlobalAlpha = ctx.globalAlpha;
  12879. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12880. path.stroke(ctx);
  12881. ctx.globalAlpha = originalGlobalAlpha;
  12882. }
  12883. else {
  12884. path.stroke(ctx);
  12885. }
  12886. }
  12887. if (lineDash && ctxLineDash) {
  12888. // PENDING
  12889. // Remove lineDash
  12890. ctx.setLineDash([]);
  12891. }
  12892. // Draw rect text
  12893. if (style.text != null) {
  12894. // Only restore transform when needs draw text.
  12895. this.restoreTransform(ctx);
  12896. this.drawRectText(ctx, this.getBoundingRect());
  12897. }
  12898. },
  12899. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12900. // Like in circle
  12901. buildPath: function (ctx, shapeCfg, inBundle) {},
  12902. createPathProxy: function () {
  12903. this.path = new PathProxy();
  12904. },
  12905. getBoundingRect: function () {
  12906. var rect = this._rect;
  12907. var style = this.style;
  12908. var needsUpdateRect = !rect;
  12909. if (needsUpdateRect) {
  12910. var path = this.path;
  12911. if (!path) {
  12912. // Create path on demand.
  12913. path = this.path = new PathProxy();
  12914. }
  12915. if (this.__dirtyPath) {
  12916. path.beginPath();
  12917. this.buildPath(path, this.shape, false);
  12918. }
  12919. rect = path.getBoundingRect();
  12920. }
  12921. this._rect = rect;
  12922. if (style.hasStroke()) {
  12923. // Needs update rect with stroke lineWidth when
  12924. // 1. Element changes scale or lineWidth
  12925. // 2. Shape is changed
  12926. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12927. if (this.__dirty || needsUpdateRect) {
  12928. rectWithStroke.copy(rect);
  12929. // FIXME Must after updateTransform
  12930. var w = style.lineWidth;
  12931. // PENDING, Min line width is needed when line is horizontal or vertical
  12932. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12933. // Only add extra hover lineWidth when there are no fill
  12934. if (!style.hasFill()) {
  12935. w = Math.max(w, this.strokeContainThreshold || 4);
  12936. }
  12937. // Consider line width
  12938. // Line scale can't be 0;
  12939. if (lineScale > 1e-10) {
  12940. rectWithStroke.width += w / lineScale;
  12941. rectWithStroke.height += w / lineScale;
  12942. rectWithStroke.x -= w / lineScale / 2;
  12943. rectWithStroke.y -= w / lineScale / 2;
  12944. }
  12945. }
  12946. // Return rect with stroke
  12947. return rectWithStroke;
  12948. }
  12949. return rect;
  12950. },
  12951. contain: function (x, y) {
  12952. var localPos = this.transformCoordToLocal(x, y);
  12953. var rect = this.getBoundingRect();
  12954. var style = this.style;
  12955. x = localPos[0];
  12956. y = localPos[1];
  12957. if (rect.contain(x, y)) {
  12958. var pathData = this.path.data;
  12959. if (style.hasStroke()) {
  12960. var lineWidth = style.lineWidth;
  12961. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12962. // Line scale can't be 0;
  12963. if (lineScale > 1e-10) {
  12964. // Only add extra hover lineWidth when there are no fill
  12965. if (!style.hasFill()) {
  12966. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12967. }
  12968. if (containStroke(
  12969. pathData, lineWidth / lineScale, x, y
  12970. )) {
  12971. return true;
  12972. }
  12973. }
  12974. }
  12975. if (style.hasFill()) {
  12976. return contain(pathData, x, y);
  12977. }
  12978. }
  12979. return false;
  12980. },
  12981. /**
  12982. * @param {boolean} dirtyPath
  12983. */
  12984. dirty: function (dirtyPath) {
  12985. if (dirtyPath == null) {
  12986. dirtyPath = true;
  12987. }
  12988. // Only mark dirty, not mark clean
  12989. if (dirtyPath) {
  12990. this.__dirtyPath = dirtyPath;
  12991. this._rect = null;
  12992. }
  12993. this.__dirty = this.__dirtyText = true;
  12994. this.__zr && this.__zr.refresh();
  12995. // Used as a clipping path
  12996. if (this.__clipTarget) {
  12997. this.__clipTarget.dirty();
  12998. }
  12999. },
  13000. /**
  13001. * Alias for animate('shape')
  13002. * @param {boolean} loop
  13003. */
  13004. animateShape: function (loop) {
  13005. return this.animate('shape', loop);
  13006. },
  13007. // Overwrite attrKV
  13008. attrKV: function (key, value) {
  13009. // FIXME
  13010. if (key === 'shape') {
  13011. this.setShape(value);
  13012. this.__dirtyPath = true;
  13013. this._rect = null;
  13014. }
  13015. else {
  13016. Displayable.prototype.attrKV.call(this, key, value);
  13017. }
  13018. },
  13019. /**
  13020. * @param {Object|string} key
  13021. * @param {*} value
  13022. */
  13023. setShape: function (key, value) {
  13024. var shape = this.shape;
  13025. // Path from string may not have shape
  13026. if (shape) {
  13027. if (isObject$1(key)) {
  13028. for (var name in key) {
  13029. if (key.hasOwnProperty(name)) {
  13030. shape[name] = key[name];
  13031. }
  13032. }
  13033. }
  13034. else {
  13035. shape[key] = value;
  13036. }
  13037. this.dirty(true);
  13038. }
  13039. return this;
  13040. },
  13041. getLineScale: function () {
  13042. var m = this.transform;
  13043. // Get the line scale.
  13044. // Determinant of `m` means how much the area is enlarged by the
  13045. // transformation. So its square root can be used as a scale factor
  13046. // for width.
  13047. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  13048. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  13049. : 1;
  13050. }
  13051. };
  13052. /**
  13053. * 扩展一个 Path element, 比如星形,圆等。
  13054. * Extend a path element
  13055. * @param {Object} props
  13056. * @param {string} props.type Path type
  13057. * @param {Function} props.init Initialize
  13058. * @param {Function} props.buildPath Overwrite buildPath method
  13059. * @param {Object} [props.style] Extended default style config
  13060. * @param {Object} [props.shape] Extended default shape config
  13061. */
  13062. Path.extend = function (defaults$$1) {
  13063. var Sub = function (opts) {
  13064. Path.call(this, opts);
  13065. if (defaults$$1.style) {
  13066. // Extend default style
  13067. this.style.extendFrom(defaults$$1.style, false);
  13068. }
  13069. // Extend default shape
  13070. var defaultShape = defaults$$1.shape;
  13071. if (defaultShape) {
  13072. this.shape = this.shape || {};
  13073. var thisShape = this.shape;
  13074. for (var name in defaultShape) {
  13075. if (
  13076. !thisShape.hasOwnProperty(name)
  13077. && defaultShape.hasOwnProperty(name)
  13078. ) {
  13079. thisShape[name] = defaultShape[name];
  13080. }
  13081. }
  13082. }
  13083. defaults$$1.init && defaults$$1.init.call(this, opts);
  13084. };
  13085. inherits(Sub, Path);
  13086. // FIXME 不能 extend position, rotation 等引用对象
  13087. for (var name in defaults$$1) {
  13088. // Extending prototype values and methods
  13089. if (name !== 'style' && name !== 'shape') {
  13090. Sub.prototype[name] = defaults$$1[name];
  13091. }
  13092. }
  13093. return Sub;
  13094. };
  13095. inherits(Path, Displayable);
  13096. var CMD$2 = PathProxy.CMD;
  13097. var points = [[], [], []];
  13098. var mathSqrt$3 = Math.sqrt;
  13099. var mathAtan2 = Math.atan2;
  13100. var transformPath = function (path, m) {
  13101. var data = path.data;
  13102. var cmd;
  13103. var nPoint;
  13104. var i;
  13105. var j;
  13106. var k;
  13107. var p;
  13108. var M = CMD$2.M;
  13109. var C = CMD$2.C;
  13110. var L = CMD$2.L;
  13111. var R = CMD$2.R;
  13112. var A = CMD$2.A;
  13113. var Q = CMD$2.Q;
  13114. for (i = 0, j = 0; i < data.length;) {
  13115. cmd = data[i++];
  13116. j = i;
  13117. nPoint = 0;
  13118. switch (cmd) {
  13119. case M:
  13120. nPoint = 1;
  13121. break;
  13122. case L:
  13123. nPoint = 1;
  13124. break;
  13125. case C:
  13126. nPoint = 3;
  13127. break;
  13128. case Q:
  13129. nPoint = 2;
  13130. break;
  13131. case A:
  13132. var x = m[4];
  13133. var y = m[5];
  13134. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13135. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13136. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13137. // cx
  13138. data[i] *= sx;
  13139. data[i++] += x;
  13140. // cy
  13141. data[i] *= sy;
  13142. data[i++] += y;
  13143. // Scale rx and ry
  13144. // FIXME Assume psi is 0 here
  13145. data[i++] *= sx;
  13146. data[i++] *= sy;
  13147. // Start angle
  13148. data[i++] += angle;
  13149. // end angle
  13150. data[i++] += angle;
  13151. // FIXME psi
  13152. i += 2;
  13153. j = i;
  13154. break;
  13155. case R:
  13156. // x0, y0
  13157. p[0] = data[i++];
  13158. p[1] = data[i++];
  13159. applyTransform(p, p, m);
  13160. data[j++] = p[0];
  13161. data[j++] = p[1];
  13162. // x1, y1
  13163. p[0] += data[i++];
  13164. p[1] += data[i++];
  13165. applyTransform(p, p, m);
  13166. data[j++] = p[0];
  13167. data[j++] = p[1];
  13168. }
  13169. for (k = 0; k < nPoint; k++) {
  13170. var p = points[k];
  13171. p[0] = data[i++];
  13172. p[1] = data[i++];
  13173. applyTransform(p, p, m);
  13174. // Write back
  13175. data[j++] = p[0];
  13176. data[j++] = p[1];
  13177. }
  13178. }
  13179. };
  13180. // command chars
  13181. // var cc = [
  13182. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13183. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13184. // ];
  13185. var mathSqrt = Math.sqrt;
  13186. var mathSin = Math.sin;
  13187. var mathCos = Math.cos;
  13188. var PI = Math.PI;
  13189. var vMag = function (v) {
  13190. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13191. };
  13192. var vRatio = function (u, v) {
  13193. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13194. };
  13195. var vAngle = function (u, v) {
  13196. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13197. * Math.acos(vRatio(u, v));
  13198. };
  13199. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13200. var psi = psiDeg * (PI / 180.0);
  13201. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13202. + mathSin(psi) * (y1 - y2) / 2.0;
  13203. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13204. + mathCos(psi) * (y1 - y2) / 2.0;
  13205. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13206. if (lambda > 1) {
  13207. rx *= mathSqrt(lambda);
  13208. ry *= mathSqrt(lambda);
  13209. }
  13210. var f = (fa === fs ? -1 : 1)
  13211. * mathSqrt((((rx * rx) * (ry * ry))
  13212. - ((rx * rx) * (yp * yp))
  13213. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13214. + (ry * ry) * (xp * xp))
  13215. ) || 0;
  13216. var cxp = f * rx * yp / ry;
  13217. var cyp = f * -ry * xp / rx;
  13218. var cx = (x1 + x2) / 2.0
  13219. + mathCos(psi) * cxp
  13220. - mathSin(psi) * cyp;
  13221. var cy = (y1 + y2) / 2.0
  13222. + mathSin(psi) * cxp
  13223. + mathCos(psi) * cyp;
  13224. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13225. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13226. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13227. var dTheta = vAngle(u, v);
  13228. if (vRatio(u, v) <= -1) {
  13229. dTheta = PI;
  13230. }
  13231. if (vRatio(u, v) >= 1) {
  13232. dTheta = 0;
  13233. }
  13234. if (fs === 0 && dTheta > 0) {
  13235. dTheta = dTheta - 2 * PI;
  13236. }
  13237. if (fs === 1 && dTheta < 0) {
  13238. dTheta = dTheta + 2 * PI;
  13239. }
  13240. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13241. }
  13242. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13243. // Consider case:
  13244. // (1) delimiter can be comma or space, where continuous commas
  13245. // or spaces should be seen as one comma.
  13246. // (2) value can be like:
  13247. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13248. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13249. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13250. // var valueSplitReg = /[\s,]+/;
  13251. function createPathProxyFromString(data) {
  13252. if (!data) {
  13253. return new PathProxy();
  13254. }
  13255. // var data = data.replace(/-/g, ' -')
  13256. // .replace(/ /g, ' ')
  13257. // .replace(/ /g, ',')
  13258. // .replace(/,,/g, ',');
  13259. // var n;
  13260. // create pipes so that we can split the data
  13261. // for (n = 0; n < cc.length; n++) {
  13262. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13263. // }
  13264. // data = data.replace(/-/g, ',-');
  13265. // create array
  13266. // var arr = cs.split('|');
  13267. // init context point
  13268. var cpx = 0;
  13269. var cpy = 0;
  13270. var subpathX = cpx;
  13271. var subpathY = cpy;
  13272. var prevCmd;
  13273. var path = new PathProxy();
  13274. var CMD = PathProxy.CMD;
  13275. // commandReg.lastIndex = 0;
  13276. // var cmdResult;
  13277. // while ((cmdResult = commandReg.exec(data)) != null) {
  13278. // var cmdStr = cmdResult[1];
  13279. // var cmdContent = cmdResult[2];
  13280. var cmdList = data.match(commandReg);
  13281. for (var l = 0; l < cmdList.length; l++) {
  13282. var cmdText = cmdList[l];
  13283. var cmdStr = cmdText.charAt(0);
  13284. var cmd;
  13285. // String#split is faster a little bit than String#replace or RegExp#exec.
  13286. // var p = cmdContent.split(valueSplitReg);
  13287. // var pLen = 0;
  13288. // for (var i = 0; i < p.length; i++) {
  13289. // // '' and other invalid str => NaN
  13290. // var val = parseFloat(p[i]);
  13291. // !isNaN(val) && (p[pLen++] = val);
  13292. // }
  13293. var p = cmdText.match(numberReg) || [];
  13294. var pLen = p.length;
  13295. for (var i = 0; i < pLen; i++) {
  13296. p[i] = parseFloat(p[i]);
  13297. }
  13298. var off = 0;
  13299. while (off < pLen) {
  13300. var ctlPtx;
  13301. var ctlPty;
  13302. var rx;
  13303. var ry;
  13304. var psi;
  13305. var fa;
  13306. var fs;
  13307. var x1 = cpx;
  13308. var y1 = cpy;
  13309. // convert l, H, h, V, and v to L
  13310. switch (cmdStr) {
  13311. case 'l':
  13312. cpx += p[off++];
  13313. cpy += p[off++];
  13314. cmd = CMD.L;
  13315. path.addData(cmd, cpx, cpy);
  13316. break;
  13317. case 'L':
  13318. cpx = p[off++];
  13319. cpy = p[off++];
  13320. cmd = CMD.L;
  13321. path.addData(cmd, cpx, cpy);
  13322. break;
  13323. case 'm':
  13324. cpx += p[off++];
  13325. cpy += p[off++];
  13326. cmd = CMD.M;
  13327. path.addData(cmd, cpx, cpy);
  13328. subpathX = cpx;
  13329. subpathY = cpy;
  13330. cmdStr = 'l';
  13331. break;
  13332. case 'M':
  13333. cpx = p[off++];
  13334. cpy = p[off++];
  13335. cmd = CMD.M;
  13336. path.addData(cmd, cpx, cpy);
  13337. subpathX = cpx;
  13338. subpathY = cpy;
  13339. cmdStr = 'L';
  13340. break;
  13341. case 'h':
  13342. cpx += p[off++];
  13343. cmd = CMD.L;
  13344. path.addData(cmd, cpx, cpy);
  13345. break;
  13346. case 'H':
  13347. cpx = p[off++];
  13348. cmd = CMD.L;
  13349. path.addData(cmd, cpx, cpy);
  13350. break;
  13351. case 'v':
  13352. cpy += p[off++];
  13353. cmd = CMD.L;
  13354. path.addData(cmd, cpx, cpy);
  13355. break;
  13356. case 'V':
  13357. cpy = p[off++];
  13358. cmd = CMD.L;
  13359. path.addData(cmd, cpx, cpy);
  13360. break;
  13361. case 'C':
  13362. cmd = CMD.C;
  13363. path.addData(
  13364. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13365. );
  13366. cpx = p[off - 2];
  13367. cpy = p[off - 1];
  13368. break;
  13369. case 'c':
  13370. cmd = CMD.C;
  13371. path.addData(
  13372. cmd,
  13373. p[off++] + cpx, p[off++] + cpy,
  13374. p[off++] + cpx, p[off++] + cpy,
  13375. p[off++] + cpx, p[off++] + cpy
  13376. );
  13377. cpx += p[off - 2];
  13378. cpy += p[off - 1];
  13379. break;
  13380. case 'S':
  13381. ctlPtx = cpx;
  13382. ctlPty = cpy;
  13383. var len = path.len();
  13384. var pathData = path.data;
  13385. if (prevCmd === CMD.C) {
  13386. ctlPtx += cpx - pathData[len - 4];
  13387. ctlPty += cpy - pathData[len - 3];
  13388. }
  13389. cmd = CMD.C;
  13390. x1 = p[off++];
  13391. y1 = p[off++];
  13392. cpx = p[off++];
  13393. cpy = p[off++];
  13394. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13395. break;
  13396. case 's':
  13397. ctlPtx = cpx;
  13398. ctlPty = cpy;
  13399. var len = path.len();
  13400. var pathData = path.data;
  13401. if (prevCmd === CMD.C) {
  13402. ctlPtx += cpx - pathData[len - 4];
  13403. ctlPty += cpy - pathData[len - 3];
  13404. }
  13405. cmd = CMD.C;
  13406. x1 = cpx + p[off++];
  13407. y1 = cpy + p[off++];
  13408. cpx += p[off++];
  13409. cpy += p[off++];
  13410. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13411. break;
  13412. case 'Q':
  13413. x1 = p[off++];
  13414. y1 = p[off++];
  13415. cpx = p[off++];
  13416. cpy = p[off++];
  13417. cmd = CMD.Q;
  13418. path.addData(cmd, x1, y1, cpx, cpy);
  13419. break;
  13420. case 'q':
  13421. x1 = p[off++] + cpx;
  13422. y1 = p[off++] + cpy;
  13423. cpx += p[off++];
  13424. cpy += p[off++];
  13425. cmd = CMD.Q;
  13426. path.addData(cmd, x1, y1, cpx, cpy);
  13427. break;
  13428. case 'T':
  13429. ctlPtx = cpx;
  13430. ctlPty = cpy;
  13431. var len = path.len();
  13432. var pathData = path.data;
  13433. if (prevCmd === CMD.Q) {
  13434. ctlPtx += cpx - pathData[len - 4];
  13435. ctlPty += cpy - pathData[len - 3];
  13436. }
  13437. cpx = p[off++];
  13438. cpy = p[off++];
  13439. cmd = CMD.Q;
  13440. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13441. break;
  13442. case 't':
  13443. ctlPtx = cpx;
  13444. ctlPty = cpy;
  13445. var len = path.len();
  13446. var pathData = path.data;
  13447. if (prevCmd === CMD.Q) {
  13448. ctlPtx += cpx - pathData[len - 4];
  13449. ctlPty += cpy - pathData[len - 3];
  13450. }
  13451. cpx += p[off++];
  13452. cpy += p[off++];
  13453. cmd = CMD.Q;
  13454. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13455. break;
  13456. case 'A':
  13457. rx = p[off++];
  13458. ry = p[off++];
  13459. psi = p[off++];
  13460. fa = p[off++];
  13461. fs = p[off++];
  13462. x1 = cpx, y1 = cpy;
  13463. cpx = p[off++];
  13464. cpy = p[off++];
  13465. cmd = CMD.A;
  13466. processArc(
  13467. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13468. );
  13469. break;
  13470. case 'a':
  13471. rx = p[off++];
  13472. ry = p[off++];
  13473. psi = p[off++];
  13474. fa = p[off++];
  13475. fs = p[off++];
  13476. x1 = cpx, y1 = cpy;
  13477. cpx += p[off++];
  13478. cpy += p[off++];
  13479. cmd = CMD.A;
  13480. processArc(
  13481. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13482. );
  13483. break;
  13484. }
  13485. }
  13486. if (cmdStr === 'z' || cmdStr === 'Z') {
  13487. cmd = CMD.Z;
  13488. path.addData(cmd);
  13489. // z may be in the middle of the path.
  13490. cpx = subpathX;
  13491. cpy = subpathY;
  13492. }
  13493. prevCmd = cmd;
  13494. }
  13495. path.toStatic();
  13496. return path;
  13497. }
  13498. // TODO Optimize double memory cost problem
  13499. function createPathOptions(str, opts) {
  13500. var pathProxy = createPathProxyFromString(str);
  13501. opts = opts || {};
  13502. opts.buildPath = function (path) {
  13503. if (path.setData) {
  13504. path.setData(pathProxy.data);
  13505. // Svg and vml renderer don't have context
  13506. var ctx = path.getContext();
  13507. if (ctx) {
  13508. path.rebuildPath(ctx);
  13509. }
  13510. }
  13511. else {
  13512. var ctx = path;
  13513. pathProxy.rebuildPath(ctx);
  13514. }
  13515. };
  13516. opts.applyTransform = function (m) {
  13517. transformPath(pathProxy, m);
  13518. this.dirty(true);
  13519. };
  13520. return opts;
  13521. }
  13522. /**
  13523. * Create a Path object from path string data
  13524. * http://www.w3.org/TR/SVG/paths.html#PathData
  13525. * @param {Object} opts Other options
  13526. */
  13527. function createFromString(str, opts) {
  13528. return new Path(createPathOptions(str, opts));
  13529. }
  13530. /**
  13531. * Create a Path class from path string data
  13532. * @param {string} str
  13533. * @param {Object} opts Other options
  13534. */
  13535. function extendFromString(str, opts) {
  13536. return Path.extend(createPathOptions(str, opts));
  13537. }
  13538. /**
  13539. * Merge multiple paths
  13540. */
  13541. // TODO Apply transform
  13542. // TODO stroke dash
  13543. // TODO Optimize double memory cost problem
  13544. function mergePath$1(pathEls, opts) {
  13545. var pathList = [];
  13546. var len = pathEls.length;
  13547. for (var i = 0; i < len; i++) {
  13548. var pathEl = pathEls[i];
  13549. if (!pathEl.path) {
  13550. pathEl.createPathProxy();
  13551. }
  13552. if (pathEl.__dirtyPath) {
  13553. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13554. }
  13555. pathList.push(pathEl.path);
  13556. }
  13557. var pathBundle = new Path(opts);
  13558. // Need path proxy.
  13559. pathBundle.createPathProxy();
  13560. pathBundle.buildPath = function (path) {
  13561. path.appendPath(pathList);
  13562. // Svg and vml renderer don't have context
  13563. var ctx = path.getContext();
  13564. if (ctx) {
  13565. path.rebuildPath(ctx);
  13566. }
  13567. };
  13568. return pathBundle;
  13569. }
  13570. /**
  13571. * @alias zrender/graphic/Text
  13572. * @extends module:zrender/graphic/Displayable
  13573. * @constructor
  13574. * @param {Object} opts
  13575. */
  13576. var Text = function (opts) { // jshint ignore:line
  13577. Displayable.call(this, opts);
  13578. };
  13579. Text.prototype = {
  13580. constructor: Text,
  13581. type: 'text',
  13582. brush: function (ctx, prevEl) {
  13583. var style = this.style;
  13584. // Optimize, avoid normalize every time.
  13585. this.__dirty && normalizeTextStyle(style, true);
  13586. // Use props with prefix 'text'.
  13587. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13588. style.shadowOffsetX = style.shadowOffsetY = null;
  13589. var text = style.text;
  13590. // Convert to string
  13591. text != null && (text += '');
  13592. // Do not apply style.bind in Text node. Because the real bind job
  13593. // is in textHelper.renderText, and performance of text render should
  13594. // be considered.
  13595. // style.bind(ctx, this, prevEl);
  13596. if (!needDrawText(text, style)) {
  13597. // The current el.style is not applied
  13598. // and should not be used as cache.
  13599. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13600. return;
  13601. }
  13602. this.setTransform(ctx);
  13603. renderText(this, ctx, text, style, null, prevEl);
  13604. this.restoreTransform(ctx);
  13605. },
  13606. getBoundingRect: function () {
  13607. var style = this.style;
  13608. // Optimize, avoid normalize every time.
  13609. this.__dirty && normalizeTextStyle(style, true);
  13610. if (!this._rect) {
  13611. var text = style.text;
  13612. text != null ? (text += '') : (text = '');
  13613. var rect = getBoundingRect(
  13614. style.text + '',
  13615. style.font,
  13616. style.textAlign,
  13617. style.textVerticalAlign,
  13618. style.textPadding,
  13619. style.textLineHeight,
  13620. style.rich
  13621. );
  13622. rect.x += style.x || 0;
  13623. rect.y += style.y || 0;
  13624. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13625. var w = style.textStrokeWidth;
  13626. rect.x -= w / 2;
  13627. rect.y -= w / 2;
  13628. rect.width += w;
  13629. rect.height += w;
  13630. }
  13631. this._rect = rect;
  13632. }
  13633. return this._rect;
  13634. }
  13635. };
  13636. inherits(Text, Displayable);
  13637. /**
  13638. * 圆形
  13639. * @module zrender/shape/Circle
  13640. */
  13641. var Circle = Path.extend({
  13642. type: 'circle',
  13643. shape: {
  13644. cx: 0,
  13645. cy: 0,
  13646. r: 0
  13647. },
  13648. buildPath: function (ctx, shape, inBundle) {
  13649. // Better stroking in ShapeBundle
  13650. // Always do it may have performence issue ( fill may be 2x more cost)
  13651. if (inBundle) {
  13652. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13653. }
  13654. // else {
  13655. // if (ctx.allocate && !ctx.data.length) {
  13656. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13657. // }
  13658. // }
  13659. // Better stroking in ShapeBundle
  13660. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13661. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13662. }
  13663. });
  13664. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13665. // where exception "unexpected call to method or property access"
  13666. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13667. // whose area size is zero is drawn and ctx.clip() is called and
  13668. // shadowBlur is set. See #4572, #3112, #5777.
  13669. // (e.g.,
  13670. // ctx.moveTo(10, 10);
  13671. // ctx.lineTo(20, 10);
  13672. // ctx.closePath();
  13673. // ctx.clip();
  13674. // ctx.shadowBlur = 10;
  13675. // ...
  13676. // ctx.fill();
  13677. // )
  13678. var shadowTemp = [
  13679. ['shadowBlur', 0],
  13680. ['shadowColor', '#000'],
  13681. ['shadowOffsetX', 0],
  13682. ['shadowOffsetY', 0]
  13683. ];
  13684. var fixClipWithShadow = function (orignalBrush) {
  13685. // version string can be: '11.0'
  13686. return (env$1.browser.ie && env$1.browser.version >= 11)
  13687. ? function () {
  13688. var clipPaths = this.__clipPaths;
  13689. var style = this.style;
  13690. var modified;
  13691. if (clipPaths) {
  13692. for (var i = 0; i < clipPaths.length; i++) {
  13693. var clipPath = clipPaths[i];
  13694. var shape = clipPath && clipPath.shape;
  13695. var type = clipPath && clipPath.type;
  13696. if (shape && (
  13697. (type === 'sector' && shape.startAngle === shape.endAngle)
  13698. || (type === 'rect' && (!shape.width || !shape.height))
  13699. )) {
  13700. for (var j = 0; j < shadowTemp.length; j++) {
  13701. // It is save to put shadowTemp static, because shadowTemp
  13702. // will be all modified each item brush called.
  13703. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13704. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13705. }
  13706. modified = true;
  13707. break;
  13708. }
  13709. }
  13710. }
  13711. orignalBrush.apply(this, arguments);
  13712. if (modified) {
  13713. for (var j = 0; j < shadowTemp.length; j++) {
  13714. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13715. }
  13716. }
  13717. }
  13718. : orignalBrush;
  13719. };
  13720. /**
  13721. * 扇形
  13722. * @module zrender/graphic/shape/Sector
  13723. */
  13724. var Sector = Path.extend({
  13725. type: 'sector',
  13726. shape: {
  13727. cx: 0,
  13728. cy: 0,
  13729. r0: 0,
  13730. r: 0,
  13731. startAngle: 0,
  13732. endAngle: Math.PI * 2,
  13733. clockwise: true
  13734. },
  13735. brush: fixClipWithShadow(Path.prototype.brush),
  13736. buildPath: function (ctx, shape) {
  13737. var x = shape.cx;
  13738. var y = shape.cy;
  13739. var r0 = Math.max(shape.r0 || 0, 0);
  13740. var r = Math.max(shape.r, 0);
  13741. var startAngle = shape.startAngle;
  13742. var endAngle = shape.endAngle;
  13743. var clockwise = shape.clockwise;
  13744. var unitX = Math.cos(startAngle);
  13745. var unitY = Math.sin(startAngle);
  13746. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13747. ctx.lineTo(unitX * r + x, unitY * r + y);
  13748. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13749. ctx.lineTo(
  13750. Math.cos(endAngle) * r0 + x,
  13751. Math.sin(endAngle) * r0 + y
  13752. );
  13753. if (r0 !== 0) {
  13754. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13755. }
  13756. ctx.closePath();
  13757. }
  13758. });
  13759. /**
  13760. * 圆环
  13761. * @module zrender/graphic/shape/Ring
  13762. */
  13763. var Ring = Path.extend({
  13764. type: 'ring',
  13765. shape: {
  13766. cx: 0,
  13767. cy: 0,
  13768. r: 0,
  13769. r0: 0
  13770. },
  13771. buildPath: function (ctx, shape) {
  13772. var x = shape.cx;
  13773. var y = shape.cy;
  13774. var PI2 = Math.PI * 2;
  13775. ctx.moveTo(x + shape.r, y);
  13776. ctx.arc(x, y, shape.r, 0, PI2, false);
  13777. ctx.moveTo(x + shape.r0, y);
  13778. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13779. }
  13780. });
  13781. /**
  13782. * Catmull-Rom spline 插值折线
  13783. * @module zrender/shape/util/smoothSpline
  13784. * @author pissang (https://www.github.com/pissang)
  13785. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13786. * errorrik (errorrik@gmail.com)
  13787. */
  13788. /**
  13789. * @inner
  13790. */
  13791. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13792. var v0 = (p2 - p0) * 0.5;
  13793. var v1 = (p3 - p1) * 0.5;
  13794. return (2 * (p1 - p2) + v0 + v1) * t3
  13795. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13796. + v0 * t + p1;
  13797. }
  13798. /**
  13799. * @alias module:zrender/shape/util/smoothSpline
  13800. * @param {Array} points 线段顶点数组
  13801. * @param {boolean} isLoop
  13802. * @return {Array}
  13803. */
  13804. var smoothSpline = function (points, isLoop) {
  13805. var len$$1 = points.length;
  13806. var ret = [];
  13807. var distance$$1 = 0;
  13808. for (var i = 1; i < len$$1; i++) {
  13809. distance$$1 += distance(points[i - 1], points[i]);
  13810. }
  13811. var segs = distance$$1 / 2;
  13812. segs = segs < len$$1 ? len$$1 : segs;
  13813. for (var i = 0; i < segs; i++) {
  13814. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13815. var idx = Math.floor(pos);
  13816. var w = pos - idx;
  13817. var p0;
  13818. var p1 = points[idx % len$$1];
  13819. var p2;
  13820. var p3;
  13821. if (!isLoop) {
  13822. p0 = points[idx === 0 ? idx : idx - 1];
  13823. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13824. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13825. }
  13826. else {
  13827. p0 = points[(idx - 1 + len$$1) % len$$1];
  13828. p2 = points[(idx + 1) % len$$1];
  13829. p3 = points[(idx + 2) % len$$1];
  13830. }
  13831. var w2 = w * w;
  13832. var w3 = w * w2;
  13833. ret.push([
  13834. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13835. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13836. ]);
  13837. }
  13838. return ret;
  13839. };
  13840. /**
  13841. * 贝塞尔平滑曲线
  13842. * @module zrender/shape/util/smoothBezier
  13843. * @author pissang (https://www.github.com/pissang)
  13844. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13845. * errorrik (errorrik@gmail.com)
  13846. */
  13847. /**
  13848. * 贝塞尔平滑曲线
  13849. * @alias module:zrender/shape/util/smoothBezier
  13850. * @param {Array} points 线段顶点数组
  13851. * @param {number} smooth 平滑等级, 0-1
  13852. * @param {boolean} isLoop
  13853. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13854. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13855. * 整个折线的包围盒做一个并集用来约束控制点。
  13856. * @param {Array} 计算出来的控制点数组
  13857. */
  13858. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13859. var cps = [];
  13860. var v = [];
  13861. var v1 = [];
  13862. var v2 = [];
  13863. var prevPoint;
  13864. var nextPoint;
  13865. var min$$1;
  13866. var max$$1;
  13867. if (constraint) {
  13868. min$$1 = [Infinity, Infinity];
  13869. max$$1 = [-Infinity, -Infinity];
  13870. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13871. min(min$$1, min$$1, points[i]);
  13872. max(max$$1, max$$1, points[i]);
  13873. }
  13874. // 与指定的包围盒做并集
  13875. min(min$$1, min$$1, constraint[0]);
  13876. max(max$$1, max$$1, constraint[1]);
  13877. }
  13878. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13879. var point = points[i];
  13880. if (isLoop) {
  13881. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13882. nextPoint = points[(i + 1) % len$$1];
  13883. }
  13884. else {
  13885. if (i === 0 || i === len$$1 - 1) {
  13886. cps.push(clone$1(points[i]));
  13887. continue;
  13888. }
  13889. else {
  13890. prevPoint = points[i - 1];
  13891. nextPoint = points[i + 1];
  13892. }
  13893. }
  13894. sub(v, nextPoint, prevPoint);
  13895. // use degree to scale the handle length
  13896. scale(v, v, smooth);
  13897. var d0 = distance(point, prevPoint);
  13898. var d1 = distance(point, nextPoint);
  13899. var sum = d0 + d1;
  13900. if (sum !== 0) {
  13901. d0 /= sum;
  13902. d1 /= sum;
  13903. }
  13904. scale(v1, v, -d0);
  13905. scale(v2, v, d1);
  13906. var cp0 = add([], point, v1);
  13907. var cp1 = add([], point, v2);
  13908. if (constraint) {
  13909. max(cp0, cp0, min$$1);
  13910. min(cp0, cp0, max$$1);
  13911. max(cp1, cp1, min$$1);
  13912. min(cp1, cp1, max$$1);
  13913. }
  13914. cps.push(cp0);
  13915. cps.push(cp1);
  13916. }
  13917. if (isLoop) {
  13918. cps.push(cps.shift());
  13919. }
  13920. return cps;
  13921. };
  13922. function buildPath$1(ctx, shape, closePath) {
  13923. var points = shape.points;
  13924. var smooth = shape.smooth;
  13925. if (points && points.length >= 2) {
  13926. if (smooth && smooth !== 'spline') {
  13927. var controlPoints = smoothBezier(
  13928. points, smooth, closePath, shape.smoothConstraint
  13929. );
  13930. ctx.moveTo(points[0][0], points[0][1]);
  13931. var len = points.length;
  13932. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13933. var cp1 = controlPoints[i * 2];
  13934. var cp2 = controlPoints[i * 2 + 1];
  13935. var p = points[(i + 1) % len];
  13936. ctx.bezierCurveTo(
  13937. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13938. );
  13939. }
  13940. }
  13941. else {
  13942. if (smooth === 'spline') {
  13943. points = smoothSpline(points, closePath);
  13944. }
  13945. ctx.moveTo(points[0][0], points[0][1]);
  13946. for (var i = 1, l = points.length; i < l; i++) {
  13947. ctx.lineTo(points[i][0], points[i][1]);
  13948. }
  13949. }
  13950. closePath && ctx.closePath();
  13951. }
  13952. }
  13953. /**
  13954. * 多边形
  13955. * @module zrender/shape/Polygon
  13956. */
  13957. var Polygon = Path.extend({
  13958. type: 'polygon',
  13959. shape: {
  13960. points: null,
  13961. smooth: false,
  13962. smoothConstraint: null
  13963. },
  13964. buildPath: function (ctx, shape) {
  13965. buildPath$1(ctx, shape, true);
  13966. }
  13967. });
  13968. /**
  13969. * @module zrender/graphic/shape/Polyline
  13970. */
  13971. var Polyline = Path.extend({
  13972. type: 'polyline',
  13973. shape: {
  13974. points: null,
  13975. smooth: false,
  13976. smoothConstraint: null
  13977. },
  13978. style: {
  13979. stroke: '#000',
  13980. fill: null
  13981. },
  13982. buildPath: function (ctx, shape) {
  13983. buildPath$1(ctx, shape, false);
  13984. }
  13985. });
  13986. /**
  13987. * Sub-pixel optimize for canvas rendering, prevent from blur
  13988. * when rendering a thin vertical/horizontal line.
  13989. */
  13990. var round = Math.round;
  13991. /**
  13992. * Sub pixel optimize line for canvas
  13993. *
  13994. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13995. * `outputShape` and `inputShape` can be the same object.
  13996. * `outputShape` object can be used repeatly, because all of
  13997. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13998. * @param {Object} [inputShape]
  13999. * @param {number} [inputShape.x1]
  14000. * @param {number} [inputShape.y1]
  14001. * @param {number} [inputShape.x2]
  14002. * @param {number} [inputShape.y2]
  14003. * @param {Object} [style]
  14004. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14005. */
  14006. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  14007. if (!inputShape) {
  14008. return;
  14009. }
  14010. var x1 = inputShape.x1;
  14011. var x2 = inputShape.x2;
  14012. var y1 = inputShape.y1;
  14013. var y2 = inputShape.y2;
  14014. outputShape.x1 = x1;
  14015. outputShape.x2 = x2;
  14016. outputShape.y1 = y1;
  14017. outputShape.y2 = y2;
  14018. var lineWidth = style && style.lineWidth;
  14019. if (!lineWidth) {
  14020. return;
  14021. }
  14022. if (round(x1 * 2) === round(x2 * 2)) {
  14023. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  14024. }
  14025. if (round(y1 * 2) === round(y2 * 2)) {
  14026. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  14027. }
  14028. }
  14029. /**
  14030. * Sub pixel optimize rect for canvas
  14031. *
  14032. * @param {Object} outputShape The modification will be performed on `outputShape`.
  14033. * `outputShape` and `inputShape` can be the same object.
  14034. * `outputShape` object can be used repeatly, because all of
  14035. * the `x`, `y`, `width`, `height` will be assigned in this method.
  14036. * @param {Object} [inputShape]
  14037. * @param {number} [inputShape.x]
  14038. * @param {number} [inputShape.y]
  14039. * @param {number} [inputShape.width]
  14040. * @param {number} [inputShape.height]
  14041. * @param {Object} [style]
  14042. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  14043. */
  14044. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  14045. if (!inputShape) {
  14046. return;
  14047. }
  14048. var originX = inputShape.x;
  14049. var originY = inputShape.y;
  14050. var originWidth = inputShape.width;
  14051. var originHeight = inputShape.height;
  14052. outputShape.x = originX;
  14053. outputShape.y = originY;
  14054. outputShape.width = originWidth;
  14055. outputShape.height = originHeight;
  14056. var lineWidth = style && style.lineWidth;
  14057. if (!lineWidth) {
  14058. return;
  14059. }
  14060. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  14061. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  14062. outputShape.width = Math.max(
  14063. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  14064. originWidth === 0 ? 0 : 1
  14065. );
  14066. outputShape.height = Math.max(
  14067. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  14068. originHeight === 0 ? 0 : 1
  14069. );
  14070. }
  14071. /**
  14072. * Sub pixel optimize for canvas
  14073. *
  14074. * @param {number} position Coordinate, such as x, y
  14075. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  14076. * @param {boolean=} positiveOrNegative Default false (negative).
  14077. * @return {number} Optimized position.
  14078. */
  14079. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  14080. if (!lineWidth) {
  14081. return position;
  14082. }
  14083. // Assure that (position + lineWidth / 2) is near integer edge,
  14084. // otherwise line will be fuzzy in canvas.
  14085. var doubledPosition = round(position * 2);
  14086. return (doubledPosition + round(lineWidth)) % 2 === 0
  14087. ? doubledPosition / 2
  14088. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14089. }
  14090. /**
  14091. * 矩形
  14092. * @module zrender/graphic/shape/Rect
  14093. */
  14094. // Avoid create repeatly.
  14095. var subPixelOptimizeOutputShape = {};
  14096. var Rect = Path.extend({
  14097. type: 'rect',
  14098. shape: {
  14099. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14100. // r缩写为1 相当于 [1, 1, 1, 1]
  14101. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14102. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14103. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14104. r: 0,
  14105. x: 0,
  14106. y: 0,
  14107. width: 0,
  14108. height: 0
  14109. },
  14110. buildPath: function (ctx, shape) {
  14111. var x;
  14112. var y;
  14113. var width;
  14114. var height;
  14115. if (this.subPixelOptimize) {
  14116. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14117. x = subPixelOptimizeOutputShape.x;
  14118. y = subPixelOptimizeOutputShape.y;
  14119. width = subPixelOptimizeOutputShape.width;
  14120. height = subPixelOptimizeOutputShape.height;
  14121. subPixelOptimizeOutputShape.r = shape.r;
  14122. shape = subPixelOptimizeOutputShape;
  14123. }
  14124. else {
  14125. x = shape.x;
  14126. y = shape.y;
  14127. width = shape.width;
  14128. height = shape.height;
  14129. }
  14130. if (!shape.r) {
  14131. ctx.rect(x, y, width, height);
  14132. }
  14133. else {
  14134. buildPath(ctx, shape);
  14135. }
  14136. ctx.closePath();
  14137. return;
  14138. }
  14139. });
  14140. /**
  14141. * 直线
  14142. * @module zrender/graphic/shape/Line
  14143. */
  14144. // Avoid create repeatly.
  14145. var subPixelOptimizeOutputShape$1 = {};
  14146. var Line = Path.extend({
  14147. type: 'line',
  14148. shape: {
  14149. // Start point
  14150. x1: 0,
  14151. y1: 0,
  14152. // End point
  14153. x2: 0,
  14154. y2: 0,
  14155. percent: 1
  14156. },
  14157. style: {
  14158. stroke: '#000',
  14159. fill: null
  14160. },
  14161. buildPath: function (ctx, shape) {
  14162. var x1;
  14163. var y1;
  14164. var x2;
  14165. var y2;
  14166. if (this.subPixelOptimize) {
  14167. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14168. x1 = subPixelOptimizeOutputShape$1.x1;
  14169. y1 = subPixelOptimizeOutputShape$1.y1;
  14170. x2 = subPixelOptimizeOutputShape$1.x2;
  14171. y2 = subPixelOptimizeOutputShape$1.y2;
  14172. }
  14173. else {
  14174. x1 = shape.x1;
  14175. y1 = shape.y1;
  14176. x2 = shape.x2;
  14177. y2 = shape.y2;
  14178. }
  14179. var percent = shape.percent;
  14180. if (percent === 0) {
  14181. return;
  14182. }
  14183. ctx.moveTo(x1, y1);
  14184. if (percent < 1) {
  14185. x2 = x1 * (1 - percent) + x2 * percent;
  14186. y2 = y1 * (1 - percent) + y2 * percent;
  14187. }
  14188. ctx.lineTo(x2, y2);
  14189. },
  14190. /**
  14191. * Get point at percent
  14192. * @param {number} percent
  14193. * @return {Array.<number>}
  14194. */
  14195. pointAt: function (p) {
  14196. var shape = this.shape;
  14197. return [
  14198. shape.x1 * (1 - p) + shape.x2 * p,
  14199. shape.y1 * (1 - p) + shape.y2 * p
  14200. ];
  14201. }
  14202. });
  14203. /**
  14204. * 贝塞尔曲线
  14205. * @module zrender/shape/BezierCurve
  14206. */
  14207. var out = [];
  14208. function someVectorAt(shape, t, isTangent) {
  14209. var cpx2 = shape.cpx2;
  14210. var cpy2 = shape.cpy2;
  14211. if (cpx2 === null || cpy2 === null) {
  14212. return [
  14213. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14214. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14215. ];
  14216. }
  14217. else {
  14218. return [
  14219. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14220. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14221. ];
  14222. }
  14223. }
  14224. var BezierCurve = Path.extend({
  14225. type: 'bezier-curve',
  14226. shape: {
  14227. x1: 0,
  14228. y1: 0,
  14229. x2: 0,
  14230. y2: 0,
  14231. cpx1: 0,
  14232. cpy1: 0,
  14233. // cpx2: 0,
  14234. // cpy2: 0
  14235. // Curve show percent, for animating
  14236. percent: 1
  14237. },
  14238. style: {
  14239. stroke: '#000',
  14240. fill: null
  14241. },
  14242. buildPath: function (ctx, shape) {
  14243. var x1 = shape.x1;
  14244. var y1 = shape.y1;
  14245. var x2 = shape.x2;
  14246. var y2 = shape.y2;
  14247. var cpx1 = shape.cpx1;
  14248. var cpy1 = shape.cpy1;
  14249. var cpx2 = shape.cpx2;
  14250. var cpy2 = shape.cpy2;
  14251. var percent = shape.percent;
  14252. if (percent === 0) {
  14253. return;
  14254. }
  14255. ctx.moveTo(x1, y1);
  14256. if (cpx2 == null || cpy2 == null) {
  14257. if (percent < 1) {
  14258. quadraticSubdivide(
  14259. x1, cpx1, x2, percent, out
  14260. );
  14261. cpx1 = out[1];
  14262. x2 = out[2];
  14263. quadraticSubdivide(
  14264. y1, cpy1, y2, percent, out
  14265. );
  14266. cpy1 = out[1];
  14267. y2 = out[2];
  14268. }
  14269. ctx.quadraticCurveTo(
  14270. cpx1, cpy1,
  14271. x2, y2
  14272. );
  14273. }
  14274. else {
  14275. if (percent < 1) {
  14276. cubicSubdivide(
  14277. x1, cpx1, cpx2, x2, percent, out
  14278. );
  14279. cpx1 = out[1];
  14280. cpx2 = out[2];
  14281. x2 = out[3];
  14282. cubicSubdivide(
  14283. y1, cpy1, cpy2, y2, percent, out
  14284. );
  14285. cpy1 = out[1];
  14286. cpy2 = out[2];
  14287. y2 = out[3];
  14288. }
  14289. ctx.bezierCurveTo(
  14290. cpx1, cpy1,
  14291. cpx2, cpy2,
  14292. x2, y2
  14293. );
  14294. }
  14295. },
  14296. /**
  14297. * Get point at percent
  14298. * @param {number} t
  14299. * @return {Array.<number>}
  14300. */
  14301. pointAt: function (t) {
  14302. return someVectorAt(this.shape, t, false);
  14303. },
  14304. /**
  14305. * Get tangent at percent
  14306. * @param {number} t
  14307. * @return {Array.<number>}
  14308. */
  14309. tangentAt: function (t) {
  14310. var p = someVectorAt(this.shape, t, true);
  14311. return normalize(p, p);
  14312. }
  14313. });
  14314. /**
  14315. * 圆弧
  14316. * @module zrender/graphic/shape/Arc
  14317. */
  14318. var Arc = Path.extend({
  14319. type: 'arc',
  14320. shape: {
  14321. cx: 0,
  14322. cy: 0,
  14323. r: 0,
  14324. startAngle: 0,
  14325. endAngle: Math.PI * 2,
  14326. clockwise: true
  14327. },
  14328. style: {
  14329. stroke: '#000',
  14330. fill: null
  14331. },
  14332. buildPath: function (ctx, shape) {
  14333. var x = shape.cx;
  14334. var y = shape.cy;
  14335. var r = Math.max(shape.r, 0);
  14336. var startAngle = shape.startAngle;
  14337. var endAngle = shape.endAngle;
  14338. var clockwise = shape.clockwise;
  14339. var unitX = Math.cos(startAngle);
  14340. var unitY = Math.sin(startAngle);
  14341. ctx.moveTo(unitX * r + x, unitY * r + y);
  14342. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14343. }
  14344. });
  14345. // CompoundPath to improve performance
  14346. var CompoundPath = Path.extend({
  14347. type: 'compound',
  14348. shape: {
  14349. paths: null
  14350. },
  14351. _updatePathDirty: function () {
  14352. var dirtyPath = this.__dirtyPath;
  14353. var paths = this.shape.paths;
  14354. for (var i = 0; i < paths.length; i++) {
  14355. // Mark as dirty if any subpath is dirty
  14356. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14357. }
  14358. this.__dirtyPath = dirtyPath;
  14359. this.__dirty = this.__dirty || dirtyPath;
  14360. },
  14361. beforeBrush: function () {
  14362. this._updatePathDirty();
  14363. var paths = this.shape.paths || [];
  14364. var scale = this.getGlobalScale();
  14365. // Update path scale
  14366. for (var i = 0; i < paths.length; i++) {
  14367. if (!paths[i].path) {
  14368. paths[i].createPathProxy();
  14369. }
  14370. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14371. }
  14372. },
  14373. buildPath: function (ctx, shape) {
  14374. var paths = shape.paths || [];
  14375. for (var i = 0; i < paths.length; i++) {
  14376. paths[i].buildPath(ctx, paths[i].shape, true);
  14377. }
  14378. },
  14379. afterBrush: function () {
  14380. var paths = this.shape.paths || [];
  14381. for (var i = 0; i < paths.length; i++) {
  14382. paths[i].__dirtyPath = false;
  14383. }
  14384. },
  14385. getBoundingRect: function () {
  14386. this._updatePathDirty();
  14387. return Path.prototype.getBoundingRect.call(this);
  14388. }
  14389. });
  14390. /**
  14391. * @param {Array.<Object>} colorStops
  14392. */
  14393. var Gradient = function (colorStops) {
  14394. this.colorStops = colorStops || [];
  14395. };
  14396. Gradient.prototype = {
  14397. constructor: Gradient,
  14398. addColorStop: function (offset, color) {
  14399. this.colorStops.push({
  14400. offset: offset,
  14401. color: color
  14402. });
  14403. }
  14404. };
  14405. /**
  14406. * x, y, x2, y2 are all percent from 0 to 1
  14407. * @param {number} [x=0]
  14408. * @param {number} [y=0]
  14409. * @param {number} [x2=1]
  14410. * @param {number} [y2=0]
  14411. * @param {Array.<Object>} colorStops
  14412. * @param {boolean} [globalCoord=false]
  14413. */
  14414. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14415. // Should do nothing more in this constructor. Because gradient can be
  14416. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14417. // this constructor will not be called.
  14418. this.x = x == null ? 0 : x;
  14419. this.y = y == null ? 0 : y;
  14420. this.x2 = x2 == null ? 1 : x2;
  14421. this.y2 = y2 == null ? 0 : y2;
  14422. // Can be cloned
  14423. this.type = 'linear';
  14424. // If use global coord
  14425. this.global = globalCoord || false;
  14426. Gradient.call(this, colorStops);
  14427. };
  14428. LinearGradient.prototype = {
  14429. constructor: LinearGradient
  14430. };
  14431. inherits(LinearGradient, Gradient);
  14432. /**
  14433. * x, y, r are all percent from 0 to 1
  14434. * @param {number} [x=0.5]
  14435. * @param {number} [y=0.5]
  14436. * @param {number} [r=0.5]
  14437. * @param {Array.<Object>} [colorStops]
  14438. * @param {boolean} [globalCoord=false]
  14439. */
  14440. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14441. // Should do nothing more in this constructor. Because gradient can be
  14442. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14443. // this constructor will not be called.
  14444. this.x = x == null ? 0.5 : x;
  14445. this.y = y == null ? 0.5 : y;
  14446. this.r = r == null ? 0.5 : r;
  14447. // Can be cloned
  14448. this.type = 'radial';
  14449. // If use global coord
  14450. this.global = globalCoord || false;
  14451. Gradient.call(this, colorStops);
  14452. };
  14453. RadialGradient.prototype = {
  14454. constructor: RadialGradient
  14455. };
  14456. inherits(RadialGradient, Gradient);
  14457. /**
  14458. * Displayable for incremental rendering. It will be rendered in a separate layer
  14459. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14460. * addDisplayables will render the added displayables incremetally.
  14461. *
  14462. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14463. */
  14464. // TODO Style override ?
  14465. function IncrementalDisplayble(opts) {
  14466. Displayable.call(this, opts);
  14467. this._displayables = [];
  14468. this._temporaryDisplayables = [];
  14469. this._cursor = 0;
  14470. this.notClear = true;
  14471. }
  14472. IncrementalDisplayble.prototype.incremental = true;
  14473. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14474. this._displayables = [];
  14475. this._temporaryDisplayables = [];
  14476. this._cursor = 0;
  14477. this.dirty();
  14478. this.notClear = false;
  14479. };
  14480. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14481. if (notPersistent) {
  14482. this._temporaryDisplayables.push(displayable);
  14483. }
  14484. else {
  14485. this._displayables.push(displayable);
  14486. }
  14487. this.dirty();
  14488. };
  14489. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14490. notPersistent = notPersistent || false;
  14491. for (var i = 0; i < displayables.length; i++) {
  14492. this.addDisplayable(displayables[i], notPersistent);
  14493. }
  14494. };
  14495. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14496. for (var i = this._cursor; i < this._displayables.length; i++) {
  14497. cb && cb(this._displayables[i]);
  14498. }
  14499. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14500. cb && cb(this._temporaryDisplayables[i]);
  14501. }
  14502. };
  14503. IncrementalDisplayble.prototype.update = function () {
  14504. this.updateTransform();
  14505. for (var i = this._cursor; i < this._displayables.length; i++) {
  14506. var displayable = this._displayables[i];
  14507. // PENDING
  14508. displayable.parent = this;
  14509. displayable.update();
  14510. displayable.parent = null;
  14511. }
  14512. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14513. var displayable = this._temporaryDisplayables[i];
  14514. // PENDING
  14515. displayable.parent = this;
  14516. displayable.update();
  14517. displayable.parent = null;
  14518. }
  14519. };
  14520. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14521. // Render persistant displayables.
  14522. for (var i = this._cursor; i < this._displayables.length; i++) {
  14523. var displayable = this._displayables[i];
  14524. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14525. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14526. displayable.afterBrush && displayable.afterBrush(ctx);
  14527. }
  14528. this._cursor = i;
  14529. // Render temporary displayables.
  14530. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14531. var displayable = this._temporaryDisplayables[i];
  14532. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14533. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14534. displayable.afterBrush && displayable.afterBrush(ctx);
  14535. }
  14536. this._temporaryDisplayables = [];
  14537. this.notClear = true;
  14538. };
  14539. var m = [];
  14540. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14541. if (!this._rect) {
  14542. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14543. for (var i = 0; i < this._displayables.length; i++) {
  14544. var displayable = this._displayables[i];
  14545. var childRect = displayable.getBoundingRect().clone();
  14546. if (displayable.needLocalTransform()) {
  14547. childRect.applyTransform(displayable.getLocalTransform(m));
  14548. }
  14549. rect.union(childRect);
  14550. }
  14551. this._rect = rect;
  14552. }
  14553. return this._rect;
  14554. };
  14555. IncrementalDisplayble.prototype.contain = function (x, y) {
  14556. var localPos = this.transformCoordToLocal(x, y);
  14557. var rect = this.getBoundingRect();
  14558. if (rect.contain(localPos[0], localPos[1])) {
  14559. for (var i = 0; i < this._displayables.length; i++) {
  14560. var displayable = this._displayables[i];
  14561. if (displayable.contain(x, y)) {
  14562. return true;
  14563. }
  14564. }
  14565. }
  14566. return false;
  14567. };
  14568. inherits(IncrementalDisplayble, Displayable);
  14569. /*
  14570. * Licensed to the Apache Software Foundation (ASF) under one
  14571. * or more contributor license agreements. See the NOTICE file
  14572. * distributed with this work for additional information
  14573. * regarding copyright ownership. The ASF licenses this file
  14574. * to you under the Apache License, Version 2.0 (the
  14575. * "License"); you may not use this file except in compliance
  14576. * with the License. You may obtain a copy of the License at
  14577. *
  14578. * http://www.apache.org/licenses/LICENSE-2.0
  14579. *
  14580. * Unless required by applicable law or agreed to in writing,
  14581. * software distributed under the License is distributed on an
  14582. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14583. * KIND, either express or implied. See the License for the
  14584. * specific language governing permissions and limitations
  14585. * under the License.
  14586. */
  14587. var mathMax$1 = Math.max;
  14588. var mathMin$1 = Math.min;
  14589. var EMPTY_OBJ = {};
  14590. var Z2_EMPHASIS_LIFT = 1;
  14591. // key: label model property nane, value: style property name.
  14592. var CACHED_LABEL_STYLE_PROPERTIES = {
  14593. color: 'textFill',
  14594. textBorderColor: 'textStroke',
  14595. textBorderWidth: 'textStrokeWidth'
  14596. };
  14597. var EMPHASIS = 'emphasis';
  14598. var NORMAL = 'normal';
  14599. // Reserve 0 as default.
  14600. var _highlightNextDigit = 1;
  14601. var _highlightKeyMap = {};
  14602. var _customShapeMap = {};
  14603. /**
  14604. * Extend shape with parameters
  14605. */
  14606. function extendShape(opts) {
  14607. return Path.extend(opts);
  14608. }
  14609. /**
  14610. * Extend path
  14611. */
  14612. function extendPath(pathData, opts) {
  14613. return extendFromString(pathData, opts);
  14614. }
  14615. /**
  14616. * Register a user defined shape.
  14617. * The shape class can be fetched by `getShapeClass`
  14618. * This method will overwrite the registered shapes, including
  14619. * the registered built-in shapes, if using the same `name`.
  14620. * The shape can be used in `custom series` and
  14621. * `graphic component` by declaring `{type: name}`.
  14622. *
  14623. * @param {string} name
  14624. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14625. */
  14626. function registerShape(name, ShapeClass) {
  14627. _customShapeMap[name] = ShapeClass;
  14628. }
  14629. /**
  14630. * Find shape class registered by `registerShape`. Usually used in
  14631. * fetching user defined shape.
  14632. *
  14633. * [Caution]:
  14634. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14635. * to use user registered shapes.
  14636. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14637. * `registerShape` by default. That enables users to get both built-in
  14638. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14639. * the built-in shapes by using names like 'circle', 'rect' via calling
  14640. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14641. * in case that it is overwritten by users, except that some features, like
  14642. * `custom series`, `graphic component`, do it deliberately.
  14643. *
  14644. * (2) In the features like `custom series`, `graphic component`, the user input
  14645. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14646. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14647. * are reserved names, that is, if some user register a shape named `'image'`,
  14648. * the shape will not be used. If we intending to add some more reserved names
  14649. * in feature, that might bring break changes (disable some existing user shape
  14650. * names). But that case probably rearly happen. So we dont make more mechanism
  14651. * to resolve this issue here.
  14652. *
  14653. * @param {string} name
  14654. * @return {Object} The shape class. If not found, return nothing.
  14655. */
  14656. function getShapeClass(name) {
  14657. if (_customShapeMap.hasOwnProperty(name)) {
  14658. return _customShapeMap[name];
  14659. }
  14660. }
  14661. /**
  14662. * Create a path element from path data string
  14663. * @param {string} pathData
  14664. * @param {Object} opts
  14665. * @param {module:zrender/core/BoundingRect} rect
  14666. * @param {string} [layout=cover] 'center' or 'cover'
  14667. */
  14668. function makePath(pathData, opts, rect, layout) {
  14669. var path = createFromString(pathData, opts);
  14670. if (rect) {
  14671. if (layout === 'center') {
  14672. rect = centerGraphic(rect, path.getBoundingRect());
  14673. }
  14674. resizePath(path, rect);
  14675. }
  14676. return path;
  14677. }
  14678. /**
  14679. * Create a image element from image url
  14680. * @param {string} imageUrl image url
  14681. * @param {Object} opts options
  14682. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14683. * @param {string} [layout=cover] 'center' or 'cover'
  14684. */
  14685. function makeImage(imageUrl, rect, layout) {
  14686. var path = new ZImage({
  14687. style: {
  14688. image: imageUrl,
  14689. x: rect.x,
  14690. y: rect.y,
  14691. width: rect.width,
  14692. height: rect.height
  14693. },
  14694. onload: function (img) {
  14695. if (layout === 'center') {
  14696. var boundingRect = {
  14697. width: img.width,
  14698. height: img.height
  14699. };
  14700. path.setStyle(centerGraphic(rect, boundingRect));
  14701. }
  14702. }
  14703. });
  14704. return path;
  14705. }
  14706. /**
  14707. * Get position of centered element in bounding box.
  14708. *
  14709. * @param {Object} rect element local bounding box
  14710. * @param {Object} boundingRect constraint bounding box
  14711. * @return {Object} element position containing x, y, width, and height
  14712. */
  14713. function centerGraphic(rect, boundingRect) {
  14714. // Set rect to center, keep width / height ratio.
  14715. var aspect = boundingRect.width / boundingRect.height;
  14716. var width = rect.height * aspect;
  14717. var height;
  14718. if (width <= rect.width) {
  14719. height = rect.height;
  14720. }
  14721. else {
  14722. width = rect.width;
  14723. height = width / aspect;
  14724. }
  14725. var cx = rect.x + rect.width / 2;
  14726. var cy = rect.y + rect.height / 2;
  14727. return {
  14728. x: cx - width / 2,
  14729. y: cy - height / 2,
  14730. width: width,
  14731. height: height
  14732. };
  14733. }
  14734. var mergePath = mergePath$1;
  14735. /**
  14736. * Resize a path to fit the rect
  14737. * @param {module:zrender/graphic/Path} path
  14738. * @param {Object} rect
  14739. */
  14740. function resizePath(path, rect) {
  14741. if (!path.applyTransform) {
  14742. return;
  14743. }
  14744. var pathRect = path.getBoundingRect();
  14745. var m = pathRect.calculateTransform(rect);
  14746. path.applyTransform(m);
  14747. }
  14748. /**
  14749. * Sub pixel optimize line for canvas
  14750. *
  14751. * @param {Object} param
  14752. * @param {Object} [param.shape]
  14753. * @param {number} [param.shape.x1]
  14754. * @param {number} [param.shape.y1]
  14755. * @param {number} [param.shape.x2]
  14756. * @param {number} [param.shape.y2]
  14757. * @param {Object} [param.style]
  14758. * @param {number} [param.style.lineWidth]
  14759. * @return {Object} Modified param
  14760. */
  14761. function subPixelOptimizeLine(param) {
  14762. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  14763. return param;
  14764. }
  14765. /**
  14766. * Sub pixel optimize rect for canvas
  14767. *
  14768. * @param {Object} param
  14769. * @param {Object} [param.shape]
  14770. * @param {number} [param.shape.x]
  14771. * @param {number} [param.shape.y]
  14772. * @param {number} [param.shape.width]
  14773. * @param {number} [param.shape.height]
  14774. * @param {Object} [param.style]
  14775. * @param {number} [param.style.lineWidth]
  14776. * @return {Object} Modified param
  14777. */
  14778. function subPixelOptimizeRect(param) {
  14779. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  14780. return param;
  14781. }
  14782. /**
  14783. * Sub pixel optimize for canvas
  14784. *
  14785. * @param {number} position Coordinate, such as x, y
  14786. * @param {number} lineWidth Should be nonnegative integer.
  14787. * @param {boolean=} positiveOrNegative Default false (negative).
  14788. * @return {number} Optimized position.
  14789. */
  14790. var subPixelOptimize = subPixelOptimize$1;
  14791. function hasFillOrStroke(fillOrStroke) {
  14792. return fillOrStroke != null && fillOrStroke !== 'none';
  14793. }
  14794. // Most lifted color are duplicated.
  14795. var liftedColorMap = createHashMap();
  14796. var liftedColorCount = 0;
  14797. function liftColor(color) {
  14798. if (typeof color !== 'string') {
  14799. return color;
  14800. }
  14801. var liftedColor = liftedColorMap.get(color);
  14802. if (!liftedColor) {
  14803. liftedColor = lift(color, -0.1);
  14804. if (liftedColorCount < 10000) {
  14805. liftedColorMap.set(color, liftedColor);
  14806. liftedColorCount++;
  14807. }
  14808. }
  14809. return liftedColor;
  14810. }
  14811. function cacheElementStl(el) {
  14812. if (!el.__hoverStlDirty) {
  14813. return;
  14814. }
  14815. el.__hoverStlDirty = false;
  14816. var hoverStyle = el.__hoverStl;
  14817. if (!hoverStyle) {
  14818. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14819. return;
  14820. }
  14821. var normalStyle = el.__cachedNormalStl = {};
  14822. el.__cachedNormalZ2 = el.z2;
  14823. var elStyle = el.style;
  14824. for (var name in hoverStyle) {
  14825. // See comment in `singleEnterEmphasis`.
  14826. if (hoverStyle[name] != null) {
  14827. normalStyle[name] = elStyle[name];
  14828. }
  14829. }
  14830. // Always cache fill and stroke to normalStyle for lifting color.
  14831. normalStyle.fill = elStyle.fill;
  14832. normalStyle.stroke = elStyle.stroke;
  14833. }
  14834. function singleEnterEmphasis(el) {
  14835. var hoverStl = el.__hoverStl;
  14836. if (!hoverStl || el.__highlighted) {
  14837. return;
  14838. }
  14839. var zr = el.__zr;
  14840. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  14841. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14842. if (el.isGroup || (!zr && el.useHoverLayer)) {
  14843. return;
  14844. }
  14845. var elTarget = el;
  14846. var targetStyle = el.style;
  14847. if (useHoverLayer) {
  14848. elTarget = zr.addHover(el);
  14849. targetStyle = elTarget.style;
  14850. }
  14851. rollbackDefaultTextStyle(targetStyle);
  14852. if (!useHoverLayer) {
  14853. cacheElementStl(elTarget);
  14854. }
  14855. // styles can be:
  14856. // {
  14857. // label: {
  14858. // show: false,
  14859. // position: 'outside',
  14860. // fontSize: 18
  14861. // },
  14862. // emphasis: {
  14863. // label: {
  14864. // show: true
  14865. // }
  14866. // }
  14867. // },
  14868. // where properties of `emphasis` may not appear in `normal`. We previously use
  14869. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14870. // But consider rich text and setOption in merge mode, it is impossible to cover
  14871. // all properties in merge. So we use merge mode when setting style here.
  14872. // But we choose the merge strategy that only properties that is not `null/undefined`.
  14873. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  14874. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  14875. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  14876. // style any more in `emphasis`. Users can both set properties directly on normal and
  14877. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  14878. targetStyle.extendFrom(hoverStl);
  14879. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14880. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14881. applyDefaultTextStyle(targetStyle);
  14882. if (!useHoverLayer) {
  14883. el.dirty(false);
  14884. el.z2 += Z2_EMPHASIS_LIFT;
  14885. }
  14886. }
  14887. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14888. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14889. targetStyle[prop] = liftColor(targetStyle[prop]);
  14890. }
  14891. }
  14892. function singleEnterNormal(el) {
  14893. var highlighted = el.__highlighted;
  14894. if (!highlighted) {
  14895. return;
  14896. }
  14897. el.__highlighted = false;
  14898. if (el.isGroup) {
  14899. return;
  14900. }
  14901. if (highlighted === 'layer') {
  14902. el.__zr && el.__zr.removeHover(el);
  14903. }
  14904. else {
  14905. var style = el.style;
  14906. var normalStl = el.__cachedNormalStl;
  14907. if (normalStl) {
  14908. rollbackDefaultTextStyle(style);
  14909. el.setStyle(normalStl);
  14910. applyDefaultTextStyle(style);
  14911. }
  14912. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14913. // when `el` is on emphasis state. So here by comparing with 1, we try
  14914. // hard to make the bug case rare.
  14915. var normalZ2 = el.__cachedNormalZ2;
  14916. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14917. el.z2 = normalZ2;
  14918. }
  14919. }
  14920. }
  14921. function traverseUpdate(el, updater, commonParam) {
  14922. // If root is group, also enter updater for `highDownOnUpdate`.
  14923. var fromState = NORMAL;
  14924. var toState = NORMAL;
  14925. var trigger;
  14926. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  14927. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  14928. updater(el, commonParam);
  14929. el.__highlighted && (toState = EMPHASIS, trigger = true);
  14930. el.isGroup && el.traverse(function (child) {
  14931. !child.isGroup && updater(child, commonParam);
  14932. });
  14933. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  14934. }
  14935. /**
  14936. * Set hover style (namely "emphasis style") of element, based on the current
  14937. * style of the given `el`.
  14938. * This method should be called after all of the normal styles have been adopted
  14939. * to the `el`. See the reason on `setHoverStyle`.
  14940. *
  14941. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14942. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  14943. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  14944. * Often used when item group has a label element and it's hoverStyle is different.
  14945. * @param {Object|boolean} [hoverStl] The specified hover style.
  14946. * If set as `false`, disable the hover style.
  14947. * Similarly, The `el.hoverStyle` can alse be set
  14948. * as `false` to disable the hover style.
  14949. * Otherwise, use the default hover style if not provided.
  14950. */
  14951. function setElementHoverStyle(el, hoverStl) {
  14952. // For performance consideration, it might be better to make the "hover style" only the
  14953. // difference properties from the "normal style", but not a entire copy of all styles.
  14954. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  14955. el.__hoverStlDirty = true;
  14956. // FIXME
  14957. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14958. // It probably should be saved on `data` of series. Consider the cases:
  14959. // (1) A highlighted elements are moved out of the view port and re-enter
  14960. // again by dataZoom.
  14961. // (2) call `setOption` and replace elements totally when they are highlighted.
  14962. if (el.__highlighted) {
  14963. // Consider the case:
  14964. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14965. // should be adapted to the `el`. Notice here new "normal styles" should have
  14966. // been set outside and the cached "normal style" is out of date.
  14967. el.__cachedNormalStl = null;
  14968. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14969. // of this method. In most cases, `z2` is not set and hover style should be able
  14970. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14971. // `doSingleLeaveHover` for details.
  14972. singleEnterNormal(el);
  14973. singleEnterEmphasis(el);
  14974. }
  14975. }
  14976. function onElementMouseOver(e) {
  14977. !shouldSilent(this, e)
  14978. // "emphasis" event highlight has higher priority than mouse highlight.
  14979. && !this.__highByOuter
  14980. && traverseUpdate(this, singleEnterEmphasis);
  14981. }
  14982. function onElementMouseOut(e) {
  14983. !shouldSilent(this, e)
  14984. // "emphasis" event highlight has higher priority than mouse highlight.
  14985. && !this.__highByOuter
  14986. && traverseUpdate(this, singleEnterNormal);
  14987. }
  14988. function onElementEmphasisEvent(highlightDigit) {
  14989. this.__highByOuter |= 1 << (highlightDigit || 0);
  14990. traverseUpdate(this, singleEnterEmphasis);
  14991. }
  14992. function onElementNormalEvent(highlightDigit) {
  14993. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  14994. && traverseUpdate(this, singleEnterNormal);
  14995. }
  14996. function shouldSilent(el, e) {
  14997. return el.__highDownSilentOnTouch && e.zrByTouch;
  14998. }
  14999. /**
  15000. * Set hover style (namely "emphasis style") of element,
  15001. * based on the current style of the given `el`.
  15002. *
  15003. * (1)
  15004. * **CONSTRAINTS** for this method:
  15005. * <A> This method MUST be called after all of the normal styles having been adopted
  15006. * to the `el`.
  15007. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  15008. * "normal style" having been set to the el.
  15009. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  15010. * a default hover style).
  15011. *
  15012. * The reason: this method treat the current style of the `el` as the "normal style"
  15013. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  15014. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  15015. * logic, where the el should shift from the original emphasis style to the new
  15016. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  15017. *
  15018. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  15019. * not found a better solution yet to fit the backward compatibility, performance and
  15020. * the current programming style.
  15021. *
  15022. * (2)
  15023. * Call the method for a "root" element once. Do not call it for each descendants.
  15024. * If the descendants elemenets of a group has itself hover style different from the
  15025. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  15026. * not call this method for them.
  15027. *
  15028. * (3) These input parameters can be set directly on `el`:
  15029. *
  15030. * @param {module:zrender/Element} el
  15031. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  15032. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  15033. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  15034. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  15035. */
  15036. function setHoverStyle(el, hoverStyle) {
  15037. setAsHighDownDispatcher(el, true);
  15038. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  15039. }
  15040. /**
  15041. * @param {module:zrender/Element} el
  15042. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  15043. * Since `setHoverStyle` has the constraint that it must be called after
  15044. * all of the normal style updated, `highDownOnUpdate` is not needed to
  15045. * trigger if both `fromState` and `toState` is 'normal', and needed to
  15046. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  15047. * to sync outside style settings to "emphasis" state.
  15048. * @this {string} This dispatcher `el`.
  15049. * @param {string} fromState Can be "normal" or "emphasis".
  15050. * `fromState` might equal to `toState`,
  15051. * for example, when this method is called when `el` is
  15052. * on "emphasis" state.
  15053. * @param {string} toState Can be "normal" or "emphasis".
  15054. *
  15055. * FIXME
  15056. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  15057. * Because it is not a complete solution. The update
  15058. * listener should not have been mount in element,
  15059. * and the normal/emphasis state should not have
  15060. * mantained on elements.
  15061. *
  15062. * @param {boolean} [el.highDownSilentOnTouch=false]
  15063. * In touch device, mouseover event will be trigger on touchstart event
  15064. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  15065. * conveniently use hoverStyle when tap on touch screen without additional
  15066. * code for compatibility.
  15067. * But if the chart/component has select feature, which usually also use
  15068. * hoverStyle, there might be conflict between 'select-highlight' and
  15069. * 'hover-highlight' especially when roam is enabled (see geo for example).
  15070. * In this case, `highDownSilentOnTouch` should be used to disable
  15071. * hover-highlight on touch device.
  15072. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  15073. */
  15074. function setAsHighDownDispatcher(el, asDispatcher) {
  15075. var disable = asDispatcher === false;
  15076. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  15077. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  15078. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  15079. el.__highDownOnUpdate = el.highDownOnUpdate;
  15080. // Simple optimize, since this method might be
  15081. // called for each elements of a group in some cases.
  15082. if (!disable || el.__highDownDispatcher) {
  15083. var method = disable ? 'off' : 'on';
  15084. // Duplicated function will be auto-ignored, see Eventful.js.
  15085. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  15086. // Emphasis, normal can be triggered manually by API or other components like hover link.
  15087. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  15088. // Also keep previous record.
  15089. el.__highByOuter = el.__highByOuter || 0;
  15090. el.__highDownDispatcher = !disable;
  15091. }
  15092. }
  15093. /**
  15094. * @param {module:zrender/src/Element} el
  15095. * @return {boolean}
  15096. */
  15097. function isHighDownDispatcher(el) {
  15098. return !!(el && el.__highDownDispatcher);
  15099. }
  15100. /**
  15101. * Support hightlight/downplay record on each elements.
  15102. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15103. * user triggerred hightlight/downplay should not conflict.
  15104. * Only all of the highlightDigit cleared, return to normal.
  15105. * @param {string} highlightKey
  15106. * @return {number} highlightDigit
  15107. */
  15108. function getHighlightDigit(highlightKey) {
  15109. var highlightDigit = _highlightKeyMap[highlightKey];
  15110. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15111. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15112. }
  15113. return highlightDigit;
  15114. }
  15115. /**
  15116. * See more info in `setTextStyleCommon`.
  15117. * @param {Object|module:zrender/graphic/Style} normalStyle
  15118. * @param {Object} emphasisStyle
  15119. * @param {module:echarts/model/Model} normalModel
  15120. * @param {module:echarts/model/Model} emphasisModel
  15121. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15122. * @param {string|Function} [opt.defaultText]
  15123. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15124. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15125. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15126. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15127. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15128. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15129. * @param {Object} [normalSpecified]
  15130. * @param {Object} [emphasisSpecified]
  15131. */
  15132. function setLabelStyle(
  15133. normalStyle, emphasisStyle,
  15134. normalModel, emphasisModel,
  15135. opt,
  15136. normalSpecified, emphasisSpecified
  15137. ) {
  15138. opt = opt || EMPTY_OBJ;
  15139. var labelFetcher = opt.labelFetcher;
  15140. var labelDataIndex = opt.labelDataIndex;
  15141. var labelDimIndex = opt.labelDimIndex;
  15142. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15143. // is not supported util someone requests.
  15144. var showNormal = normalModel.getShallow('show');
  15145. var showEmphasis = emphasisModel.getShallow('show');
  15146. // Consider performance, only fetch label when necessary.
  15147. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15148. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15149. var baseText;
  15150. if (showNormal || showEmphasis) {
  15151. if (labelFetcher) {
  15152. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15153. }
  15154. if (baseText == null) {
  15155. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15156. }
  15157. }
  15158. var normalStyleText = showNormal ? baseText : null;
  15159. var emphasisStyleText = showEmphasis
  15160. ? retrieve2(
  15161. labelFetcher
  15162. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15163. : null,
  15164. baseText
  15165. )
  15166. : null;
  15167. // Optimize: If style.text is null, text will not be drawn.
  15168. if (normalStyleText != null || emphasisStyleText != null) {
  15169. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15170. // values have to be set on `normalStyle`.
  15171. // If we set default values on `emphasisStyle`, consider case:
  15172. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15173. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15174. // Then the 'red' will not work on emphasis.
  15175. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15176. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15177. }
  15178. normalStyle.text = normalStyleText;
  15179. emphasisStyle.text = emphasisStyleText;
  15180. }
  15181. /**
  15182. * Modify label style manually.
  15183. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15184. *
  15185. * @param {module:zrender/src/Element} el
  15186. * @param {Object} [normalStyleProps] optional
  15187. * @param {Object} [emphasisStyleProps] optional
  15188. */
  15189. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15190. var elStyle = el.style;
  15191. if (normalStyleProps) {
  15192. rollbackDefaultTextStyle(elStyle);
  15193. el.setStyle(normalStyleProps);
  15194. applyDefaultTextStyle(elStyle);
  15195. }
  15196. elStyle = el.__hoverStl;
  15197. if (emphasisStyleProps && elStyle) {
  15198. rollbackDefaultTextStyle(elStyle);
  15199. extend(elStyle, emphasisStyleProps);
  15200. applyDefaultTextStyle(elStyle);
  15201. }
  15202. }
  15203. /**
  15204. * Set basic textStyle properties.
  15205. * See more info in `setTextStyleCommon`.
  15206. * @param {Object|module:zrender/graphic/Style} textStyle
  15207. * @param {module:echarts/model/Model} model
  15208. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15209. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15210. * @param {boolean} [isEmphasis]
  15211. */
  15212. function setTextStyle(
  15213. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15214. ) {
  15215. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15216. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15217. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15218. return textStyle;
  15219. }
  15220. /**
  15221. * Set text option in the style.
  15222. * See more info in `setTextStyleCommon`.
  15223. * @deprecated
  15224. * @param {Object} textStyle
  15225. * @param {module:echarts/model/Model} labelModel
  15226. * @param {string|boolean} defaultColor Default text color.
  15227. * If set as false, it will be processed as a emphasis style.
  15228. */
  15229. function setText(textStyle, labelModel, defaultColor) {
  15230. var opt = {isRectText: true};
  15231. var isEmphasis;
  15232. if (defaultColor === false) {
  15233. isEmphasis = true;
  15234. }
  15235. else {
  15236. // Support setting color as 'auto' to get visual color.
  15237. opt.autoColor = defaultColor;
  15238. }
  15239. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15240. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15241. }
  15242. /**
  15243. * The uniform entry of set text style, that is, retrieve style definitions
  15244. * from `model` and set to `textStyle` object.
  15245. *
  15246. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15247. * properties will be set. (Consider the states of normal and emphasis and
  15248. * default value can be adopted, merge would make the logic too complicated
  15249. * to manage.)
  15250. *
  15251. * The `textStyle` object can either be a plain object or an instance of
  15252. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15253. * After this mothod called, the `textStyle` object can then be used in
  15254. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15255. *
  15256. * Default value will be adopted and `insideRollbackOpt` will be created.
  15257. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15258. *
  15259. * opt: {
  15260. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15261. * isRectText: boolean,
  15262. * autoColor: string, specify a color when color is 'auto',
  15263. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15264. * If autoColor specified, it is used as default textFill.
  15265. * useInsideStyle:
  15266. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15267. * if `textFill` is not specified.
  15268. * `false`: Do not use inside style.
  15269. * `null/undefined`: use inside style if `isRectText` is true and
  15270. * `textFill` is not specified and textPosition contains `'inside'`.
  15271. * forceRich: boolean
  15272. * }
  15273. */
  15274. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15275. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15276. opt = opt || EMPTY_OBJ;
  15277. if (opt.isRectText) {
  15278. var textPosition;
  15279. if (opt.getTextPosition) {
  15280. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15281. }
  15282. else {
  15283. textPosition = textStyleModel.getShallow('position')
  15284. || (isEmphasis ? null : 'inside');
  15285. // 'outside' is not a valid zr textPostion value, but used
  15286. // in bar series, and magric type should be considered.
  15287. textPosition === 'outside' && (textPosition = 'top');
  15288. }
  15289. textStyle.textPosition = textPosition;
  15290. textStyle.textOffset = textStyleModel.getShallow('offset');
  15291. var labelRotate = textStyleModel.getShallow('rotate');
  15292. labelRotate != null && (labelRotate *= Math.PI / 180);
  15293. textStyle.textRotation = labelRotate;
  15294. textStyle.textDistance = retrieve2(
  15295. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15296. );
  15297. }
  15298. var ecModel = textStyleModel.ecModel;
  15299. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15300. // Consider case:
  15301. // {
  15302. // data: [{
  15303. // value: 12,
  15304. // label: {
  15305. // rich: {
  15306. // // no 'a' here but using parent 'a'.
  15307. // }
  15308. // }
  15309. // }],
  15310. // rich: {
  15311. // a: { ... }
  15312. // }
  15313. // }
  15314. var richItemNames = getRichItemNames(textStyleModel);
  15315. var richResult;
  15316. if (richItemNames) {
  15317. richResult = {};
  15318. for (var name in richItemNames) {
  15319. if (richItemNames.hasOwnProperty(name)) {
  15320. // Cascade is supported in rich.
  15321. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15322. // In rich, never `disableBox`.
  15323. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15324. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15325. // That might confuses users. So probably we should put `textStyleModel` as the
  15326. // root ancestor of the `richTextStyle`. But that would be a break change.
  15327. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15328. }
  15329. }
  15330. }
  15331. textStyle.rich = richResult;
  15332. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15333. if (opt.forceRich && !opt.textStyle) {
  15334. opt.textStyle = {};
  15335. }
  15336. return textStyle;
  15337. }
  15338. // Consider case:
  15339. // {
  15340. // data: [{
  15341. // value: 12,
  15342. // label: {
  15343. // rich: {
  15344. // // no 'a' here but using parent 'a'.
  15345. // }
  15346. // }
  15347. // }],
  15348. // rich: {
  15349. // a: { ... }
  15350. // }
  15351. // }
  15352. function getRichItemNames(textStyleModel) {
  15353. // Use object to remove duplicated names.
  15354. var richItemNameMap;
  15355. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15356. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15357. if (rich) {
  15358. richItemNameMap = richItemNameMap || {};
  15359. for (var name in rich) {
  15360. if (rich.hasOwnProperty(name)) {
  15361. richItemNameMap[name] = 1;
  15362. }
  15363. }
  15364. }
  15365. textStyleModel = textStyleModel.parentModel;
  15366. }
  15367. return richItemNameMap;
  15368. }
  15369. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15370. // In merge mode, default value should not be given.
  15371. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15372. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15373. || globalTextStyle.color;
  15374. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15375. || globalTextStyle.textBorderColor;
  15376. textStyle.textStrokeWidth = retrieve2(
  15377. textStyleModel.getShallow('textBorderWidth'),
  15378. globalTextStyle.textBorderWidth
  15379. );
  15380. if (!isEmphasis) {
  15381. if (isBlock) {
  15382. textStyle.insideRollbackOpt = opt;
  15383. applyDefaultTextStyle(textStyle);
  15384. }
  15385. // Set default finally.
  15386. if (textStyle.textFill == null) {
  15387. textStyle.textFill = opt.autoColor;
  15388. }
  15389. }
  15390. // Do not use `getFont` here, because merge should be supported, where
  15391. // part of these properties may be changed in emphasis style, and the
  15392. // others should remain their original value got from normal style.
  15393. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15394. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15395. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15396. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15397. textStyle.textAlign = textStyleModel.getShallow('align');
  15398. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15399. || textStyleModel.getShallow('baseline');
  15400. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15401. textStyle.textWidth = textStyleModel.getShallow('width');
  15402. textStyle.textHeight = textStyleModel.getShallow('height');
  15403. textStyle.textTag = textStyleModel.getShallow('tag');
  15404. if (!isBlock || !opt.disableBox) {
  15405. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15406. textStyle.textPadding = textStyleModel.getShallow('padding');
  15407. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15408. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15409. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15410. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15411. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15412. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15413. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15414. }
  15415. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15416. || globalTextStyle.textShadowColor;
  15417. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15418. || globalTextStyle.textShadowBlur;
  15419. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15420. || globalTextStyle.textShadowOffsetX;
  15421. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15422. || globalTextStyle.textShadowOffsetY;
  15423. }
  15424. function getAutoColor(color, opt) {
  15425. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15426. }
  15427. /**
  15428. * Give some default value to the input `textStyle` object, based on the current settings
  15429. * in this `textStyle` object.
  15430. *
  15431. * The Scenario:
  15432. * when text position is `inside` and `textFill` is not specified, we show
  15433. * text border by default for better view. But it should be considered that text position
  15434. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15435. * restore the style.
  15436. *
  15437. * Usage (& NOTICE):
  15438. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15439. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15440. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15441. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15442. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15443. */
  15444. function applyDefaultTextStyle(textStyle) {
  15445. var textPosition = textStyle.textPosition;
  15446. var opt = textStyle.insideRollbackOpt;
  15447. var insideRollback;
  15448. if (opt && textStyle.textFill == null) {
  15449. var autoColor = opt.autoColor;
  15450. var isRectText = opt.isRectText;
  15451. var useInsideStyle = opt.useInsideStyle;
  15452. var useInsideStyleCache = useInsideStyle !== false
  15453. && (useInsideStyle === true
  15454. || (isRectText
  15455. && textPosition
  15456. // textPosition can be [10, 30]
  15457. && typeof textPosition === 'string'
  15458. && textPosition.indexOf('inside') >= 0
  15459. )
  15460. );
  15461. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15462. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15463. if (useInsideStyleCache || useAutoColorCache) {
  15464. insideRollback = {
  15465. textFill: textStyle.textFill,
  15466. textStroke: textStyle.textStroke,
  15467. textStrokeWidth: textStyle.textStrokeWidth
  15468. };
  15469. }
  15470. if (useInsideStyleCache) {
  15471. textStyle.textFill = '#fff';
  15472. // Consider text with #fff overflow its container.
  15473. if (textStyle.textStroke == null) {
  15474. textStyle.textStroke = autoColor;
  15475. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15476. }
  15477. }
  15478. if (useAutoColorCache) {
  15479. textStyle.textFill = autoColor;
  15480. }
  15481. }
  15482. // Always set `insideRollback`, so that the previous one can be cleared.
  15483. textStyle.insideRollback = insideRollback;
  15484. }
  15485. /**
  15486. * Consider the case: in a scatter,
  15487. * label: {
  15488. * normal: {position: 'inside'},
  15489. * emphasis: {position: 'top'}
  15490. * }
  15491. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15492. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15493. * should be retured to 'autoColor', but not keep '#fff'.
  15494. */
  15495. function rollbackDefaultTextStyle(style) {
  15496. var insideRollback = style.insideRollback;
  15497. if (insideRollback) {
  15498. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15499. style.textFill = insideRollback.textFill;
  15500. style.textStroke = insideRollback.textStroke;
  15501. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15502. style.insideRollback = null;
  15503. }
  15504. }
  15505. function getFont(opt, ecModel) {
  15506. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15507. return trim([
  15508. // FIXME in node-canvas fontWeight is before fontStyle
  15509. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15510. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15511. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15512. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15513. ].join(' '));
  15514. }
  15515. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15516. if (typeof dataIndex === 'function') {
  15517. cb = dataIndex;
  15518. dataIndex = null;
  15519. }
  15520. // Do not check 'animation' property directly here. Consider this case:
  15521. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15522. // but its parent model (`seriesModel`) does.
  15523. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15524. if (animationEnabled) {
  15525. var postfix = isUpdate ? 'Update' : '';
  15526. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15527. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15528. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15529. if (typeof animationDelay === 'function') {
  15530. animationDelay = animationDelay(
  15531. dataIndex,
  15532. animatableModel.getAnimationDelayParams
  15533. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15534. : null
  15535. );
  15536. }
  15537. if (typeof duration === 'function') {
  15538. duration = duration(dataIndex);
  15539. }
  15540. duration > 0
  15541. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15542. : (el.stopAnimation(), el.attr(props), cb && cb());
  15543. }
  15544. else {
  15545. el.stopAnimation();
  15546. el.attr(props);
  15547. cb && cb();
  15548. }
  15549. }
  15550. /**
  15551. * Update graphic element properties with or without animation according to the
  15552. * configuration in series.
  15553. *
  15554. * Caution: this method will stop previous animation.
  15555. * So do not use this method to one element twice before
  15556. * animation starts, unless you know what you are doing.
  15557. *
  15558. * @param {module:zrender/Element} el
  15559. * @param {Object} props
  15560. * @param {module:echarts/model/Model} [animatableModel]
  15561. * @param {number} [dataIndex]
  15562. * @param {Function} [cb]
  15563. * @example
  15564. * graphic.updateProps(el, {
  15565. * position: [100, 100]
  15566. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15567. * // Or
  15568. * graphic.updateProps(el, {
  15569. * position: [100, 100]
  15570. * }, seriesModel, function () { console.log('Animation done!'); });
  15571. */
  15572. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15573. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15574. }
  15575. /**
  15576. * Init graphic element properties with or without animation according to the
  15577. * configuration in series.
  15578. *
  15579. * Caution: this method will stop previous animation.
  15580. * So do not use this method to one element twice before
  15581. * animation starts, unless you know what you are doing.
  15582. *
  15583. * @param {module:zrender/Element} el
  15584. * @param {Object} props
  15585. * @param {module:echarts/model/Model} [animatableModel]
  15586. * @param {number} [dataIndex]
  15587. * @param {Function} cb
  15588. */
  15589. function initProps(el, props, animatableModel, dataIndex, cb) {
  15590. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15591. }
  15592. /**
  15593. * Get transform matrix of target (param target),
  15594. * in coordinate of its ancestor (param ancestor)
  15595. *
  15596. * @param {module:zrender/mixin/Transformable} target
  15597. * @param {module:zrender/mixin/Transformable} [ancestor]
  15598. */
  15599. function getTransform(target, ancestor) {
  15600. var mat = identity([]);
  15601. while (target && target !== ancestor) {
  15602. mul$1(mat, target.getLocalTransform(), mat);
  15603. target = target.parent;
  15604. }
  15605. return mat;
  15606. }
  15607. /**
  15608. * Apply transform to an vertex.
  15609. * @param {Array.<number>} target [x, y]
  15610. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15611. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15612. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15613. * @param {boolean=} invert Whether use invert matrix.
  15614. * @return {Array.<number>} [x, y]
  15615. */
  15616. function applyTransform$1(target, transform, invert$$1) {
  15617. if (transform && !isArrayLike(transform)) {
  15618. transform = Transformable.getLocalTransform(transform);
  15619. }
  15620. if (invert$$1) {
  15621. transform = invert([], transform);
  15622. }
  15623. return applyTransform([], target, transform);
  15624. }
  15625. /**
  15626. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15627. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15628. * @param {boolean=} invert Whether use invert matrix.
  15629. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15630. */
  15631. function transformDirection(direction, transform, invert$$1) {
  15632. // Pick a base, ensure that transform result will not be (0, 0).
  15633. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15634. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15635. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15636. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15637. var vertex = [
  15638. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15639. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15640. ];
  15641. vertex = applyTransform$1(vertex, transform, invert$$1);
  15642. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15643. ? (vertex[0] > 0 ? 'right' : 'left')
  15644. : (vertex[1] > 0 ? 'bottom' : 'top');
  15645. }
  15646. /**
  15647. * Apply group transition animation from g1 to g2.
  15648. * If no animatableModel, no animation.
  15649. */
  15650. function groupTransition(g1, g2, animatableModel, cb) {
  15651. if (!g1 || !g2) {
  15652. return;
  15653. }
  15654. function getElMap(g) {
  15655. var elMap = {};
  15656. g.traverse(function (el) {
  15657. if (!el.isGroup && el.anid) {
  15658. elMap[el.anid] = el;
  15659. }
  15660. });
  15661. return elMap;
  15662. }
  15663. function getAnimatableProps(el) {
  15664. var obj = {
  15665. position: clone$1(el.position),
  15666. rotation: el.rotation
  15667. };
  15668. if (el.shape) {
  15669. obj.shape = extend({}, el.shape);
  15670. }
  15671. return obj;
  15672. }
  15673. var elMap1 = getElMap(g1);
  15674. g2.traverse(function (el) {
  15675. if (!el.isGroup && el.anid) {
  15676. var oldEl = elMap1[el.anid];
  15677. if (oldEl) {
  15678. var newProp = getAnimatableProps(el);
  15679. el.attr(getAnimatableProps(oldEl));
  15680. updateProps(el, newProp, animatableModel, el.dataIndex);
  15681. }
  15682. // else {
  15683. // if (el.previousProps) {
  15684. // graphic.updateProps
  15685. // }
  15686. // }
  15687. }
  15688. });
  15689. }
  15690. /**
  15691. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15692. * @param {Object} rect {x, y, width, height}
  15693. * @return {Array.<Array.<number>>} A new clipped points.
  15694. */
  15695. function clipPointsByRect(points, rect) {
  15696. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15697. // and when element have border.
  15698. return map(points, function (point) {
  15699. var x = point[0];
  15700. x = mathMax$1(x, rect.x);
  15701. x = mathMin$1(x, rect.x + rect.width);
  15702. var y = point[1];
  15703. y = mathMax$1(y, rect.y);
  15704. y = mathMin$1(y, rect.y + rect.height);
  15705. return [x, y];
  15706. });
  15707. }
  15708. /**
  15709. * @param {Object} targetRect {x, y, width, height}
  15710. * @param {Object} rect {x, y, width, height}
  15711. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15712. */
  15713. function clipRectByRect(targetRect, rect) {
  15714. var x = mathMax$1(targetRect.x, rect.x);
  15715. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15716. var y = mathMax$1(targetRect.y, rect.y);
  15717. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15718. // If the total rect is cliped, nothing, including the border,
  15719. // should be painted. So return undefined.
  15720. if (x2 >= x && y2 >= y) {
  15721. return {
  15722. x: x,
  15723. y: y,
  15724. width: x2 - x,
  15725. height: y2 - y
  15726. };
  15727. }
  15728. }
  15729. /**
  15730. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15731. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15732. * @param {Object} [rect] {x, y, width, height}
  15733. * @return {module:zrender/Element} Icon path or image element.
  15734. */
  15735. function createIcon(iconStr, opt, rect) {
  15736. opt = extend({rectHover: true}, opt);
  15737. var style = opt.style = {strokeNoScale: true};
  15738. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15739. if (iconStr) {
  15740. return iconStr.indexOf('image://') === 0
  15741. ? (
  15742. style.image = iconStr.slice(8),
  15743. defaults(style, rect),
  15744. new ZImage(opt)
  15745. )
  15746. : (
  15747. makePath(
  15748. iconStr.replace('path://', ''),
  15749. opt,
  15750. rect,
  15751. 'center'
  15752. )
  15753. );
  15754. }
  15755. }
  15756. /**
  15757. * Return `true` if the given line (line `a`) and the given polygon
  15758. * are intersect.
  15759. * Note that we do not count colinear as intersect here because no
  15760. * requirement for that. We could do that if required in future.
  15761. *
  15762. * @param {number} a1x
  15763. * @param {number} a1y
  15764. * @param {number} a2x
  15765. * @param {number} a2y
  15766. * @param {Array.<Array.<number>>} points Points of the polygon.
  15767. * @return {boolean}
  15768. */
  15769. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  15770. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  15771. var p = points[i];
  15772. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  15773. return true;
  15774. }
  15775. p2 = p;
  15776. }
  15777. }
  15778. /**
  15779. * Return `true` if the given two lines (line `a` and line `b`)
  15780. * are intersect.
  15781. * Note that we do not count colinear as intersect here because no
  15782. * requirement for that. We could do that if required in future.
  15783. *
  15784. * @param {number} a1x
  15785. * @param {number} a1y
  15786. * @param {number} a2x
  15787. * @param {number} a2y
  15788. * @param {number} b1x
  15789. * @param {number} b1y
  15790. * @param {number} b2x
  15791. * @param {number} b2y
  15792. * @return {boolean}
  15793. */
  15794. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  15795. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  15796. var mx = a2x - a1x;
  15797. var my = a2y - a1y;
  15798. var nx = b2x - b1x;
  15799. var ny = b2y - b1y;
  15800. // `vec_m` and `vec_n` are parallel iff
  15801. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  15802. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  15803. if (nearZero(nmCrossProduct)) {
  15804. return false;
  15805. }
  15806. // `vec_m` and `vec_n` are intersect iff
  15807. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  15808. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  15809. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  15810. var b1a1x = a1x - b1x;
  15811. var b1a1y = a1y - b1y;
  15812. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  15813. if (q < 0 || q > 1) {
  15814. return false;
  15815. }
  15816. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  15817. if (p < 0 || p > 1) {
  15818. return false;
  15819. }
  15820. return true;
  15821. }
  15822. /**
  15823. * Cross product of 2-dimension vector.
  15824. */
  15825. function crossProduct2d(x1, y1, x2, y2) {
  15826. return x1 * y2 - x2 * y1;
  15827. }
  15828. function nearZero(val) {
  15829. return val <= (1e-6) && val >= -(1e-6);
  15830. }
  15831. // Register built-in shapes. These shapes might be overwirtten
  15832. // by users, although we do not recommend that.
  15833. registerShape('circle', Circle);
  15834. registerShape('sector', Sector);
  15835. registerShape('ring', Ring);
  15836. registerShape('polygon', Polygon);
  15837. registerShape('polyline', Polyline);
  15838. registerShape('rect', Rect);
  15839. registerShape('line', Line);
  15840. registerShape('bezierCurve', BezierCurve);
  15841. registerShape('arc', Arc);
  15842. var graphic = (Object.freeze || Object)({
  15843. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15844. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  15845. extendShape: extendShape,
  15846. extendPath: extendPath,
  15847. registerShape: registerShape,
  15848. getShapeClass: getShapeClass,
  15849. makePath: makePath,
  15850. makeImage: makeImage,
  15851. mergePath: mergePath,
  15852. resizePath: resizePath,
  15853. subPixelOptimizeLine: subPixelOptimizeLine,
  15854. subPixelOptimizeRect: subPixelOptimizeRect,
  15855. subPixelOptimize: subPixelOptimize,
  15856. setElementHoverStyle: setElementHoverStyle,
  15857. setHoverStyle: setHoverStyle,
  15858. setAsHighDownDispatcher: setAsHighDownDispatcher,
  15859. isHighDownDispatcher: isHighDownDispatcher,
  15860. getHighlightDigit: getHighlightDigit,
  15861. setLabelStyle: setLabelStyle,
  15862. modifyLabelStyle: modifyLabelStyle,
  15863. setTextStyle: setTextStyle,
  15864. setText: setText,
  15865. getFont: getFont,
  15866. updateProps: updateProps,
  15867. initProps: initProps,
  15868. getTransform: getTransform,
  15869. applyTransform: applyTransform$1,
  15870. transformDirection: transformDirection,
  15871. groupTransition: groupTransition,
  15872. clipPointsByRect: clipPointsByRect,
  15873. clipRectByRect: clipRectByRect,
  15874. createIcon: createIcon,
  15875. linePolygonIntersect: linePolygonIntersect,
  15876. lineLineIntersect: lineLineIntersect,
  15877. Group: Group,
  15878. Image: ZImage,
  15879. Text: Text,
  15880. Circle: Circle,
  15881. Sector: Sector,
  15882. Ring: Ring,
  15883. Polygon: Polygon,
  15884. Polyline: Polyline,
  15885. Rect: Rect,
  15886. Line: Line,
  15887. BezierCurve: BezierCurve,
  15888. Arc: Arc,
  15889. IncrementalDisplayable: IncrementalDisplayble,
  15890. CompoundPath: CompoundPath,
  15891. LinearGradient: LinearGradient,
  15892. RadialGradient: RadialGradient,
  15893. BoundingRect: BoundingRect
  15894. });
  15895. /*
  15896. * Licensed to the Apache Software Foundation (ASF) under one
  15897. * or more contributor license agreements. See the NOTICE file
  15898. * distributed with this work for additional information
  15899. * regarding copyright ownership. The ASF licenses this file
  15900. * to you under the Apache License, Version 2.0 (the
  15901. * "License"); you may not use this file except in compliance
  15902. * with the License. You may obtain a copy of the License at
  15903. *
  15904. * http://www.apache.org/licenses/LICENSE-2.0
  15905. *
  15906. * Unless required by applicable law or agreed to in writing,
  15907. * software distributed under the License is distributed on an
  15908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15909. * KIND, either express or implied. See the License for the
  15910. * specific language governing permissions and limitations
  15911. * under the License.
  15912. */
  15913. var PATH_COLOR = ['textStyle', 'color'];
  15914. var textStyleMixin = {
  15915. /**
  15916. * Get color property or get color from option.textStyle.color
  15917. * @param {boolean} [isEmphasis]
  15918. * @return {string}
  15919. */
  15920. getTextColor: function (isEmphasis) {
  15921. var ecModel = this.ecModel;
  15922. return this.getShallow('color')
  15923. || (
  15924. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15925. );
  15926. },
  15927. /**
  15928. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15929. * @return {string}
  15930. */
  15931. getFont: function () {
  15932. return getFont({
  15933. fontStyle: this.getShallow('fontStyle'),
  15934. fontWeight: this.getShallow('fontWeight'),
  15935. fontSize: this.getShallow('fontSize'),
  15936. fontFamily: this.getShallow('fontFamily')
  15937. }, this.ecModel);
  15938. },
  15939. getTextRect: function (text) {
  15940. return getBoundingRect(
  15941. text,
  15942. this.getFont(),
  15943. this.getShallow('align'),
  15944. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15945. this.getShallow('padding'),
  15946. this.getShallow('lineHeight'),
  15947. this.getShallow('rich'),
  15948. this.getShallow('truncateText')
  15949. );
  15950. }
  15951. };
  15952. /*
  15953. * Licensed to the Apache Software Foundation (ASF) under one
  15954. * or more contributor license agreements. See the NOTICE file
  15955. * distributed with this work for additional information
  15956. * regarding copyright ownership. The ASF licenses this file
  15957. * to you under the Apache License, Version 2.0 (the
  15958. * "License"); you may not use this file except in compliance
  15959. * with the License. You may obtain a copy of the License at
  15960. *
  15961. * http://www.apache.org/licenses/LICENSE-2.0
  15962. *
  15963. * Unless required by applicable law or agreed to in writing,
  15964. * software distributed under the License is distributed on an
  15965. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15966. * KIND, either express or implied. See the License for the
  15967. * specific language governing permissions and limitations
  15968. * under the License.
  15969. */
  15970. var getItemStyle = makeStyleMapper(
  15971. [
  15972. ['fill', 'color'],
  15973. ['stroke', 'borderColor'],
  15974. ['lineWidth', 'borderWidth'],
  15975. ['opacity'],
  15976. ['shadowBlur'],
  15977. ['shadowOffsetX'],
  15978. ['shadowOffsetY'],
  15979. ['shadowColor'],
  15980. ['textPosition'],
  15981. ['textAlign']
  15982. ]
  15983. );
  15984. var itemStyleMixin = {
  15985. getItemStyle: function (excludes, includes) {
  15986. var style = getItemStyle(this, excludes, includes);
  15987. var lineDash = this.getBorderLineDash();
  15988. lineDash && (style.lineDash = lineDash);
  15989. return style;
  15990. },
  15991. getBorderLineDash: function () {
  15992. var lineType = this.get('borderType');
  15993. return (lineType === 'solid' || lineType == null) ? null
  15994. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15995. }
  15996. };
  15997. /*
  15998. * Licensed to the Apache Software Foundation (ASF) under one
  15999. * or more contributor license agreements. See the NOTICE file
  16000. * distributed with this work for additional information
  16001. * regarding copyright ownership. The ASF licenses this file
  16002. * to you under the Apache License, Version 2.0 (the
  16003. * "License"); you may not use this file except in compliance
  16004. * with the License. You may obtain a copy of the License at
  16005. *
  16006. * http://www.apache.org/licenses/LICENSE-2.0
  16007. *
  16008. * Unless required by applicable law or agreed to in writing,
  16009. * software distributed under the License is distributed on an
  16010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16011. * KIND, either express or implied. See the License for the
  16012. * specific language governing permissions and limitations
  16013. * under the License.
  16014. */
  16015. /**
  16016. * @module echarts/model/Model
  16017. */
  16018. var mixin$1 = mixin;
  16019. var inner = makeInner();
  16020. /**
  16021. * @alias module:echarts/model/Model
  16022. * @constructor
  16023. * @param {Object} [option]
  16024. * @param {module:echarts/model/Model} [parentModel]
  16025. * @param {module:echarts/model/Global} [ecModel]
  16026. */
  16027. function Model(option, parentModel, ecModel) {
  16028. /**
  16029. * @type {module:echarts/model/Model}
  16030. * @readOnly
  16031. */
  16032. this.parentModel = parentModel;
  16033. /**
  16034. * @type {module:echarts/model/Global}
  16035. * @readOnly
  16036. */
  16037. this.ecModel = ecModel;
  16038. /**
  16039. * @type {Object}
  16040. * @protected
  16041. */
  16042. this.option = option;
  16043. // Simple optimization
  16044. // if (this.init) {
  16045. // if (arguments.length <= 4) {
  16046. // this.init(option, parentModel, ecModel, extraOpt);
  16047. // }
  16048. // else {
  16049. // this.init.apply(this, arguments);
  16050. // }
  16051. // }
  16052. }
  16053. Model.prototype = {
  16054. constructor: Model,
  16055. /**
  16056. * Model 的初始化函数
  16057. * @param {Object} option
  16058. */
  16059. init: null,
  16060. /**
  16061. * 从新的 Option merge
  16062. */
  16063. mergeOption: function (option) {
  16064. merge(this.option, option, true);
  16065. },
  16066. /**
  16067. * @param {string|Array.<string>} path
  16068. * @param {boolean} [ignoreParent=false]
  16069. * @return {*}
  16070. */
  16071. get: function (path, ignoreParent) {
  16072. if (path == null) {
  16073. return this.option;
  16074. }
  16075. return doGet(
  16076. this.option,
  16077. this.parsePath(path),
  16078. !ignoreParent && getParent(this, path)
  16079. );
  16080. },
  16081. /**
  16082. * @param {string} key
  16083. * @param {boolean} [ignoreParent=false]
  16084. * @return {*}
  16085. */
  16086. getShallow: function (key, ignoreParent) {
  16087. var option = this.option;
  16088. var val = option == null ? option : option[key];
  16089. var parentModel = !ignoreParent && getParent(this, key);
  16090. if (val == null && parentModel) {
  16091. val = parentModel.getShallow(key);
  16092. }
  16093. return val;
  16094. },
  16095. /**
  16096. * @param {string|Array.<string>} [path]
  16097. * @param {module:echarts/model/Model} [parentModel]
  16098. * @return {module:echarts/model/Model}
  16099. */
  16100. getModel: function (path, parentModel) {
  16101. var obj = path == null
  16102. ? this.option
  16103. : doGet(this.option, path = this.parsePath(path));
  16104. var thisParentModel;
  16105. parentModel = parentModel || (
  16106. (thisParentModel = getParent(this, path))
  16107. && thisParentModel.getModel(path)
  16108. );
  16109. return new Model(obj, parentModel, this.ecModel);
  16110. },
  16111. /**
  16112. * If model has option
  16113. */
  16114. isEmpty: function () {
  16115. return this.option == null;
  16116. },
  16117. restoreData: function () {},
  16118. // Pending
  16119. clone: function () {
  16120. var Ctor = this.constructor;
  16121. return new Ctor(clone(this.option));
  16122. },
  16123. setReadOnly: function (properties) {
  16124. // clazzUtil.setReadOnly(this, properties);
  16125. },
  16126. // If path is null/undefined, return null/undefined.
  16127. parsePath: function (path) {
  16128. if (typeof path === 'string') {
  16129. path = path.split('.');
  16130. }
  16131. return path;
  16132. },
  16133. /**
  16134. * @param {Function} getParentMethod
  16135. * param {Array.<string>|string} path
  16136. * return {module:echarts/model/Model}
  16137. */
  16138. customizeGetParent: function (getParentMethod) {
  16139. inner(this).getParent = getParentMethod;
  16140. },
  16141. isAnimationEnabled: function () {
  16142. if (!env$1.node) {
  16143. if (this.option.animation != null) {
  16144. return !!this.option.animation;
  16145. }
  16146. else if (this.parentModel) {
  16147. return this.parentModel.isAnimationEnabled();
  16148. }
  16149. }
  16150. }
  16151. };
  16152. function doGet(obj, pathArr, parentModel) {
  16153. for (var i = 0; i < pathArr.length; i++) {
  16154. // Ignore empty
  16155. if (!pathArr[i]) {
  16156. continue;
  16157. }
  16158. // obj could be number/string/... (like 0)
  16159. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16160. if (obj == null) {
  16161. break;
  16162. }
  16163. }
  16164. if (obj == null && parentModel) {
  16165. obj = parentModel.get(pathArr);
  16166. }
  16167. return obj;
  16168. }
  16169. // `path` can be null/undefined
  16170. function getParent(model, path) {
  16171. var getParentMethod = inner(model).getParent;
  16172. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16173. }
  16174. // Enable Model.extend.
  16175. enableClassExtend(Model);
  16176. enableClassCheck(Model);
  16177. mixin$1(Model, lineStyleMixin);
  16178. mixin$1(Model, areaStyleMixin);
  16179. mixin$1(Model, textStyleMixin);
  16180. mixin$1(Model, itemStyleMixin);
  16181. /*
  16182. * Licensed to the Apache Software Foundation (ASF) under one
  16183. * or more contributor license agreements. See the NOTICE file
  16184. * distributed with this work for additional information
  16185. * regarding copyright ownership. The ASF licenses this file
  16186. * to you under the Apache License, Version 2.0 (the
  16187. * "License"); you may not use this file except in compliance
  16188. * with the License. You may obtain a copy of the License at
  16189. *
  16190. * http://www.apache.org/licenses/LICENSE-2.0
  16191. *
  16192. * Unless required by applicable law or agreed to in writing,
  16193. * software distributed under the License is distributed on an
  16194. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16195. * KIND, either express or implied. See the License for the
  16196. * specific language governing permissions and limitations
  16197. * under the License.
  16198. */
  16199. var base = 0;
  16200. /**
  16201. * @public
  16202. * @param {string} type
  16203. * @return {string}
  16204. */
  16205. function getUID(type) {
  16206. // Considering the case of crossing js context,
  16207. // use Math.random to make id as unique as possible.
  16208. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16209. }
  16210. /**
  16211. * @inner
  16212. */
  16213. function enableSubTypeDefaulter(entity) {
  16214. var subTypeDefaulters = {};
  16215. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16216. componentType = parseClassType$1(componentType);
  16217. subTypeDefaulters[componentType.main] = defaulter;
  16218. };
  16219. entity.determineSubType = function (componentType, option) {
  16220. var type = option.type;
  16221. if (!type) {
  16222. var componentTypeMain = parseClassType$1(componentType).main;
  16223. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16224. type = subTypeDefaulters[componentTypeMain](option);
  16225. }
  16226. }
  16227. return type;
  16228. };
  16229. return entity;
  16230. }
  16231. /**
  16232. * Topological travel on Activity Network (Activity On Vertices).
  16233. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16234. *
  16235. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16236. *
  16237. * If there is circle dependencey, Error will be thrown.
  16238. *
  16239. */
  16240. function enableTopologicalTravel(entity, dependencyGetter) {
  16241. /**
  16242. * @public
  16243. * @param {Array.<string>} targetNameList Target Component type list.
  16244. * Can be ['aa', 'bb', 'aa.xx']
  16245. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16246. * @param {Function} callback Params: componentType, dependencies.
  16247. * @param {Object} context Scope of callback.
  16248. */
  16249. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16250. if (!targetNameList.length) {
  16251. return;
  16252. }
  16253. var result = makeDepndencyGraph(fullNameList);
  16254. var graph = result.graph;
  16255. var stack = result.noEntryList;
  16256. var targetNameSet = {};
  16257. each$1(targetNameList, function (name) {
  16258. targetNameSet[name] = true;
  16259. });
  16260. while (stack.length) {
  16261. var currComponentType = stack.pop();
  16262. var currVertex = graph[currComponentType];
  16263. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16264. if (isInTargetNameSet) {
  16265. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16266. delete targetNameSet[currComponentType];
  16267. }
  16268. each$1(
  16269. currVertex.successor,
  16270. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16271. );
  16272. }
  16273. each$1(targetNameSet, function () {
  16274. throw new Error('Circle dependency may exists');
  16275. });
  16276. function removeEdge(succComponentType) {
  16277. graph[succComponentType].entryCount--;
  16278. if (graph[succComponentType].entryCount === 0) {
  16279. stack.push(succComponentType);
  16280. }
  16281. }
  16282. // Consider this case: legend depends on series, and we call
  16283. // chart.setOption({series: [...]}), where only series is in option.
  16284. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16285. // not be called, but only sereis.mergeOption is called. Thus legend
  16286. // have no chance to update its local record about series (like which
  16287. // name of series is available in legend).
  16288. function removeEdgeAndAdd(succComponentType) {
  16289. targetNameSet[succComponentType] = true;
  16290. removeEdge(succComponentType);
  16291. }
  16292. };
  16293. /**
  16294. * DepndencyGraph: {Object}
  16295. * key: conponentType,
  16296. * value: {
  16297. * successor: [conponentTypes...],
  16298. * originalDeps: [conponentTypes...],
  16299. * entryCount: {number}
  16300. * }
  16301. */
  16302. function makeDepndencyGraph(fullNameList) {
  16303. var graph = {};
  16304. var noEntryList = [];
  16305. each$1(fullNameList, function (name) {
  16306. var thisItem = createDependencyGraphItem(graph, name);
  16307. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16308. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16309. thisItem.entryCount = availableDeps.length;
  16310. if (thisItem.entryCount === 0) {
  16311. noEntryList.push(name);
  16312. }
  16313. each$1(availableDeps, function (dependentName) {
  16314. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16315. thisItem.predecessor.push(dependentName);
  16316. }
  16317. var thatItem = createDependencyGraphItem(graph, dependentName);
  16318. if (indexOf(thatItem.successor, dependentName) < 0) {
  16319. thatItem.successor.push(name);
  16320. }
  16321. });
  16322. });
  16323. return {graph: graph, noEntryList: noEntryList};
  16324. }
  16325. function createDependencyGraphItem(graph, name) {
  16326. if (!graph[name]) {
  16327. graph[name] = {predecessor: [], successor: []};
  16328. }
  16329. return graph[name];
  16330. }
  16331. function getAvailableDependencies(originalDeps, fullNameList) {
  16332. var availableDeps = [];
  16333. each$1(originalDeps, function (dep) {
  16334. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16335. });
  16336. return availableDeps;
  16337. }
  16338. }
  16339. /*
  16340. * Licensed to the Apache Software Foundation (ASF) under one
  16341. * or more contributor license agreements. See the NOTICE file
  16342. * distributed with this work for additional information
  16343. * regarding copyright ownership. The ASF licenses this file
  16344. * to you under the Apache License, Version 2.0 (the
  16345. * "License"); you may not use this file except in compliance
  16346. * with the License. You may obtain a copy of the License at
  16347. *
  16348. * http://www.apache.org/licenses/LICENSE-2.0
  16349. *
  16350. * Unless required by applicable law or agreed to in writing,
  16351. * software distributed under the License is distributed on an
  16352. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16353. * KIND, either express or implied. See the License for the
  16354. * specific language governing permissions and limitations
  16355. * under the License.
  16356. */
  16357. /*
  16358. * A third-party license is embeded for some of the code in this file:
  16359. * The method "quantile" was copied from "d3.js".
  16360. * (See more details in the comment of the method below.)
  16361. * The use of the source code of this file is also subject to the terms
  16362. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16363. * </licenses/LICENSE-d3>).
  16364. */
  16365. var RADIAN_EPSILON = 1e-4;
  16366. function _trim(str) {
  16367. return str.replace(/^\s+|\s+$/g, '');
  16368. }
  16369. /**
  16370. * Linear mapping a value from domain to range
  16371. * @memberOf module:echarts/util/number
  16372. * @param {(number|Array.<number>)} val
  16373. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16374. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16375. * @param {boolean} clamp
  16376. * @return {(number|Array.<number>}
  16377. */
  16378. function linearMap(val, domain, range, clamp) {
  16379. var subDomain = domain[1] - domain[0];
  16380. var subRange = range[1] - range[0];
  16381. if (subDomain === 0) {
  16382. return subRange === 0
  16383. ? range[0]
  16384. : (range[0] + range[1]) / 2;
  16385. }
  16386. // Avoid accuracy problem in edge, such as
  16387. // 146.39 - 62.83 === 83.55999999999999.
  16388. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16389. // It is a little verbose for efficiency considering this method
  16390. // is a hotspot.
  16391. if (clamp) {
  16392. if (subDomain > 0) {
  16393. if (val <= domain[0]) {
  16394. return range[0];
  16395. }
  16396. else if (val >= domain[1]) {
  16397. return range[1];
  16398. }
  16399. }
  16400. else {
  16401. if (val >= domain[0]) {
  16402. return range[0];
  16403. }
  16404. else if (val <= domain[1]) {
  16405. return range[1];
  16406. }
  16407. }
  16408. }
  16409. else {
  16410. if (val === domain[0]) {
  16411. return range[0];
  16412. }
  16413. if (val === domain[1]) {
  16414. return range[1];
  16415. }
  16416. }
  16417. return (val - domain[0]) / subDomain * subRange + range[0];
  16418. }
  16419. /**
  16420. * Convert a percent string to absolute number.
  16421. * Returns NaN if percent is not a valid string or number
  16422. * @memberOf module:echarts/util/number
  16423. * @param {string|number} percent
  16424. * @param {number} all
  16425. * @return {number}
  16426. */
  16427. function parsePercent$1(percent, all) {
  16428. switch (percent) {
  16429. case 'center':
  16430. case 'middle':
  16431. percent = '50%';
  16432. break;
  16433. case 'left':
  16434. case 'top':
  16435. percent = '0%';
  16436. break;
  16437. case 'right':
  16438. case 'bottom':
  16439. percent = '100%';
  16440. break;
  16441. }
  16442. if (typeof percent === 'string') {
  16443. if (_trim(percent).match(/%$/)) {
  16444. return parseFloat(percent) / 100 * all;
  16445. }
  16446. return parseFloat(percent);
  16447. }
  16448. return percent == null ? NaN : +percent;
  16449. }
  16450. /**
  16451. * (1) Fix rounding error of float numbers.
  16452. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16453. *
  16454. * @param {number} x
  16455. * @param {number} [precision]
  16456. * @param {boolean} [returnStr]
  16457. * @return {number|string}
  16458. */
  16459. function round$1(x, precision, returnStr) {
  16460. if (precision == null) {
  16461. precision = 10;
  16462. }
  16463. // Avoid range error
  16464. precision = Math.min(Math.max(0, precision), 20);
  16465. x = (+x).toFixed(precision);
  16466. return returnStr ? x : +x;
  16467. }
  16468. /**
  16469. * asc sort arr.
  16470. * The input arr will be modified.
  16471. *
  16472. * @param {Array} arr
  16473. * @return {Array} The input arr.
  16474. */
  16475. /**
  16476. * Get precision
  16477. * @param {number} val
  16478. */
  16479. /**
  16480. * @param {string|number} val
  16481. * @return {number}
  16482. */
  16483. function getPrecisionSafe(val) {
  16484. var str = val.toString();
  16485. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16486. var eIndex = str.indexOf('e');
  16487. if (eIndex > 0) {
  16488. var precision = +str.slice(eIndex + 1);
  16489. return precision < 0 ? -precision : 0;
  16490. }
  16491. else {
  16492. var dotIndex = str.indexOf('.');
  16493. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16494. }
  16495. }
  16496. /**
  16497. * Minimal dicernible data precisioin according to a single pixel.
  16498. *
  16499. * @param {Array.<number>} dataExtent
  16500. * @param {Array.<number>} pixelExtent
  16501. * @return {number} precision
  16502. */
  16503. function getPixelPrecision(dataExtent, pixelExtent) {
  16504. var log = Math.log;
  16505. var LN10 = Math.LN10;
  16506. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16507. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16508. // toFixed() digits argument must be between 0 and 20.
  16509. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16510. return !isFinite(precision) ? 20 : precision;
  16511. }
  16512. /**
  16513. * Get a data of given precision, assuring the sum of percentages
  16514. * in valueList is 1.
  16515. * The largest remainer method is used.
  16516. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16517. *
  16518. * @param {Array.<number>} valueList a list of all data
  16519. * @param {number} idx index of the data to be processed in valueList
  16520. * @param {number} precision integer number showing digits of precision
  16521. * @return {number} percent ranging from 0 to 100
  16522. */
  16523. function getPercentWithPrecision(valueList, idx, precision) {
  16524. if (!valueList[idx]) {
  16525. return 0;
  16526. }
  16527. var sum = reduce(valueList, function (acc, val) {
  16528. return acc + (isNaN(val) ? 0 : val);
  16529. }, 0);
  16530. if (sum === 0) {
  16531. return 0;
  16532. }
  16533. var digits = Math.pow(10, precision);
  16534. var votesPerQuota = map(valueList, function (val) {
  16535. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16536. });
  16537. var targetSeats = digits * 100;
  16538. var seats = map(votesPerQuota, function (votes) {
  16539. // Assign automatic seats.
  16540. return Math.floor(votes);
  16541. });
  16542. var currentSum = reduce(seats, function (acc, val) {
  16543. return acc + val;
  16544. }, 0);
  16545. var remainder = map(votesPerQuota, function (votes, idx) {
  16546. return votes - seats[idx];
  16547. });
  16548. // Has remainding votes.
  16549. while (currentSum < targetSeats) {
  16550. // Find next largest remainder.
  16551. var max = Number.NEGATIVE_INFINITY;
  16552. var maxId = null;
  16553. for (var i = 0, len = remainder.length; i < len; ++i) {
  16554. if (remainder[i] > max) {
  16555. max = remainder[i];
  16556. maxId = i;
  16557. }
  16558. }
  16559. // Add a vote to max remainder.
  16560. ++seats[maxId];
  16561. remainder[maxId] = 0;
  16562. ++currentSum;
  16563. }
  16564. return seats[idx] / digits;
  16565. }
  16566. // Number.MAX_SAFE_INTEGER, ie do not support.
  16567. /**
  16568. * To 0 - 2 * PI, considering negative radian.
  16569. * @param {number} radian
  16570. * @return {number}
  16571. */
  16572. function remRadian(radian) {
  16573. var pi2 = Math.PI * 2;
  16574. return (radian % pi2 + pi2) % pi2;
  16575. }
  16576. /**
  16577. * @param {type} radian
  16578. * @return {boolean}
  16579. */
  16580. function isRadianAroundZero(val) {
  16581. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16582. }
  16583. /* eslint-disable */
  16584. 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
  16585. /* eslint-enable */
  16586. /**
  16587. * @param {string|Date|number} value These values can be accepted:
  16588. * + An instance of Date, represent a time in its own time zone.
  16589. * + Or string in a subset of ISO 8601, only including:
  16590. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16591. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16592. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16593. * all of which will be treated as local time if time zone is not specified
  16594. * (see <https://momentjs.com/>).
  16595. * + Or other string format, including (all of which will be treated as loacal time):
  16596. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16597. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16598. * + a timestamp, which represent a time in UTC.
  16599. * @return {Date} date
  16600. */
  16601. function parseDate(value) {
  16602. if (value instanceof Date) {
  16603. return value;
  16604. }
  16605. else if (typeof value === 'string') {
  16606. // Different browsers parse date in different way, so we parse it manually.
  16607. // Some other issues:
  16608. // new Date('1970-01-01') is UTC,
  16609. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16610. // See issue #3623
  16611. var match = TIME_REG.exec(value);
  16612. if (!match) {
  16613. // return Invalid Date.
  16614. return new Date(NaN);
  16615. }
  16616. // Use local time when no timezone offset specifed.
  16617. if (!match[8]) {
  16618. // match[n] can only be string or undefined.
  16619. // But take care of '12' + 1 => '121'.
  16620. return new Date(
  16621. +match[1],
  16622. +(match[2] || 1) - 1,
  16623. +match[3] || 1,
  16624. +match[4] || 0,
  16625. +(match[5] || 0),
  16626. +match[6] || 0,
  16627. +match[7] || 0
  16628. );
  16629. }
  16630. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16631. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16632. // For example, system timezone is set as "Time Zone: America/Toronto",
  16633. // then these code will get different result:
  16634. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16635. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16636. // So we should not use `new Date`, but use `Date.UTC`.
  16637. else {
  16638. var hour = +match[4] || 0;
  16639. if (match[8].toUpperCase() !== 'Z') {
  16640. hour -= match[8].slice(0, 3);
  16641. }
  16642. return new Date(Date.UTC(
  16643. +match[1],
  16644. +(match[2] || 1) - 1,
  16645. +match[3] || 1,
  16646. hour,
  16647. +(match[5] || 0),
  16648. +match[6] || 0,
  16649. +match[7] || 0
  16650. ));
  16651. }
  16652. }
  16653. else if (value == null) {
  16654. return new Date(NaN);
  16655. }
  16656. return new Date(Math.round(value));
  16657. }
  16658. /**
  16659. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16660. *
  16661. * @param {number} val
  16662. * @return {number}
  16663. */
  16664. function quantity(val) {
  16665. return Math.pow(10, quantityExponent(val));
  16666. }
  16667. /**
  16668. * Exponent of the quantity of a number
  16669. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16670. *
  16671. * @param {number} val non-negative value
  16672. * @return {number}
  16673. */
  16674. function quantityExponent(val) {
  16675. if (val === 0) {
  16676. return 0;
  16677. }
  16678. var exp = Math.floor(Math.log(val) / Math.LN10);
  16679. /**
  16680. * exp is expected to be the rounded-down result of the base-10 log of val.
  16681. * But due to the precision loss with Math.log(val), we need to restore it
  16682. * using 10^exp to make sure we can get val back from exp. #11249
  16683. */
  16684. if (val / Math.pow(10, exp) >= 10) {
  16685. exp++;
  16686. }
  16687. return exp;
  16688. }
  16689. /**
  16690. * find a “nice” number approximately equal to x. Round the number if round = true,
  16691. * take ceiling if round = false. The primary observation is that the “nicest”
  16692. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16693. *
  16694. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16695. *
  16696. * @param {number} val Non-negative value.
  16697. * @param {boolean} round
  16698. * @return {number}
  16699. */
  16700. function nice(val, round) {
  16701. var exponent = quantityExponent(val);
  16702. var exp10 = Math.pow(10, exponent);
  16703. var f = val / exp10; // 1 <= f < 10
  16704. var nf;
  16705. if (round) {
  16706. if (f < 1.5) {
  16707. nf = 1;
  16708. }
  16709. else if (f < 2.5) {
  16710. nf = 2;
  16711. }
  16712. else if (f < 4) {
  16713. nf = 3;
  16714. }
  16715. else if (f < 7) {
  16716. nf = 5;
  16717. }
  16718. else {
  16719. nf = 10;
  16720. }
  16721. }
  16722. else {
  16723. if (f < 1) {
  16724. nf = 1;
  16725. }
  16726. else if (f < 2) {
  16727. nf = 2;
  16728. }
  16729. else if (f < 3) {
  16730. nf = 3;
  16731. }
  16732. else if (f < 5) {
  16733. nf = 5;
  16734. }
  16735. else {
  16736. nf = 10;
  16737. }
  16738. }
  16739. val = nf * exp10;
  16740. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16741. // 20 is the uppper bound of toFixed.
  16742. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16743. }
  16744. /**
  16745. * This code was copied from "d3.js"
  16746. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  16747. * See the license statement at the head of this file.
  16748. * @param {Array.<number>} ascArr
  16749. */
  16750. /**
  16751. * Order intervals asc, and split them when overlap.
  16752. * expect(numberUtil.reformIntervals([
  16753. * {interval: [18, 62], close: [1, 1]},
  16754. * {interval: [-Infinity, -70], close: [0, 0]},
  16755. * {interval: [-70, -26], close: [1, 1]},
  16756. * {interval: [-26, 18], close: [1, 1]},
  16757. * {interval: [62, 150], close: [1, 1]},
  16758. * {interval: [106, 150], close: [1, 1]},
  16759. * {interval: [150, Infinity], close: [0, 0]}
  16760. * ])).toEqual([
  16761. * {interval: [-Infinity, -70], close: [0, 0]},
  16762. * {interval: [-70, -26], close: [1, 1]},
  16763. * {interval: [-26, 18], close: [0, 1]},
  16764. * {interval: [18, 62], close: [0, 1]},
  16765. * {interval: [62, 150], close: [0, 1]},
  16766. * {interval: [150, Infinity], close: [0, 0]}
  16767. * ]);
  16768. * @param {Array.<Object>} list, where `close` mean open or close
  16769. * of the interval, and Infinity can be used.
  16770. * @return {Array.<Object>} The origin list, which has been reformed.
  16771. */
  16772. /**
  16773. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16774. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16775. * subtraction forces infinities to NaN
  16776. *
  16777. * @param {*} v
  16778. * @return {boolean}
  16779. */
  16780. /*
  16781. * Licensed to the Apache Software Foundation (ASF) under one
  16782. * or more contributor license agreements. See the NOTICE file
  16783. * distributed with this work for additional information
  16784. * regarding copyright ownership. The ASF licenses this file
  16785. * to you under the Apache License, Version 2.0 (the
  16786. * "License"); you may not use this file except in compliance
  16787. * with the License. You may obtain a copy of the License at
  16788. *
  16789. * http://www.apache.org/licenses/LICENSE-2.0
  16790. *
  16791. * Unless required by applicable law or agreed to in writing,
  16792. * software distributed under the License is distributed on an
  16793. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16794. * KIND, either express or implied. See the License for the
  16795. * specific language governing permissions and limitations
  16796. * under the License.
  16797. */
  16798. // import Text from 'zrender/src/graphic/Text';
  16799. /**
  16800. * 每三位默认加,格式化
  16801. * @param {string|number} x
  16802. * @return {string}
  16803. */
  16804. function addCommas(x) {
  16805. if (isNaN(x)) {
  16806. return '-';
  16807. }
  16808. x = (x + '').split('.');
  16809. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16810. + (x.length > 1 ? ('.' + x[1]) : '');
  16811. }
  16812. /**
  16813. * @param {string} str
  16814. * @param {boolean} [upperCaseFirst=false]
  16815. * @return {string} str
  16816. */
  16817. var normalizeCssArray$1 = normalizeCssArray;
  16818. var replaceReg = /([&<>"'])/g;
  16819. var replaceMap = {
  16820. '&': '&amp;',
  16821. '<': '&lt;',
  16822. '>': '&gt;',
  16823. '"': '&quot;',
  16824. '\'': '&#39;'
  16825. };
  16826. function encodeHTML(source) {
  16827. return source == null
  16828. ? ''
  16829. : (source + '').replace(replaceReg, function (str, c) {
  16830. return replaceMap[c];
  16831. });
  16832. }
  16833. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16834. var wrapVar = function (varName, seriesIdx) {
  16835. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16836. };
  16837. /**
  16838. * Template formatter
  16839. * @param {string} tpl
  16840. * @param {Array.<Object>|Object} paramsList
  16841. * @param {boolean} [encode=false]
  16842. * @return {string}
  16843. */
  16844. function formatTpl(tpl, paramsList, encode) {
  16845. if (!isArray(paramsList)) {
  16846. paramsList = [paramsList];
  16847. }
  16848. var seriesLen = paramsList.length;
  16849. if (!seriesLen) {
  16850. return '';
  16851. }
  16852. var $vars = paramsList[0].$vars || [];
  16853. for (var i = 0; i < $vars.length; i++) {
  16854. var alias = TPL_VAR_ALIAS[i];
  16855. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16856. }
  16857. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16858. for (var k = 0; k < $vars.length; k++) {
  16859. var val = paramsList[seriesIdx][$vars[k]];
  16860. tpl = tpl.replace(
  16861. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16862. encode ? encodeHTML(val) : val
  16863. );
  16864. }
  16865. }
  16866. return tpl;
  16867. }
  16868. /**
  16869. * simple Template formatter
  16870. *
  16871. * @param {string} tpl
  16872. * @param {Object} param
  16873. * @param {boolean} [encode=false]
  16874. * @return {string}
  16875. */
  16876. /**
  16877. * @param {Object|string} [opt] If string, means color.
  16878. * @param {string} [opt.color]
  16879. * @param {string} [opt.extraCssText]
  16880. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16881. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16882. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16883. * @return {string}
  16884. */
  16885. function getTooltipMarker(opt, extraCssText) {
  16886. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16887. var color = opt.color;
  16888. var type = opt.type;
  16889. var extraCssText = opt.extraCssText;
  16890. var renderMode = opt.renderMode || 'html';
  16891. var markerId = opt.markerId || 'X';
  16892. if (!color) {
  16893. return '';
  16894. }
  16895. if (renderMode === 'html') {
  16896. return type === 'subItem'
  16897. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16898. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16899. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16900. : '<span style="display:inline-block;margin-right:5px;'
  16901. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16902. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16903. }
  16904. else {
  16905. // Space for rich element marker
  16906. return {
  16907. renderMode: renderMode,
  16908. content: '{marker' + markerId + '|} ',
  16909. style: {
  16910. color: color
  16911. }
  16912. };
  16913. }
  16914. }
  16915. function pad(str, len) {
  16916. str += '';
  16917. return '0000'.substr(0, len - str.length) + str;
  16918. }
  16919. /**
  16920. * ISO Date format
  16921. * @param {string} tpl
  16922. * @param {number} value
  16923. * @param {boolean} [isUTC=false] Default in local time.
  16924. * see `module:echarts/scale/Time`
  16925. * and `module:echarts/util/number#parseDate`.
  16926. * @inner
  16927. */
  16928. function formatTime(tpl, value, isUTC) {
  16929. if (tpl === 'week'
  16930. || tpl === 'month'
  16931. || tpl === 'quarter'
  16932. || tpl === 'half-year'
  16933. || tpl === 'year'
  16934. ) {
  16935. tpl = 'MM-dd\nyyyy';
  16936. }
  16937. var date = parseDate(value);
  16938. var utc = isUTC ? 'UTC' : '';
  16939. var y = date['get' + utc + 'FullYear']();
  16940. var M = date['get' + utc + 'Month']() + 1;
  16941. var d = date['get' + utc + 'Date']();
  16942. var h = date['get' + utc + 'Hours']();
  16943. var m = date['get' + utc + 'Minutes']();
  16944. var s = date['get' + utc + 'Seconds']();
  16945. var S = date['get' + utc + 'Milliseconds']();
  16946. tpl = tpl.replace('MM', pad(M, 2))
  16947. .replace('M', M)
  16948. .replace('yyyy', y)
  16949. .replace('yy', y % 100)
  16950. .replace('dd', pad(d, 2))
  16951. .replace('d', d)
  16952. .replace('hh', pad(h, 2))
  16953. .replace('h', h)
  16954. .replace('mm', pad(m, 2))
  16955. .replace('m', m)
  16956. .replace('ss', pad(s, 2))
  16957. .replace('s', s)
  16958. .replace('SSS', pad(S, 3));
  16959. return tpl;
  16960. }
  16961. /**
  16962. * Capital first
  16963. * @param {string} str
  16964. * @return {string}
  16965. */
  16966. var truncateText$1 = truncateText;
  16967. /**
  16968. * @public
  16969. * @param {Object} opt
  16970. * @param {string} opt.text
  16971. * @param {string} opt.font
  16972. * @param {string} [opt.textAlign='left']
  16973. * @param {string} [opt.textVerticalAlign='top']
  16974. * @param {Array.<number>} [opt.textPadding]
  16975. * @param {number} [opt.textLineHeight]
  16976. * @param {Object} [opt.rich]
  16977. * @param {Object} [opt.truncate]
  16978. * @return {Object} {x, y, width, height, lineHeight}
  16979. */
  16980. /**
  16981. * @deprecated
  16982. * the `textLineHeight` was added later.
  16983. * For backward compatiblility, put it as the last parameter.
  16984. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16985. */
  16986. /*
  16987. * Licensed to the Apache Software Foundation (ASF) under one
  16988. * or more contributor license agreements. See the NOTICE file
  16989. * distributed with this work for additional information
  16990. * regarding copyright ownership. The ASF licenses this file
  16991. * to you under the Apache License, Version 2.0 (the
  16992. * "License"); you may not use this file except in compliance
  16993. * with the License. You may obtain a copy of the License at
  16994. *
  16995. * http://www.apache.org/licenses/LICENSE-2.0
  16996. *
  16997. * Unless required by applicable law or agreed to in writing,
  16998. * software distributed under the License is distributed on an
  16999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17000. * KIND, either express or implied. See the License for the
  17001. * specific language governing permissions and limitations
  17002. * under the License.
  17003. */
  17004. // Layout helpers for each component positioning
  17005. var each$3 = each$1;
  17006. /**
  17007. * @public
  17008. */
  17009. var LOCATION_PARAMS = [
  17010. 'left', 'right', 'top', 'bottom', 'width', 'height'
  17011. ];
  17012. /**
  17013. * @public
  17014. */
  17015. var HV_NAMES = [
  17016. ['width', 'left', 'right'],
  17017. ['height', 'top', 'bottom']
  17018. ];
  17019. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  17020. var x = 0;
  17021. var y = 0;
  17022. if (maxWidth == null) {
  17023. maxWidth = Infinity;
  17024. }
  17025. if (maxHeight == null) {
  17026. maxHeight = Infinity;
  17027. }
  17028. var currentLineMaxSize = 0;
  17029. group.eachChild(function (child, idx) {
  17030. var position = child.position;
  17031. var rect = child.getBoundingRect();
  17032. var nextChild = group.childAt(idx + 1);
  17033. var nextChildRect = nextChild && nextChild.getBoundingRect();
  17034. var nextX;
  17035. var nextY;
  17036. if (orient === 'horizontal') {
  17037. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  17038. nextX = x + moveX;
  17039. // Wrap when width exceeds maxWidth or meet a `newline` group
  17040. // FIXME compare before adding gap?
  17041. if (nextX > maxWidth || child.newline) {
  17042. x = 0;
  17043. nextX = moveX;
  17044. y += currentLineMaxSize + gap;
  17045. currentLineMaxSize = rect.height;
  17046. }
  17047. else {
  17048. // FIXME: consider rect.y is not `0`?
  17049. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  17050. }
  17051. }
  17052. else {
  17053. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  17054. nextY = y + moveY;
  17055. // Wrap when width exceeds maxHeight or meet a `newline` group
  17056. if (nextY > maxHeight || child.newline) {
  17057. x += currentLineMaxSize + gap;
  17058. y = 0;
  17059. nextY = moveY;
  17060. currentLineMaxSize = rect.width;
  17061. }
  17062. else {
  17063. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  17064. }
  17065. }
  17066. if (child.newline) {
  17067. return;
  17068. }
  17069. position[0] = x;
  17070. position[1] = y;
  17071. orient === 'horizontal'
  17072. ? (x = nextX + gap)
  17073. : (y = nextY + gap);
  17074. });
  17075. }
  17076. /**
  17077. * VBox or HBox layouting
  17078. * @param {string} orient
  17079. * @param {module:zrender/container/Group} group
  17080. * @param {number} gap
  17081. * @param {number} [width=Infinity]
  17082. * @param {number} [height=Infinity]
  17083. */
  17084. /**
  17085. * VBox layouting
  17086. * @param {module:zrender/container/Group} group
  17087. * @param {number} gap
  17088. * @param {number} [width=Infinity]
  17089. * @param {number} [height=Infinity]
  17090. */
  17091. var vbox = curry(boxLayout, 'vertical');
  17092. /**
  17093. * HBox layouting
  17094. * @param {module:zrender/container/Group} group
  17095. * @param {number} gap
  17096. * @param {number} [width=Infinity]
  17097. * @param {number} [height=Infinity]
  17098. */
  17099. var hbox = curry(boxLayout, 'horizontal');
  17100. /**
  17101. * If x or x2 is not specified or 'center' 'left' 'right',
  17102. * the width would be as long as possible.
  17103. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17104. * the height would be as long as possible.
  17105. *
  17106. * @param {Object} positionInfo
  17107. * @param {number|string} [positionInfo.x]
  17108. * @param {number|string} [positionInfo.y]
  17109. * @param {number|string} [positionInfo.x2]
  17110. * @param {number|string} [positionInfo.y2]
  17111. * @param {Object} containerRect {width, height}
  17112. * @param {string|number} margin
  17113. * @return {Object} {width, height}
  17114. */
  17115. /**
  17116. * Parse position info.
  17117. *
  17118. * @param {Object} positionInfo
  17119. * @param {number|string} [positionInfo.left]
  17120. * @param {number|string} [positionInfo.top]
  17121. * @param {number|string} [positionInfo.right]
  17122. * @param {number|string} [positionInfo.bottom]
  17123. * @param {number|string} [positionInfo.width]
  17124. * @param {number|string} [positionInfo.height]
  17125. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17126. * @param {Object} containerRect
  17127. * @param {string|number} [margin]
  17128. *
  17129. * @return {module:zrender/core/BoundingRect}
  17130. */
  17131. function getLayoutRect(
  17132. positionInfo, containerRect, margin
  17133. ) {
  17134. margin = normalizeCssArray$1(margin || 0);
  17135. var containerWidth = containerRect.width;
  17136. var containerHeight = containerRect.height;
  17137. var left = parsePercent$1(positionInfo.left, containerWidth);
  17138. var top = parsePercent$1(positionInfo.top, containerHeight);
  17139. var right = parsePercent$1(positionInfo.right, containerWidth);
  17140. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17141. var width = parsePercent$1(positionInfo.width, containerWidth);
  17142. var height = parsePercent$1(positionInfo.height, containerHeight);
  17143. var verticalMargin = margin[2] + margin[0];
  17144. var horizontalMargin = margin[1] + margin[3];
  17145. var aspect = positionInfo.aspect;
  17146. // If width is not specified, calculate width from left and right
  17147. if (isNaN(width)) {
  17148. width = containerWidth - right - horizontalMargin - left;
  17149. }
  17150. if (isNaN(height)) {
  17151. height = containerHeight - bottom - verticalMargin - top;
  17152. }
  17153. if (aspect != null) {
  17154. // If width and height are not given
  17155. // 1. Graph should not exceeds the container
  17156. // 2. Aspect must be keeped
  17157. // 3. Graph should take the space as more as possible
  17158. // FIXME
  17159. // Margin is not considered, because there is no case that both
  17160. // using margin and aspect so far.
  17161. if (isNaN(width) && isNaN(height)) {
  17162. if (aspect > containerWidth / containerHeight) {
  17163. width = containerWidth * 0.8;
  17164. }
  17165. else {
  17166. height = containerHeight * 0.8;
  17167. }
  17168. }
  17169. // Calculate width or height with given aspect
  17170. if (isNaN(width)) {
  17171. width = aspect * height;
  17172. }
  17173. if (isNaN(height)) {
  17174. height = width / aspect;
  17175. }
  17176. }
  17177. // If left is not specified, calculate left from right and width
  17178. if (isNaN(left)) {
  17179. left = containerWidth - right - width - horizontalMargin;
  17180. }
  17181. if (isNaN(top)) {
  17182. top = containerHeight - bottom - height - verticalMargin;
  17183. }
  17184. // Align left and top
  17185. switch (positionInfo.left || positionInfo.right) {
  17186. case 'center':
  17187. left = containerWidth / 2 - width / 2 - margin[3];
  17188. break;
  17189. case 'right':
  17190. left = containerWidth - width - horizontalMargin;
  17191. break;
  17192. }
  17193. switch (positionInfo.top || positionInfo.bottom) {
  17194. case 'middle':
  17195. case 'center':
  17196. top = containerHeight / 2 - height / 2 - margin[0];
  17197. break;
  17198. case 'bottom':
  17199. top = containerHeight - height - verticalMargin;
  17200. break;
  17201. }
  17202. // If something is wrong and left, top, width, height are calculated as NaN
  17203. left = left || 0;
  17204. top = top || 0;
  17205. if (isNaN(width)) {
  17206. // Width may be NaN if only one value is given except width
  17207. width = containerWidth - horizontalMargin - left - (right || 0);
  17208. }
  17209. if (isNaN(height)) {
  17210. // Height may be NaN if only one value is given except height
  17211. height = containerHeight - verticalMargin - top - (bottom || 0);
  17212. }
  17213. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17214. rect.margin = margin;
  17215. return rect;
  17216. }
  17217. /**
  17218. * Position a zr element in viewport
  17219. * Group position is specified by either
  17220. * {left, top}, {right, bottom}
  17221. * If all properties exists, right and bottom will be igonred.
  17222. *
  17223. * Logic:
  17224. * 1. Scale (against origin point in parent coord)
  17225. * 2. Rotate (against origin point in parent coord)
  17226. * 3. Traslate (with el.position by this method)
  17227. * So this method only fixes the last step 'Traslate', which does not affect
  17228. * scaling and rotating.
  17229. *
  17230. * If be called repeatly with the same input el, the same result will be gotten.
  17231. *
  17232. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17233. * @param {Object} positionInfo
  17234. * @param {number|string} [positionInfo.left]
  17235. * @param {number|string} [positionInfo.top]
  17236. * @param {number|string} [positionInfo.right]
  17237. * @param {number|string} [positionInfo.bottom]
  17238. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17239. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17240. * @param {Object} containerRect
  17241. * @param {string|number} margin
  17242. * @param {Object} [opt]
  17243. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17244. * @param {Array.<number>} [opt.boundingMode='all']
  17245. * Specify how to calculate boundingRect when locating.
  17246. * 'all': Position the boundingRect that is transformed and uioned
  17247. * both itself and its descendants.
  17248. * This mode simplies confine the elements in the bounding
  17249. * of their container (e.g., using 'right: 0').
  17250. * 'raw': Position the boundingRect that is not transformed and only itself.
  17251. * This mode is useful when you want a element can overflow its
  17252. * container. (Consider a rotated circle needs to be located in a corner.)
  17253. * In this mode positionInfo.width/height can only be number.
  17254. */
  17255. /**
  17256. * @param {Object} option Contains some of the properties in HV_NAMES.
  17257. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17258. */
  17259. /**
  17260. * Consider Case:
  17261. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17262. * through setOption or media query, using normal zrUtil.merge will cause
  17263. * {right: 0} does not take effect.
  17264. *
  17265. * @example
  17266. * ComponentModel.extend({
  17267. * init: function () {
  17268. * ...
  17269. * var inputPositionParams = layout.getLayoutParams(option);
  17270. * this.mergeOption(inputPositionParams);
  17271. * },
  17272. * mergeOption: function (newOption) {
  17273. * newOption && zrUtil.merge(thisOption, newOption, true);
  17274. * layout.mergeLayoutParam(thisOption, newOption);
  17275. * }
  17276. * });
  17277. *
  17278. * @param {Object} targetOption
  17279. * @param {Object} newOption
  17280. * @param {Object|string} [opt]
  17281. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17282. * that width (or height) should not be calculated by left and right (or top and bottom).
  17283. */
  17284. function mergeLayoutParam(targetOption, newOption, opt) {
  17285. !isObject$1(opt) && (opt = {});
  17286. var ignoreSize = opt.ignoreSize;
  17287. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17288. var hResult = merge$$1(HV_NAMES[0], 0);
  17289. var vResult = merge$$1(HV_NAMES[1], 1);
  17290. copy(HV_NAMES[0], targetOption, hResult);
  17291. copy(HV_NAMES[1], targetOption, vResult);
  17292. function merge$$1(names, hvIdx) {
  17293. var newParams = {};
  17294. var newValueCount = 0;
  17295. var merged = {};
  17296. var mergedValueCount = 0;
  17297. var enoughParamNumber = 2;
  17298. each$3(names, function (name) {
  17299. merged[name] = targetOption[name];
  17300. });
  17301. each$3(names, function (name) {
  17302. // Consider case: newOption.width is null, which is
  17303. // set by user for removing width setting.
  17304. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17305. hasValue(newParams, name) && newValueCount++;
  17306. hasValue(merged, name) && mergedValueCount++;
  17307. });
  17308. if (ignoreSize[hvIdx]) {
  17309. // Only one of left/right is premitted to exist.
  17310. if (hasValue(newOption, names[1])) {
  17311. merged[names[2]] = null;
  17312. }
  17313. else if (hasValue(newOption, names[2])) {
  17314. merged[names[1]] = null;
  17315. }
  17316. return merged;
  17317. }
  17318. // Case: newOption: {width: ..., right: ...},
  17319. // or targetOption: {right: ...} and newOption: {width: ...},
  17320. // There is no conflict when merged only has params count
  17321. // little than enoughParamNumber.
  17322. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17323. return merged;
  17324. }
  17325. // Case: newOption: {width: ..., right: ...},
  17326. // Than we can make sure user only want those two, and ignore
  17327. // all origin params in targetOption.
  17328. else if (newValueCount >= enoughParamNumber) {
  17329. return newParams;
  17330. }
  17331. else {
  17332. // Chose another param from targetOption by priority.
  17333. for (var i = 0; i < names.length; i++) {
  17334. var name = names[i];
  17335. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17336. newParams[name] = targetOption[name];
  17337. break;
  17338. }
  17339. }
  17340. return newParams;
  17341. }
  17342. }
  17343. function hasProp(obj, name) {
  17344. return obj.hasOwnProperty(name);
  17345. }
  17346. function hasValue(obj, name) {
  17347. return obj[name] != null && obj[name] !== 'auto';
  17348. }
  17349. function copy(names, target, source) {
  17350. each$3(names, function (name) {
  17351. target[name] = source[name];
  17352. });
  17353. }
  17354. }
  17355. /**
  17356. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17357. * @param {Object} source
  17358. * @return {Object} Result contains those props.
  17359. */
  17360. function getLayoutParams(source) {
  17361. return copyLayoutParams({}, source);
  17362. }
  17363. /**
  17364. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17365. * @param {Object} source
  17366. * @return {Object} Result contains those props.
  17367. */
  17368. function copyLayoutParams(target, source) {
  17369. source && target && each$3(LOCATION_PARAMS, function (name) {
  17370. source.hasOwnProperty(name) && (target[name] = source[name]);
  17371. });
  17372. return target;
  17373. }
  17374. /*
  17375. * Licensed to the Apache Software Foundation (ASF) under one
  17376. * or more contributor license agreements. See the NOTICE file
  17377. * distributed with this work for additional information
  17378. * regarding copyright ownership. The ASF licenses this file
  17379. * to you under the Apache License, Version 2.0 (the
  17380. * "License"); you may not use this file except in compliance
  17381. * with the License. You may obtain a copy of the License at
  17382. *
  17383. * http://www.apache.org/licenses/LICENSE-2.0
  17384. *
  17385. * Unless required by applicable law or agreed to in writing,
  17386. * software distributed under the License is distributed on an
  17387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17388. * KIND, either express or implied. See the License for the
  17389. * specific language governing permissions and limitations
  17390. * under the License.
  17391. */
  17392. var boxLayoutMixin = {
  17393. getBoxLayoutParams: function () {
  17394. return {
  17395. left: this.get('left'),
  17396. top: this.get('top'),
  17397. right: this.get('right'),
  17398. bottom: this.get('bottom'),
  17399. width: this.get('width'),
  17400. height: this.get('height')
  17401. };
  17402. }
  17403. };
  17404. /*
  17405. * Licensed to the Apache Software Foundation (ASF) under one
  17406. * or more contributor license agreements. See the NOTICE file
  17407. * distributed with this work for additional information
  17408. * regarding copyright ownership. The ASF licenses this file
  17409. * to you under the Apache License, Version 2.0 (the
  17410. * "License"); you may not use this file except in compliance
  17411. * with the License. You may obtain a copy of the License at
  17412. *
  17413. * http://www.apache.org/licenses/LICENSE-2.0
  17414. *
  17415. * Unless required by applicable law or agreed to in writing,
  17416. * software distributed under the License is distributed on an
  17417. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17418. * KIND, either express or implied. See the License for the
  17419. * specific language governing permissions and limitations
  17420. * under the License.
  17421. */
  17422. /**
  17423. * Component model
  17424. *
  17425. * @module echarts/model/Component
  17426. */
  17427. var inner$1 = makeInner();
  17428. /**
  17429. * @alias module:echarts/model/Component
  17430. * @constructor
  17431. * @param {Object} option
  17432. * @param {module:echarts/model/Model} parentModel
  17433. * @param {module:echarts/model/Model} ecModel
  17434. */
  17435. var ComponentModel = Model.extend({
  17436. type: 'component',
  17437. /**
  17438. * @readOnly
  17439. * @type {string}
  17440. */
  17441. id: '',
  17442. /**
  17443. * Because simplified concept is probably better, series.name (or component.name)
  17444. * has been having too many resposibilities:
  17445. * (1) Generating id (which requires name in option should not be modified).
  17446. * (2) As an index to mapping series when merging option or calling API (a name
  17447. * can refer to more then one components, which is convinient is some case).
  17448. * (3) Display.
  17449. * @readOnly
  17450. */
  17451. name: '',
  17452. /**
  17453. * @readOnly
  17454. * @type {string}
  17455. */
  17456. mainType: '',
  17457. /**
  17458. * @readOnly
  17459. * @type {string}
  17460. */
  17461. subType: '',
  17462. /**
  17463. * @readOnly
  17464. * @type {number}
  17465. */
  17466. componentIndex: 0,
  17467. /**
  17468. * @type {Object}
  17469. * @protected
  17470. */
  17471. defaultOption: null,
  17472. /**
  17473. * @type {module:echarts/model/Global}
  17474. * @readOnly
  17475. */
  17476. ecModel: null,
  17477. /**
  17478. * key: componentType
  17479. * value: Component model list, can not be null.
  17480. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17481. * @readOnly
  17482. */
  17483. dependentModels: [],
  17484. /**
  17485. * @type {string}
  17486. * @readOnly
  17487. */
  17488. uid: null,
  17489. /**
  17490. * Support merge layout params.
  17491. * Only support 'box' now (left/right/top/bottom/width/height).
  17492. * @type {string|Object} Object can be {ignoreSize: true}
  17493. * @readOnly
  17494. */
  17495. layoutMode: null,
  17496. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17497. Model.call(this, option, parentModel, ecModel, extraOpt);
  17498. this.uid = getUID('ec_cpt_model');
  17499. },
  17500. init: function (option, parentModel, ecModel, extraOpt) {
  17501. this.mergeDefaultAndTheme(option, ecModel);
  17502. },
  17503. mergeDefaultAndTheme: function (option, ecModel) {
  17504. var layoutMode = this.layoutMode;
  17505. var inputPositionParams = layoutMode
  17506. ? getLayoutParams(option) : {};
  17507. var themeModel = ecModel.getTheme();
  17508. merge(option, themeModel.get(this.mainType));
  17509. merge(option, this.getDefaultOption());
  17510. if (layoutMode) {
  17511. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17512. }
  17513. },
  17514. mergeOption: function (option, extraOpt) {
  17515. merge(this.option, option, true);
  17516. var layoutMode = this.layoutMode;
  17517. if (layoutMode) {
  17518. mergeLayoutParam(this.option, option, layoutMode);
  17519. }
  17520. },
  17521. // Hooker after init or mergeOption
  17522. optionUpdated: function (newCptOption, isInit) {},
  17523. getDefaultOption: function () {
  17524. var fields = inner$1(this);
  17525. if (!fields.defaultOption) {
  17526. var optList = [];
  17527. var Class = this.constructor;
  17528. while (Class) {
  17529. var opt = Class.prototype.defaultOption;
  17530. opt && optList.push(opt);
  17531. Class = Class.superClass;
  17532. }
  17533. var defaultOption = {};
  17534. for (var i = optList.length - 1; i >= 0; i--) {
  17535. defaultOption = merge(defaultOption, optList[i], true);
  17536. }
  17537. fields.defaultOption = defaultOption;
  17538. }
  17539. return fields.defaultOption;
  17540. },
  17541. getReferringComponents: function (mainType) {
  17542. return this.ecModel.queryComponents({
  17543. mainType: mainType,
  17544. index: this.get(mainType + 'Index', true),
  17545. id: this.get(mainType + 'Id', true)
  17546. });
  17547. }
  17548. });
  17549. // Reset ComponentModel.extend, add preConstruct.
  17550. // clazzUtil.enableClassExtend(
  17551. // ComponentModel,
  17552. // function (option, parentModel, ecModel, extraOpt) {
  17553. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17554. // zrUtil.extend(this, extraOpt);
  17555. // this.uid = componentUtil.getUID('componentModel');
  17556. // // this.setReadOnly([
  17557. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17558. // // 'dependentModels', 'componentIndex'
  17559. // // ]);
  17560. // }
  17561. // );
  17562. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17563. enableClassManagement(
  17564. ComponentModel, {registerWhenExtend: true}
  17565. );
  17566. enableSubTypeDefaulter(ComponentModel);
  17567. // Add capability of ComponentModel.topologicalTravel.
  17568. enableTopologicalTravel(ComponentModel, getDependencies);
  17569. function getDependencies(componentType) {
  17570. var deps = [];
  17571. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17572. deps = deps.concat(Clazz.prototype.dependencies || []);
  17573. });
  17574. // Ensure main type.
  17575. deps = map(deps, function (type) {
  17576. return parseClassType$1(type).main;
  17577. });
  17578. // Hack dataset for convenience.
  17579. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17580. deps.unshift('dataset');
  17581. }
  17582. return deps;
  17583. }
  17584. mixin(ComponentModel, boxLayoutMixin);
  17585. /*
  17586. * Licensed to the Apache Software Foundation (ASF) under one
  17587. * or more contributor license agreements. See the NOTICE file
  17588. * distributed with this work for additional information
  17589. * regarding copyright ownership. The ASF licenses this file
  17590. * to you under the Apache License, Version 2.0 (the
  17591. * "License"); you may not use this file except in compliance
  17592. * with the License. You may obtain a copy of the License at
  17593. *
  17594. * http://www.apache.org/licenses/LICENSE-2.0
  17595. *
  17596. * Unless required by applicable law or agreed to in writing,
  17597. * software distributed under the License is distributed on an
  17598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17599. * KIND, either express or implied. See the License for the
  17600. * specific language governing permissions and limitations
  17601. * under the License.
  17602. */
  17603. var platform = '';
  17604. // Navigator not exists in node
  17605. if (typeof navigator !== 'undefined') {
  17606. platform = navigator.platform || '';
  17607. }
  17608. var globalDefault = {
  17609. // backgroundColor: 'rgba(0,0,0,0)',
  17610. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17611. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17612. // Light colors:
  17613. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17614. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17615. // Dark colors:
  17616. color: [
  17617. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17618. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17619. ],
  17620. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17621. // If xAxis and yAxis declared, grid is created by default.
  17622. // grid: {},
  17623. textStyle: {
  17624. // color: '#000',
  17625. // decoration: 'none',
  17626. // PENDING
  17627. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17628. // fontFamily: 'Arial, Verdana, sans-serif',
  17629. fontSize: 12,
  17630. fontStyle: 'normal',
  17631. fontWeight: 'normal'
  17632. },
  17633. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17634. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17635. // Default is source-over
  17636. blendMode: null,
  17637. animation: 'auto',
  17638. animationDuration: 1000,
  17639. animationDurationUpdate: 300,
  17640. animationEasing: 'exponentialOut',
  17641. animationEasingUpdate: 'cubicOut',
  17642. animationThreshold: 2000,
  17643. // Configuration for progressive/incremental rendering
  17644. progressiveThreshold: 3000,
  17645. progressive: 400,
  17646. // Threshold of if use single hover layer to optimize.
  17647. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17648. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17649. // which is unexpected.
  17650. // see example <echarts/test/heatmap-large.html>.
  17651. hoverLayerThreshold: 3000,
  17652. // See: module:echarts/scale/Time
  17653. useUTC: false
  17654. };
  17655. /*
  17656. * Licensed to the Apache Software Foundation (ASF) under one
  17657. * or more contributor license agreements. See the NOTICE file
  17658. * distributed with this work for additional information
  17659. * regarding copyright ownership. The ASF licenses this file
  17660. * to you under the Apache License, Version 2.0 (the
  17661. * "License"); you may not use this file except in compliance
  17662. * with the License. You may obtain a copy of the License at
  17663. *
  17664. * http://www.apache.org/licenses/LICENSE-2.0
  17665. *
  17666. * Unless required by applicable law or agreed to in writing,
  17667. * software distributed under the License is distributed on an
  17668. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17669. * KIND, either express or implied. See the License for the
  17670. * specific language governing permissions and limitations
  17671. * under the License.
  17672. */
  17673. var inner$2 = makeInner();
  17674. function getNearestColorPalette(colors, requestColorNum) {
  17675. var paletteNum = colors.length;
  17676. // TODO colors must be in order
  17677. for (var i = 0; i < paletteNum; i++) {
  17678. if (colors[i].length > requestColorNum) {
  17679. return colors[i];
  17680. }
  17681. }
  17682. return colors[paletteNum - 1];
  17683. }
  17684. var colorPaletteMixin = {
  17685. clearColorPalette: function () {
  17686. inner$2(this).colorIdx = 0;
  17687. inner$2(this).colorNameMap = {};
  17688. },
  17689. /**
  17690. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17691. * twise with the same parameters will get different result.
  17692. * @param {Object} [scope=this]
  17693. * @param {Object} [requestColorNum]
  17694. * @return {string} color string.
  17695. */
  17696. getColorFromPalette: function (name, scope, requestColorNum) {
  17697. scope = scope || this;
  17698. var scopeFields = inner$2(scope);
  17699. var colorIdx = scopeFields.colorIdx || 0;
  17700. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17701. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17702. if (colorNameMap.hasOwnProperty(name)) {
  17703. return colorNameMap[name];
  17704. }
  17705. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17706. var layeredColorPalette = this.get('colorLayer', true);
  17707. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17708. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17709. // In case can't find in layered color palette.
  17710. colorPalette = colorPalette || defaultColorPalette;
  17711. if (!colorPalette || !colorPalette.length) {
  17712. return;
  17713. }
  17714. var color = colorPalette[colorIdx];
  17715. if (name) {
  17716. colorNameMap[name] = color;
  17717. }
  17718. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17719. return color;
  17720. }
  17721. };
  17722. /*
  17723. * Licensed to the Apache Software Foundation (ASF) under one
  17724. * or more contributor license agreements. See the NOTICE file
  17725. * distributed with this work for additional information
  17726. * regarding copyright ownership. The ASF licenses this file
  17727. * to you under the Apache License, Version 2.0 (the
  17728. * "License"); you may not use this file except in compliance
  17729. * with the License. You may obtain a copy of the License at
  17730. *
  17731. * http://www.apache.org/licenses/LICENSE-2.0
  17732. *
  17733. * Unless required by applicable law or agreed to in writing,
  17734. * software distributed under the License is distributed on an
  17735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17736. * KIND, either express or implied. See the License for the
  17737. * specific language governing permissions and limitations
  17738. * under the License.
  17739. */
  17740. // Avoid typo.
  17741. var SOURCE_FORMAT_ORIGINAL = 'original';
  17742. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17743. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17744. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17745. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17746. // ??? CHANGE A NAME
  17747. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17748. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17749. var SERIES_LAYOUT_BY_ROW = 'row';
  17750. /*
  17751. * Licensed to the Apache Software Foundation (ASF) under one
  17752. * or more contributor license agreements. See the NOTICE file
  17753. * distributed with this work for additional information
  17754. * regarding copyright ownership. The ASF licenses this file
  17755. * to you under the Apache License, Version 2.0 (the
  17756. * "License"); you may not use this file except in compliance
  17757. * with the License. You may obtain a copy of the License at
  17758. *
  17759. * http://www.apache.org/licenses/LICENSE-2.0
  17760. *
  17761. * Unless required by applicable law or agreed to in writing,
  17762. * software distributed under the License is distributed on an
  17763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17764. * KIND, either express or implied. See the License for the
  17765. * specific language governing permissions and limitations
  17766. * under the License.
  17767. */
  17768. /**
  17769. * [sourceFormat]
  17770. *
  17771. * + "original":
  17772. * This format is only used in series.data, where
  17773. * itemStyle can be specified in data item.
  17774. *
  17775. * + "arrayRows":
  17776. * [
  17777. * ['product', 'score', 'amount'],
  17778. * ['Matcha Latte', 89.3, 95.8],
  17779. * ['Milk Tea', 92.1, 89.4],
  17780. * ['Cheese Cocoa', 94.4, 91.2],
  17781. * ['Walnut Brownie', 85.4, 76.9]
  17782. * ]
  17783. *
  17784. * + "objectRows":
  17785. * [
  17786. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17787. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17788. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17789. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17790. * ]
  17791. *
  17792. * + "keyedColumns":
  17793. * {
  17794. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17795. * 'count': [823, 235, 1042, 988],
  17796. * 'score': [95.8, 81.4, 91.2, 76.9]
  17797. * }
  17798. *
  17799. * + "typedArray"
  17800. *
  17801. * + "unknown"
  17802. */
  17803. /**
  17804. * @constructor
  17805. * @param {Object} fields
  17806. * @param {string} fields.sourceFormat
  17807. * @param {Array|Object} fields.fromDataset
  17808. * @param {Array|Object} [fields.data]
  17809. * @param {string} [seriesLayoutBy='column']
  17810. * @param {Array.<Object|string>} [dimensionsDefine]
  17811. * @param {Objet|HashMap} [encodeDefine]
  17812. * @param {number} [startIndex=0]
  17813. * @param {number} [dimensionsDetectCount]
  17814. */
  17815. function Source(fields) {
  17816. /**
  17817. * @type {boolean}
  17818. */
  17819. this.fromDataset = fields.fromDataset;
  17820. /**
  17821. * Not null/undefined.
  17822. * @type {Array|Object}
  17823. */
  17824. this.data = fields.data || (
  17825. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17826. );
  17827. /**
  17828. * See also "detectSourceFormat".
  17829. * Not null/undefined.
  17830. * @type {string}
  17831. */
  17832. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17833. /**
  17834. * 'row' or 'column'
  17835. * Not null/undefined.
  17836. * @type {string} seriesLayoutBy
  17837. */
  17838. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17839. /**
  17840. * dimensions definition in option.
  17841. * can be null/undefined.
  17842. * @type {Array.<Object|string>}
  17843. */
  17844. this.dimensionsDefine = fields.dimensionsDefine;
  17845. /**
  17846. * encode definition in option.
  17847. * can be null/undefined.
  17848. * @type {Objet|HashMap}
  17849. */
  17850. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17851. /**
  17852. * Not null/undefined, uint.
  17853. * @type {number}
  17854. */
  17855. this.startIndex = fields.startIndex || 0;
  17856. /**
  17857. * Can be null/undefined (when unknown), uint.
  17858. * @type {number}
  17859. */
  17860. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17861. }
  17862. /**
  17863. * Wrap original series data for some compatibility cases.
  17864. */
  17865. Source.seriesDataToSource = function (data) {
  17866. return new Source({
  17867. data: data,
  17868. sourceFormat: isTypedArray(data)
  17869. ? SOURCE_FORMAT_TYPED_ARRAY
  17870. : SOURCE_FORMAT_ORIGINAL,
  17871. fromDataset: false
  17872. });
  17873. };
  17874. enableClassCheck(Source);
  17875. /*
  17876. * Licensed to the Apache Software Foundation (ASF) under one
  17877. * or more contributor license agreements. See the NOTICE file
  17878. * distributed with this work for additional information
  17879. * regarding copyright ownership. The ASF licenses this file
  17880. * to you under the Apache License, Version 2.0 (the
  17881. * "License"); you may not use this file except in compliance
  17882. * with the License. You may obtain a copy of the License at
  17883. *
  17884. * http://www.apache.org/licenses/LICENSE-2.0
  17885. *
  17886. * Unless required by applicable law or agreed to in writing,
  17887. * software distributed under the License is distributed on an
  17888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17889. * KIND, either express or implied. See the License for the
  17890. * specific language governing permissions and limitations
  17891. * under the License.
  17892. */
  17893. // The result of `guessOrdinal`.
  17894. var BE_ORDINAL = {
  17895. Must: 1, // Encounter string but not '-' and not number-like.
  17896. Might: 2, // Encounter string but number-like.
  17897. Not: 3 // Other cases
  17898. };
  17899. var inner$3 = makeInner();
  17900. /**
  17901. * @see {module:echarts/data/Source}
  17902. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17903. * @return {string} sourceFormat
  17904. */
  17905. function detectSourceFormat(datasetModel) {
  17906. var data = datasetModel.option.source;
  17907. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17908. if (isTypedArray(data)) {
  17909. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17910. }
  17911. else if (isArray(data)) {
  17912. // FIXME Whether tolerate null in top level array?
  17913. if (data.length === 0) {
  17914. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17915. }
  17916. for (var i = 0, len = data.length; i < len; i++) {
  17917. var item = data[i];
  17918. if (item == null) {
  17919. continue;
  17920. }
  17921. else if (isArray(item)) {
  17922. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17923. break;
  17924. }
  17925. else if (isObject$1(item)) {
  17926. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17927. break;
  17928. }
  17929. }
  17930. }
  17931. else if (isObject$1(data)) {
  17932. for (var key in data) {
  17933. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17934. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17935. break;
  17936. }
  17937. }
  17938. }
  17939. else if (data != null) {
  17940. throw new Error('Invalid data');
  17941. }
  17942. inner$3(datasetModel).sourceFormat = sourceFormat;
  17943. }
  17944. /**
  17945. * [Scenarios]:
  17946. * (1) Provide source data directly:
  17947. * series: {
  17948. * encode: {...},
  17949. * dimensions: [...]
  17950. * seriesLayoutBy: 'row',
  17951. * data: [[...]]
  17952. * }
  17953. * (2) Refer to datasetModel.
  17954. * series: [{
  17955. * encode: {...}
  17956. * // Ignore datasetIndex means `datasetIndex: 0`
  17957. * // and the dimensions defination in dataset is used
  17958. * }, {
  17959. * encode: {...},
  17960. * seriesLayoutBy: 'column',
  17961. * datasetIndex: 1
  17962. * }]
  17963. *
  17964. * Get data from series itself or datset.
  17965. * @return {module:echarts/data/Source} source
  17966. */
  17967. function getSource(seriesModel) {
  17968. return inner$3(seriesModel).source;
  17969. }
  17970. /**
  17971. * MUST be called before mergeOption of all series.
  17972. * @param {module:echarts/model/Global} ecModel
  17973. */
  17974. function resetSourceDefaulter(ecModel) {
  17975. // `datasetMap` is used to make default encode.
  17976. inner$3(ecModel).datasetMap = createHashMap();
  17977. }
  17978. /**
  17979. * [Caution]:
  17980. * MUST be called after series option merged and
  17981. * before "series.getInitailData()" called.
  17982. *
  17983. * [The rule of making default encode]:
  17984. * Category axis (if exists) alway map to the first dimension.
  17985. * Each other axis occupies a subsequent dimension.
  17986. *
  17987. * [Why make default encode]:
  17988. * Simplify the typing of encode in option, avoiding the case like that:
  17989. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17990. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17991. *
  17992. * @param {module:echarts/model/Series} seriesModel
  17993. */
  17994. function prepareSource(seriesModel) {
  17995. var seriesOption = seriesModel.option;
  17996. var data = seriesOption.data;
  17997. var sourceFormat = isTypedArray(data)
  17998. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17999. var fromDataset = false;
  18000. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  18001. var sourceHeader = seriesOption.sourceHeader;
  18002. var dimensionsDefine = seriesOption.dimensions;
  18003. var datasetModel = getDatasetModel(seriesModel);
  18004. if (datasetModel) {
  18005. var datasetOption = datasetModel.option;
  18006. data = datasetOption.source;
  18007. sourceFormat = inner$3(datasetModel).sourceFormat;
  18008. fromDataset = true;
  18009. // These settings from series has higher priority.
  18010. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  18011. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  18012. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  18013. }
  18014. var completeResult = completeBySourceData(
  18015. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  18016. );
  18017. inner$3(seriesModel).source = new Source({
  18018. data: data,
  18019. fromDataset: fromDataset,
  18020. seriesLayoutBy: seriesLayoutBy,
  18021. sourceFormat: sourceFormat,
  18022. dimensionsDefine: completeResult.dimensionsDefine,
  18023. startIndex: completeResult.startIndex,
  18024. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  18025. // Note: dataset option does not have `encode`.
  18026. encodeDefine: seriesOption.encode
  18027. });
  18028. }
  18029. // return {startIndex, dimensionsDefine, dimensionsCount}
  18030. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  18031. if (!data) {
  18032. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  18033. }
  18034. var dimensionsDetectCount;
  18035. var startIndex;
  18036. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18037. // Rule: Most of the first line are string: it is header.
  18038. // Caution: consider a line with 5 string and 1 number,
  18039. // it still can not be sure it is a head, because the
  18040. // 5 string may be 5 values of category columns.
  18041. if (sourceHeader === 'auto' || sourceHeader == null) {
  18042. arrayRowsTravelFirst(function (val) {
  18043. // '-' is regarded as null/undefined.
  18044. if (val != null && val !== '-') {
  18045. if (isString(val)) {
  18046. startIndex == null && (startIndex = 1);
  18047. }
  18048. else {
  18049. startIndex = 0;
  18050. }
  18051. }
  18052. // 10 is an experience number, avoid long loop.
  18053. }, seriesLayoutBy, data, 10);
  18054. }
  18055. else {
  18056. startIndex = sourceHeader ? 1 : 0;
  18057. }
  18058. if (!dimensionsDefine && startIndex === 1) {
  18059. dimensionsDefine = [];
  18060. arrayRowsTravelFirst(function (val, index) {
  18061. dimensionsDefine[index] = val != null ? val : '';
  18062. }, seriesLayoutBy, data);
  18063. }
  18064. dimensionsDetectCount = dimensionsDefine
  18065. ? dimensionsDefine.length
  18066. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  18067. ? data.length
  18068. : data[0]
  18069. ? data[0].length
  18070. : null;
  18071. }
  18072. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18073. if (!dimensionsDefine) {
  18074. dimensionsDefine = objectRowsCollectDimensions(data);
  18075. }
  18076. }
  18077. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18078. if (!dimensionsDefine) {
  18079. dimensionsDefine = [];
  18080. each$1(data, function (colArr, key) {
  18081. dimensionsDefine.push(key);
  18082. });
  18083. }
  18084. }
  18085. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18086. var value0 = getDataItemValue(data[0]);
  18087. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  18088. }
  18089. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18090. if (__DEV__) {
  18091. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18092. }
  18093. }
  18094. return {
  18095. startIndex: startIndex,
  18096. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18097. dimensionsDetectCount: dimensionsDetectCount
  18098. };
  18099. }
  18100. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18101. // which is reasonable. But dimension name is duplicated.
  18102. // Returns undefined or an array contains only object without null/undefiend or string.
  18103. function normalizeDimensionsDefine(dimensionsDefine) {
  18104. if (!dimensionsDefine) {
  18105. // The meaning of null/undefined is different from empty array.
  18106. return;
  18107. }
  18108. var nameMap = createHashMap();
  18109. return map(dimensionsDefine, function (item, index) {
  18110. item = extend({}, isObject$1(item) ? item : {name: item});
  18111. // User can set null in dimensions.
  18112. // We dont auto specify name, othewise a given name may
  18113. // cause it be refered unexpectedly.
  18114. if (item.name == null) {
  18115. return item;
  18116. }
  18117. // Also consider number form like 2012.
  18118. item.name += '';
  18119. // User may also specify displayName.
  18120. // displayName will always exists except user not
  18121. // specified or dim name is not specified or detected.
  18122. // (A auto generated dim name will not be used as
  18123. // displayName).
  18124. if (item.displayName == null) {
  18125. item.displayName = item.name;
  18126. }
  18127. var exist = nameMap.get(item.name);
  18128. if (!exist) {
  18129. nameMap.set(item.name, {count: 1});
  18130. }
  18131. else {
  18132. item.name += '-' + exist.count++;
  18133. }
  18134. return item;
  18135. });
  18136. }
  18137. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18138. maxLoop == null && (maxLoop = Infinity);
  18139. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18140. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18141. cb(data[i] ? data[i][0] : null, i);
  18142. }
  18143. }
  18144. else {
  18145. var value0 = data[0] || [];
  18146. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18147. cb(value0[i], i);
  18148. }
  18149. }
  18150. }
  18151. function objectRowsCollectDimensions(data) {
  18152. var firstIndex = 0;
  18153. var obj;
  18154. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18155. if (obj) {
  18156. var dimensions = [];
  18157. each$1(obj, function (value, key) {
  18158. dimensions.push(key);
  18159. });
  18160. return dimensions;
  18161. }
  18162. }
  18163. /**
  18164. * [The strategy of the arrengment of data dimensions for dataset]:
  18165. * "value way": all axes are non-category axes. So series one by one take
  18166. * several (the number is coordSysDims.length) dimensions from dataset.
  18167. * The result of data arrengment of data dimensions like:
  18168. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18169. * "category way": at least one axis is category axis. So the the first data
  18170. * dimension is always mapped to the first category axis and shared by
  18171. * all of the series. The other data dimensions are taken by series like
  18172. * "value way" does.
  18173. * The result of data arrengment of data dimensions like:
  18174. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18175. *
  18176. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18177. * @param {module:model/Series} seriesModel
  18178. * @param {module:data/Source} source
  18179. * @return {Object} encode Never be `null/undefined`.
  18180. */
  18181. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18182. var encode = {};
  18183. var datasetModel = getDatasetModel(seriesModel);
  18184. // Currently only make default when using dataset, util more reqirements occur.
  18185. if (!datasetModel || !coordDimensions) {
  18186. return encode;
  18187. }
  18188. var encodeItemName = [];
  18189. var encodeSeriesName = [];
  18190. var ecModel = seriesModel.ecModel;
  18191. var datasetMap = inner$3(ecModel).datasetMap;
  18192. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18193. var baseCategoryDimIndex;
  18194. var categoryWayValueDimStart;
  18195. coordDimensions = coordDimensions.slice();
  18196. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18197. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18198. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18199. baseCategoryDimIndex = coordDimIdx;
  18200. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18201. }
  18202. encode[coordDimInfo.name] = [];
  18203. });
  18204. var datasetRecord = datasetMap.get(key)
  18205. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18206. // TODO
  18207. // Auto detect first time axis and do arrangement.
  18208. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18209. var coordDimName = coordDimInfo.name;
  18210. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18211. // In value way.
  18212. if (baseCategoryDimIndex == null) {
  18213. var start = datasetRecord.valueWayDim;
  18214. pushDim(encode[coordDimName], start, count);
  18215. pushDim(encodeSeriesName, start, count);
  18216. datasetRecord.valueWayDim += count;
  18217. // ??? TODO give a better default series name rule?
  18218. // especially when encode x y specified.
  18219. // consider: when mutiple series share one dimension
  18220. // category axis, series name should better use
  18221. // the other dimsion name. On the other hand, use
  18222. // both dimensions name.
  18223. }
  18224. // In category way, the first category axis.
  18225. else if (baseCategoryDimIndex === coordDimIdx) {
  18226. pushDim(encode[coordDimName], 0, count);
  18227. pushDim(encodeItemName, 0, count);
  18228. }
  18229. // In category way, the other axis.
  18230. else {
  18231. var start = datasetRecord.categoryWayDim;
  18232. pushDim(encode[coordDimName], start, count);
  18233. pushDim(encodeSeriesName, start, count);
  18234. datasetRecord.categoryWayDim += count;
  18235. }
  18236. });
  18237. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18238. for (var i = 0; i < idxCount; i++) {
  18239. dimIdxArr.push(idxFrom + i);
  18240. }
  18241. }
  18242. function getDataDimCountOnCoordDim(coordDimInfo) {
  18243. var dimsDef = coordDimInfo.dimsDef;
  18244. return dimsDef ? dimsDef.length : 1;
  18245. }
  18246. encodeItemName.length && (encode.itemName = encodeItemName);
  18247. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18248. return encode;
  18249. }
  18250. /**
  18251. * Work for data like [{name: ..., value: ...}, ...].
  18252. *
  18253. * @param {module:model/Series} seriesModel
  18254. * @param {module:data/Source} source
  18255. * @return {Object} encode Never be `null/undefined`.
  18256. */
  18257. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18258. var encode = {};
  18259. var datasetModel = getDatasetModel(seriesModel);
  18260. // Currently only make default when using dataset, util more reqirements occur.
  18261. if (!datasetModel) {
  18262. return encode;
  18263. }
  18264. var sourceFormat = source.sourceFormat;
  18265. var dimensionsDefine = source.dimensionsDefine;
  18266. var potentialNameDimIndex;
  18267. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18268. each$1(dimensionsDefine, function (dim, idx) {
  18269. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18270. potentialNameDimIndex = idx;
  18271. }
  18272. });
  18273. }
  18274. // idxResult: {v, n}.
  18275. var idxResult = (function () {
  18276. var idxRes0 = {};
  18277. var idxRes1 = {};
  18278. var guessRecords = [];
  18279. // 5 is an experience value.
  18280. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18281. var guessResult = doGuessOrdinal(
  18282. source.data, sourceFormat, source.seriesLayoutBy,
  18283. dimensionsDefine, source.startIndex, i
  18284. );
  18285. guessRecords.push(guessResult);
  18286. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18287. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18288. // and then find a name dim with the priority:
  18289. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18290. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18291. idxRes0.v = i;
  18292. }
  18293. if (idxRes0.n == null
  18294. || (idxRes0.n === idxRes0.v)
  18295. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18296. ) {
  18297. idxRes0.n = i;
  18298. }
  18299. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18300. return idxRes0;
  18301. }
  18302. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18303. // find the first BE_ORDINAL.Might as the value dim,
  18304. // and then find a name dim with the priority:
  18305. // "other dim" > "the value dim itself".
  18306. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18307. // treated as number.
  18308. if (!isPureNumber) {
  18309. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18310. idxRes1.v = i;
  18311. }
  18312. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18313. idxRes1.n = i;
  18314. }
  18315. }
  18316. }
  18317. function fulfilled(idxResult) {
  18318. return idxResult.v != null && idxResult.n != null;
  18319. }
  18320. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18321. })();
  18322. if (idxResult) {
  18323. encode.value = idxResult.v;
  18324. // `potentialNameDimIndex` has highest priority.
  18325. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18326. // By default, label use itemName in charts.
  18327. // So we dont set encodeLabel here.
  18328. encode.itemName = [nameDimIndex];
  18329. encode.seriesName = [nameDimIndex];
  18330. }
  18331. return encode;
  18332. }
  18333. /**
  18334. * If return null/undefined, indicate that should not use datasetModel.
  18335. */
  18336. function getDatasetModel(seriesModel) {
  18337. var option = seriesModel.option;
  18338. // Caution: consider the scenario:
  18339. // A dataset is declared and a series is not expected to use the dataset,
  18340. // and at the beginning `setOption({series: { noData })` (just prepare other
  18341. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18342. // the user should set an empty array to avoid that dataset is used by default.
  18343. var thisData = option.data;
  18344. if (!thisData) {
  18345. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18346. }
  18347. }
  18348. /**
  18349. * The rule should not be complex, otherwise user might not
  18350. * be able to known where the data is wrong.
  18351. * The code is ugly, but how to make it neat?
  18352. *
  18353. * @param {module:echars/data/Source} source
  18354. * @param {number} dimIndex
  18355. * @return {BE_ORDINAL} guess result.
  18356. */
  18357. function guessOrdinal(source, dimIndex) {
  18358. return doGuessOrdinal(
  18359. source.data,
  18360. source.sourceFormat,
  18361. source.seriesLayoutBy,
  18362. source.dimensionsDefine,
  18363. source.startIndex,
  18364. dimIndex
  18365. );
  18366. }
  18367. // dimIndex may be overflow source data.
  18368. // return {BE_ORDINAL}
  18369. function doGuessOrdinal(
  18370. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18371. ) {
  18372. var result;
  18373. // Experience value.
  18374. var maxLoop = 5;
  18375. if (isTypedArray(data)) {
  18376. return BE_ORDINAL.Not;
  18377. }
  18378. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18379. // always exists in source.
  18380. var dimName;
  18381. var dimType;
  18382. if (dimensionsDefine) {
  18383. var dimDefItem = dimensionsDefine[dimIndex];
  18384. if (isObject$1(dimDefItem)) {
  18385. dimName = dimDefItem.name;
  18386. dimType = dimDefItem.type;
  18387. }
  18388. else if (isString(dimDefItem)) {
  18389. dimName = dimDefItem;
  18390. }
  18391. }
  18392. if (dimType != null) {
  18393. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18394. }
  18395. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18396. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18397. var sample = data[dimIndex];
  18398. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18399. if ((result = detectValue(sample[startIndex + i])) != null) {
  18400. return result;
  18401. }
  18402. }
  18403. }
  18404. else {
  18405. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18406. var row = data[startIndex + i];
  18407. if (row && (result = detectValue(row[dimIndex])) != null) {
  18408. return result;
  18409. }
  18410. }
  18411. }
  18412. }
  18413. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18414. if (!dimName) {
  18415. return BE_ORDINAL.Not;
  18416. }
  18417. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18418. var item = data[i];
  18419. if (item && (result = detectValue(item[dimName])) != null) {
  18420. return result;
  18421. }
  18422. }
  18423. }
  18424. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18425. if (!dimName) {
  18426. return BE_ORDINAL.Not;
  18427. }
  18428. var sample = data[dimName];
  18429. if (!sample || isTypedArray(sample)) {
  18430. return BE_ORDINAL.Not;
  18431. }
  18432. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18433. if ((result = detectValue(sample[i])) != null) {
  18434. return result;
  18435. }
  18436. }
  18437. }
  18438. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18439. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18440. var item = data[i];
  18441. var val = getDataItemValue(item);
  18442. if (!isArray(val)) {
  18443. return BE_ORDINAL.Not;
  18444. }
  18445. if ((result = detectValue(val[dimIndex])) != null) {
  18446. return result;
  18447. }
  18448. }
  18449. }
  18450. function detectValue(val) {
  18451. var beStr = isString(val);
  18452. // Consider usage convenience, '1', '2' will be treated as "number".
  18453. // `isFinit('')` get `true`.
  18454. if (val != null && isFinite(val) && val !== '') {
  18455. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18456. }
  18457. else if (beStr && val !== '-') {
  18458. return BE_ORDINAL.Must;
  18459. }
  18460. }
  18461. return BE_ORDINAL.Not;
  18462. }
  18463. /*
  18464. * Licensed to the Apache Software Foundation (ASF) under one
  18465. * or more contributor license agreements. See the NOTICE file
  18466. * distributed with this work for additional information
  18467. * regarding copyright ownership. The ASF licenses this file
  18468. * to you under the Apache License, Version 2.0 (the
  18469. * "License"); you may not use this file except in compliance
  18470. * with the License. You may obtain a copy of the License at
  18471. *
  18472. * http://www.apache.org/licenses/LICENSE-2.0
  18473. *
  18474. * Unless required by applicable law or agreed to in writing,
  18475. * software distributed under the License is distributed on an
  18476. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18477. * KIND, either express or implied. See the License for the
  18478. * specific language governing permissions and limitations
  18479. * under the License.
  18480. */
  18481. /**
  18482. * ECharts global model
  18483. *
  18484. * @module {echarts/model/Global}
  18485. */
  18486. /**
  18487. * Caution: If the mechanism should be changed some day, these cases
  18488. * should be considered:
  18489. *
  18490. * (1) In `merge option` mode, if using the same option to call `setOption`
  18491. * many times, the result should be the same (try our best to ensure that).
  18492. * (2) In `merge option` mode, if a component has no id/name specified, it
  18493. * will be merged by index, and the result sequence of the components is
  18494. * consistent to the original sequence.
  18495. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18496. * `mergeOption` in module:echarts/model/OptionManager.
  18497. */
  18498. var OPTION_INNER_KEY = '\0_ec_inner';
  18499. /**
  18500. * @alias module:echarts/model/Global
  18501. *
  18502. * @param {Object} option
  18503. * @param {module:echarts/model/Model} parentModel
  18504. * @param {Object} theme
  18505. */
  18506. var GlobalModel = Model.extend({
  18507. init: function (option, parentModel, theme, optionManager) {
  18508. theme = theme || {};
  18509. this.option = null; // Mark as not initialized.
  18510. /**
  18511. * @type {module:echarts/model/Model}
  18512. * @private
  18513. */
  18514. this._theme = new Model(theme);
  18515. /**
  18516. * @type {module:echarts/model/OptionManager}
  18517. */
  18518. this._optionManager = optionManager;
  18519. },
  18520. setOption: function (option, optionPreprocessorFuncs) {
  18521. assert$1(
  18522. !(OPTION_INNER_KEY in option),
  18523. 'please use chart.getOption()'
  18524. );
  18525. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18526. this.resetOption(null);
  18527. },
  18528. /**
  18529. * @param {string} type null/undefined: reset all.
  18530. * 'recreate': force recreate all.
  18531. * 'timeline': only reset timeline option
  18532. * 'media': only reset media query option
  18533. * @return {boolean} Whether option changed.
  18534. */
  18535. resetOption: function (type) {
  18536. var optionChanged = false;
  18537. var optionManager = this._optionManager;
  18538. if (!type || type === 'recreate') {
  18539. var baseOption = optionManager.mountOption(type === 'recreate');
  18540. if (!this.option || type === 'recreate') {
  18541. initBase.call(this, baseOption);
  18542. }
  18543. else {
  18544. this.restoreData();
  18545. this.mergeOption(baseOption);
  18546. }
  18547. optionChanged = true;
  18548. }
  18549. if (type === 'timeline' || type === 'media') {
  18550. this.restoreData();
  18551. }
  18552. if (!type || type === 'recreate' || type === 'timeline') {
  18553. var timelineOption = optionManager.getTimelineOption(this);
  18554. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18555. }
  18556. if (!type || type === 'recreate' || type === 'media') {
  18557. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18558. if (mediaOptions.length) {
  18559. each$1(mediaOptions, function (mediaOption) {
  18560. this.mergeOption(mediaOption, optionChanged = true);
  18561. }, this);
  18562. }
  18563. }
  18564. return optionChanged;
  18565. },
  18566. /**
  18567. * @protected
  18568. */
  18569. mergeOption: function (newOption) {
  18570. var option = this.option;
  18571. var componentsMap = this._componentsMap;
  18572. var newCptTypes = [];
  18573. resetSourceDefaulter(this);
  18574. // If no component class, merge directly.
  18575. // For example: color, animaiton options, etc.
  18576. each$1(newOption, function (componentOption, mainType) {
  18577. if (componentOption == null) {
  18578. return;
  18579. }
  18580. if (!ComponentModel.hasClass(mainType)) {
  18581. // globalSettingTask.dirty();
  18582. option[mainType] = option[mainType] == null
  18583. ? clone(componentOption)
  18584. : merge(option[mainType], componentOption, true);
  18585. }
  18586. else if (mainType) {
  18587. newCptTypes.push(mainType);
  18588. }
  18589. });
  18590. ComponentModel.topologicalTravel(
  18591. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18592. );
  18593. function visitComponent(mainType, dependencies) {
  18594. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18595. var mapResult = mappingToExists(
  18596. componentsMap.get(mainType), newCptOptionList
  18597. );
  18598. makeIdAndName(mapResult);
  18599. // Set mainType and complete subType.
  18600. each$1(mapResult, function (item, index) {
  18601. var opt = item.option;
  18602. if (isObject$1(opt)) {
  18603. item.keyInfo.mainType = mainType;
  18604. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18605. }
  18606. });
  18607. var dependentModels = getComponentsByTypes(
  18608. componentsMap, dependencies
  18609. );
  18610. option[mainType] = [];
  18611. componentsMap.set(mainType, []);
  18612. each$1(mapResult, function (resultItem, index) {
  18613. var componentModel = resultItem.exist;
  18614. var newCptOption = resultItem.option;
  18615. assert$1(
  18616. isObject$1(newCptOption) || componentModel,
  18617. 'Empty component definition'
  18618. );
  18619. // Consider where is no new option and should be merged using {},
  18620. // see removeEdgeAndAdd in topologicalTravel and
  18621. // ComponentModel.getAllClassMainTypes.
  18622. if (!newCptOption) {
  18623. componentModel.mergeOption({}, this);
  18624. componentModel.optionUpdated({}, false);
  18625. }
  18626. else {
  18627. var ComponentModelClass = ComponentModel.getClass(
  18628. mainType, resultItem.keyInfo.subType, true
  18629. );
  18630. if (componentModel && componentModel.constructor === ComponentModelClass) {
  18631. componentModel.name = resultItem.keyInfo.name;
  18632. // componentModel.settingTask && componentModel.settingTask.dirty();
  18633. componentModel.mergeOption(newCptOption, this);
  18634. componentModel.optionUpdated(newCptOption, false);
  18635. }
  18636. else {
  18637. // PENDING Global as parent ?
  18638. var extraOpt = extend(
  18639. {
  18640. dependentModels: dependentModels,
  18641. componentIndex: index
  18642. },
  18643. resultItem.keyInfo
  18644. );
  18645. componentModel = new ComponentModelClass(
  18646. newCptOption, this, this, extraOpt
  18647. );
  18648. extend(componentModel, extraOpt);
  18649. componentModel.init(newCptOption, this, this, extraOpt);
  18650. // Call optionUpdated after init.
  18651. // newCptOption has been used as componentModel.option
  18652. // and may be merged with theme and default, so pass null
  18653. // to avoid confusion.
  18654. componentModel.optionUpdated(null, true);
  18655. }
  18656. }
  18657. componentsMap.get(mainType)[index] = componentModel;
  18658. option[mainType][index] = componentModel.option;
  18659. }, this);
  18660. // Backup series for filtering.
  18661. if (mainType === 'series') {
  18662. createSeriesIndices(this, componentsMap.get('series'));
  18663. }
  18664. }
  18665. this._seriesIndicesMap = createHashMap(
  18666. this._seriesIndices = this._seriesIndices || []
  18667. );
  18668. },
  18669. /**
  18670. * Get option for output (cloned option and inner info removed)
  18671. * @public
  18672. * @return {Object}
  18673. */
  18674. getOption: function () {
  18675. var option = clone(this.option);
  18676. each$1(option, function (opts, mainType) {
  18677. if (ComponentModel.hasClass(mainType)) {
  18678. var opts = normalizeToArray(opts);
  18679. for (var i = opts.length - 1; i >= 0; i--) {
  18680. // Remove options with inner id.
  18681. if (isIdInner(opts[i])) {
  18682. opts.splice(i, 1);
  18683. }
  18684. }
  18685. option[mainType] = opts;
  18686. }
  18687. });
  18688. delete option[OPTION_INNER_KEY];
  18689. return option;
  18690. },
  18691. /**
  18692. * @return {module:echarts/model/Model}
  18693. */
  18694. getTheme: function () {
  18695. return this._theme;
  18696. },
  18697. /**
  18698. * @param {string} mainType
  18699. * @param {number} [idx=0]
  18700. * @return {module:echarts/model/Component}
  18701. */
  18702. getComponent: function (mainType, idx) {
  18703. var list = this._componentsMap.get(mainType);
  18704. if (list) {
  18705. return list[idx || 0];
  18706. }
  18707. },
  18708. /**
  18709. * If none of index and id and name used, return all components with mainType.
  18710. * @param {Object} condition
  18711. * @param {string} condition.mainType
  18712. * @param {string} [condition.subType] If ignore, only query by mainType
  18713. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18714. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18715. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18716. * @return {Array.<module:echarts/model/Component>}
  18717. */
  18718. queryComponents: function (condition) {
  18719. var mainType = condition.mainType;
  18720. if (!mainType) {
  18721. return [];
  18722. }
  18723. var index = condition.index;
  18724. var id = condition.id;
  18725. var name = condition.name;
  18726. var cpts = this._componentsMap.get(mainType);
  18727. if (!cpts || !cpts.length) {
  18728. return [];
  18729. }
  18730. var result;
  18731. if (index != null) {
  18732. if (!isArray(index)) {
  18733. index = [index];
  18734. }
  18735. result = filter(map(index, function (idx) {
  18736. return cpts[idx];
  18737. }), function (val) {
  18738. return !!val;
  18739. });
  18740. }
  18741. else if (id != null) {
  18742. var isIdArray = isArray(id);
  18743. result = filter(cpts, function (cpt) {
  18744. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18745. || (!isIdArray && cpt.id === id);
  18746. });
  18747. }
  18748. else if (name != null) {
  18749. var isNameArray = isArray(name);
  18750. result = filter(cpts, function (cpt) {
  18751. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18752. || (!isNameArray && cpt.name === name);
  18753. });
  18754. }
  18755. else {
  18756. // Return all components with mainType
  18757. result = cpts.slice();
  18758. }
  18759. return filterBySubType(result, condition);
  18760. },
  18761. /**
  18762. * The interface is different from queryComponents,
  18763. * which is convenient for inner usage.
  18764. *
  18765. * @usage
  18766. * var result = findComponents(
  18767. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18768. * );
  18769. * var result = findComponents(
  18770. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18771. * );
  18772. * var result = findComponents(
  18773. * {mainType: 'series',
  18774. * filter: function (model, index) {...}}
  18775. * );
  18776. * // result like [component0, componnet1, ...]
  18777. *
  18778. * @param {Object} condition
  18779. * @param {string} condition.mainType Mandatory.
  18780. * @param {string} [condition.subType] Optional.
  18781. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18782. * where xxx is mainType.
  18783. * If query attribute is null/undefined or has no index/id/name,
  18784. * do not filtering by query conditions, which is convenient for
  18785. * no-payload situations or when target of action is global.
  18786. * @param {Function} [condition.filter] parameter: component, return boolean.
  18787. * @return {Array.<module:echarts/model/Component>}
  18788. */
  18789. findComponents: function (condition) {
  18790. var query = condition.query;
  18791. var mainType = condition.mainType;
  18792. var queryCond = getQueryCond(query);
  18793. var result = queryCond
  18794. ? this.queryComponents(queryCond)
  18795. : this._componentsMap.get(mainType);
  18796. return doFilter(filterBySubType(result, condition));
  18797. function getQueryCond(q) {
  18798. var indexAttr = mainType + 'Index';
  18799. var idAttr = mainType + 'Id';
  18800. var nameAttr = mainType + 'Name';
  18801. return q && (
  18802. q[indexAttr] != null
  18803. || q[idAttr] != null
  18804. || q[nameAttr] != null
  18805. )
  18806. ? {
  18807. mainType: mainType,
  18808. // subType will be filtered finally.
  18809. index: q[indexAttr],
  18810. id: q[idAttr],
  18811. name: q[nameAttr]
  18812. }
  18813. : null;
  18814. }
  18815. function doFilter(res) {
  18816. return condition.filter
  18817. ? filter(res, condition.filter)
  18818. : res;
  18819. }
  18820. },
  18821. /**
  18822. * @usage
  18823. * eachComponent('legend', function (legendModel, index) {
  18824. * ...
  18825. * });
  18826. * eachComponent(function (componentType, model, index) {
  18827. * // componentType does not include subType
  18828. * // (componentType is 'xxx' but not 'xxx.aa')
  18829. * });
  18830. * eachComponent(
  18831. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18832. * function (model, index) {...}
  18833. * );
  18834. * eachComponent(
  18835. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18836. * function (model, index) {...}
  18837. * );
  18838. *
  18839. * @param {string|Object=} mainType When mainType is object, the definition
  18840. * is the same as the method 'findComponents'.
  18841. * @param {Function} cb
  18842. * @param {*} context
  18843. */
  18844. eachComponent: function (mainType, cb, context) {
  18845. var componentsMap = this._componentsMap;
  18846. if (typeof mainType === 'function') {
  18847. context = cb;
  18848. cb = mainType;
  18849. componentsMap.each(function (components, componentType) {
  18850. each$1(components, function (component, index) {
  18851. cb.call(context, componentType, component, index);
  18852. });
  18853. });
  18854. }
  18855. else if (isString(mainType)) {
  18856. each$1(componentsMap.get(mainType), cb, context);
  18857. }
  18858. else if (isObject$1(mainType)) {
  18859. var queryResult = this.findComponents(mainType);
  18860. each$1(queryResult, cb, context);
  18861. }
  18862. },
  18863. /**
  18864. * @param {string} name
  18865. * @return {Array.<module:echarts/model/Series>}
  18866. */
  18867. getSeriesByName: function (name) {
  18868. var series = this._componentsMap.get('series');
  18869. return filter(series, function (oneSeries) {
  18870. return oneSeries.name === name;
  18871. });
  18872. },
  18873. /**
  18874. * @param {number} seriesIndex
  18875. * @return {module:echarts/model/Series}
  18876. */
  18877. getSeriesByIndex: function (seriesIndex) {
  18878. return this._componentsMap.get('series')[seriesIndex];
  18879. },
  18880. /**
  18881. * Get series list before filtered by type.
  18882. * FIXME: rename to getRawSeriesByType?
  18883. *
  18884. * @param {string} subType
  18885. * @return {Array.<module:echarts/model/Series>}
  18886. */
  18887. getSeriesByType: function (subType) {
  18888. var series = this._componentsMap.get('series');
  18889. return filter(series, function (oneSeries) {
  18890. return oneSeries.subType === subType;
  18891. });
  18892. },
  18893. /**
  18894. * @return {Array.<module:echarts/model/Series>}
  18895. */
  18896. getSeries: function () {
  18897. return this._componentsMap.get('series').slice();
  18898. },
  18899. /**
  18900. * @return {number}
  18901. */
  18902. getSeriesCount: function () {
  18903. return this._componentsMap.get('series').length;
  18904. },
  18905. /**
  18906. * After filtering, series may be different
  18907. * frome raw series.
  18908. *
  18909. * @param {Function} cb
  18910. * @param {*} context
  18911. */
  18912. eachSeries: function (cb, context) {
  18913. assertSeriesInitialized(this);
  18914. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18915. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18916. cb.call(context, series, rawSeriesIndex);
  18917. }, this);
  18918. },
  18919. /**
  18920. * Iterate raw series before filtered.
  18921. *
  18922. * @param {Function} cb
  18923. * @param {*} context
  18924. */
  18925. eachRawSeries: function (cb, context) {
  18926. each$1(this._componentsMap.get('series'), cb, context);
  18927. },
  18928. /**
  18929. * After filtering, series may be different.
  18930. * frome raw series.
  18931. *
  18932. * @param {string} subType.
  18933. * @param {Function} cb
  18934. * @param {*} context
  18935. */
  18936. eachSeriesByType: function (subType, cb, context) {
  18937. assertSeriesInitialized(this);
  18938. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18939. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18940. if (series.subType === subType) {
  18941. cb.call(context, series, rawSeriesIndex);
  18942. }
  18943. }, this);
  18944. },
  18945. /**
  18946. * Iterate raw series before filtered of given type.
  18947. *
  18948. * @parma {string} subType
  18949. * @param {Function} cb
  18950. * @param {*} context
  18951. */
  18952. eachRawSeriesByType: function (subType, cb, context) {
  18953. return each$1(this.getSeriesByType(subType), cb, context);
  18954. },
  18955. /**
  18956. * @param {module:echarts/model/Series} seriesModel
  18957. */
  18958. isSeriesFiltered: function (seriesModel) {
  18959. assertSeriesInitialized(this);
  18960. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18961. },
  18962. /**
  18963. * @return {Array.<number>}
  18964. */
  18965. getCurrentSeriesIndices: function () {
  18966. return (this._seriesIndices || []).slice();
  18967. },
  18968. /**
  18969. * @param {Function} cb
  18970. * @param {*} context
  18971. */
  18972. filterSeries: function (cb, context) {
  18973. assertSeriesInitialized(this);
  18974. var filteredSeries = filter(
  18975. this._componentsMap.get('series'), cb, context
  18976. );
  18977. createSeriesIndices(this, filteredSeries);
  18978. },
  18979. restoreData: function (payload) {
  18980. var componentsMap = this._componentsMap;
  18981. createSeriesIndices(this, componentsMap.get('series'));
  18982. var componentTypes = [];
  18983. componentsMap.each(function (components, componentType) {
  18984. componentTypes.push(componentType);
  18985. });
  18986. ComponentModel.topologicalTravel(
  18987. componentTypes,
  18988. ComponentModel.getAllClassMainTypes(),
  18989. function (componentType, dependencies) {
  18990. each$1(componentsMap.get(componentType), function (component) {
  18991. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18992. && component.restoreData();
  18993. });
  18994. }
  18995. );
  18996. }
  18997. });
  18998. function isNotTargetSeries(seriesModel, payload) {
  18999. if (payload) {
  19000. var index = payload.seiresIndex;
  19001. var id = payload.seriesId;
  19002. var name = payload.seriesName;
  19003. return (index != null && seriesModel.componentIndex !== index)
  19004. || (id != null && seriesModel.id !== id)
  19005. || (name != null && seriesModel.name !== name);
  19006. }
  19007. }
  19008. /**
  19009. * @inner
  19010. */
  19011. function mergeTheme(option, theme) {
  19012. // PENDING
  19013. // NOT use `colorLayer` in theme if option has `color`
  19014. var notMergeColorLayer = option.color && !option.colorLayer;
  19015. each$1(theme, function (themeItem, name) {
  19016. if (name === 'colorLayer' && notMergeColorLayer) {
  19017. return;
  19018. }
  19019. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  19020. if (!ComponentModel.hasClass(name)) {
  19021. if (typeof themeItem === 'object') {
  19022. option[name] = !option[name]
  19023. ? clone(themeItem)
  19024. : merge(option[name], themeItem, false);
  19025. }
  19026. else {
  19027. if (option[name] == null) {
  19028. option[name] = themeItem;
  19029. }
  19030. }
  19031. }
  19032. });
  19033. }
  19034. function initBase(baseOption) {
  19035. baseOption = baseOption;
  19036. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  19037. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  19038. this.option = {};
  19039. this.option[OPTION_INNER_KEY] = 1;
  19040. /**
  19041. * Init with series: [], in case of calling findSeries method
  19042. * before series initialized.
  19043. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  19044. * @private
  19045. */
  19046. this._componentsMap = createHashMap({series: []});
  19047. /**
  19048. * Mapping between filtered series list and raw series list.
  19049. * key: filtered series indices, value: raw series indices.
  19050. * @type {Array.<nubmer>}
  19051. * @private
  19052. */
  19053. this._seriesIndices;
  19054. this._seriesIndicesMap;
  19055. mergeTheme(baseOption, this._theme.option);
  19056. // TODO Needs clone when merging to the unexisted property
  19057. merge(baseOption, globalDefault, false);
  19058. this.mergeOption(baseOption);
  19059. }
  19060. /**
  19061. * @inner
  19062. * @param {Array.<string>|string} types model types
  19063. * @return {Object} key: {string} type, value: {Array.<Object>} models
  19064. */
  19065. function getComponentsByTypes(componentsMap, types) {
  19066. if (!isArray(types)) {
  19067. types = types ? [types] : [];
  19068. }
  19069. var ret = {};
  19070. each$1(types, function (type) {
  19071. ret[type] = (componentsMap.get(type) || []).slice();
  19072. });
  19073. return ret;
  19074. }
  19075. /**
  19076. * @inner
  19077. */
  19078. function determineSubType(mainType, newCptOption, existComponent) {
  19079. var subType = newCptOption.type
  19080. ? newCptOption.type
  19081. : existComponent
  19082. ? existComponent.subType
  19083. // Use determineSubType only when there is no existComponent.
  19084. : ComponentModel.determineSubType(mainType, newCptOption);
  19085. // tooltip, markline, markpoint may always has no subType
  19086. return subType;
  19087. }
  19088. /**
  19089. * @inner
  19090. */
  19091. function createSeriesIndices(ecModel, seriesModels) {
  19092. ecModel._seriesIndicesMap = createHashMap(
  19093. ecModel._seriesIndices = map(seriesModels, function (series) {
  19094. return series.componentIndex;
  19095. }) || []
  19096. );
  19097. }
  19098. /**
  19099. * @inner
  19100. */
  19101. function filterBySubType(components, condition) {
  19102. // Using hasOwnProperty for restrict. Consider
  19103. // subType is undefined in user payload.
  19104. return condition.hasOwnProperty('subType')
  19105. ? filter(components, function (cpt) {
  19106. return cpt.subType === condition.subType;
  19107. })
  19108. : components;
  19109. }
  19110. /**
  19111. * @inner
  19112. */
  19113. function assertSeriesInitialized(ecModel) {
  19114. // Components that use _seriesIndices should depends on series component,
  19115. // which make sure that their initialization is after series.
  19116. if (__DEV__) {
  19117. if (!ecModel._seriesIndices) {
  19118. throw new Error('Option should contains series.');
  19119. }
  19120. }
  19121. }
  19122. mixin(GlobalModel, colorPaletteMixin);
  19123. /*
  19124. * Licensed to the Apache Software Foundation (ASF) under one
  19125. * or more contributor license agreements. See the NOTICE file
  19126. * distributed with this work for additional information
  19127. * regarding copyright ownership. The ASF licenses this file
  19128. * to you under the Apache License, Version 2.0 (the
  19129. * "License"); you may not use this file except in compliance
  19130. * with the License. You may obtain a copy of the License at
  19131. *
  19132. * http://www.apache.org/licenses/LICENSE-2.0
  19133. *
  19134. * Unless required by applicable law or agreed to in writing,
  19135. * software distributed under the License is distributed on an
  19136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19137. * KIND, either express or implied. See the License for the
  19138. * specific language governing permissions and limitations
  19139. * under the License.
  19140. */
  19141. var echartsAPIList = [
  19142. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19143. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19144. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19145. ];
  19146. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19147. function ExtensionAPI(chartInstance) {
  19148. each$1(echartsAPIList, function (name) {
  19149. this[name] = bind(chartInstance[name], chartInstance);
  19150. }, this);
  19151. }
  19152. /*
  19153. * Licensed to the Apache Software Foundation (ASF) under one
  19154. * or more contributor license agreements. See the NOTICE file
  19155. * distributed with this work for additional information
  19156. * regarding copyright ownership. The ASF licenses this file
  19157. * to you under the Apache License, Version 2.0 (the
  19158. * "License"); you may not use this file except in compliance
  19159. * with the License. You may obtain a copy of the License at
  19160. *
  19161. * http://www.apache.org/licenses/LICENSE-2.0
  19162. *
  19163. * Unless required by applicable law or agreed to in writing,
  19164. * software distributed under the License is distributed on an
  19165. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19166. * KIND, either express or implied. See the License for the
  19167. * specific language governing permissions and limitations
  19168. * under the License.
  19169. */
  19170. var coordinateSystemCreators = {};
  19171. function CoordinateSystemManager() {
  19172. this._coordinateSystems = [];
  19173. }
  19174. CoordinateSystemManager.prototype = {
  19175. constructor: CoordinateSystemManager,
  19176. create: function (ecModel, api) {
  19177. var coordinateSystems = [];
  19178. each$1(coordinateSystemCreators, function (creater, type) {
  19179. var list = creater.create(ecModel, api);
  19180. coordinateSystems = coordinateSystems.concat(list || []);
  19181. });
  19182. this._coordinateSystems = coordinateSystems;
  19183. },
  19184. update: function (ecModel, api) {
  19185. each$1(this._coordinateSystems, function (coordSys) {
  19186. coordSys.update && coordSys.update(ecModel, api);
  19187. });
  19188. },
  19189. getCoordinateSystems: function () {
  19190. return this._coordinateSystems.slice();
  19191. }
  19192. };
  19193. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19194. coordinateSystemCreators[type] = coordinateSystemCreator;
  19195. };
  19196. CoordinateSystemManager.get = function (type) {
  19197. return coordinateSystemCreators[type];
  19198. };
  19199. /*
  19200. * Licensed to the Apache Software Foundation (ASF) under one
  19201. * or more contributor license agreements. See the NOTICE file
  19202. * distributed with this work for additional information
  19203. * regarding copyright ownership. The ASF licenses this file
  19204. * to you under the Apache License, Version 2.0 (the
  19205. * "License"); you may not use this file except in compliance
  19206. * with the License. You may obtain a copy of the License at
  19207. *
  19208. * http://www.apache.org/licenses/LICENSE-2.0
  19209. *
  19210. * Unless required by applicable law or agreed to in writing,
  19211. * software distributed under the License is distributed on an
  19212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19213. * KIND, either express or implied. See the License for the
  19214. * specific language governing permissions and limitations
  19215. * under the License.
  19216. */
  19217. /**
  19218. * ECharts option manager
  19219. *
  19220. * @module {echarts/model/OptionManager}
  19221. */
  19222. var each$4 = each$1;
  19223. var clone$3 = clone;
  19224. var map$1 = map;
  19225. var merge$1 = merge;
  19226. var QUERY_REG = /^(min|max)?(.+)$/;
  19227. /**
  19228. * TERM EXPLANATIONS:
  19229. *
  19230. * [option]:
  19231. *
  19232. * An object that contains definitions of components. For example:
  19233. * var option = {
  19234. * title: {...},
  19235. * legend: {...},
  19236. * visualMap: {...},
  19237. * series: [
  19238. * {data: [...]},
  19239. * {data: [...]},
  19240. * ...
  19241. * ]
  19242. * };
  19243. *
  19244. * [rawOption]:
  19245. *
  19246. * An object input to echarts.setOption. 'rawOption' may be an
  19247. * 'option', or may be an object contains multi-options. For example:
  19248. * var option = {
  19249. * baseOption: {
  19250. * title: {...},
  19251. * legend: {...},
  19252. * series: [
  19253. * {data: [...]},
  19254. * {data: [...]},
  19255. * ...
  19256. * ]
  19257. * },
  19258. * timeline: {...},
  19259. * options: [
  19260. * {title: {...}, series: {data: [...]}},
  19261. * {title: {...}, series: {data: [...]}},
  19262. * ...
  19263. * ],
  19264. * media: [
  19265. * {
  19266. * query: {maxWidth: 320},
  19267. * option: {series: {x: 20}, visualMap: {show: false}}
  19268. * },
  19269. * {
  19270. * query: {minWidth: 320, maxWidth: 720},
  19271. * option: {series: {x: 500}, visualMap: {show: true}}
  19272. * },
  19273. * {
  19274. * option: {series: {x: 1200}, visualMap: {show: true}}
  19275. * }
  19276. * ]
  19277. * };
  19278. *
  19279. * @alias module:echarts/model/OptionManager
  19280. * @param {module:echarts/ExtensionAPI} api
  19281. */
  19282. function OptionManager(api) {
  19283. /**
  19284. * @private
  19285. * @type {module:echarts/ExtensionAPI}
  19286. */
  19287. this._api = api;
  19288. /**
  19289. * @private
  19290. * @type {Array.<number>}
  19291. */
  19292. this._timelineOptions = [];
  19293. /**
  19294. * @private
  19295. * @type {Array.<Object>}
  19296. */
  19297. this._mediaList = [];
  19298. /**
  19299. * @private
  19300. * @type {Object}
  19301. */
  19302. this._mediaDefault;
  19303. /**
  19304. * -1, means default.
  19305. * empty means no media.
  19306. * @private
  19307. * @type {Array.<number>}
  19308. */
  19309. this._currentMediaIndices = [];
  19310. /**
  19311. * @private
  19312. * @type {Object}
  19313. */
  19314. this._optionBackup;
  19315. /**
  19316. * @private
  19317. * @type {Object}
  19318. */
  19319. this._newBaseOption;
  19320. }
  19321. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19322. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19323. // rawOption cloned and backuped when timeline changed, which does no
  19324. // good to performance. What's more, that both timeline and setOption
  19325. // method supply 'notMerge' brings complex and some problems.
  19326. // Consider this case:
  19327. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19328. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19329. OptionManager.prototype = {
  19330. constructor: OptionManager,
  19331. /**
  19332. * @public
  19333. * @param {Object} rawOption Raw option.
  19334. * @param {module:echarts/model/Global} ecModel
  19335. * @param {Array.<Function>} optionPreprocessorFuncs
  19336. * @return {Object} Init option
  19337. */
  19338. setOption: function (rawOption, optionPreprocessorFuncs) {
  19339. if (rawOption) {
  19340. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19341. each$1(normalizeToArray(rawOption.series), function (series) {
  19342. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19343. });
  19344. }
  19345. // Caution: some series modify option data, if do not clone,
  19346. // it should ensure that the repeat modify correctly
  19347. // (create a new object when modify itself).
  19348. rawOption = clone$3(rawOption);
  19349. // FIXME
  19350. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19351. var oldOptionBackup = this._optionBackup;
  19352. var newParsedOption = parseRawOption.call(
  19353. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19354. );
  19355. this._newBaseOption = newParsedOption.baseOption;
  19356. // For setOption at second time (using merge mode);
  19357. if (oldOptionBackup) {
  19358. // Only baseOption can be merged.
  19359. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19360. // For simplicity, timeline options and media options do not support merge,
  19361. // that is, if you `setOption` twice and both has timeline options, the latter
  19362. // timeline opitons will not be merged to the formers, but just substitude them.
  19363. if (newParsedOption.timelineOptions.length) {
  19364. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19365. }
  19366. if (newParsedOption.mediaList.length) {
  19367. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19368. }
  19369. if (newParsedOption.mediaDefault) {
  19370. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19371. }
  19372. }
  19373. else {
  19374. this._optionBackup = newParsedOption;
  19375. }
  19376. },
  19377. /**
  19378. * @param {boolean} isRecreate
  19379. * @return {Object}
  19380. */
  19381. mountOption: function (isRecreate) {
  19382. var optionBackup = this._optionBackup;
  19383. // TODO
  19384. // 如果没有reset功能则不clone。
  19385. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19386. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19387. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19388. this._currentMediaIndices = [];
  19389. return clone$3(isRecreate
  19390. // this._optionBackup.baseOption, which is created at the first `setOption`
  19391. // called, and is merged into every new option by inner method `mergeOption`
  19392. // each time `setOption` called, can be only used in `isRecreate`, because
  19393. // its reliability is under suspicion. In other cases option merge is
  19394. // performed by `model.mergeOption`.
  19395. ? optionBackup.baseOption : this._newBaseOption
  19396. );
  19397. },
  19398. /**
  19399. * @param {module:echarts/model/Global} ecModel
  19400. * @return {Object}
  19401. */
  19402. getTimelineOption: function (ecModel) {
  19403. var option;
  19404. var timelineOptions = this._timelineOptions;
  19405. if (timelineOptions.length) {
  19406. // getTimelineOption can only be called after ecModel inited,
  19407. // so we can get currentIndex from timelineModel.
  19408. var timelineModel = ecModel.getComponent('timeline');
  19409. if (timelineModel) {
  19410. option = clone$3(
  19411. timelineOptions[timelineModel.getCurrentIndex()],
  19412. true
  19413. );
  19414. }
  19415. }
  19416. return option;
  19417. },
  19418. /**
  19419. * @param {module:echarts/model/Global} ecModel
  19420. * @return {Array.<Object>}
  19421. */
  19422. getMediaOption: function (ecModel) {
  19423. var ecWidth = this._api.getWidth();
  19424. var ecHeight = this._api.getHeight();
  19425. var mediaList = this._mediaList;
  19426. var mediaDefault = this._mediaDefault;
  19427. var indices = [];
  19428. var result = [];
  19429. // No media defined.
  19430. if (!mediaList.length && !mediaDefault) {
  19431. return result;
  19432. }
  19433. // Multi media may be applied, the latter defined media has higher priority.
  19434. for (var i = 0, len = mediaList.length; i < len; i++) {
  19435. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19436. indices.push(i);
  19437. }
  19438. }
  19439. // FIXME
  19440. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19441. if (!indices.length && mediaDefault) {
  19442. indices = [-1];
  19443. }
  19444. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19445. result = map$1(indices, function (index) {
  19446. return clone$3(
  19447. index === -1 ? mediaDefault.option : mediaList[index].option
  19448. );
  19449. });
  19450. }
  19451. // Otherwise return nothing.
  19452. this._currentMediaIndices = indices;
  19453. return result;
  19454. }
  19455. };
  19456. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19457. var timelineOptions = [];
  19458. var mediaList = [];
  19459. var mediaDefault;
  19460. var baseOption;
  19461. // Compatible with ec2.
  19462. var timelineOpt = rawOption.timeline;
  19463. if (rawOption.baseOption) {
  19464. baseOption = rawOption.baseOption;
  19465. }
  19466. // For timeline
  19467. if (timelineOpt || rawOption.options) {
  19468. baseOption = baseOption || {};
  19469. timelineOptions = (rawOption.options || []).slice();
  19470. }
  19471. // For media query
  19472. if (rawOption.media) {
  19473. baseOption = baseOption || {};
  19474. var media = rawOption.media;
  19475. each$4(media, function (singleMedia) {
  19476. if (singleMedia && singleMedia.option) {
  19477. if (singleMedia.query) {
  19478. mediaList.push(singleMedia);
  19479. }
  19480. else if (!mediaDefault) {
  19481. // Use the first media default.
  19482. mediaDefault = singleMedia;
  19483. }
  19484. }
  19485. });
  19486. }
  19487. // For normal option
  19488. if (!baseOption) {
  19489. baseOption = rawOption;
  19490. }
  19491. // Set timelineOpt to baseOption in ec3,
  19492. // which is convenient for merge option.
  19493. if (!baseOption.timeline) {
  19494. baseOption.timeline = timelineOpt;
  19495. }
  19496. // Preprocess.
  19497. each$4([baseOption].concat(timelineOptions)
  19498. .concat(map(mediaList, function (media) {
  19499. return media.option;
  19500. })),
  19501. function (option) {
  19502. each$4(optionPreprocessorFuncs, function (preProcess) {
  19503. preProcess(option, isNew);
  19504. });
  19505. }
  19506. );
  19507. return {
  19508. baseOption: baseOption,
  19509. timelineOptions: timelineOptions,
  19510. mediaDefault: mediaDefault,
  19511. mediaList: mediaList
  19512. };
  19513. }
  19514. /**
  19515. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19516. * Support: width, height, aspectRatio
  19517. * Can use max or min as prefix.
  19518. */
  19519. function applyMediaQuery(query, ecWidth, ecHeight) {
  19520. var realMap = {
  19521. width: ecWidth,
  19522. height: ecHeight,
  19523. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19524. };
  19525. var applicatable = true;
  19526. each$1(query, function (value, attr) {
  19527. var matched = attr.match(QUERY_REG);
  19528. if (!matched || !matched[1] || !matched[2]) {
  19529. return;
  19530. }
  19531. var operator = matched[1];
  19532. var realAttr = matched[2].toLowerCase();
  19533. if (!compare(realMap[realAttr], value, operator)) {
  19534. applicatable = false;
  19535. }
  19536. });
  19537. return applicatable;
  19538. }
  19539. function compare(real, expect, operator) {
  19540. if (operator === 'min') {
  19541. return real >= expect;
  19542. }
  19543. else if (operator === 'max') {
  19544. return real <= expect;
  19545. }
  19546. else { // Equals
  19547. return real === expect;
  19548. }
  19549. }
  19550. function indicesEquals(indices1, indices2) {
  19551. // indices is always order by asc and has only finite number.
  19552. return indices1.join(',') === indices2.join(',');
  19553. }
  19554. /**
  19555. * Consider case:
  19556. * `chart.setOption(opt1);`
  19557. * Then user do some interaction like dataZoom, dataView changing.
  19558. * `chart.setOption(opt2);`
  19559. * Then user press 'reset button' in toolbox.
  19560. *
  19561. * After doing that all of the interaction effects should be reset, the
  19562. * chart should be the same as the result of invoke
  19563. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19564. *
  19565. * Although it is not able ensure that
  19566. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19567. * `chart.setOption(merge(opt1, opt2));` exactly,
  19568. * this might be the only simple way to implement that feature.
  19569. *
  19570. * MEMO: We've considered some other approaches:
  19571. * 1. Each model handle its self restoration but not uniform treatment.
  19572. * (Too complex in logic and error-prone)
  19573. * 2. Use a shadow ecModel. (Performace expensive)
  19574. */
  19575. function mergeOption(oldOption, newOption) {
  19576. newOption = newOption || {};
  19577. each$4(newOption, function (newCptOpt, mainType) {
  19578. if (newCptOpt == null) {
  19579. return;
  19580. }
  19581. var oldCptOpt = oldOption[mainType];
  19582. if (!ComponentModel.hasClass(mainType)) {
  19583. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19584. }
  19585. else {
  19586. newCptOpt = normalizeToArray(newCptOpt);
  19587. oldCptOpt = normalizeToArray(oldCptOpt);
  19588. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19589. oldOption[mainType] = map$1(mapResult, function (item) {
  19590. return (item.option && item.exist)
  19591. ? merge$1(item.exist, item.option, true)
  19592. : (item.exist || item.option);
  19593. });
  19594. }
  19595. });
  19596. }
  19597. /*
  19598. * Licensed to the Apache Software Foundation (ASF) under one
  19599. * or more contributor license agreements. See the NOTICE file
  19600. * distributed with this work for additional information
  19601. * regarding copyright ownership. The ASF licenses this file
  19602. * to you under the Apache License, Version 2.0 (the
  19603. * "License"); you may not use this file except in compliance
  19604. * with the License. You may obtain a copy of the License at
  19605. *
  19606. * http://www.apache.org/licenses/LICENSE-2.0
  19607. *
  19608. * Unless required by applicable law or agreed to in writing,
  19609. * software distributed under the License is distributed on an
  19610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19611. * KIND, either express or implied. See the License for the
  19612. * specific language governing permissions and limitations
  19613. * under the License.
  19614. */
  19615. var each$5 = each$1;
  19616. var isObject$3 = isObject$1;
  19617. var POSSIBLE_STYLES = [
  19618. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19619. 'chordStyle', 'label', 'labelLine'
  19620. ];
  19621. function compatEC2ItemStyle(opt) {
  19622. var itemStyleOpt = opt && opt.itemStyle;
  19623. if (!itemStyleOpt) {
  19624. return;
  19625. }
  19626. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19627. var styleName = POSSIBLE_STYLES[i];
  19628. var normalItemStyleOpt = itemStyleOpt.normal;
  19629. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19630. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19631. opt[styleName] = opt[styleName] || {};
  19632. if (!opt[styleName].normal) {
  19633. opt[styleName].normal = normalItemStyleOpt[styleName];
  19634. }
  19635. else {
  19636. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19637. }
  19638. normalItemStyleOpt[styleName] = null;
  19639. }
  19640. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19641. opt[styleName] = opt[styleName] || {};
  19642. if (!opt[styleName].emphasis) {
  19643. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19644. }
  19645. else {
  19646. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19647. }
  19648. emphasisItemStyleOpt[styleName] = null;
  19649. }
  19650. }
  19651. }
  19652. function convertNormalEmphasis(opt, optType, useExtend) {
  19653. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19654. var normalOpt = opt[optType].normal;
  19655. var emphasisOpt = opt[optType].emphasis;
  19656. if (normalOpt) {
  19657. // Timeline controlStyle has other properties besides normal and emphasis
  19658. if (useExtend) {
  19659. opt[optType].normal = opt[optType].emphasis = null;
  19660. defaults(opt[optType], normalOpt);
  19661. }
  19662. else {
  19663. opt[optType] = normalOpt;
  19664. }
  19665. }
  19666. if (emphasisOpt) {
  19667. opt.emphasis = opt.emphasis || {};
  19668. opt.emphasis[optType] = emphasisOpt;
  19669. }
  19670. }
  19671. }
  19672. function removeEC3NormalStatus(opt) {
  19673. convertNormalEmphasis(opt, 'itemStyle');
  19674. convertNormalEmphasis(opt, 'lineStyle');
  19675. convertNormalEmphasis(opt, 'areaStyle');
  19676. convertNormalEmphasis(opt, 'label');
  19677. convertNormalEmphasis(opt, 'labelLine');
  19678. // treemap
  19679. convertNormalEmphasis(opt, 'upperLabel');
  19680. // graph
  19681. convertNormalEmphasis(opt, 'edgeLabel');
  19682. }
  19683. function compatTextStyle(opt, propName) {
  19684. // Check whether is not object (string\null\undefined ...)
  19685. var labelOptSingle = isObject$3(opt) && opt[propName];
  19686. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19687. if (textStyle) {
  19688. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19689. var propName = TEXT_STYLE_OPTIONS[i];
  19690. if (textStyle.hasOwnProperty(propName)) {
  19691. labelOptSingle[propName] = textStyle[propName];
  19692. }
  19693. }
  19694. }
  19695. }
  19696. function compatEC3CommonStyles(opt) {
  19697. if (opt) {
  19698. removeEC3NormalStatus(opt);
  19699. compatTextStyle(opt, 'label');
  19700. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19701. }
  19702. }
  19703. function processSeries(seriesOpt) {
  19704. if (!isObject$3(seriesOpt)) {
  19705. return;
  19706. }
  19707. compatEC2ItemStyle(seriesOpt);
  19708. removeEC3NormalStatus(seriesOpt);
  19709. compatTextStyle(seriesOpt, 'label');
  19710. // treemap
  19711. compatTextStyle(seriesOpt, 'upperLabel');
  19712. // graph
  19713. compatTextStyle(seriesOpt, 'edgeLabel');
  19714. if (seriesOpt.emphasis) {
  19715. compatTextStyle(seriesOpt.emphasis, 'label');
  19716. // treemap
  19717. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19718. // graph
  19719. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19720. }
  19721. var markPoint = seriesOpt.markPoint;
  19722. if (markPoint) {
  19723. compatEC2ItemStyle(markPoint);
  19724. compatEC3CommonStyles(markPoint);
  19725. }
  19726. var markLine = seriesOpt.markLine;
  19727. if (markLine) {
  19728. compatEC2ItemStyle(markLine);
  19729. compatEC3CommonStyles(markLine);
  19730. }
  19731. var markArea = seriesOpt.markArea;
  19732. if (markArea) {
  19733. compatEC3CommonStyles(markArea);
  19734. }
  19735. var data = seriesOpt.data;
  19736. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19737. // then the backward compat based on option type will not be performed.
  19738. if (seriesOpt.type === 'graph') {
  19739. data = data || seriesOpt.nodes;
  19740. var edgeData = seriesOpt.links || seriesOpt.edges;
  19741. if (edgeData && !isTypedArray(edgeData)) {
  19742. for (var i = 0; i < edgeData.length; i++) {
  19743. compatEC3CommonStyles(edgeData[i]);
  19744. }
  19745. }
  19746. each$1(seriesOpt.categories, function (opt) {
  19747. removeEC3NormalStatus(opt);
  19748. });
  19749. }
  19750. if (data && !isTypedArray(data)) {
  19751. for (var i = 0; i < data.length; i++) {
  19752. compatEC3CommonStyles(data[i]);
  19753. }
  19754. }
  19755. // mark point data
  19756. var markPoint = seriesOpt.markPoint;
  19757. if (markPoint && markPoint.data) {
  19758. var mpData = markPoint.data;
  19759. for (var i = 0; i < mpData.length; i++) {
  19760. compatEC3CommonStyles(mpData[i]);
  19761. }
  19762. }
  19763. // mark line data
  19764. var markLine = seriesOpt.markLine;
  19765. if (markLine && markLine.data) {
  19766. var mlData = markLine.data;
  19767. for (var i = 0; i < mlData.length; i++) {
  19768. if (isArray(mlData[i])) {
  19769. compatEC3CommonStyles(mlData[i][0]);
  19770. compatEC3CommonStyles(mlData[i][1]);
  19771. }
  19772. else {
  19773. compatEC3CommonStyles(mlData[i]);
  19774. }
  19775. }
  19776. }
  19777. // Series
  19778. if (seriesOpt.type === 'gauge') {
  19779. compatTextStyle(seriesOpt, 'axisLabel');
  19780. compatTextStyle(seriesOpt, 'title');
  19781. compatTextStyle(seriesOpt, 'detail');
  19782. }
  19783. else if (seriesOpt.type === 'treemap') {
  19784. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19785. each$1(seriesOpt.levels, function (opt) {
  19786. removeEC3NormalStatus(opt);
  19787. });
  19788. }
  19789. else if (seriesOpt.type === 'tree') {
  19790. removeEC3NormalStatus(seriesOpt.leaves);
  19791. }
  19792. // sunburst starts from ec4, so it does not need to compat levels.
  19793. }
  19794. function toArr(o) {
  19795. return isArray(o) ? o : o ? [o] : [];
  19796. }
  19797. function toObj(o) {
  19798. return (isArray(o) ? o[0] : o) || {};
  19799. }
  19800. var compatStyle = function (option, isTheme) {
  19801. each$5(toArr(option.series), function (seriesOpt) {
  19802. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19803. });
  19804. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19805. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19806. each$5(
  19807. axes,
  19808. function (axisName) {
  19809. each$5(toArr(option[axisName]), function (axisOpt) {
  19810. if (axisOpt) {
  19811. compatTextStyle(axisOpt, 'axisLabel');
  19812. compatTextStyle(axisOpt.axisPointer, 'label');
  19813. }
  19814. });
  19815. }
  19816. );
  19817. each$5(toArr(option.parallel), function (parallelOpt) {
  19818. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19819. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19820. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19821. });
  19822. each$5(toArr(option.calendar), function (calendarOpt) {
  19823. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19824. compatTextStyle(calendarOpt, 'dayLabel');
  19825. compatTextStyle(calendarOpt, 'monthLabel');
  19826. compatTextStyle(calendarOpt, 'yearLabel');
  19827. });
  19828. // radar.name.textStyle
  19829. each$5(toArr(option.radar), function (radarOpt) {
  19830. compatTextStyle(radarOpt, 'name');
  19831. });
  19832. each$5(toArr(option.geo), function (geoOpt) {
  19833. if (isObject$3(geoOpt)) {
  19834. compatEC3CommonStyles(geoOpt);
  19835. each$5(toArr(geoOpt.regions), function (regionObj) {
  19836. compatEC3CommonStyles(regionObj);
  19837. });
  19838. }
  19839. });
  19840. each$5(toArr(option.timeline), function (timelineOpt) {
  19841. compatEC3CommonStyles(timelineOpt);
  19842. convertNormalEmphasis(timelineOpt, 'label');
  19843. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19844. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19845. var data = timelineOpt.data;
  19846. isArray(data) && each$1(data, function (item) {
  19847. if (isObject$1(item)) {
  19848. convertNormalEmphasis(item, 'label');
  19849. convertNormalEmphasis(item, 'itemStyle');
  19850. }
  19851. });
  19852. });
  19853. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19854. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19855. each$5(toolboxOpt.feature, function (featureOpt) {
  19856. convertNormalEmphasis(featureOpt, 'iconStyle');
  19857. });
  19858. });
  19859. compatTextStyle(toObj(option.axisPointer), 'label');
  19860. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19861. };
  19862. /*
  19863. * Licensed to the Apache Software Foundation (ASF) under one
  19864. * or more contributor license agreements. See the NOTICE file
  19865. * distributed with this work for additional information
  19866. * regarding copyright ownership. The ASF licenses this file
  19867. * to you under the Apache License, Version 2.0 (the
  19868. * "License"); you may not use this file except in compliance
  19869. * with the License. You may obtain a copy of the License at
  19870. *
  19871. * http://www.apache.org/licenses/LICENSE-2.0
  19872. *
  19873. * Unless required by applicable law or agreed to in writing,
  19874. * software distributed under the License is distributed on an
  19875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19876. * KIND, either express or implied. See the License for the
  19877. * specific language governing permissions and limitations
  19878. * under the License.
  19879. */
  19880. // Compatitable with 2.0
  19881. function get(opt, path) {
  19882. path = path.split(',');
  19883. var obj = opt;
  19884. for (var i = 0; i < path.length; i++) {
  19885. obj = obj && obj[path[i]];
  19886. if (obj == null) {
  19887. break;
  19888. }
  19889. }
  19890. return obj;
  19891. }
  19892. function set$1(opt, path, val, overwrite) {
  19893. path = path.split(',');
  19894. var obj = opt;
  19895. var key;
  19896. for (var i = 0; i < path.length - 1; i++) {
  19897. key = path[i];
  19898. if (obj[key] == null) {
  19899. obj[key] = {};
  19900. }
  19901. obj = obj[key];
  19902. }
  19903. if (overwrite || obj[path[i]] == null) {
  19904. obj[path[i]] = val;
  19905. }
  19906. }
  19907. function compatLayoutProperties(option) {
  19908. each$1(LAYOUT_PROPERTIES, function (prop) {
  19909. if (prop[0] in option && !(prop[1] in option)) {
  19910. option[prop[1]] = option[prop[0]];
  19911. }
  19912. });
  19913. }
  19914. var LAYOUT_PROPERTIES = [
  19915. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19916. ];
  19917. var COMPATITABLE_COMPONENTS = [
  19918. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19919. ];
  19920. var backwardCompat = function (option, isTheme) {
  19921. compatStyle(option, isTheme);
  19922. // Make sure series array for model initialization.
  19923. option.series = normalizeToArray(option.series);
  19924. each$1(option.series, function (seriesOpt) {
  19925. if (!isObject$1(seriesOpt)) {
  19926. return;
  19927. }
  19928. var seriesType = seriesOpt.type;
  19929. if (seriesType === 'line') {
  19930. if (seriesOpt.clipOverflow != null) {
  19931. seriesOpt.clip = seriesOpt.clipOverflow;
  19932. }
  19933. }
  19934. else if (seriesType === 'pie' || seriesType === 'gauge') {
  19935. if (seriesOpt.clockWise != null) {
  19936. seriesOpt.clockwise = seriesOpt.clockWise;
  19937. }
  19938. }
  19939. else if (seriesType === 'gauge') {
  19940. var pointerColor = get(seriesOpt, 'pointer.color');
  19941. pointerColor != null
  19942. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  19943. }
  19944. compatLayoutProperties(seriesOpt);
  19945. });
  19946. // dataRange has changed to visualMap
  19947. if (option.dataRange) {
  19948. option.visualMap = option.dataRange;
  19949. }
  19950. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19951. var options = option[componentName];
  19952. if (options) {
  19953. if (!isArray(options)) {
  19954. options = [options];
  19955. }
  19956. each$1(options, function (option) {
  19957. compatLayoutProperties(option);
  19958. });
  19959. }
  19960. });
  19961. };
  19962. /*
  19963. * Licensed to the Apache Software Foundation (ASF) under one
  19964. * or more contributor license agreements. See the NOTICE file
  19965. * distributed with this work for additional information
  19966. * regarding copyright ownership. The ASF licenses this file
  19967. * to you under the Apache License, Version 2.0 (the
  19968. * "License"); you may not use this file except in compliance
  19969. * with the License. You may obtain a copy of the License at
  19970. *
  19971. * http://www.apache.org/licenses/LICENSE-2.0
  19972. *
  19973. * Unless required by applicable law or agreed to in writing,
  19974. * software distributed under the License is distributed on an
  19975. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19976. * KIND, either express or implied. See the License for the
  19977. * specific language governing permissions and limitations
  19978. * under the License.
  19979. */
  19980. // (1) [Caution]: the logic is correct based on the premises:
  19981. // data processing stage is blocked in stream.
  19982. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19983. // (2) Only register once when import repeatly.
  19984. // Should be executed after series filtered and before stack calculation.
  19985. var dataStack = function (ecModel) {
  19986. var stackInfoMap = createHashMap();
  19987. ecModel.eachSeries(function (seriesModel) {
  19988. var stack = seriesModel.get('stack');
  19989. // Compatibal: when `stack` is set as '', do not stack.
  19990. if (stack) {
  19991. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19992. var data = seriesModel.getData();
  19993. var stackInfo = {
  19994. // Used for calculate axis extent automatically.
  19995. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19996. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19997. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19998. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19999. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  20000. data: data,
  20001. seriesModel: seriesModel
  20002. };
  20003. // If stacked on axis that do not support data stack.
  20004. if (!stackInfo.stackedDimension
  20005. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  20006. ) {
  20007. return;
  20008. }
  20009. stackInfoList.length && data.setCalculationInfo(
  20010. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  20011. );
  20012. stackInfoList.push(stackInfo);
  20013. }
  20014. });
  20015. stackInfoMap.each(calculateStack);
  20016. };
  20017. function calculateStack(stackInfoList) {
  20018. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  20019. var resultVal = [];
  20020. var resultNaN = [NaN, NaN];
  20021. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  20022. var targetData = targetStackInfo.data;
  20023. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  20024. // Should not write on raw data, because stack series model list changes
  20025. // depending on legend selection.
  20026. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  20027. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  20028. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  20029. // should also be NaN, to draw a appropriate belt area.
  20030. if (isNaN(sum)) {
  20031. return resultNaN;
  20032. }
  20033. var byValue;
  20034. var stackedDataRawIndex;
  20035. if (isStackedByIndex) {
  20036. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  20037. }
  20038. else {
  20039. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  20040. }
  20041. // If stackOver is NaN, chart view will render point on value start.
  20042. var stackedOver = NaN;
  20043. for (var j = idxInStack - 1; j >= 0; j--) {
  20044. var stackInfo = stackInfoList[j];
  20045. // Has been optimized by inverted indices on `stackedByDimension`.
  20046. if (!isStackedByIndex) {
  20047. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  20048. }
  20049. if (stackedDataRawIndex >= 0) {
  20050. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  20051. // Considering positive stack, negative stack and empty data
  20052. if ((sum >= 0 && val > 0) // Positive stack
  20053. || (sum <= 0 && val < 0) // Negative stack
  20054. ) {
  20055. sum += val;
  20056. stackedOver = val;
  20057. break;
  20058. }
  20059. }
  20060. }
  20061. resultVal[0] = sum;
  20062. resultVal[1] = stackedOver;
  20063. return resultVal;
  20064. });
  20065. targetData.hostModel.setData(newData);
  20066. // Update for consequent calculation
  20067. targetStackInfo.data = newData;
  20068. });
  20069. }
  20070. /*
  20071. * Licensed to the Apache Software Foundation (ASF) under one
  20072. * or more contributor license agreements. See the NOTICE file
  20073. * distributed with this work for additional information
  20074. * regarding copyright ownership. The ASF licenses this file
  20075. * to you under the Apache License, Version 2.0 (the
  20076. * "License"); you may not use this file except in compliance
  20077. * with the License. You may obtain a copy of the License at
  20078. *
  20079. * http://www.apache.org/licenses/LICENSE-2.0
  20080. *
  20081. * Unless required by applicable law or agreed to in writing,
  20082. * software distributed under the License is distributed on an
  20083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20084. * KIND, either express or implied. See the License for the
  20085. * specific language governing permissions and limitations
  20086. * under the License.
  20087. */
  20088. // TODO
  20089. // ??? refactor? check the outer usage of data provider.
  20090. // merge with defaultDimValueGetter?
  20091. /**
  20092. * If normal array used, mutable chunk size is supported.
  20093. * If typed array used, chunk size must be fixed.
  20094. */
  20095. function DefaultDataProvider(source, dimSize) {
  20096. if (!Source.isInstance(source)) {
  20097. source = Source.seriesDataToSource(source);
  20098. }
  20099. this._source = source;
  20100. var data = this._data = source.data;
  20101. var sourceFormat = source.sourceFormat;
  20102. // Typed array. TODO IE10+?
  20103. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20104. if (__DEV__) {
  20105. if (dimSize == null) {
  20106. throw new Error('Typed array data must specify dimension size');
  20107. }
  20108. }
  20109. this._offset = 0;
  20110. this._dimSize = dimSize;
  20111. this._data = data;
  20112. }
  20113. var methods = providerMethods[
  20114. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20115. ? sourceFormat + '_' + source.seriesLayoutBy
  20116. : sourceFormat
  20117. ];
  20118. if (__DEV__) {
  20119. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20120. }
  20121. extend(this, methods);
  20122. }
  20123. var providerProto = DefaultDataProvider.prototype;
  20124. // If data is pure without style configuration
  20125. providerProto.pure = false;
  20126. // If data is persistent and will not be released after use.
  20127. providerProto.persistent = true;
  20128. // ???! FIXME legacy data provider do not has method getSource
  20129. providerProto.getSource = function () {
  20130. return this._source;
  20131. };
  20132. var providerMethods = {
  20133. 'arrayRows_column': {
  20134. pure: true,
  20135. count: function () {
  20136. return Math.max(0, this._data.length - this._source.startIndex);
  20137. },
  20138. getItem: function (idx) {
  20139. return this._data[idx + this._source.startIndex];
  20140. },
  20141. appendData: appendDataSimply
  20142. },
  20143. 'arrayRows_row': {
  20144. pure: true,
  20145. count: function () {
  20146. var row = this._data[0];
  20147. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20148. },
  20149. getItem: function (idx) {
  20150. idx += this._source.startIndex;
  20151. var item = [];
  20152. var data = this._data;
  20153. for (var i = 0; i < data.length; i++) {
  20154. var row = data[i];
  20155. item.push(row ? row[idx] : null);
  20156. }
  20157. return item;
  20158. },
  20159. appendData: function () {
  20160. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20161. }
  20162. },
  20163. 'objectRows': {
  20164. pure: true,
  20165. count: countSimply,
  20166. getItem: getItemSimply,
  20167. appendData: appendDataSimply
  20168. },
  20169. 'keyedColumns': {
  20170. pure: true,
  20171. count: function () {
  20172. var dimName = this._source.dimensionsDefine[0].name;
  20173. var col = this._data[dimName];
  20174. return col ? col.length : 0;
  20175. },
  20176. getItem: function (idx) {
  20177. var item = [];
  20178. var dims = this._source.dimensionsDefine;
  20179. for (var i = 0; i < dims.length; i++) {
  20180. var col = this._data[dims[i].name];
  20181. item.push(col ? col[idx] : null);
  20182. }
  20183. return item;
  20184. },
  20185. appendData: function (newData) {
  20186. var data = this._data;
  20187. each$1(newData, function (newCol, key) {
  20188. var oldCol = data[key] || (data[key] = []);
  20189. for (var i = 0; i < (newCol || []).length; i++) {
  20190. oldCol.push(newCol[i]);
  20191. }
  20192. });
  20193. }
  20194. },
  20195. 'original': {
  20196. count: countSimply,
  20197. getItem: getItemSimply,
  20198. appendData: appendDataSimply
  20199. },
  20200. 'typedArray': {
  20201. persistent: false,
  20202. pure: true,
  20203. count: function () {
  20204. return this._data ? (this._data.length / this._dimSize) : 0;
  20205. },
  20206. getItem: function (idx, out) {
  20207. idx = idx - this._offset;
  20208. out = out || [];
  20209. var offset = this._dimSize * idx;
  20210. for (var i = 0; i < this._dimSize; i++) {
  20211. out[i] = this._data[offset + i];
  20212. }
  20213. return out;
  20214. },
  20215. appendData: function (newData) {
  20216. if (__DEV__) {
  20217. assert$1(
  20218. isTypedArray(newData),
  20219. 'Added data must be TypedArray if data in initialization is TypedArray'
  20220. );
  20221. }
  20222. this._data = newData;
  20223. },
  20224. // Clean self if data is already used.
  20225. clean: function () {
  20226. // PENDING
  20227. this._offset += this.count();
  20228. this._data = null;
  20229. }
  20230. }
  20231. };
  20232. function countSimply() {
  20233. return this._data.length;
  20234. }
  20235. function getItemSimply(idx) {
  20236. return this._data[idx];
  20237. }
  20238. function appendDataSimply(newData) {
  20239. for (var i = 0; i < newData.length; i++) {
  20240. this._data.push(newData[i]);
  20241. }
  20242. }
  20243. var rawValueGetters = {
  20244. arrayRows: getRawValueSimply,
  20245. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20246. return dimIndex != null ? dataItem[dimName] : dataItem;
  20247. },
  20248. keyedColumns: getRawValueSimply,
  20249. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20250. // FIXME
  20251. // In some case (markpoint in geo (geo-map.html)), dataItem
  20252. // is {coord: [...]}
  20253. var value = getDataItemValue(dataItem);
  20254. return (dimIndex == null || !(value instanceof Array))
  20255. ? value
  20256. : value[dimIndex];
  20257. },
  20258. typedArray: getRawValueSimply
  20259. };
  20260. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20261. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20262. }
  20263. var defaultDimValueGetters = {
  20264. arrayRows: getDimValueSimply,
  20265. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20266. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20267. },
  20268. keyedColumns: getDimValueSimply,
  20269. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20270. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20271. // If dataItem is an plain object with no value field, the var `value`
  20272. // will be assigned with the object, but it will be tread correctly
  20273. // in the `convertDataValue`.
  20274. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20275. // If any dataItem is like { value: 10 }
  20276. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20277. this.hasItemOption = true;
  20278. }
  20279. return converDataValue(
  20280. (value instanceof Array)
  20281. ? value[dimIndex]
  20282. // If value is a single number or something else not array.
  20283. : value,
  20284. this._dimensionInfos[dimName]
  20285. );
  20286. },
  20287. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20288. return dataItem[dimIndex];
  20289. }
  20290. };
  20291. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20292. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20293. }
  20294. /**
  20295. * This helper method convert value in data.
  20296. * @param {string|number|Date} value
  20297. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20298. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20299. */
  20300. function converDataValue(value, dimInfo) {
  20301. // Performance sensitive.
  20302. var dimType = dimInfo && dimInfo.type;
  20303. if (dimType === 'ordinal') {
  20304. // If given value is a category string
  20305. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20306. return ordinalMeta
  20307. ? ordinalMeta.parseAndCollect(value)
  20308. : value;
  20309. }
  20310. if (dimType === 'time'
  20311. // spead up when using timestamp
  20312. && typeof value !== 'number'
  20313. && value != null
  20314. && value !== '-'
  20315. ) {
  20316. value = +parseDate(value);
  20317. }
  20318. // dimType defaults 'number'.
  20319. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20320. // parse to NaN.
  20321. return (value == null || value === '')
  20322. ? NaN
  20323. // If string (like '-'), using '+' parse to NaN
  20324. // If object, also parse to NaN
  20325. : +value;
  20326. }
  20327. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20328. // Consider persistent.
  20329. // Caution: why use raw value to display on label or tooltip?
  20330. // A reason is to avoid format. For example time value we do not know
  20331. // how to format is expected. More over, if stack is used, calculated
  20332. // value may be 0.91000000001, which have brings trouble to display.
  20333. // TODO: consider how to treat null/undefined/NaN when display?
  20334. /**
  20335. * @param {module:echarts/data/List} data
  20336. * @param {number} dataIndex
  20337. * @param {string|number} [dim] dimName or dimIndex
  20338. * @return {Array.<number>|string|number} can be null/undefined.
  20339. */
  20340. function retrieveRawValue(data, dataIndex, dim) {
  20341. if (!data) {
  20342. return;
  20343. }
  20344. // Consider data may be not persistent.
  20345. var dataItem = data.getRawDataItem(dataIndex);
  20346. if (dataItem == null) {
  20347. return;
  20348. }
  20349. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20350. var dimName;
  20351. var dimIndex;
  20352. var dimInfo = data.getDimensionInfo(dim);
  20353. if (dimInfo) {
  20354. dimName = dimInfo.name;
  20355. dimIndex = dimInfo.index;
  20356. }
  20357. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20358. }
  20359. /**
  20360. * Compatible with some cases (in pie, map) like:
  20361. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20362. * where only sourceFormat is 'original' and 'objectRows' supported.
  20363. *
  20364. * ??? TODO
  20365. * Supported detail options in data item when using 'arrayRows'.
  20366. *
  20367. * @param {module:echarts/data/List} data
  20368. * @param {number} dataIndex
  20369. * @param {string} attr like 'selected'
  20370. */
  20371. function retrieveRawAttr(data, dataIndex, attr) {
  20372. if (!data) {
  20373. return;
  20374. }
  20375. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20376. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20377. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20378. ) {
  20379. return;
  20380. }
  20381. var dataItem = data.getRawDataItem(dataIndex);
  20382. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20383. dataItem = null;
  20384. }
  20385. if (dataItem) {
  20386. return dataItem[attr];
  20387. }
  20388. }
  20389. /*
  20390. * Licensed to the Apache Software Foundation (ASF) under one
  20391. * or more contributor license agreements. See the NOTICE file
  20392. * distributed with this work for additional information
  20393. * regarding copyright ownership. The ASF licenses this file
  20394. * to you under the Apache License, Version 2.0 (the
  20395. * "License"); you may not use this file except in compliance
  20396. * with the License. You may obtain a copy of the License at
  20397. *
  20398. * http://www.apache.org/licenses/LICENSE-2.0
  20399. *
  20400. * Unless required by applicable law or agreed to in writing,
  20401. * software distributed under the License is distributed on an
  20402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20403. * KIND, either express or implied. See the License for the
  20404. * specific language governing permissions and limitations
  20405. * under the License.
  20406. */
  20407. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20408. // PENDING A little ugly
  20409. var dataFormatMixin = {
  20410. /**
  20411. * Get params for formatter
  20412. * @param {number} dataIndex
  20413. * @param {string} [dataType]
  20414. * @return {Object}
  20415. */
  20416. getDataParams: function (dataIndex, dataType) {
  20417. var data = this.getData(dataType);
  20418. var rawValue = this.getRawValue(dataIndex, dataType);
  20419. var rawDataIndex = data.getRawIndex(dataIndex);
  20420. var name = data.getName(dataIndex);
  20421. var itemOpt = data.getRawDataItem(dataIndex);
  20422. var color = data.getItemVisual(dataIndex, 'color');
  20423. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20424. var tooltipModel = this.ecModel.getComponent('tooltip');
  20425. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20426. var renderMode = getTooltipRenderMode(renderModeOption);
  20427. var mainType = this.mainType;
  20428. var isSeries = mainType === 'series';
  20429. var userOutput = data.userOutput;
  20430. return {
  20431. componentType: mainType,
  20432. componentSubType: this.subType,
  20433. componentIndex: this.componentIndex,
  20434. seriesType: isSeries ? this.subType : null,
  20435. seriesIndex: this.seriesIndex,
  20436. seriesId: isSeries ? this.id : null,
  20437. seriesName: isSeries ? this.name : null,
  20438. name: name,
  20439. dataIndex: rawDataIndex,
  20440. data: itemOpt,
  20441. dataType: dataType,
  20442. value: rawValue,
  20443. color: color,
  20444. borderColor: borderColor,
  20445. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20446. encode: userOutput ? userOutput.encode : null,
  20447. marker: getTooltipMarker({
  20448. color: color,
  20449. renderMode: renderMode
  20450. }),
  20451. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20452. $vars: ['seriesName', 'name', 'value']
  20453. };
  20454. },
  20455. /**
  20456. * Format label
  20457. * @param {number} dataIndex
  20458. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20459. * @param {string} [dataType]
  20460. * @param {number} [dimIndex] Only used in some chart that
  20461. * use formatter in different dimensions, like radar.
  20462. * @param {string} [labelProp='label']
  20463. * @return {string} If not formatter, return null/undefined
  20464. */
  20465. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20466. status = status || 'normal';
  20467. var data = this.getData(dataType);
  20468. var itemModel = data.getItemModel(dataIndex);
  20469. var params = this.getDataParams(dataIndex, dataType);
  20470. if (dimIndex != null && (params.value instanceof Array)) {
  20471. params.value = params.value[dimIndex];
  20472. }
  20473. var formatter = itemModel.get(
  20474. status === 'normal'
  20475. ? [labelProp || 'label', 'formatter']
  20476. : [status, labelProp || 'label', 'formatter']
  20477. );
  20478. if (typeof formatter === 'function') {
  20479. params.status = status;
  20480. params.dimensionIndex = dimIndex;
  20481. return formatter(params);
  20482. }
  20483. else if (typeof formatter === 'string') {
  20484. var str = formatTpl(formatter, params);
  20485. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20486. // Do not support '}' in dim name util have to.
  20487. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20488. var len = dim.length;
  20489. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20490. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20491. }
  20492. return retrieveRawValue(data, dataIndex, dim);
  20493. });
  20494. }
  20495. },
  20496. /**
  20497. * Get raw value in option
  20498. * @param {number} idx
  20499. * @param {string} [dataType]
  20500. * @return {Array|number|string}
  20501. */
  20502. getRawValue: function (idx, dataType) {
  20503. return retrieveRawValue(this.getData(dataType), idx);
  20504. },
  20505. /**
  20506. * Should be implemented.
  20507. * @param {number} dataIndex
  20508. * @param {boolean} [multipleSeries=false]
  20509. * @param {number} [dataType]
  20510. * @return {string} tooltip string
  20511. */
  20512. formatTooltip: function () {
  20513. // Empty function
  20514. }
  20515. };
  20516. /*
  20517. * Licensed to the Apache Software Foundation (ASF) under one
  20518. * or more contributor license agreements. See the NOTICE file
  20519. * distributed with this work for additional information
  20520. * regarding copyright ownership. The ASF licenses this file
  20521. * to you under the Apache License, Version 2.0 (the
  20522. * "License"); you may not use this file except in compliance
  20523. * with the License. You may obtain a copy of the License at
  20524. *
  20525. * http://www.apache.org/licenses/LICENSE-2.0
  20526. *
  20527. * Unless required by applicable law or agreed to in writing,
  20528. * software distributed under the License is distributed on an
  20529. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20530. * KIND, either express or implied. See the License for the
  20531. * specific language governing permissions and limitations
  20532. * under the License.
  20533. */
  20534. /**
  20535. * @param {Object} define
  20536. * @return See the return of `createTask`.
  20537. */
  20538. function createTask(define) {
  20539. return new Task(define);
  20540. }
  20541. /**
  20542. * @constructor
  20543. * @param {Object} define
  20544. * @param {Function} define.reset Custom reset
  20545. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20546. * @param {Function} [define.count] count is used to determin data task.
  20547. * @param {Function} [define.onDirty] count is used to determin data task.
  20548. */
  20549. function Task(define) {
  20550. define = define || {};
  20551. this._reset = define.reset;
  20552. this._plan = define.plan;
  20553. this._count = define.count;
  20554. this._onDirty = define.onDirty;
  20555. this._dirty = true;
  20556. // Context must be specified implicitly, to
  20557. // avoid miss update context when model changed.
  20558. this.context;
  20559. }
  20560. var taskProto = Task.prototype;
  20561. /**
  20562. * @param {Object} performArgs
  20563. * @param {number} [performArgs.step] Specified step.
  20564. * @param {number} [performArgs.skip] Skip customer perform call.
  20565. * @param {number} [performArgs.modBy] Sampling window size.
  20566. * @param {number} [performArgs.modDataCount] Sampling count.
  20567. */
  20568. taskProto.perform = function (performArgs) {
  20569. var upTask = this._upstream;
  20570. var skip = performArgs && performArgs.skip;
  20571. // TODO some refactor.
  20572. // Pull data. Must pull data each time, because context.data
  20573. // may be updated by Series.setData.
  20574. if (this._dirty && upTask) {
  20575. var context = this.context;
  20576. context.data = context.outputData = upTask.context.outputData;
  20577. }
  20578. if (this.__pipeline) {
  20579. this.__pipeline.currentTask = this;
  20580. }
  20581. var planResult;
  20582. if (this._plan && !skip) {
  20583. planResult = this._plan(this.context);
  20584. }
  20585. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20586. // elements uniformed distributed when progress, especially when moving or zooming.
  20587. var lastModBy = normalizeModBy(this._modBy);
  20588. var lastModDataCount = this._modDataCount || 0;
  20589. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20590. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20591. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20592. planResult = 'reset';
  20593. }
  20594. function normalizeModBy(val) {
  20595. !(val >= 1) && (val = 1); // jshint ignore:line
  20596. return val;
  20597. }
  20598. var forceFirstProgress;
  20599. if (this._dirty || planResult === 'reset') {
  20600. this._dirty = false;
  20601. forceFirstProgress = reset(this, skip);
  20602. }
  20603. this._modBy = modBy;
  20604. this._modDataCount = modDataCount;
  20605. var step = performArgs && performArgs.step;
  20606. if (upTask) {
  20607. if (__DEV__) {
  20608. assert$1(upTask._outputDueEnd != null);
  20609. }
  20610. this._dueEnd = upTask._outputDueEnd;
  20611. }
  20612. // DataTask or overallTask
  20613. else {
  20614. if (__DEV__) {
  20615. assert$1(!this._progress || this._count);
  20616. }
  20617. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20618. }
  20619. // Note: Stubs, that its host overall task let it has progress, has progress.
  20620. // If no progress, pass index from upstream to downstream each time plan called.
  20621. if (this._progress) {
  20622. var start = this._dueIndex;
  20623. var end = Math.min(
  20624. step != null ? this._dueIndex + step : Infinity,
  20625. this._dueEnd
  20626. );
  20627. if (!skip && (forceFirstProgress || start < end)) {
  20628. var progress = this._progress;
  20629. if (isArray(progress)) {
  20630. for (var i = 0; i < progress.length; i++) {
  20631. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20632. }
  20633. }
  20634. else {
  20635. doProgress(this, progress, start, end, modBy, modDataCount);
  20636. }
  20637. }
  20638. this._dueIndex = end;
  20639. // If no `outputDueEnd`, assume that output data and
  20640. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20641. var outputDueEnd = this._settedOutputEnd != null
  20642. ? this._settedOutputEnd : end;
  20643. if (__DEV__) {
  20644. // ??? Can not rollback.
  20645. assert$1(outputDueEnd >= this._outputDueEnd);
  20646. }
  20647. this._outputDueEnd = outputDueEnd;
  20648. }
  20649. else {
  20650. // (1) Some overall task has no progress.
  20651. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20652. // This should always be performed so it can be passed to downstream.
  20653. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20654. ? this._settedOutputEnd : this._dueEnd;
  20655. }
  20656. return this.unfinished();
  20657. };
  20658. var iterator = (function () {
  20659. var end;
  20660. var current;
  20661. var modBy;
  20662. var modDataCount;
  20663. var winCount;
  20664. var it = {
  20665. reset: function (s, e, sStep, sCount) {
  20666. current = s;
  20667. end = e;
  20668. modBy = sStep;
  20669. modDataCount = sCount;
  20670. winCount = Math.ceil(modDataCount / modBy);
  20671. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20672. }
  20673. };
  20674. return it;
  20675. function sequentialNext() {
  20676. return current < end ? current++ : null;
  20677. }
  20678. function modNext() {
  20679. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20680. var result = current >= end
  20681. ? null
  20682. : dataIndex < modDataCount
  20683. ? dataIndex
  20684. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20685. // Use normal linear rendering mode.
  20686. : current;
  20687. current++;
  20688. return result;
  20689. }
  20690. })();
  20691. taskProto.dirty = function () {
  20692. this._dirty = true;
  20693. this._onDirty && this._onDirty(this.context);
  20694. };
  20695. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20696. iterator.reset(start, end, modBy, modDataCount);
  20697. taskIns._callingProgress = progress;
  20698. taskIns._callingProgress({
  20699. start: start, end: end, count: end - start, next: iterator.next
  20700. }, taskIns.context);
  20701. }
  20702. function reset(taskIns, skip) {
  20703. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20704. taskIns._settedOutputEnd = null;
  20705. var progress;
  20706. var forceFirstProgress;
  20707. if (!skip && taskIns._reset) {
  20708. progress = taskIns._reset(taskIns.context);
  20709. if (progress && progress.progress) {
  20710. forceFirstProgress = progress.forceFirstProgress;
  20711. progress = progress.progress;
  20712. }
  20713. // To simplify no progress checking, array must has item.
  20714. if (isArray(progress) && !progress.length) {
  20715. progress = null;
  20716. }
  20717. }
  20718. taskIns._progress = progress;
  20719. taskIns._modBy = taskIns._modDataCount = null;
  20720. var downstream = taskIns._downstream;
  20721. downstream && downstream.dirty();
  20722. return forceFirstProgress;
  20723. }
  20724. /**
  20725. * @return {boolean}
  20726. */
  20727. taskProto.unfinished = function () {
  20728. return this._progress && this._dueIndex < this._dueEnd;
  20729. };
  20730. /**
  20731. * @param {Object} downTask The downstream task.
  20732. * @return {Object} The downstream task.
  20733. */
  20734. taskProto.pipe = function (downTask) {
  20735. if (__DEV__) {
  20736. assert$1(downTask && !downTask._disposed && downTask !== this);
  20737. }
  20738. // If already downstream, do not dirty downTask.
  20739. if (this._downstream !== downTask || this._dirty) {
  20740. this._downstream = downTask;
  20741. downTask._upstream = this;
  20742. downTask.dirty();
  20743. }
  20744. };
  20745. taskProto.dispose = function () {
  20746. if (this._disposed) {
  20747. return;
  20748. }
  20749. this._upstream && (this._upstream._downstream = null);
  20750. this._downstream && (this._downstream._upstream = null);
  20751. this._dirty = false;
  20752. this._disposed = true;
  20753. };
  20754. taskProto.getUpstream = function () {
  20755. return this._upstream;
  20756. };
  20757. taskProto.getDownstream = function () {
  20758. return this._downstream;
  20759. };
  20760. taskProto.setOutputEnd = function (end) {
  20761. // This only happend in dataTask, dataZoom, map, currently.
  20762. // where dataZoom do not set end each time, but only set
  20763. // when reset. So we should record the setted end, in case
  20764. // that the stub of dataZoom perform again and earse the
  20765. // setted end by upstream.
  20766. this._outputDueEnd = this._settedOutputEnd = end;
  20767. };
  20768. ///////////////////////////////////////////////////////////
  20769. // For stream debug (Should be commented out after used!)
  20770. // Usage: printTask(this, 'begin');
  20771. // Usage: printTask(this, null, {someExtraProp});
  20772. // function printTask(task, prefix, extra) {
  20773. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20774. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20775. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20776. // var props = [];
  20777. // if (task.__pipeline) {
  20778. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20779. // props.push({text: 'idx', value: val});
  20780. // } else {
  20781. // var stubCount = 0;
  20782. // task.agentStubMap.each(() => stubCount++);
  20783. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20784. // }
  20785. // props.push({text: 'uid', value: task.uidDebug});
  20786. // if (task.__pipeline) {
  20787. // props.push({text: 'pid', value: task.__pipeline.id});
  20788. // task.agent && props.push(
  20789. // {text: 'stubFor', value: task.agent.uidDebug}
  20790. // );
  20791. // }
  20792. // props.push(
  20793. // {text: 'dirty', value: task._dirty},
  20794. // {text: 'dueIndex', value: task._dueIndex},
  20795. // {text: 'dueEnd', value: task._dueEnd},
  20796. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20797. // );
  20798. // if (extra) {
  20799. // Object.keys(extra).forEach(key => {
  20800. // props.push({text: key, value: extra[key]});
  20801. // });
  20802. // }
  20803. // var args = ['color: blue'];
  20804. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20805. // args.push('color: black', 'color: red'),
  20806. // `${item.text}: %c${item.value}`
  20807. // )).join('%c, ');
  20808. // console.log.apply(console, [msg].concat(args));
  20809. // // console.log(this);
  20810. // }
  20811. /*
  20812. * Licensed to the Apache Software Foundation (ASF) under one
  20813. * or more contributor license agreements. See the NOTICE file
  20814. * distributed with this work for additional information
  20815. * regarding copyright ownership. The ASF licenses this file
  20816. * to you under the Apache License, Version 2.0 (the
  20817. * "License"); you may not use this file except in compliance
  20818. * with the License. You may obtain a copy of the License at
  20819. *
  20820. * http://www.apache.org/licenses/LICENSE-2.0
  20821. *
  20822. * Unless required by applicable law or agreed to in writing,
  20823. * software distributed under the License is distributed on an
  20824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20825. * KIND, either express or implied. See the License for the
  20826. * specific language governing permissions and limitations
  20827. * under the License.
  20828. */
  20829. var inner$4 = makeInner();
  20830. var SeriesModel = ComponentModel.extend({
  20831. type: 'series.__base__',
  20832. /**
  20833. * @readOnly
  20834. */
  20835. seriesIndex: 0,
  20836. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20837. coordinateSystem: null,
  20838. /**
  20839. * @type {Object}
  20840. * @protected
  20841. */
  20842. defaultOption: null,
  20843. /**
  20844. * legend visual provider to the legend component
  20845. * @type {Object}
  20846. */
  20847. // PENDING
  20848. legendVisualProvider: null,
  20849. /**
  20850. * Access path of color for visual
  20851. */
  20852. visualColorAccessPath: 'itemStyle.color',
  20853. /**
  20854. * Access path of borderColor for visual
  20855. */
  20856. visualBorderColorAccessPath: 'itemStyle.borderColor',
  20857. /**
  20858. * Support merge layout params.
  20859. * Only support 'box' now (left/right/top/bottom/width/height).
  20860. * @type {string|Object} Object can be {ignoreSize: true}
  20861. * @readOnly
  20862. */
  20863. layoutMode: null,
  20864. init: function (option, parentModel, ecModel, extraOpt) {
  20865. /**
  20866. * @type {number}
  20867. * @readOnly
  20868. */
  20869. this.seriesIndex = this.componentIndex;
  20870. this.dataTask = createTask({
  20871. count: dataTaskCount,
  20872. reset: dataTaskReset
  20873. });
  20874. this.dataTask.context = {model: this};
  20875. this.mergeDefaultAndTheme(option, ecModel);
  20876. prepareSource(this);
  20877. var data = this.getInitialData(option, ecModel);
  20878. wrapData(data, this);
  20879. this.dataTask.context.data = data;
  20880. if (__DEV__) {
  20881. assert$1(data, 'getInitialData returned invalid data.');
  20882. }
  20883. /**
  20884. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20885. * @private
  20886. */
  20887. inner$4(this).dataBeforeProcessed = data;
  20888. // If we reverse the order (make data firstly, and then make
  20889. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20890. // cause data.graph.data !== data when using
  20891. // module:echarts/data/Graph or module:echarts/data/Tree.
  20892. // See module:echarts/data/helper/linkList
  20893. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20894. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20895. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20896. // Call `seriesModel.getRawData()` instead.
  20897. // this.restoreData();
  20898. autoSeriesName(this);
  20899. },
  20900. /**
  20901. * Util for merge default and theme to option
  20902. * @param {Object} option
  20903. * @param {module:echarts/model/Global} ecModel
  20904. */
  20905. mergeDefaultAndTheme: function (option, ecModel) {
  20906. var layoutMode = this.layoutMode;
  20907. var inputPositionParams = layoutMode
  20908. ? getLayoutParams(option) : {};
  20909. // Backward compat: using subType on theme.
  20910. // But if name duplicate between series subType
  20911. // (for example: parallel) add component mainType,
  20912. // add suffix 'Series'.
  20913. var themeSubType = this.subType;
  20914. if (ComponentModel.hasClass(themeSubType)) {
  20915. themeSubType += 'Series';
  20916. }
  20917. merge(
  20918. option,
  20919. ecModel.getTheme().get(this.subType)
  20920. );
  20921. merge(option, this.getDefaultOption());
  20922. // Default label emphasis `show`
  20923. defaultEmphasis(option, 'label', ['show']);
  20924. this.fillDataTextStyle(option.data);
  20925. if (layoutMode) {
  20926. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20927. }
  20928. },
  20929. mergeOption: function (newSeriesOption, ecModel) {
  20930. // this.settingTask.dirty();
  20931. newSeriesOption = merge(this.option, newSeriesOption, true);
  20932. this.fillDataTextStyle(newSeriesOption.data);
  20933. var layoutMode = this.layoutMode;
  20934. if (layoutMode) {
  20935. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20936. }
  20937. prepareSource(this);
  20938. var data = this.getInitialData(newSeriesOption, ecModel);
  20939. wrapData(data, this);
  20940. this.dataTask.dirty();
  20941. this.dataTask.context.data = data;
  20942. inner$4(this).dataBeforeProcessed = data;
  20943. autoSeriesName(this);
  20944. },
  20945. fillDataTextStyle: function (data) {
  20946. // Default data label emphasis `show`
  20947. // FIXME Tree structure data ?
  20948. // FIXME Performance ?
  20949. if (data && !isTypedArray(data)) {
  20950. var props = ['show'];
  20951. for (var i = 0; i < data.length; i++) {
  20952. if (data[i] && data[i].label) {
  20953. defaultEmphasis(data[i], 'label', props);
  20954. }
  20955. }
  20956. }
  20957. },
  20958. /**
  20959. * Init a data structure from data related option in series
  20960. * Must be overwritten
  20961. */
  20962. getInitialData: function () {},
  20963. /**
  20964. * Append data to list
  20965. * @param {Object} params
  20966. * @param {Array|TypedArray} params.data
  20967. */
  20968. appendData: function (params) {
  20969. // FIXME ???
  20970. // (1) If data from dataset, forbidden append.
  20971. // (2) support append data of dataset.
  20972. var data = this.getRawData();
  20973. data.appendData(params.data);
  20974. },
  20975. /**
  20976. * Consider some method like `filter`, `map` need make new data,
  20977. * We should make sure that `seriesModel.getData()` get correct
  20978. * data in the stream procedure. So we fetch data from upstream
  20979. * each time `task.perform` called.
  20980. * @param {string} [dataType]
  20981. * @return {module:echarts/data/List}
  20982. */
  20983. getData: function (dataType) {
  20984. var task = getCurrentTask(this);
  20985. if (task) {
  20986. var data = task.context.data;
  20987. return dataType == null ? data : data.getLinkedData(dataType);
  20988. }
  20989. else {
  20990. // When series is not alive (that may happen when click toolbox
  20991. // restore or setOption with not merge mode), series data may
  20992. // be still need to judge animation or something when graphic
  20993. // elements want to know whether fade out.
  20994. return inner$4(this).data;
  20995. }
  20996. },
  20997. /**
  20998. * @param {module:echarts/data/List} data
  20999. */
  21000. setData: function (data) {
  21001. var task = getCurrentTask(this);
  21002. if (task) {
  21003. var context = task.context;
  21004. // Consider case: filter, data sample.
  21005. if (context.data !== data && task.modifyOutputEnd) {
  21006. task.setOutputEnd(data.count());
  21007. }
  21008. context.outputData = data;
  21009. // Caution: setData should update context.data,
  21010. // Because getData may be called multiply in a
  21011. // single stage and expect to get the data just
  21012. // set. (For example, AxisProxy, x y both call
  21013. // getData and setDate sequentially).
  21014. // So the context.data should be fetched from
  21015. // upstream each time when a stage starts to be
  21016. // performed.
  21017. if (task !== this.dataTask) {
  21018. context.data = data;
  21019. }
  21020. }
  21021. inner$4(this).data = data;
  21022. },
  21023. /**
  21024. * @see {module:echarts/data/helper/sourceHelper#getSource}
  21025. * @return {module:echarts/data/Source} source
  21026. */
  21027. getSource: function () {
  21028. return getSource(this);
  21029. },
  21030. /**
  21031. * Get data before processed
  21032. * @return {module:echarts/data/List}
  21033. */
  21034. getRawData: function () {
  21035. return inner$4(this).dataBeforeProcessed;
  21036. },
  21037. /**
  21038. * Get base axis if has coordinate system and has axis.
  21039. * By default use coordSys.getBaseAxis();
  21040. * Can be overrided for some chart.
  21041. * @return {type} description
  21042. */
  21043. getBaseAxis: function () {
  21044. var coordSys = this.coordinateSystem;
  21045. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  21046. },
  21047. // FIXME
  21048. /**
  21049. * Default tooltip formatter
  21050. *
  21051. * @param {number} dataIndex
  21052. * @param {boolean} [multipleSeries=false]
  21053. * @param {number} [dataType]
  21054. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  21055. * 'html' is used for rendering tooltip in extra DOM form, and the result
  21056. * string is used as DOM HTML content.
  21057. * 'richText' is used for rendering tooltip in rich text form, for those where
  21058. * DOM operation is not supported.
  21059. * @return {Object} formatted tooltip with `html` and `markers`
  21060. */
  21061. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  21062. var series = this;
  21063. renderMode = renderMode || 'html';
  21064. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  21065. var isRichText = renderMode === 'richText';
  21066. var markers = {};
  21067. var markerId = 0;
  21068. function formatArrayValue(value) {
  21069. // ??? TODO refactor these logic.
  21070. // check: category-no-encode-has-axis-data in dataset.html
  21071. var vertially = reduce(value, function (vertially, val, idx) {
  21072. var dimItem = data.getDimensionInfo(idx);
  21073. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  21074. }, 0);
  21075. var result = [];
  21076. tooltipDims.length
  21077. ? each$1(tooltipDims, function (dim) {
  21078. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  21079. })
  21080. // By default, all dims is used on tooltip.
  21081. : each$1(value, setEachItem);
  21082. function setEachItem(val, dim) {
  21083. var dimInfo = data.getDimensionInfo(dim);
  21084. // If `dimInfo.tooltip` is not set, show tooltip.
  21085. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  21086. return;
  21087. }
  21088. var dimType = dimInfo.type;
  21089. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21090. var dimHead = getTooltipMarker({
  21091. color: color,
  21092. type: 'subItem',
  21093. renderMode: renderMode,
  21094. markerId: markName
  21095. });
  21096. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21097. var valStr = (vertially
  21098. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21099. : ''
  21100. )
  21101. // FIXME should not format time for raw data?
  21102. + encodeHTML(dimType === 'ordinal'
  21103. ? val + ''
  21104. : dimType === 'time'
  21105. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21106. : addCommas(val)
  21107. );
  21108. valStr && result.push(valStr);
  21109. if (isRichText) {
  21110. markers[markName] = color;
  21111. ++markerId;
  21112. }
  21113. }
  21114. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21115. var content = newLine + result.join(newLine || ', ');
  21116. return {
  21117. renderMode: renderMode,
  21118. content: content,
  21119. style: markers
  21120. };
  21121. }
  21122. function formatSingleValue(val) {
  21123. // return encodeHTML(addCommas(val));
  21124. return {
  21125. renderMode: renderMode,
  21126. content: encodeHTML(addCommas(val)),
  21127. style: markers
  21128. };
  21129. }
  21130. var data = this.getData();
  21131. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21132. var tooltipDimLen = tooltipDims.length;
  21133. var value = this.getRawValue(dataIndex);
  21134. var isValueArr = isArray(value);
  21135. var color = data.getItemVisual(dataIndex, 'color');
  21136. if (isObject$1(color) && color.colorStops) {
  21137. color = (color.colorStops[0] || {}).color;
  21138. }
  21139. color = color || 'transparent';
  21140. // Complicated rule for pretty tooltip.
  21141. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21142. ? formatArrayValue(value)
  21143. : tooltipDimLen
  21144. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21145. : formatSingleValue(isValueArr ? value[0] : value);
  21146. var content = formattedValue.content;
  21147. var markName = series.seriesIndex + 'at' + markerId;
  21148. var colorEl = getTooltipMarker({
  21149. color: color,
  21150. type: 'item',
  21151. renderMode: renderMode,
  21152. markerId: markName
  21153. });
  21154. markers[markName] = color;
  21155. ++markerId;
  21156. var name = data.getName(dataIndex);
  21157. var seriesName = this.name;
  21158. if (!isNameSpecified(this)) {
  21159. seriesName = '';
  21160. }
  21161. seriesName = seriesName
  21162. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21163. : '';
  21164. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21165. var html = !multipleSeries
  21166. ? seriesName + colorStr
  21167. + (name
  21168. ? encodeHTML(name) + ': ' + content
  21169. : content
  21170. )
  21171. : colorStr + seriesName + content;
  21172. return {
  21173. html: html,
  21174. markers: markers
  21175. };
  21176. },
  21177. /**
  21178. * @return {boolean}
  21179. */
  21180. isAnimationEnabled: function () {
  21181. if (env$1.node) {
  21182. return false;
  21183. }
  21184. var animationEnabled = this.getShallow('animation');
  21185. if (animationEnabled) {
  21186. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21187. animationEnabled = false;
  21188. }
  21189. }
  21190. return animationEnabled;
  21191. },
  21192. restoreData: function () {
  21193. this.dataTask.dirty();
  21194. },
  21195. getColorFromPalette: function (name, scope, requestColorNum) {
  21196. var ecModel = this.ecModel;
  21197. // PENDING
  21198. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21199. if (!color) {
  21200. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21201. }
  21202. return color;
  21203. },
  21204. /**
  21205. * Use `data.mapDimension(coordDim, true)` instead.
  21206. * @deprecated
  21207. */
  21208. coordDimToDataDim: function (coordDim) {
  21209. return this.getRawData().mapDimension(coordDim, true);
  21210. },
  21211. /**
  21212. * Get progressive rendering count each step
  21213. * @return {number}
  21214. */
  21215. getProgressive: function () {
  21216. return this.get('progressive');
  21217. },
  21218. /**
  21219. * Get progressive rendering count each step
  21220. * @return {number}
  21221. */
  21222. getProgressiveThreshold: function () {
  21223. return this.get('progressiveThreshold');
  21224. },
  21225. /**
  21226. * Get data indices for show tooltip content. See tooltip.
  21227. * @abstract
  21228. * @param {Array.<string>|string} dim
  21229. * @param {Array.<number>} value
  21230. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21231. * @return {Object} {dataIndices, nestestValue}.
  21232. */
  21233. getAxisTooltipData: null,
  21234. /**
  21235. * See tooltip.
  21236. * @abstract
  21237. * @param {number} dataIndex
  21238. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21239. */
  21240. getTooltipPosition: null,
  21241. /**
  21242. * @see {module:echarts/stream/Scheduler}
  21243. */
  21244. pipeTask: null,
  21245. /**
  21246. * Convinient for override in extended class.
  21247. * @protected
  21248. * @type {Function}
  21249. */
  21250. preventIncremental: null,
  21251. /**
  21252. * @public
  21253. * @readOnly
  21254. * @type {Object}
  21255. */
  21256. pipelineContext: null
  21257. });
  21258. mixin(SeriesModel, dataFormatMixin);
  21259. mixin(SeriesModel, colorPaletteMixin);
  21260. /**
  21261. * MUST be called after `prepareSource` called
  21262. * Here we need to make auto series, especially for auto legend. But we
  21263. * do not modify series.name in option to avoid side effects.
  21264. */
  21265. function autoSeriesName(seriesModel) {
  21266. // User specified name has higher priority, otherwise it may cause
  21267. // series can not be queried unexpectedly.
  21268. var name = seriesModel.name;
  21269. if (!isNameSpecified(seriesModel)) {
  21270. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21271. }
  21272. }
  21273. function getSeriesAutoName(seriesModel) {
  21274. var data = seriesModel.getRawData();
  21275. var dataDims = data.mapDimension('seriesName', true);
  21276. var nameArr = [];
  21277. each$1(dataDims, function (dataDim) {
  21278. var dimInfo = data.getDimensionInfo(dataDim);
  21279. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21280. });
  21281. return nameArr.join(' ');
  21282. }
  21283. function dataTaskCount(context) {
  21284. return context.model.getRawData().count();
  21285. }
  21286. function dataTaskReset(context) {
  21287. var seriesModel = context.model;
  21288. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21289. return dataTaskProgress;
  21290. }
  21291. function dataTaskProgress(param, context) {
  21292. // Avoid repead cloneShallow when data just created in reset.
  21293. if (param.end > context.outputData.count()) {
  21294. context.model.getRawData().cloneShallow(context.outputData);
  21295. }
  21296. }
  21297. // TODO refactor
  21298. function wrapData(data, seriesModel) {
  21299. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21300. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21301. });
  21302. }
  21303. function onDataSelfChange(seriesModel) {
  21304. var task = getCurrentTask(seriesModel);
  21305. if (task) {
  21306. // Consider case: filter, selectRange
  21307. task.setOutputEnd(this.count());
  21308. }
  21309. }
  21310. function getCurrentTask(seriesModel) {
  21311. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21312. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21313. if (pipeline) {
  21314. // When pipline finished, the currrentTask keep the last
  21315. // task (renderTask).
  21316. var task = pipeline.currentTask;
  21317. if (task) {
  21318. var agentStubMap = task.agentStubMap;
  21319. if (agentStubMap) {
  21320. task = agentStubMap.get(seriesModel.uid);
  21321. }
  21322. }
  21323. return task;
  21324. }
  21325. }
  21326. /*
  21327. * Licensed to the Apache Software Foundation (ASF) under one
  21328. * or more contributor license agreements. See the NOTICE file
  21329. * distributed with this work for additional information
  21330. * regarding copyright ownership. The ASF licenses this file
  21331. * to you under the Apache License, Version 2.0 (the
  21332. * "License"); you may not use this file except in compliance
  21333. * with the License. You may obtain a copy of the License at
  21334. *
  21335. * http://www.apache.org/licenses/LICENSE-2.0
  21336. *
  21337. * Unless required by applicable law or agreed to in writing,
  21338. * software distributed under the License is distributed on an
  21339. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21340. * KIND, either express or implied. See the License for the
  21341. * specific language governing permissions and limitations
  21342. * under the License.
  21343. */
  21344. var Component = function () {
  21345. /**
  21346. * @type {module:zrender/container/Group}
  21347. * @readOnly
  21348. */
  21349. this.group = new Group();
  21350. /**
  21351. * @type {string}
  21352. * @readOnly
  21353. */
  21354. this.uid = getUID('viewComponent');
  21355. };
  21356. Component.prototype = {
  21357. constructor: Component,
  21358. init: function (ecModel, api) {},
  21359. render: function (componentModel, ecModel, api, payload) {},
  21360. dispose: function () {},
  21361. /**
  21362. * @param {string} eventType
  21363. * @param {Object} query
  21364. * @param {module:zrender/Element} targetEl
  21365. * @param {Object} packedEvent
  21366. * @return {boolen} Pass only when return `true`.
  21367. */
  21368. filterForExposedEvent: null
  21369. };
  21370. var componentProto = Component.prototype;
  21371. componentProto.updateView =
  21372. componentProto.updateLayout =
  21373. componentProto.updateVisual =
  21374. function (seriesModel, ecModel, api, payload) {
  21375. // Do nothing;
  21376. };
  21377. // Enable Component.extend.
  21378. enableClassExtend(Component);
  21379. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21380. enableClassManagement(Component, {registerWhenExtend: true});
  21381. /*
  21382. * Licensed to the Apache Software Foundation (ASF) under one
  21383. * or more contributor license agreements. See the NOTICE file
  21384. * distributed with this work for additional information
  21385. * regarding copyright ownership. The ASF licenses this file
  21386. * to you under the Apache License, Version 2.0 (the
  21387. * "License"); you may not use this file except in compliance
  21388. * with the License. You may obtain a copy of the License at
  21389. *
  21390. * http://www.apache.org/licenses/LICENSE-2.0
  21391. *
  21392. * Unless required by applicable law or agreed to in writing,
  21393. * software distributed under the License is distributed on an
  21394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21395. * KIND, either express or implied. See the License for the
  21396. * specific language governing permissions and limitations
  21397. * under the License.
  21398. */
  21399. /**
  21400. * @return {string} If large mode changed, return string 'reset';
  21401. */
  21402. var createRenderPlanner = function () {
  21403. var inner = makeInner();
  21404. return function (seriesModel) {
  21405. var fields = inner(seriesModel);
  21406. var pipelineContext = seriesModel.pipelineContext;
  21407. var originalLarge = fields.large;
  21408. var originalProgressive = fields.progressiveRender;
  21409. // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  21410. // exists. See #11611 . Probably we need to modify this structure, see the comment
  21411. // on `performRawSeries` in `Schedular.js`.
  21412. var large = fields.large = pipelineContext && pipelineContext.large;
  21413. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  21414. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21415. };
  21416. };
  21417. /*
  21418. * Licensed to the Apache Software Foundation (ASF) under one
  21419. * or more contributor license agreements. See the NOTICE file
  21420. * distributed with this work for additional information
  21421. * regarding copyright ownership. The ASF licenses this file
  21422. * to you under the Apache License, Version 2.0 (the
  21423. * "License"); you may not use this file except in compliance
  21424. * with the License. You may obtain a copy of the License at
  21425. *
  21426. * http://www.apache.org/licenses/LICENSE-2.0
  21427. *
  21428. * Unless required by applicable law or agreed to in writing,
  21429. * software distributed under the License is distributed on an
  21430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21431. * KIND, either express or implied. See the License for the
  21432. * specific language governing permissions and limitations
  21433. * under the License.
  21434. */
  21435. var inner$5 = makeInner();
  21436. var renderPlanner = createRenderPlanner();
  21437. function Chart() {
  21438. /**
  21439. * @type {module:zrender/container/Group}
  21440. * @readOnly
  21441. */
  21442. this.group = new Group();
  21443. /**
  21444. * @type {string}
  21445. * @readOnly
  21446. */
  21447. this.uid = getUID('viewChart');
  21448. this.renderTask = createTask({
  21449. plan: renderTaskPlan,
  21450. reset: renderTaskReset
  21451. });
  21452. this.renderTask.context = {view: this};
  21453. }
  21454. Chart.prototype = {
  21455. type: 'chart',
  21456. /**
  21457. * Init the chart.
  21458. * @param {module:echarts/model/Global} ecModel
  21459. * @param {module:echarts/ExtensionAPI} api
  21460. */
  21461. init: function (ecModel, api) {},
  21462. /**
  21463. * Render the chart.
  21464. * @param {module:echarts/model/Series} seriesModel
  21465. * @param {module:echarts/model/Global} ecModel
  21466. * @param {module:echarts/ExtensionAPI} api
  21467. * @param {Object} payload
  21468. */
  21469. render: function (seriesModel, ecModel, api, payload) {},
  21470. /**
  21471. * Highlight series or specified data item.
  21472. * @param {module:echarts/model/Series} seriesModel
  21473. * @param {module:echarts/model/Global} ecModel
  21474. * @param {module:echarts/ExtensionAPI} api
  21475. * @param {Object} payload
  21476. */
  21477. highlight: function (seriesModel, ecModel, api, payload) {
  21478. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21479. },
  21480. /**
  21481. * Downplay series or specified data item.
  21482. * @param {module:echarts/model/Series} seriesModel
  21483. * @param {module:echarts/model/Global} ecModel
  21484. * @param {module:echarts/ExtensionAPI} api
  21485. * @param {Object} payload
  21486. */
  21487. downplay: function (seriesModel, ecModel, api, payload) {
  21488. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21489. },
  21490. /**
  21491. * Remove self.
  21492. * @param {module:echarts/model/Global} ecModel
  21493. * @param {module:echarts/ExtensionAPI} api
  21494. */
  21495. remove: function (ecModel, api) {
  21496. this.group.removeAll();
  21497. },
  21498. /**
  21499. * Dispose self.
  21500. * @param {module:echarts/model/Global} ecModel
  21501. * @param {module:echarts/ExtensionAPI} api
  21502. */
  21503. dispose: function () {},
  21504. /**
  21505. * Rendering preparation in progressive mode.
  21506. * @param {module:echarts/model/Series} seriesModel
  21507. * @param {module:echarts/model/Global} ecModel
  21508. * @param {module:echarts/ExtensionAPI} api
  21509. * @param {Object} payload
  21510. */
  21511. incrementalPrepareRender: null,
  21512. /**
  21513. * Render in progressive mode.
  21514. * @param {Object} params See taskParams in `stream/task.js`
  21515. * @param {module:echarts/model/Series} seriesModel
  21516. * @param {module:echarts/model/Global} ecModel
  21517. * @param {module:echarts/ExtensionAPI} api
  21518. * @param {Object} payload
  21519. */
  21520. incrementalRender: null,
  21521. /**
  21522. * Update transform directly.
  21523. * @param {module:echarts/model/Series} seriesModel
  21524. * @param {module:echarts/model/Global} ecModel
  21525. * @param {module:echarts/ExtensionAPI} api
  21526. * @param {Object} payload
  21527. * @return {Object} {update: true}
  21528. */
  21529. updateTransform: null,
  21530. /**
  21531. * The view contains the given point.
  21532. * @interface
  21533. * @param {Array.<number>} point
  21534. * @return {boolean}
  21535. */
  21536. // containPoint: function () {}
  21537. /**
  21538. * @param {string} eventType
  21539. * @param {Object} query
  21540. * @param {module:zrender/Element} targetEl
  21541. * @param {Object} packedEvent
  21542. * @return {boolen} Pass only when return `true`.
  21543. */
  21544. filterForExposedEvent: null
  21545. };
  21546. var chartProto = Chart.prototype;
  21547. chartProto.updateView =
  21548. chartProto.updateLayout =
  21549. chartProto.updateVisual =
  21550. function (seriesModel, ecModel, api, payload) {
  21551. this.render(seriesModel, ecModel, api, payload);
  21552. };
  21553. /**
  21554. * Set state of single element
  21555. * @param {module:zrender/Element} el
  21556. * @param {string} state 'normal'|'emphasis'
  21557. * @param {number} highlightDigit
  21558. */
  21559. function elSetState(el, state, highlightDigit) {
  21560. if (el) {
  21561. el.trigger(state, highlightDigit);
  21562. if (el.isGroup
  21563. // Simple optimize.
  21564. && !isHighDownDispatcher(el)
  21565. ) {
  21566. for (var i = 0, len = el.childCount(); i < len; i++) {
  21567. elSetState(el.childAt(i), state, highlightDigit);
  21568. }
  21569. }
  21570. }
  21571. }
  21572. /**
  21573. * @param {module:echarts/data/List} data
  21574. * @param {Object} payload
  21575. * @param {string} state 'normal'|'emphasis'
  21576. */
  21577. function toggleHighlight(data, payload, state) {
  21578. var dataIndex = queryDataIndex(data, payload);
  21579. var highlightDigit = (payload && payload.highlightKey != null)
  21580. ? getHighlightDigit(payload.highlightKey)
  21581. : null;
  21582. if (dataIndex != null) {
  21583. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21584. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  21585. });
  21586. }
  21587. else {
  21588. data.eachItemGraphicEl(function (el) {
  21589. elSetState(el, state, highlightDigit);
  21590. });
  21591. }
  21592. }
  21593. // Enable Chart.extend.
  21594. enableClassExtend(Chart, ['dispose']);
  21595. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21596. enableClassManagement(Chart, {registerWhenExtend: true});
  21597. Chart.markUpdateMethod = function (payload, methodName) {
  21598. inner$5(payload).updateMethod = methodName;
  21599. };
  21600. function renderTaskPlan(context) {
  21601. return renderPlanner(context.model);
  21602. }
  21603. function renderTaskReset(context) {
  21604. var seriesModel = context.model;
  21605. var ecModel = context.ecModel;
  21606. var api = context.api;
  21607. var payload = context.payload;
  21608. // ???! remove updateView updateVisual
  21609. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21610. var view = context.view;
  21611. var updateMethod = payload && inner$5(payload).updateMethod;
  21612. var methodName = progressiveRender
  21613. ? 'incrementalPrepareRender'
  21614. : (updateMethod && view[updateMethod])
  21615. ? updateMethod
  21616. // `appendData` is also supported when data amount
  21617. // is less than progressive threshold.
  21618. : 'render';
  21619. if (methodName !== 'render') {
  21620. view[methodName](seriesModel, ecModel, api, payload);
  21621. }
  21622. return progressMethodMap[methodName];
  21623. }
  21624. var progressMethodMap = {
  21625. incrementalPrepareRender: {
  21626. progress: function (params, context) {
  21627. context.view.incrementalRender(
  21628. params, context.model, context.ecModel, context.api, context.payload
  21629. );
  21630. }
  21631. },
  21632. render: {
  21633. // Put view.render in `progress` to support appendData. But in this case
  21634. // view.render should not be called in reset, otherwise it will be called
  21635. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21636. // in any cases.
  21637. forceFirstProgress: true,
  21638. progress: function (params, context) {
  21639. context.view.render(
  21640. context.model, context.ecModel, context.api, context.payload
  21641. );
  21642. }
  21643. }
  21644. };
  21645. /*
  21646. * Licensed to the Apache Software Foundation (ASF) under one
  21647. * or more contributor license agreements. See the NOTICE file
  21648. * distributed with this work for additional information
  21649. * regarding copyright ownership. The ASF licenses this file
  21650. * to you under the Apache License, Version 2.0 (the
  21651. * "License"); you may not use this file except in compliance
  21652. * with the License. You may obtain a copy of the License at
  21653. *
  21654. * http://www.apache.org/licenses/LICENSE-2.0
  21655. *
  21656. * Unless required by applicable law or agreed to in writing,
  21657. * software distributed under the License is distributed on an
  21658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21659. * KIND, either express or implied. See the License for the
  21660. * specific language governing permissions and limitations
  21661. * under the License.
  21662. */
  21663. /**
  21664. * @public
  21665. * @param {(Function)} fn
  21666. * @param {number} [delay=0] Unit: ms.
  21667. * @param {boolean} [debounce=false]
  21668. * true: If call interval less than `delay`, only the last call works.
  21669. * false: If call interval less than `delay, call works on fixed rate.
  21670. * @return {(Function)} throttled fn.
  21671. */
  21672. function throttle(fn, delay, debounce) {
  21673. var currCall;
  21674. var lastCall = 0;
  21675. var lastExec = 0;
  21676. var timer = null;
  21677. var diff;
  21678. var scope;
  21679. var args;
  21680. var debounceNextCall;
  21681. delay = delay || 0;
  21682. function exec() {
  21683. lastExec = (new Date()).getTime();
  21684. timer = null;
  21685. fn.apply(scope, args || []);
  21686. }
  21687. var cb = function () {
  21688. currCall = (new Date()).getTime();
  21689. scope = this;
  21690. args = arguments;
  21691. var thisDelay = debounceNextCall || delay;
  21692. var thisDebounce = debounceNextCall || debounce;
  21693. debounceNextCall = null;
  21694. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21695. clearTimeout(timer);
  21696. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21697. // than a new call of `cb`, that is, preserving the command order. Consider
  21698. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21699. // happens, either the `exec` is called dierectly, or the call is delayed.
  21700. // But the delayed call should never be later than next call of `cb`. Under
  21701. // this assurance, we can simply update view state each time `dispatchAction`
  21702. // triggered by user roaming, but not need to add extra code to avoid the
  21703. // state being "rolled-back".
  21704. if (thisDebounce) {
  21705. timer = setTimeout(exec, thisDelay);
  21706. }
  21707. else {
  21708. if (diff >= 0) {
  21709. exec();
  21710. }
  21711. else {
  21712. timer = setTimeout(exec, -diff);
  21713. }
  21714. }
  21715. lastCall = currCall;
  21716. };
  21717. /**
  21718. * Clear throttle.
  21719. * @public
  21720. */
  21721. cb.clear = function () {
  21722. if (timer) {
  21723. clearTimeout(timer);
  21724. timer = null;
  21725. }
  21726. };
  21727. /**
  21728. * Enable debounce once.
  21729. */
  21730. cb.debounceNextCall = function (debounceDelay) {
  21731. debounceNextCall = debounceDelay;
  21732. };
  21733. return cb;
  21734. }
  21735. /**
  21736. * Create throttle method or update throttle rate.
  21737. *
  21738. * @example
  21739. * ComponentView.prototype.render = function () {
  21740. * ...
  21741. * throttle.createOrUpdate(
  21742. * this,
  21743. * '_dispatchAction',
  21744. * this.model.get('throttle'),
  21745. * 'fixRate'
  21746. * );
  21747. * };
  21748. * ComponentView.prototype.remove = function () {
  21749. * throttle.clear(this, '_dispatchAction');
  21750. * };
  21751. * ComponentView.prototype.dispose = function () {
  21752. * throttle.clear(this, '_dispatchAction');
  21753. * };
  21754. *
  21755. * @public
  21756. * @param {Object} obj
  21757. * @param {string} fnAttr
  21758. * @param {number} [rate]
  21759. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21760. * @return {Function} throttled function.
  21761. */
  21762. /**
  21763. * Clear throttle. Example see throttle.createOrUpdate.
  21764. *
  21765. * @public
  21766. * @param {Object} obj
  21767. * @param {string} fnAttr
  21768. */
  21769. /*
  21770. * Licensed to the Apache Software Foundation (ASF) under one
  21771. * or more contributor license agreements. See the NOTICE file
  21772. * distributed with this work for additional information
  21773. * regarding copyright ownership. The ASF licenses this file
  21774. * to you under the Apache License, Version 2.0 (the
  21775. * "License"); you may not use this file except in compliance
  21776. * with the License. You may obtain a copy of the License at
  21777. *
  21778. * http://www.apache.org/licenses/LICENSE-2.0
  21779. *
  21780. * Unless required by applicable law or agreed to in writing,
  21781. * software distributed under the License is distributed on an
  21782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21783. * KIND, either express or implied. See the License for the
  21784. * specific language governing permissions and limitations
  21785. * under the License.
  21786. */
  21787. var seriesColor = {
  21788. createOnAllSeries: true,
  21789. performRawSeries: true,
  21790. reset: function (seriesModel, ecModel) {
  21791. var data = seriesModel.getData();
  21792. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21793. // Set in itemStyle
  21794. var color = seriesModel.get(colorAccessPath);
  21795. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  21796. ? color : null;
  21797. // Default color
  21798. if (!color || colorCallback) {
  21799. color = seriesModel.getColorFromPalette(
  21800. // TODO series count changed.
  21801. seriesModel.name, null, ecModel.getSeriesCount()
  21802. );
  21803. }
  21804. data.setVisual('color', color);
  21805. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  21806. var borderColor = seriesModel.get(borderColorAccessPath);
  21807. data.setVisual('borderColor', borderColor);
  21808. // Only visible series has each data be visual encoded
  21809. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21810. if (colorCallback) {
  21811. data.each(function (idx) {
  21812. data.setItemVisual(
  21813. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  21814. );
  21815. });
  21816. }
  21817. // itemStyle in each data item
  21818. var dataEach = function (data, idx) {
  21819. var itemModel = data.getItemModel(idx);
  21820. var color = itemModel.get(colorAccessPath, true);
  21821. var borderColor = itemModel.get(borderColorAccessPath, true);
  21822. if (color != null) {
  21823. data.setItemVisual(idx, 'color', color);
  21824. }
  21825. if (borderColor != null) {
  21826. data.setItemVisual(idx, 'borderColor', borderColor);
  21827. }
  21828. };
  21829. return { dataEach: data.hasItemOption ? dataEach : null };
  21830. }
  21831. }
  21832. };
  21833. /*
  21834. * Licensed to the Apache Software Foundation (ASF) under one
  21835. * or more contributor license agreements. See the NOTICE file
  21836. * distributed with this work for additional information
  21837. * regarding copyright ownership. The ASF licenses this file
  21838. * to you under the Apache License, Version 2.0 (the
  21839. * "License"); you may not use this file except in compliance
  21840. * with the License. You may obtain a copy of the License at
  21841. *
  21842. * http://www.apache.org/licenses/LICENSE-2.0
  21843. *
  21844. * Unless required by applicable law or agreed to in writing,
  21845. * software distributed under the License is distributed on an
  21846. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21847. * KIND, either express or implied. See the License for the
  21848. * specific language governing permissions and limitations
  21849. * under the License.
  21850. */
  21851. /**
  21852. * Language: (Simplified) Chinese.
  21853. */
  21854. var lang = {
  21855. legend: {
  21856. selector: {
  21857. all: '全选',
  21858. inverse: '反选'
  21859. }
  21860. },
  21861. toolbox: {
  21862. brush: {
  21863. title: {
  21864. rect: '矩形选择',
  21865. polygon: '圈选',
  21866. lineX: '横向选择',
  21867. lineY: '纵向选择',
  21868. keep: '保持选择',
  21869. clear: '清除选择'
  21870. }
  21871. },
  21872. dataView: {
  21873. title: '数据视图',
  21874. lang: ['数据视图', '关闭', '刷新']
  21875. },
  21876. dataZoom: {
  21877. title: {
  21878. zoom: '区域缩放',
  21879. back: '区域缩放还原'
  21880. }
  21881. },
  21882. magicType: {
  21883. title: {
  21884. line: '切换为折线图',
  21885. bar: '切换为柱状图',
  21886. stack: '切换为堆叠',
  21887. tiled: '切换为平铺'
  21888. }
  21889. },
  21890. restore: {
  21891. title: '还原'
  21892. },
  21893. saveAsImage: {
  21894. title: '保存为图片',
  21895. lang: ['右键另存为图片']
  21896. }
  21897. },
  21898. series: {
  21899. typeNames: {
  21900. pie: '饼图',
  21901. bar: '柱状图',
  21902. line: '折线图',
  21903. scatter: '散点图',
  21904. effectScatter: '涟漪散点图',
  21905. radar: '雷达图',
  21906. tree: '树图',
  21907. treemap: '矩形树图',
  21908. boxplot: '箱型图',
  21909. candlestick: 'K线图',
  21910. k: 'K线图',
  21911. heatmap: '热力图',
  21912. map: '地图',
  21913. parallel: '平行坐标图',
  21914. lines: '线图',
  21915. graph: '关系图',
  21916. sankey: '桑基图',
  21917. funnel: '漏斗图',
  21918. gauge: '仪表盘图',
  21919. pictorialBar: '象形柱图',
  21920. themeRiver: '主题河流图',
  21921. sunburst: '旭日图'
  21922. }
  21923. },
  21924. aria: {
  21925. general: {
  21926. withTitle: '这是一个关于“{title}”的图表。',
  21927. withoutTitle: '这是一个图表,'
  21928. },
  21929. series: {
  21930. single: {
  21931. prefix: '',
  21932. withName: '图表类型是{seriesType},表示{seriesName}。',
  21933. withoutName: '图表类型是{seriesType}。'
  21934. },
  21935. multiple: {
  21936. prefix: '它由{seriesCount}个图表系列组成。',
  21937. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21938. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21939. separator: {
  21940. middle: ';',
  21941. end: '。'
  21942. }
  21943. }
  21944. },
  21945. data: {
  21946. allData: '其数据是——',
  21947. partialData: '其中,前{displayCnt}项是——',
  21948. withName: '{name}的数据是{value}',
  21949. withoutName: '{value}',
  21950. separator: {
  21951. middle: ',',
  21952. end: ''
  21953. }
  21954. }
  21955. }
  21956. };
  21957. /*
  21958. * Licensed to the Apache Software Foundation (ASF) under one
  21959. * or more contributor license agreements. See the NOTICE file
  21960. * distributed with this work for additional information
  21961. * regarding copyright ownership. The ASF licenses this file
  21962. * to you under the Apache License, Version 2.0 (the
  21963. * "License"); you may not use this file except in compliance
  21964. * with the License. You may obtain a copy of the License at
  21965. *
  21966. * http://www.apache.org/licenses/LICENSE-2.0
  21967. *
  21968. * Unless required by applicable law or agreed to in writing,
  21969. * software distributed under the License is distributed on an
  21970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21971. * KIND, either express or implied. See the License for the
  21972. * specific language governing permissions and limitations
  21973. * under the License.
  21974. */
  21975. var aria = function (dom, ecModel) {
  21976. var ariaModel = ecModel.getModel('aria');
  21977. if (!ariaModel.get('show')) {
  21978. return;
  21979. }
  21980. else if (ariaModel.get('description')) {
  21981. dom.setAttribute('aria-label', ariaModel.get('description'));
  21982. return;
  21983. }
  21984. var seriesCnt = 0;
  21985. ecModel.eachSeries(function (seriesModel, idx) {
  21986. ++seriesCnt;
  21987. }, this);
  21988. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21989. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21990. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21991. var ariaLabel;
  21992. if (seriesCnt < 1) {
  21993. // No series, no aria label
  21994. return;
  21995. }
  21996. else {
  21997. var title = getTitle();
  21998. if (title) {
  21999. ariaLabel = replace(getConfig('general.withTitle'), {
  22000. title: title
  22001. });
  22002. }
  22003. else {
  22004. ariaLabel = getConfig('general.withoutTitle');
  22005. }
  22006. var seriesLabels = [];
  22007. var prefix = seriesCnt > 1
  22008. ? 'series.multiple.prefix'
  22009. : 'series.single.prefix';
  22010. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  22011. ecModel.eachSeries(function (seriesModel, idx) {
  22012. if (idx < displaySeriesCnt) {
  22013. var seriesLabel;
  22014. var seriesName = seriesModel.get('name');
  22015. var seriesTpl = 'series.'
  22016. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  22017. seriesLabel = getConfig(seriesName
  22018. ? seriesTpl + 'withName'
  22019. : seriesTpl + 'withoutName');
  22020. seriesLabel = replace(seriesLabel, {
  22021. seriesId: seriesModel.seriesIndex,
  22022. seriesName: seriesModel.get('name'),
  22023. seriesType: getSeriesTypeName(seriesModel.subType)
  22024. });
  22025. var data = seriesModel.getData();
  22026. window.data = data;
  22027. if (data.count() > maxDataCnt) {
  22028. // Show part of data
  22029. seriesLabel += replace(getConfig('data.partialData'), {
  22030. displayCnt: maxDataCnt
  22031. });
  22032. }
  22033. else {
  22034. seriesLabel += getConfig('data.allData');
  22035. }
  22036. var dataLabels = [];
  22037. for (var i = 0; i < data.count(); i++) {
  22038. if (i < maxDataCnt) {
  22039. var name = data.getName(i);
  22040. var value = retrieveRawValue(data, i);
  22041. dataLabels.push(
  22042. replace(
  22043. name
  22044. ? getConfig('data.withName')
  22045. : getConfig('data.withoutName'),
  22046. {
  22047. name: name,
  22048. value: value
  22049. }
  22050. )
  22051. );
  22052. }
  22053. }
  22054. seriesLabel += dataLabels
  22055. .join(getConfig('data.separator.middle'))
  22056. + getConfig('data.separator.end');
  22057. seriesLabels.push(seriesLabel);
  22058. }
  22059. });
  22060. ariaLabel += seriesLabels
  22061. .join(getConfig('series.multiple.separator.middle'))
  22062. + getConfig('series.multiple.separator.end');
  22063. dom.setAttribute('aria-label', ariaLabel);
  22064. }
  22065. function replace(str, keyValues) {
  22066. if (typeof str !== 'string') {
  22067. return str;
  22068. }
  22069. var result = str;
  22070. each$1(keyValues, function (value, key) {
  22071. result = result.replace(
  22072. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  22073. value
  22074. );
  22075. });
  22076. return result;
  22077. }
  22078. function getConfig(path) {
  22079. var userConfig = ariaModel.get(path);
  22080. if (userConfig == null) {
  22081. var pathArr = path.split('.');
  22082. var result = lang.aria;
  22083. for (var i = 0; i < pathArr.length; ++i) {
  22084. result = result[pathArr[i]];
  22085. }
  22086. return result;
  22087. }
  22088. else {
  22089. return userConfig;
  22090. }
  22091. }
  22092. function getTitle() {
  22093. var title = ecModel.getModel('title').option;
  22094. if (title && title.length) {
  22095. title = title[0];
  22096. }
  22097. return title && title.text;
  22098. }
  22099. function getSeriesTypeName(type) {
  22100. return lang.series.typeNames[type] || '自定义图';
  22101. }
  22102. };
  22103. /*
  22104. * Licensed to the Apache Software Foundation (ASF) under one
  22105. * or more contributor license agreements. See the NOTICE file
  22106. * distributed with this work for additional information
  22107. * regarding copyright ownership. The ASF licenses this file
  22108. * to you under the Apache License, Version 2.0 (the
  22109. * "License"); you may not use this file except in compliance
  22110. * with the License. You may obtain a copy of the License at
  22111. *
  22112. * http://www.apache.org/licenses/LICENSE-2.0
  22113. *
  22114. * Unless required by applicable law or agreed to in writing,
  22115. * software distributed under the License is distributed on an
  22116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22117. * KIND, either express or implied. See the License for the
  22118. * specific language governing permissions and limitations
  22119. * under the License.
  22120. */
  22121. var PI$1 = Math.PI;
  22122. /**
  22123. * @param {module:echarts/ExtensionAPI} api
  22124. * @param {Object} [opts]
  22125. * @param {string} [opts.text]
  22126. * @param {string} [opts.color]
  22127. * @param {string} [opts.textColor]
  22128. * @return {module:zrender/Element}
  22129. */
  22130. var loadingDefault = function (api, opts) {
  22131. opts = opts || {};
  22132. defaults(opts, {
  22133. text: 'loading',
  22134. color: '#c23531',
  22135. textColor: '#000',
  22136. maskColor: 'rgba(255, 255, 255, 0.8)',
  22137. zlevel: 0
  22138. });
  22139. var mask = new Rect({
  22140. style: {
  22141. fill: opts.maskColor
  22142. },
  22143. zlevel: opts.zlevel,
  22144. z: 10000
  22145. });
  22146. var arc = new Arc({
  22147. shape: {
  22148. startAngle: -PI$1 / 2,
  22149. endAngle: -PI$1 / 2 + 0.1,
  22150. r: 10
  22151. },
  22152. style: {
  22153. stroke: opts.color,
  22154. lineCap: 'round',
  22155. lineWidth: 5
  22156. },
  22157. zlevel: opts.zlevel,
  22158. z: 10001
  22159. });
  22160. var labelRect = new Rect({
  22161. style: {
  22162. fill: 'none',
  22163. text: opts.text,
  22164. textPosition: 'right',
  22165. textDistance: 10,
  22166. textFill: opts.textColor
  22167. },
  22168. zlevel: opts.zlevel,
  22169. z: 10001
  22170. });
  22171. arc.animateShape(true)
  22172. .when(1000, {
  22173. endAngle: PI$1 * 3 / 2
  22174. })
  22175. .start('circularInOut');
  22176. arc.animateShape(true)
  22177. .when(1000, {
  22178. startAngle: PI$1 * 3 / 2
  22179. })
  22180. .delay(300)
  22181. .start('circularInOut');
  22182. var group = new Group();
  22183. group.add(arc);
  22184. group.add(labelRect);
  22185. group.add(mask);
  22186. // Inject resize
  22187. group.resize = function () {
  22188. var cx = api.getWidth() / 2;
  22189. var cy = api.getHeight() / 2;
  22190. arc.setShape({
  22191. cx: cx,
  22192. cy: cy
  22193. });
  22194. var r = arc.shape.r;
  22195. labelRect.setShape({
  22196. x: cx - r,
  22197. y: cy - r,
  22198. width: r * 2,
  22199. height: r * 2
  22200. });
  22201. mask.setShape({
  22202. x: 0,
  22203. y: 0,
  22204. width: api.getWidth(),
  22205. height: api.getHeight()
  22206. });
  22207. };
  22208. group.resize();
  22209. return group;
  22210. };
  22211. /*
  22212. * Licensed to the Apache Software Foundation (ASF) under one
  22213. * or more contributor license agreements. See the NOTICE file
  22214. * distributed with this work for additional information
  22215. * regarding copyright ownership. The ASF licenses this file
  22216. * to you under the Apache License, Version 2.0 (the
  22217. * "License"); you may not use this file except in compliance
  22218. * with the License. You may obtain a copy of the License at
  22219. *
  22220. * http://www.apache.org/licenses/LICENSE-2.0
  22221. *
  22222. * Unless required by applicable law or agreed to in writing,
  22223. * software distributed under the License is distributed on an
  22224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22225. * KIND, either express or implied. See the License for the
  22226. * specific language governing permissions and limitations
  22227. * under the License.
  22228. */
  22229. /**
  22230. * @module echarts/stream/Scheduler
  22231. */
  22232. /**
  22233. * @constructor
  22234. */
  22235. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22236. this.ecInstance = ecInstance;
  22237. this.api = api;
  22238. this.unfinished;
  22239. // Fix current processors in case that in some rear cases that
  22240. // processors might be registered after echarts instance created.
  22241. // Register processors incrementally for a echarts instance is
  22242. // not supported by this stream architecture.
  22243. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22244. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22245. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22246. /**
  22247. * @private
  22248. * @type {
  22249. * [handlerUID: string]: {
  22250. * seriesTaskMap?: {
  22251. * [seriesUID: string]: Task
  22252. * },
  22253. * overallTask?: Task
  22254. * }
  22255. * }
  22256. */
  22257. this._stageTaskMap = createHashMap();
  22258. }
  22259. var proto = Scheduler.prototype;
  22260. /**
  22261. * @param {module:echarts/model/Global} ecModel
  22262. * @param {Object} payload
  22263. */
  22264. proto.restoreData = function (ecModel, payload) {
  22265. // TODO: Only restroe needed series and components, but not all components.
  22266. // Currently `restoreData` of all of the series and component will be called.
  22267. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22268. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22269. // and some components like coordinate system, axes, dataZoom, visualMap only
  22270. // need their target series refresh.
  22271. // (1) If we are implementing this feature some day, we should consider these cases:
  22272. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22273. // on the settings of `dataZoom`), it should be re-performed if the component
  22274. // is modified by `setOption`.
  22275. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22276. // it should be re-performed when the result array of `getTargetSeries` changed.
  22277. // We use `dependencies` to cover these issues.
  22278. // (3) How to update target series when coordinate system related components modified.
  22279. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22280. // and this case all of the tasks will be set as dirty.
  22281. ecModel.restoreData(payload);
  22282. // Theoretically an overall task not only depends on each of its target series, but also
  22283. // depends on all of the series.
  22284. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22285. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22286. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22287. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22288. // probably cause state chaos (consider `dataZoomProcessor`).
  22289. this._stageTaskMap.each(function (taskRecord) {
  22290. var overallTask = taskRecord.overallTask;
  22291. overallTask && overallTask.dirty();
  22292. });
  22293. };
  22294. // If seriesModel provided, incremental threshold is check by series data.
  22295. proto.getPerformArgs = function (task, isBlock) {
  22296. // For overall task
  22297. if (!task.__pipeline) {
  22298. return;
  22299. }
  22300. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22301. var pCtx = pipeline.context;
  22302. var incremental = !isBlock
  22303. && pipeline.progressiveEnabled
  22304. && (!pCtx || pCtx.progressiveRender)
  22305. && task.__idxInPipeline > pipeline.blockIndex;
  22306. var step = incremental ? pipeline.step : null;
  22307. var modDataCount = pCtx && pCtx.modDataCount;
  22308. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22309. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22310. };
  22311. proto.getPipeline = function (pipelineId) {
  22312. return this._pipelineMap.get(pipelineId);
  22313. };
  22314. /**
  22315. * Current, progressive rendering starts from visual and layout.
  22316. * Always detect render mode in the same stage, avoiding that incorrect
  22317. * detection caused by data filtering.
  22318. * Caution:
  22319. * `updateStreamModes` use `seriesModel.getData()`.
  22320. */
  22321. proto.updateStreamModes = function (seriesModel, view) {
  22322. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22323. var data = seriesModel.getData();
  22324. var dataLen = data.count();
  22325. // `progressiveRender` means that can render progressively in each
  22326. // animation frame. Note that some types of series do not provide
  22327. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22328. // use the term `incremental` but not `progressive` to describe the
  22329. // case that `chart.appendData`.
  22330. var progressiveRender = pipeline.progressiveEnabled
  22331. && view.incrementalPrepareRender
  22332. && dataLen >= pipeline.threshold;
  22333. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22334. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22335. // see `test/candlestick-large3.html`
  22336. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22337. seriesModel.pipelineContext = pipeline.context = {
  22338. progressiveRender: progressiveRender,
  22339. modDataCount: modDataCount,
  22340. large: large
  22341. };
  22342. };
  22343. proto.restorePipelines = function (ecModel) {
  22344. var scheduler = this;
  22345. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22346. ecModel.eachSeries(function (seriesModel) {
  22347. var progressive = seriesModel.getProgressive();
  22348. var pipelineId = seriesModel.uid;
  22349. pipelineMap.set(pipelineId, {
  22350. id: pipelineId,
  22351. head: null,
  22352. tail: null,
  22353. threshold: seriesModel.getProgressiveThreshold(),
  22354. progressiveEnabled: progressive
  22355. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22356. blockIndex: -1,
  22357. step: Math.round(progressive || 700),
  22358. count: 0
  22359. });
  22360. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22361. });
  22362. };
  22363. proto.prepareStageTasks = function () {
  22364. var stageTaskMap = this._stageTaskMap;
  22365. var ecModel = this.ecInstance.getModel();
  22366. var api = this.api;
  22367. each$1(this._allHandlers, function (handler) {
  22368. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22369. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22370. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22371. }, this);
  22372. };
  22373. proto.prepareView = function (view, model, ecModel, api) {
  22374. var renderTask = view.renderTask;
  22375. var context = renderTask.context;
  22376. context.model = model;
  22377. context.ecModel = ecModel;
  22378. context.api = api;
  22379. renderTask.__block = !view.incrementalPrepareRender;
  22380. pipe(this, model, renderTask);
  22381. };
  22382. proto.performDataProcessorTasks = function (ecModel, payload) {
  22383. // If we do not use `block` here, it should be considered when to update modes.
  22384. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22385. };
  22386. // opt
  22387. // opt.visualType: 'visual' or 'layout'
  22388. // opt.setDirty
  22389. proto.performVisualTasks = function (ecModel, payload, opt) {
  22390. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22391. };
  22392. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22393. opt = opt || {};
  22394. var unfinished;
  22395. each$1(stageHandlers, function (stageHandler, idx) {
  22396. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22397. return;
  22398. }
  22399. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22400. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22401. var overallTask = stageHandlerRecord.overallTask;
  22402. if (overallTask) {
  22403. var overallNeedDirty;
  22404. var agentStubMap = overallTask.agentStubMap;
  22405. agentStubMap.each(function (stub) {
  22406. if (needSetDirty(opt, stub)) {
  22407. stub.dirty();
  22408. overallNeedDirty = true;
  22409. }
  22410. });
  22411. overallNeedDirty && overallTask.dirty();
  22412. updatePayload(overallTask, payload);
  22413. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22414. // Execute stubs firstly, which may set the overall task dirty,
  22415. // then execute the overall task. And stub will call seriesModel.setData,
  22416. // which ensures that in the overallTask seriesModel.getData() will not
  22417. // return incorrect data.
  22418. agentStubMap.each(function (stub) {
  22419. stub.perform(performArgs);
  22420. });
  22421. unfinished |= overallTask.perform(performArgs);
  22422. }
  22423. else if (seriesTaskMap) {
  22424. seriesTaskMap.each(function (task, pipelineId) {
  22425. if (needSetDirty(opt, task)) {
  22426. task.dirty();
  22427. }
  22428. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22429. // FIXME
  22430. // if intending to decalare `performRawSeries` in handlers, only
  22431. // stream-independent (specifically, data item independent) operations can be
  22432. // performed. Because is a series is filtered, most of the tasks will not
  22433. // be performed. A stream-dependent operation probably cause wrong biz logic.
  22434. // Perhaps we should not provide a separate callback for this case instead
  22435. // of providing the config `performRawSeries`. The stream-dependent operaions
  22436. // and stream-independent operations should better not be mixed.
  22437. performArgs.skip = !stageHandler.performRawSeries
  22438. && ecModel.isSeriesFiltered(task.context.model);
  22439. updatePayload(task, payload);
  22440. unfinished |= task.perform(performArgs);
  22441. });
  22442. }
  22443. });
  22444. function needSetDirty(opt, task) {
  22445. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22446. }
  22447. scheduler.unfinished |= unfinished;
  22448. }
  22449. proto.performSeriesTasks = function (ecModel) {
  22450. var unfinished;
  22451. ecModel.eachSeries(function (seriesModel) {
  22452. // Progress to the end for dataInit and dataRestore.
  22453. unfinished |= seriesModel.dataTask.perform();
  22454. });
  22455. this.unfinished |= unfinished;
  22456. };
  22457. proto.plan = function () {
  22458. // Travel pipelines, check block.
  22459. this._pipelineMap.each(function (pipeline) {
  22460. var task = pipeline.tail;
  22461. do {
  22462. if (task.__block) {
  22463. pipeline.blockIndex = task.__idxInPipeline;
  22464. break;
  22465. }
  22466. task = task.getUpstream();
  22467. }
  22468. while (task);
  22469. });
  22470. };
  22471. var updatePayload = proto.updatePayload = function (task, payload) {
  22472. payload !== 'remain' && (task.context.payload = payload);
  22473. };
  22474. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22475. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22476. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22477. var seriesType = stageHandler.seriesType;
  22478. var getTargetSeries = stageHandler.getTargetSeries;
  22479. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22480. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22481. // it works but it may cause other irrelevant charts blocked.
  22482. if (stageHandler.createOnAllSeries) {
  22483. ecModel.eachRawSeries(create);
  22484. }
  22485. else if (seriesType) {
  22486. ecModel.eachRawSeriesByType(seriesType, create);
  22487. }
  22488. else if (getTargetSeries) {
  22489. getTargetSeries(ecModel, api).each(create);
  22490. }
  22491. function create(seriesModel) {
  22492. var pipelineId = seriesModel.uid;
  22493. // Init tasks for each seriesModel only once.
  22494. // Reuse original task instance.
  22495. var task = seriesTaskMap.get(pipelineId)
  22496. || seriesTaskMap.set(pipelineId, createTask({
  22497. plan: seriesTaskPlan,
  22498. reset: seriesTaskReset,
  22499. count: seriesTaskCount
  22500. }));
  22501. task.context = {
  22502. model: seriesModel,
  22503. ecModel: ecModel,
  22504. api: api,
  22505. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22506. plan: stageHandler.plan,
  22507. reset: stageHandler.reset,
  22508. scheduler: scheduler
  22509. };
  22510. pipe(scheduler, seriesModel, task);
  22511. }
  22512. // Clear unused series tasks.
  22513. var pipelineMap = scheduler._pipelineMap;
  22514. seriesTaskMap.each(function (task, pipelineId) {
  22515. if (!pipelineMap.get(pipelineId)) {
  22516. task.dispose();
  22517. seriesTaskMap.removeKey(pipelineId);
  22518. }
  22519. });
  22520. }
  22521. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22522. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22523. // For overall task, the function only be called on reset stage.
  22524. || createTask({reset: overallTaskReset});
  22525. overallTask.context = {
  22526. ecModel: ecModel,
  22527. api: api,
  22528. overallReset: stageHandler.overallReset,
  22529. scheduler: scheduler
  22530. };
  22531. // Reuse orignal stubs.
  22532. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22533. var seriesType = stageHandler.seriesType;
  22534. var getTargetSeries = stageHandler.getTargetSeries;
  22535. var overallProgress = true;
  22536. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22537. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22538. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22539. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22540. // we set the pipeline block.
  22541. if (seriesType) {
  22542. ecModel.eachRawSeriesByType(seriesType, createStub);
  22543. }
  22544. else if (getTargetSeries) {
  22545. getTargetSeries(ecModel, api).each(createStub);
  22546. }
  22547. // Otherwise, (usually it is legancy case), the overall task will only be
  22548. // executed when upstream dirty. Otherwise the progressive rendering of all
  22549. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22550. // dirty info from upsteam.
  22551. else {
  22552. overallProgress = false;
  22553. each$1(ecModel.getSeries(), createStub);
  22554. }
  22555. function createStub(seriesModel) {
  22556. var pipelineId = seriesModel.uid;
  22557. var stub = agentStubMap.get(pipelineId);
  22558. if (!stub) {
  22559. stub = agentStubMap.set(pipelineId, createTask(
  22560. {reset: stubReset, onDirty: stubOnDirty}
  22561. ));
  22562. // When the result of `getTargetSeries` changed, the overallTask
  22563. // should be set as dirty and re-performed.
  22564. overallTask.dirty();
  22565. }
  22566. stub.context = {
  22567. model: seriesModel,
  22568. overallProgress: overallProgress,
  22569. modifyOutputEnd: modifyOutputEnd
  22570. };
  22571. stub.agent = overallTask;
  22572. stub.__block = overallProgress;
  22573. pipe(scheduler, seriesModel, stub);
  22574. }
  22575. // Clear unused stubs.
  22576. var pipelineMap = scheduler._pipelineMap;
  22577. agentStubMap.each(function (stub, pipelineId) {
  22578. if (!pipelineMap.get(pipelineId)) {
  22579. stub.dispose();
  22580. // When the result of `getTargetSeries` changed, the overallTask
  22581. // should be set as dirty and re-performed.
  22582. overallTask.dirty();
  22583. agentStubMap.removeKey(pipelineId);
  22584. }
  22585. });
  22586. }
  22587. function overallTaskReset(context) {
  22588. context.overallReset(
  22589. context.ecModel, context.api, context.payload
  22590. );
  22591. }
  22592. function stubReset(context, upstreamContext) {
  22593. return context.overallProgress && stubProgress;
  22594. }
  22595. function stubProgress() {
  22596. this.agent.dirty();
  22597. this.getDownstream().dirty();
  22598. }
  22599. function stubOnDirty() {
  22600. this.agent && this.agent.dirty();
  22601. }
  22602. function seriesTaskPlan(context) {
  22603. return context.plan && context.plan(
  22604. context.model, context.ecModel, context.api, context.payload
  22605. );
  22606. }
  22607. function seriesTaskReset(context) {
  22608. if (context.useClearVisual) {
  22609. context.data.clearAllVisual();
  22610. }
  22611. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22612. context.model, context.ecModel, context.api, context.payload
  22613. ));
  22614. return resetDefines.length > 1
  22615. ? map(resetDefines, function (v, idx) {
  22616. return makeSeriesTaskProgress(idx);
  22617. })
  22618. : singleSeriesTaskProgress;
  22619. }
  22620. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22621. function makeSeriesTaskProgress(resetDefineIdx) {
  22622. return function (params, context) {
  22623. var data = context.data;
  22624. var resetDefine = context.resetDefines[resetDefineIdx];
  22625. if (resetDefine && resetDefine.dataEach) {
  22626. for (var i = params.start; i < params.end; i++) {
  22627. resetDefine.dataEach(data, i);
  22628. }
  22629. }
  22630. else if (resetDefine && resetDefine.progress) {
  22631. resetDefine.progress(params, data);
  22632. }
  22633. };
  22634. }
  22635. function seriesTaskCount(context) {
  22636. return context.data.count();
  22637. }
  22638. function pipe(scheduler, seriesModel, task) {
  22639. var pipelineId = seriesModel.uid;
  22640. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22641. !pipeline.head && (pipeline.head = task);
  22642. pipeline.tail && pipeline.tail.pipe(task);
  22643. pipeline.tail = task;
  22644. task.__idxInPipeline = pipeline.count++;
  22645. task.__pipeline = pipeline;
  22646. }
  22647. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22648. if (isFunction$1(stageHandler)) {
  22649. stageHandler = {
  22650. overallReset: stageHandler,
  22651. seriesType: detectSeriseType(stageHandler)
  22652. };
  22653. }
  22654. stageHandler.uid = getUID('stageHandler');
  22655. visualType && (stageHandler.visualType = visualType);
  22656. return stageHandler;
  22657. };
  22658. /**
  22659. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22660. * To ensure that they can work normally, they should work in block mode, that is,
  22661. * they should not be started util the previous tasks finished. So they cause the
  22662. * progressive rendering disabled. We try to detect the series type, to narrow down
  22663. * the block range to only the series type they concern, but not all series.
  22664. */
  22665. function detectSeriseType(legacyFunc) {
  22666. seriesType = null;
  22667. try {
  22668. // Assume there is no async when calling `eachSeriesByType`.
  22669. legacyFunc(ecModelMock, apiMock);
  22670. }
  22671. catch (e) {
  22672. }
  22673. return seriesType;
  22674. }
  22675. var ecModelMock = {};
  22676. var apiMock = {};
  22677. var seriesType;
  22678. mockMethods(ecModelMock, GlobalModel);
  22679. mockMethods(apiMock, ExtensionAPI);
  22680. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22681. seriesType = type;
  22682. };
  22683. ecModelMock.eachComponent = function (cond) {
  22684. if (cond.mainType === 'series' && cond.subType) {
  22685. seriesType = cond.subType;
  22686. }
  22687. };
  22688. function mockMethods(target, Clz) {
  22689. /* eslint-disable */
  22690. for (var name in Clz.prototype) {
  22691. // Do not use hasOwnProperty
  22692. target[name] = noop;
  22693. }
  22694. /* eslint-enable */
  22695. }
  22696. /*
  22697. * Licensed to the Apache Software Foundation (ASF) under one
  22698. * or more contributor license agreements. See the NOTICE file
  22699. * distributed with this work for additional information
  22700. * regarding copyright ownership. The ASF licenses this file
  22701. * to you under the Apache License, Version 2.0 (the
  22702. * "License"); you may not use this file except in compliance
  22703. * with the License. You may obtain a copy of the License at
  22704. *
  22705. * http://www.apache.org/licenses/LICENSE-2.0
  22706. *
  22707. * Unless required by applicable law or agreed to in writing,
  22708. * software distributed under the License is distributed on an
  22709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22710. * KIND, either express or implied. See the License for the
  22711. * specific language governing permissions and limitations
  22712. * under the License.
  22713. */
  22714. var colorAll = [
  22715. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22716. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22717. ];
  22718. var lightTheme = {
  22719. color: colorAll,
  22720. colorLayer: [
  22721. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22722. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22723. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22724. colorAll
  22725. ]
  22726. };
  22727. /*
  22728. * Licensed to the Apache Software Foundation (ASF) under one
  22729. * or more contributor license agreements. See the NOTICE file
  22730. * distributed with this work for additional information
  22731. * regarding copyright ownership. The ASF licenses this file
  22732. * to you under the Apache License, Version 2.0 (the
  22733. * "License"); you may not use this file except in compliance
  22734. * with the License. You may obtain a copy of the License at
  22735. *
  22736. * http://www.apache.org/licenses/LICENSE-2.0
  22737. *
  22738. * Unless required by applicable law or agreed to in writing,
  22739. * software distributed under the License is distributed on an
  22740. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22741. * KIND, either express or implied. See the License for the
  22742. * specific language governing permissions and limitations
  22743. * under the License.
  22744. */
  22745. var contrastColor = '#eee';
  22746. var axisCommon = function () {
  22747. return {
  22748. axisLine: {
  22749. lineStyle: {
  22750. color: contrastColor
  22751. }
  22752. },
  22753. axisTick: {
  22754. lineStyle: {
  22755. color: contrastColor
  22756. }
  22757. },
  22758. axisLabel: {
  22759. textStyle: {
  22760. color: contrastColor
  22761. }
  22762. },
  22763. splitLine: {
  22764. lineStyle: {
  22765. type: 'dashed',
  22766. color: '#aaa'
  22767. }
  22768. },
  22769. splitArea: {
  22770. areaStyle: {
  22771. color: contrastColor
  22772. }
  22773. }
  22774. };
  22775. };
  22776. var colorPalette = [
  22777. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22778. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22779. ];
  22780. var theme = {
  22781. color: colorPalette,
  22782. backgroundColor: '#333',
  22783. tooltip: {
  22784. axisPointer: {
  22785. lineStyle: {
  22786. color: contrastColor
  22787. },
  22788. crossStyle: {
  22789. color: contrastColor
  22790. },
  22791. label: {
  22792. color: '#000'
  22793. }
  22794. }
  22795. },
  22796. legend: {
  22797. textStyle: {
  22798. color: contrastColor
  22799. }
  22800. },
  22801. textStyle: {
  22802. color: contrastColor
  22803. },
  22804. title: {
  22805. textStyle: {
  22806. color: contrastColor
  22807. }
  22808. },
  22809. toolbox: {
  22810. iconStyle: {
  22811. normal: {
  22812. borderColor: contrastColor
  22813. }
  22814. }
  22815. },
  22816. dataZoom: {
  22817. textStyle: {
  22818. color: contrastColor
  22819. }
  22820. },
  22821. visualMap: {
  22822. textStyle: {
  22823. color: contrastColor
  22824. }
  22825. },
  22826. timeline: {
  22827. lineStyle: {
  22828. color: contrastColor
  22829. },
  22830. itemStyle: {
  22831. normal: {
  22832. color: colorPalette[1]
  22833. }
  22834. },
  22835. label: {
  22836. normal: {
  22837. textStyle: {
  22838. color: contrastColor
  22839. }
  22840. }
  22841. },
  22842. controlStyle: {
  22843. normal: {
  22844. color: contrastColor,
  22845. borderColor: contrastColor
  22846. }
  22847. }
  22848. },
  22849. timeAxis: axisCommon(),
  22850. logAxis: axisCommon(),
  22851. valueAxis: axisCommon(),
  22852. categoryAxis: axisCommon(),
  22853. line: {
  22854. symbol: 'circle'
  22855. },
  22856. graph: {
  22857. color: colorPalette
  22858. },
  22859. gauge: {
  22860. title: {
  22861. textStyle: {
  22862. color: contrastColor
  22863. }
  22864. }
  22865. },
  22866. candlestick: {
  22867. itemStyle: {
  22868. normal: {
  22869. color: '#FD1050',
  22870. color0: '#0CF49B',
  22871. borderColor: '#FD1050',
  22872. borderColor0: '#0CF49B'
  22873. }
  22874. }
  22875. }
  22876. };
  22877. theme.categoryAxis.splitLine.show = false;
  22878. /*
  22879. * Licensed to the Apache Software Foundation (ASF) under one
  22880. * or more contributor license agreements. See the NOTICE file
  22881. * distributed with this work for additional information
  22882. * regarding copyright ownership. The ASF licenses this file
  22883. * to you under the Apache License, Version 2.0 (the
  22884. * "License"); you may not use this file except in compliance
  22885. * with the License. You may obtain a copy of the License at
  22886. *
  22887. * http://www.apache.org/licenses/LICENSE-2.0
  22888. *
  22889. * Unless required by applicable law or agreed to in writing,
  22890. * software distributed under the License is distributed on an
  22891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22892. * KIND, either express or implied. See the License for the
  22893. * specific language governing permissions and limitations
  22894. * under the License.
  22895. */
  22896. /**
  22897. * This module is imported by echarts directly.
  22898. *
  22899. * Notice:
  22900. * Always keep this file exists for backward compatibility.
  22901. * Because before 4.1.0, dataset is an optional component,
  22902. * some users may import this module manually.
  22903. */
  22904. ComponentModel.extend({
  22905. type: 'dataset',
  22906. /**
  22907. * @protected
  22908. */
  22909. defaultOption: {
  22910. // 'row', 'column'
  22911. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22912. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22913. sourceHeader: null,
  22914. dimensions: null,
  22915. source: null
  22916. },
  22917. optionUpdated: function () {
  22918. detectSourceFormat(this);
  22919. }
  22920. });
  22921. Component.extend({
  22922. type: 'dataset'
  22923. });
  22924. /**
  22925. * 椭圆形状
  22926. * @module zrender/graphic/shape/Ellipse
  22927. */
  22928. var Ellipse = Path.extend({
  22929. type: 'ellipse',
  22930. shape: {
  22931. cx: 0, cy: 0,
  22932. rx: 0, ry: 0
  22933. },
  22934. buildPath: function (ctx, shape) {
  22935. var k = 0.5522848;
  22936. var x = shape.cx;
  22937. var y = shape.cy;
  22938. var a = shape.rx;
  22939. var b = shape.ry;
  22940. var ox = a * k; // 水平控制点偏移量
  22941. var oy = b * k; // 垂直控制点偏移量
  22942. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22943. ctx.moveTo(x - a, y);
  22944. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22945. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22946. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22947. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22948. ctx.closePath();
  22949. }
  22950. });
  22951. // import RadialGradient from '../graphic/RadialGradient';
  22952. // import Pattern from '../graphic/Pattern';
  22953. // import * as vector from '../core/vector';
  22954. // Most of the values can be separated by comma and/or white space.
  22955. var DILIMITER_REG = /[\s,]+/;
  22956. /**
  22957. * For big svg string, this method might be time consuming.
  22958. *
  22959. * @param {string} svg xml string
  22960. * @return {Object} xml root.
  22961. */
  22962. function parseXML(svg) {
  22963. if (isString(svg)) {
  22964. var parser = new DOMParser();
  22965. svg = parser.parseFromString(svg, 'text/xml');
  22966. }
  22967. // Document node. If using $.get, doc node may be input.
  22968. if (svg.nodeType === 9) {
  22969. svg = svg.firstChild;
  22970. }
  22971. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22972. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22973. svg = svg.nextSibling;
  22974. }
  22975. return svg;
  22976. }
  22977. function SVGParser() {
  22978. this._defs = {};
  22979. this._root = null;
  22980. this._isDefine = false;
  22981. this._isText = false;
  22982. }
  22983. SVGParser.prototype.parse = function (xml, opt) {
  22984. opt = opt || {};
  22985. var svg = parseXML(xml);
  22986. if (!svg) {
  22987. throw new Error('Illegal svg');
  22988. }
  22989. var root = new Group();
  22990. this._root = root;
  22991. // parse view port
  22992. var viewBox = svg.getAttribute('viewBox') || '';
  22993. // If width/height not specified, means "100%" of `opt.width/height`.
  22994. // TODO: Other percent value not supported yet.
  22995. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22996. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22997. // If width/height not specified, set as null for output.
  22998. isNaN(width) && (width = null);
  22999. isNaN(height) && (height = null);
  23000. // Apply inline style on svg element.
  23001. parseAttributes(svg, root, null, true);
  23002. var child = svg.firstChild;
  23003. while (child) {
  23004. this._parseNode(child, root);
  23005. child = child.nextSibling;
  23006. }
  23007. var viewBoxRect;
  23008. var viewBoxTransform;
  23009. if (viewBox) {
  23010. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  23011. // Some invalid case like viewBox: 'none'.
  23012. if (viewBoxArr.length >= 4) {
  23013. viewBoxRect = {
  23014. x: parseFloat(viewBoxArr[0] || 0),
  23015. y: parseFloat(viewBoxArr[1] || 0),
  23016. width: parseFloat(viewBoxArr[2]),
  23017. height: parseFloat(viewBoxArr[3])
  23018. };
  23019. }
  23020. }
  23021. if (viewBoxRect && width != null && height != null) {
  23022. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  23023. if (!opt.ignoreViewBox) {
  23024. // If set transform on the output group, it probably bring trouble when
  23025. // some users only intend to show the clipped content inside the viewBox,
  23026. // but not intend to transform the output group. So we keep the output
  23027. // group no transform. If the user intend to use the viewBox as a
  23028. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  23029. // manually according to the viewBox info in the output of this method.
  23030. var elRoot = root;
  23031. root = new Group();
  23032. root.add(elRoot);
  23033. elRoot.scale = viewBoxTransform.scale.slice();
  23034. elRoot.position = viewBoxTransform.position.slice();
  23035. }
  23036. }
  23037. // Some shapes might be overflow the viewport, which should be
  23038. // clipped despite whether the viewBox is used, as the SVG does.
  23039. if (!opt.ignoreRootClip && width != null && height != null) {
  23040. root.setClipPath(new Rect({
  23041. shape: {x: 0, y: 0, width: width, height: height}
  23042. }));
  23043. }
  23044. // Set width/height on group just for output the viewport size.
  23045. return {
  23046. root: root,
  23047. width: width,
  23048. height: height,
  23049. viewBoxRect: viewBoxRect,
  23050. viewBoxTransform: viewBoxTransform
  23051. };
  23052. };
  23053. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  23054. var nodeName = xmlNode.nodeName.toLowerCase();
  23055. // TODO
  23056. // support <style>...</style> in svg, where nodeName is 'style',
  23057. // CSS classes is defined globally wherever the style tags are declared.
  23058. if (nodeName === 'defs') {
  23059. // define flag
  23060. this._isDefine = true;
  23061. }
  23062. else if (nodeName === 'text') {
  23063. this._isText = true;
  23064. }
  23065. var el;
  23066. if (this._isDefine) {
  23067. var parser = defineParsers[nodeName];
  23068. if (parser) {
  23069. var def = parser.call(this, xmlNode);
  23070. var id = xmlNode.getAttribute('id');
  23071. if (id) {
  23072. this._defs[id] = def;
  23073. }
  23074. }
  23075. }
  23076. else {
  23077. var parser = nodeParsers[nodeName];
  23078. if (parser) {
  23079. el = parser.call(this, xmlNode, parentGroup);
  23080. parentGroup.add(el);
  23081. }
  23082. }
  23083. var child = xmlNode.firstChild;
  23084. while (child) {
  23085. if (child.nodeType === 1) {
  23086. this._parseNode(child, el);
  23087. }
  23088. // Is text
  23089. if (child.nodeType === 3 && this._isText) {
  23090. this._parseText(child, el);
  23091. }
  23092. child = child.nextSibling;
  23093. }
  23094. // Quit define
  23095. if (nodeName === 'defs') {
  23096. this._isDefine = false;
  23097. }
  23098. else if (nodeName === 'text') {
  23099. this._isText = false;
  23100. }
  23101. };
  23102. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  23103. if (xmlNode.nodeType === 1) {
  23104. var dx = xmlNode.getAttribute('dx') || 0;
  23105. var dy = xmlNode.getAttribute('dy') || 0;
  23106. this._textX += parseFloat(dx);
  23107. this._textY += parseFloat(dy);
  23108. }
  23109. var text = new Text({
  23110. style: {
  23111. text: xmlNode.textContent,
  23112. transformText: true
  23113. },
  23114. position: [this._textX || 0, this._textY || 0]
  23115. });
  23116. inheritStyle(parentGroup, text);
  23117. parseAttributes(xmlNode, text, this._defs);
  23118. var fontSize = text.style.fontSize;
  23119. if (fontSize && fontSize < 9) {
  23120. // PENDING
  23121. text.style.fontSize = 9;
  23122. text.scale = text.scale || [1, 1];
  23123. text.scale[0] *= fontSize / 9;
  23124. text.scale[1] *= fontSize / 9;
  23125. }
  23126. var rect = text.getBoundingRect();
  23127. this._textX += rect.width;
  23128. parentGroup.add(text);
  23129. return text;
  23130. };
  23131. var nodeParsers = {
  23132. 'g': function (xmlNode, parentGroup) {
  23133. var g = new Group();
  23134. inheritStyle(parentGroup, g);
  23135. parseAttributes(xmlNode, g, this._defs);
  23136. return g;
  23137. },
  23138. 'rect': function (xmlNode, parentGroup) {
  23139. var rect = new Rect();
  23140. inheritStyle(parentGroup, rect);
  23141. parseAttributes(xmlNode, rect, this._defs);
  23142. rect.setShape({
  23143. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23144. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23145. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23146. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23147. });
  23148. // console.log(xmlNode.getAttribute('transform'));
  23149. // console.log(rect.transform);
  23150. return rect;
  23151. },
  23152. 'circle': function (xmlNode, parentGroup) {
  23153. var circle = new Circle();
  23154. inheritStyle(parentGroup, circle);
  23155. parseAttributes(xmlNode, circle, this._defs);
  23156. circle.setShape({
  23157. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23158. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23159. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23160. });
  23161. return circle;
  23162. },
  23163. 'line': function (xmlNode, parentGroup) {
  23164. var line = new Line();
  23165. inheritStyle(parentGroup, line);
  23166. parseAttributes(xmlNode, line, this._defs);
  23167. line.setShape({
  23168. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23169. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23170. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23171. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23172. });
  23173. return line;
  23174. },
  23175. 'ellipse': function (xmlNode, parentGroup) {
  23176. var ellipse = new Ellipse();
  23177. inheritStyle(parentGroup, ellipse);
  23178. parseAttributes(xmlNode, ellipse, this._defs);
  23179. ellipse.setShape({
  23180. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23181. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23182. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23183. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23184. });
  23185. return ellipse;
  23186. },
  23187. 'polygon': function (xmlNode, parentGroup) {
  23188. var points = xmlNode.getAttribute('points');
  23189. if (points) {
  23190. points = parsePoints(points);
  23191. }
  23192. var polygon = new Polygon({
  23193. shape: {
  23194. points: points || []
  23195. }
  23196. });
  23197. inheritStyle(parentGroup, polygon);
  23198. parseAttributes(xmlNode, polygon, this._defs);
  23199. return polygon;
  23200. },
  23201. 'polyline': function (xmlNode, parentGroup) {
  23202. var path = new Path();
  23203. inheritStyle(parentGroup, path);
  23204. parseAttributes(xmlNode, path, this._defs);
  23205. var points = xmlNode.getAttribute('points');
  23206. if (points) {
  23207. points = parsePoints(points);
  23208. }
  23209. var polyline = new Polyline({
  23210. shape: {
  23211. points: points || []
  23212. }
  23213. });
  23214. return polyline;
  23215. },
  23216. 'image': function (xmlNode, parentGroup) {
  23217. var img = new ZImage();
  23218. inheritStyle(parentGroup, img);
  23219. parseAttributes(xmlNode, img, this._defs);
  23220. img.setStyle({
  23221. image: xmlNode.getAttribute('xlink:href'),
  23222. x: xmlNode.getAttribute('x'),
  23223. y: xmlNode.getAttribute('y'),
  23224. width: xmlNode.getAttribute('width'),
  23225. height: xmlNode.getAttribute('height')
  23226. });
  23227. return img;
  23228. },
  23229. 'text': function (xmlNode, parentGroup) {
  23230. var x = xmlNode.getAttribute('x') || 0;
  23231. var y = xmlNode.getAttribute('y') || 0;
  23232. var dx = xmlNode.getAttribute('dx') || 0;
  23233. var dy = xmlNode.getAttribute('dy') || 0;
  23234. this._textX = parseFloat(x) + parseFloat(dx);
  23235. this._textY = parseFloat(y) + parseFloat(dy);
  23236. var g = new Group();
  23237. inheritStyle(parentGroup, g);
  23238. parseAttributes(xmlNode, g, this._defs);
  23239. return g;
  23240. },
  23241. 'tspan': function (xmlNode, parentGroup) {
  23242. var x = xmlNode.getAttribute('x');
  23243. var y = xmlNode.getAttribute('y');
  23244. if (x != null) {
  23245. // new offset x
  23246. this._textX = parseFloat(x);
  23247. }
  23248. if (y != null) {
  23249. // new offset y
  23250. this._textY = parseFloat(y);
  23251. }
  23252. var dx = xmlNode.getAttribute('dx') || 0;
  23253. var dy = xmlNode.getAttribute('dy') || 0;
  23254. var g = new Group();
  23255. inheritStyle(parentGroup, g);
  23256. parseAttributes(xmlNode, g, this._defs);
  23257. this._textX += dx;
  23258. this._textY += dy;
  23259. return g;
  23260. },
  23261. 'path': function (xmlNode, parentGroup) {
  23262. // TODO svg fill rule
  23263. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23264. // path.style.globalCompositeOperation = 'xor';
  23265. var d = xmlNode.getAttribute('d') || '';
  23266. // Performance sensitive.
  23267. var path = createFromString(d);
  23268. inheritStyle(parentGroup, path);
  23269. parseAttributes(xmlNode, path, this._defs);
  23270. return path;
  23271. }
  23272. };
  23273. var defineParsers = {
  23274. 'lineargradient': function (xmlNode) {
  23275. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23276. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23277. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23278. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23279. var gradient = new LinearGradient(x1, y1, x2, y2);
  23280. _parseGradientColorStops(xmlNode, gradient);
  23281. return gradient;
  23282. },
  23283. 'radialgradient': function (xmlNode) {
  23284. }
  23285. };
  23286. function _parseGradientColorStops(xmlNode, gradient) {
  23287. var stop = xmlNode.firstChild;
  23288. while (stop) {
  23289. if (stop.nodeType === 1) {
  23290. var offset = stop.getAttribute('offset');
  23291. if (offset.indexOf('%') > 0) { // percentage
  23292. offset = parseInt(offset, 10) / 100;
  23293. }
  23294. else if (offset) { // number from 0 to 1
  23295. offset = parseFloat(offset);
  23296. }
  23297. else {
  23298. offset = 0;
  23299. }
  23300. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23301. gradient.addColorStop(offset, stopColor);
  23302. }
  23303. stop = stop.nextSibling;
  23304. }
  23305. }
  23306. function inheritStyle(parent, child) {
  23307. if (parent && parent.__inheritedStyle) {
  23308. if (!child.__inheritedStyle) {
  23309. child.__inheritedStyle = {};
  23310. }
  23311. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23312. }
  23313. }
  23314. function parsePoints(pointsString) {
  23315. var list = trim(pointsString).split(DILIMITER_REG);
  23316. var points = [];
  23317. for (var i = 0; i < list.length; i += 2) {
  23318. var x = parseFloat(list[i]);
  23319. var y = parseFloat(list[i + 1]);
  23320. points.push([x, y]);
  23321. }
  23322. return points;
  23323. }
  23324. var attributesMap = {
  23325. 'fill': 'fill',
  23326. 'stroke': 'stroke',
  23327. 'stroke-width': 'lineWidth',
  23328. 'opacity': 'opacity',
  23329. 'fill-opacity': 'fillOpacity',
  23330. 'stroke-opacity': 'strokeOpacity',
  23331. 'stroke-dasharray': 'lineDash',
  23332. 'stroke-dashoffset': 'lineDashOffset',
  23333. 'stroke-linecap': 'lineCap',
  23334. 'stroke-linejoin': 'lineJoin',
  23335. 'stroke-miterlimit': 'miterLimit',
  23336. 'font-family': 'fontFamily',
  23337. 'font-size': 'fontSize',
  23338. 'font-style': 'fontStyle',
  23339. 'font-weight': 'fontWeight',
  23340. 'text-align': 'textAlign',
  23341. 'alignment-baseline': 'textBaseline'
  23342. };
  23343. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23344. var zrStyle = el.__inheritedStyle || {};
  23345. var isTextEl = el.type === 'text';
  23346. // TODO Shadow
  23347. if (xmlNode.nodeType === 1) {
  23348. parseTransformAttribute(xmlNode, el);
  23349. extend(zrStyle, parseStyleAttribute(xmlNode));
  23350. if (!onlyInlineStyle) {
  23351. for (var svgAttrName in attributesMap) {
  23352. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23353. var attrValue = xmlNode.getAttribute(svgAttrName);
  23354. if (attrValue != null) {
  23355. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23356. }
  23357. }
  23358. }
  23359. }
  23360. }
  23361. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23362. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23363. el.style = el.style || new Style();
  23364. var elStyle = el.style;
  23365. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23366. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23367. each$1([
  23368. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23369. ], function (propName) {
  23370. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23371. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23372. });
  23373. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23374. zrStyle.textBaseline = 'alphabetic';
  23375. }
  23376. if (zrStyle.textBaseline === 'alphabetic') {
  23377. zrStyle.textBaseline = 'bottom';
  23378. }
  23379. if (zrStyle.textAlign === 'start') {
  23380. zrStyle.textAlign = 'left';
  23381. }
  23382. if (zrStyle.textAlign === 'end') {
  23383. zrStyle.textAlign = 'right';
  23384. }
  23385. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23386. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23387. ], function (propName) {
  23388. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23389. });
  23390. if (zrStyle.lineDash) {
  23391. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23392. }
  23393. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23394. // enable stroke
  23395. el[elStrokeProp] = true;
  23396. }
  23397. el.__inheritedStyle = zrStyle;
  23398. }
  23399. var urlRegex = /url\(\s*#(.*?)\)/;
  23400. function getPaint(str, defs) {
  23401. // if (str === 'none') {
  23402. // return;
  23403. // }
  23404. var urlMatch = defs && str && str.match(urlRegex);
  23405. if (urlMatch) {
  23406. var url = trim(urlMatch[1]);
  23407. var def = defs[url];
  23408. return def;
  23409. }
  23410. return str;
  23411. }
  23412. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23413. function parseTransformAttribute(xmlNode, node) {
  23414. var transform = xmlNode.getAttribute('transform');
  23415. if (transform) {
  23416. transform = transform.replace(/,/g, ' ');
  23417. var m = null;
  23418. var transformOps = [];
  23419. transform.replace(transformRegex, function (str, type, value) {
  23420. transformOps.push(type, value);
  23421. });
  23422. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23423. var value = transformOps[i];
  23424. var type = transformOps[i - 1];
  23425. m = m || create$1();
  23426. switch (type) {
  23427. case 'translate':
  23428. value = trim(value).split(DILIMITER_REG);
  23429. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23430. break;
  23431. case 'scale':
  23432. value = trim(value).split(DILIMITER_REG);
  23433. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23434. break;
  23435. case 'rotate':
  23436. value = trim(value).split(DILIMITER_REG);
  23437. rotate(m, m, parseFloat(value[0]));
  23438. break;
  23439. case 'skew':
  23440. value = trim(value).split(DILIMITER_REG);
  23441. console.warn('Skew transform is not supported yet');
  23442. break;
  23443. case 'matrix':
  23444. var value = trim(value).split(DILIMITER_REG);
  23445. m[0] = parseFloat(value[0]);
  23446. m[1] = parseFloat(value[1]);
  23447. m[2] = parseFloat(value[2]);
  23448. m[3] = parseFloat(value[3]);
  23449. m[4] = parseFloat(value[4]);
  23450. m[5] = parseFloat(value[5]);
  23451. break;
  23452. }
  23453. }
  23454. node.setLocalTransform(m);
  23455. }
  23456. }
  23457. // Value may contain space.
  23458. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23459. function parseStyleAttribute(xmlNode) {
  23460. var style = xmlNode.getAttribute('style');
  23461. var result = {};
  23462. if (!style) {
  23463. return result;
  23464. }
  23465. var styleList = {};
  23466. styleRegex.lastIndex = 0;
  23467. var styleRegResult;
  23468. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23469. styleList[styleRegResult[1]] = styleRegResult[2];
  23470. }
  23471. for (var svgAttrName in attributesMap) {
  23472. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23473. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23474. }
  23475. }
  23476. return result;
  23477. }
  23478. /**
  23479. * @param {Array.<number>} viewBoxRect
  23480. * @param {number} width
  23481. * @param {number} height
  23482. * @return {Object} {scale, position}
  23483. */
  23484. function makeViewBoxTransform(viewBoxRect, width, height) {
  23485. var scaleX = width / viewBoxRect.width;
  23486. var scaleY = height / viewBoxRect.height;
  23487. var scale = Math.min(scaleX, scaleY);
  23488. // preserveAspectRatio 'xMidYMid'
  23489. var viewBoxScale = [scale, scale];
  23490. var viewBoxPosition = [
  23491. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23492. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23493. ];
  23494. return {
  23495. scale: viewBoxScale,
  23496. position: viewBoxPosition
  23497. };
  23498. }
  23499. /**
  23500. * @param {string|XMLElement} xml
  23501. * @param {Object} [opt]
  23502. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23503. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23504. * @param {boolean} [opt.ignoreViewBox]
  23505. * @param {boolean} [opt.ignoreRootClip]
  23506. * @return {Object} result:
  23507. * {
  23508. * root: Group, The root of the the result tree of zrender shapes,
  23509. * width: number, the viewport width of the SVG,
  23510. * height: number, the viewport height of the SVG,
  23511. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23512. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23513. * }
  23514. */
  23515. /*
  23516. * Licensed to the Apache Software Foundation (ASF) under one
  23517. * or more contributor license agreements. See the NOTICE file
  23518. * distributed with this work for additional information
  23519. * regarding copyright ownership. The ASF licenses this file
  23520. * to you under the Apache License, Version 2.0 (the
  23521. * "License"); you may not use this file except in compliance
  23522. * with the License. You may obtain a copy of the License at
  23523. *
  23524. * http://www.apache.org/licenses/LICENSE-2.0
  23525. *
  23526. * Unless required by applicable law or agreed to in writing,
  23527. * software distributed under the License is distributed on an
  23528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23529. * KIND, either express or implied. See the License for the
  23530. * specific language governing permissions and limitations
  23531. * under the License.
  23532. */
  23533. var storage = createHashMap();
  23534. // For minimize the code size of common echarts package,
  23535. // do not put too much logic in this module.
  23536. var mapDataStorage = {
  23537. // The format of record: see `echarts.registerMap`.
  23538. // Compatible with previous `echarts.registerMap`.
  23539. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23540. var records;
  23541. if (isArray(rawGeoJson)) {
  23542. records = rawGeoJson;
  23543. }
  23544. else if (rawGeoJson.svg) {
  23545. records = [{
  23546. type: 'svg',
  23547. source: rawGeoJson.svg,
  23548. specialAreas: rawGeoJson.specialAreas
  23549. }];
  23550. }
  23551. else {
  23552. // Backward compatibility.
  23553. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23554. rawSpecialAreas = rawGeoJson.specialAreas;
  23555. rawGeoJson = rawGeoJson.geoJson;
  23556. }
  23557. records = [{
  23558. type: 'geoJSON',
  23559. source: rawGeoJson,
  23560. specialAreas: rawSpecialAreas
  23561. }];
  23562. }
  23563. each$1(records, function (record) {
  23564. var type = record.type;
  23565. type === 'geoJson' && (type = record.type = 'geoJSON');
  23566. var parse = parsers[type];
  23567. if (__DEV__) {
  23568. assert$1(parse, 'Illegal map type: ' + type);
  23569. }
  23570. parse(record);
  23571. });
  23572. return storage.set(mapName, records);
  23573. },
  23574. retrieveMap: function (mapName) {
  23575. return storage.get(mapName);
  23576. }
  23577. };
  23578. var parsers = {
  23579. geoJSON: function (record) {
  23580. var source = record.source;
  23581. record.geoJSON = !isString(source)
  23582. ? source
  23583. : (typeof JSON !== 'undefined' && JSON.parse)
  23584. ? JSON.parse(source)
  23585. : (new Function('return (' + source + ');'))();
  23586. },
  23587. // Only perform parse to XML object here, which might be time
  23588. // consiming for large SVG.
  23589. // Although convert XML to zrender element is also time consiming,
  23590. // if we do it here, the clone of zrender elements has to be
  23591. // required. So we do it once for each geo instance, util real
  23592. // performance issues call for optimizing it.
  23593. svg: function (record) {
  23594. record.svgXML = parseXML(record.source);
  23595. }
  23596. };
  23597. /*
  23598. * Licensed to the Apache Software Foundation (ASF) under one
  23599. * or more contributor license agreements. See the NOTICE file
  23600. * distributed with this work for additional information
  23601. * regarding copyright ownership. The ASF licenses this file
  23602. * to you under the Apache License, Version 2.0 (the
  23603. * "License"); you may not use this file except in compliance
  23604. * with the License. You may obtain a copy of the License at
  23605. *
  23606. * http://www.apache.org/licenses/LICENSE-2.0
  23607. *
  23608. * Unless required by applicable law or agreed to in writing,
  23609. * software distributed under the License is distributed on an
  23610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23611. * KIND, either express or implied. See the License for the
  23612. * specific language governing permissions and limitations
  23613. * under the License.
  23614. */
  23615. var assert = assert$1;
  23616. var each = each$1;
  23617. var isFunction = isFunction$1;
  23618. var isObject = isObject$1;
  23619. var parseClassType = ComponentModel.parseClassType;
  23620. var version = '4.7.0';
  23621. var dependencies = {
  23622. zrender: '4.3.0'
  23623. };
  23624. var TEST_FRAME_REMAIN_TIME = 1;
  23625. var PRIORITY_PROCESSOR_FILTER = 1000;
  23626. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  23627. var PRIORITY_PROCESSOR_DATASTACK = 900;
  23628. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23629. var PRIORITY_VISUAL_LAYOUT = 1000;
  23630. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  23631. var PRIORITY_VISUAL_GLOBAL = 2000;
  23632. var PRIORITY_VISUAL_CHART = 3000;
  23633. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  23634. var PRIORITY_VISUAL_COMPONENT = 4000;
  23635. // FIXME
  23636. // necessary?
  23637. var PRIORITY_VISUAL_BRUSH = 5000;
  23638. var PRIORITY = {
  23639. PROCESSOR: {
  23640. FILTER: PRIORITY_PROCESSOR_FILTER,
  23641. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  23642. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23643. },
  23644. VISUAL: {
  23645. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23646. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  23647. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23648. CHART: PRIORITY_VISUAL_CHART,
  23649. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  23650. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23651. BRUSH: PRIORITY_VISUAL_BRUSH
  23652. }
  23653. };
  23654. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23655. // where they must not be invoked nestedly, except the only case: invoke
  23656. // dispatchAction with updateMethod "none" in main process.
  23657. // This flag is used to carry out this rule.
  23658. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23659. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23660. var OPTION_UPDATED = '__optionUpdated';
  23661. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23662. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  23663. return function (eventName, handler, context) {
  23664. if (!ignoreDisposed && this._disposed) {
  23665. disposedWarning(this.id);
  23666. return;
  23667. }
  23668. // Event name is all lowercase
  23669. eventName = eventName && eventName.toLowerCase();
  23670. Eventful.prototype[method].call(this, eventName, handler, context);
  23671. };
  23672. }
  23673. /**
  23674. * @module echarts~MessageCenter
  23675. */
  23676. function MessageCenter() {
  23677. Eventful.call(this);
  23678. }
  23679. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  23680. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  23681. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  23682. mixin(MessageCenter, Eventful);
  23683. /**
  23684. * @module echarts~ECharts
  23685. */
  23686. function ECharts(dom, theme$$1, opts) {
  23687. opts = opts || {};
  23688. // Get theme by name
  23689. if (typeof theme$$1 === 'string') {
  23690. theme$$1 = themeStorage[theme$$1];
  23691. }
  23692. /**
  23693. * @type {string}
  23694. */
  23695. this.id;
  23696. /**
  23697. * Group id
  23698. * @type {string}
  23699. */
  23700. this.group;
  23701. /**
  23702. * @type {HTMLElement}
  23703. * @private
  23704. */
  23705. this._dom = dom;
  23706. var defaultRenderer = 'canvas';
  23707. if (__DEV__) {
  23708. defaultRenderer = (
  23709. typeof window === 'undefined' ? global : window
  23710. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23711. }
  23712. /**
  23713. * @type {module:zrender/ZRender}
  23714. * @private
  23715. */
  23716. var zr = this._zr = init$1(dom, {
  23717. renderer: opts.renderer || defaultRenderer,
  23718. devicePixelRatio: opts.devicePixelRatio,
  23719. width: opts.width,
  23720. height: opts.height
  23721. });
  23722. /**
  23723. * Expect 60 fps.
  23724. * @type {Function}
  23725. * @private
  23726. */
  23727. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23728. var theme$$1 = clone(theme$$1);
  23729. theme$$1 && backwardCompat(theme$$1, true);
  23730. /**
  23731. * @type {Object}
  23732. * @private
  23733. */
  23734. this._theme = theme$$1;
  23735. /**
  23736. * @type {Array.<module:echarts/view/Chart>}
  23737. * @private
  23738. */
  23739. this._chartsViews = [];
  23740. /**
  23741. * @type {Object.<string, module:echarts/view/Chart>}
  23742. * @private
  23743. */
  23744. this._chartsMap = {};
  23745. /**
  23746. * @type {Array.<module:echarts/view/Component>}
  23747. * @private
  23748. */
  23749. this._componentsViews = [];
  23750. /**
  23751. * @type {Object.<string, module:echarts/view/Component>}
  23752. * @private
  23753. */
  23754. this._componentsMap = {};
  23755. /**
  23756. * @type {module:echarts/CoordinateSystem}
  23757. * @private
  23758. */
  23759. this._coordSysMgr = new CoordinateSystemManager();
  23760. /**
  23761. * @type {module:echarts/ExtensionAPI}
  23762. * @private
  23763. */
  23764. var api = this._api = createExtensionAPI(this);
  23765. // Sort on demand
  23766. function prioritySortFunc(a, b) {
  23767. return a.__prio - b.__prio;
  23768. }
  23769. sort(visualFuncs, prioritySortFunc);
  23770. sort(dataProcessorFuncs, prioritySortFunc);
  23771. /**
  23772. * @type {module:echarts/stream/Scheduler}
  23773. */
  23774. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23775. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23776. /**
  23777. * @type {module:echarts~MessageCenter}
  23778. * @private
  23779. */
  23780. this._messageCenter = new MessageCenter();
  23781. // Init mouse events
  23782. this._initEvents();
  23783. // In case some people write `window.onresize = chart.resize`
  23784. this.resize = bind(this.resize, this);
  23785. // Can't dispatch action during rendering procedure
  23786. this._pendingActions = [];
  23787. zr.animation.on('frame', this._onframe, this);
  23788. bindRenderedEvent(zr, this);
  23789. // ECharts instance can be used as value.
  23790. setAsPrimitive(this);
  23791. }
  23792. var echartsProto = ECharts.prototype;
  23793. echartsProto._onframe = function () {
  23794. if (this._disposed) {
  23795. return;
  23796. }
  23797. var scheduler = this._scheduler;
  23798. // Lazy update
  23799. if (this[OPTION_UPDATED]) {
  23800. var silent = this[OPTION_UPDATED].silent;
  23801. this[IN_MAIN_PROCESS] = true;
  23802. prepare(this);
  23803. updateMethods.update.call(this);
  23804. this[IN_MAIN_PROCESS] = false;
  23805. this[OPTION_UPDATED] = false;
  23806. flushPendingActions.call(this, silent);
  23807. triggerUpdatedEvent.call(this, silent);
  23808. }
  23809. // Avoid do both lazy update and progress in one frame.
  23810. else if (scheduler.unfinished) {
  23811. // Stream progress.
  23812. var remainTime = TEST_FRAME_REMAIN_TIME;
  23813. var ecModel = this._model;
  23814. var api = this._api;
  23815. scheduler.unfinished = false;
  23816. do {
  23817. var startTime = +new Date();
  23818. scheduler.performSeriesTasks(ecModel);
  23819. // Currently dataProcessorFuncs do not check threshold.
  23820. scheduler.performDataProcessorTasks(ecModel);
  23821. updateStreamModes(this, ecModel);
  23822. // Do not update coordinate system here. Because that coord system update in
  23823. // each frame is not a good user experience. So we follow the rule that
  23824. // the extent of the coordinate system is determin in the first frame (the
  23825. // frame is executed immedietely after task reset.
  23826. // this._coordSysMgr.update(ecModel, api);
  23827. // console.log('--- ec frame visual ---', remainTime);
  23828. scheduler.performVisualTasks(ecModel);
  23829. renderSeries(this, this._model, api, 'remain');
  23830. remainTime -= (+new Date() - startTime);
  23831. }
  23832. while (remainTime > 0 && scheduler.unfinished);
  23833. // Call flush explicitly for trigger finished event.
  23834. if (!scheduler.unfinished) {
  23835. this._zr.flush();
  23836. }
  23837. // Else, zr flushing be ensue within the same frame,
  23838. // because zr flushing is after onframe event.
  23839. }
  23840. };
  23841. /**
  23842. * @return {HTMLElement}
  23843. */
  23844. echartsProto.getDom = function () {
  23845. return this._dom;
  23846. };
  23847. /**
  23848. * @return {module:zrender~ZRender}
  23849. */
  23850. echartsProto.getZr = function () {
  23851. return this._zr;
  23852. };
  23853. /**
  23854. * Usage:
  23855. * chart.setOption(option, notMerge, lazyUpdate);
  23856. * chart.setOption(option, {
  23857. * notMerge: ...,
  23858. * lazyUpdate: ...,
  23859. * silent: ...
  23860. * });
  23861. *
  23862. * @param {Object} option
  23863. * @param {Object|boolean} [opts] opts or notMerge.
  23864. * @param {boolean} [opts.notMerge=false]
  23865. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23866. */
  23867. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23868. if (__DEV__) {
  23869. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23870. }
  23871. if (this._disposed) {
  23872. disposedWarning(this.id);
  23873. return;
  23874. }
  23875. var silent;
  23876. if (isObject(notMerge)) {
  23877. lazyUpdate = notMerge.lazyUpdate;
  23878. silent = notMerge.silent;
  23879. notMerge = notMerge.notMerge;
  23880. }
  23881. this[IN_MAIN_PROCESS] = true;
  23882. if (!this._model || notMerge) {
  23883. var optionManager = new OptionManager(this._api);
  23884. var theme$$1 = this._theme;
  23885. var ecModel = this._model = new GlobalModel();
  23886. ecModel.scheduler = this._scheduler;
  23887. ecModel.init(null, null, theme$$1, optionManager);
  23888. }
  23889. this._model.setOption(option, optionPreprocessorFuncs);
  23890. if (lazyUpdate) {
  23891. this[OPTION_UPDATED] = {silent: silent};
  23892. this[IN_MAIN_PROCESS] = false;
  23893. }
  23894. else {
  23895. prepare(this);
  23896. updateMethods.update.call(this);
  23897. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23898. // fetched after `setOption`.
  23899. this._zr.flush();
  23900. this[OPTION_UPDATED] = false;
  23901. this[IN_MAIN_PROCESS] = false;
  23902. flushPendingActions.call(this, silent);
  23903. triggerUpdatedEvent.call(this, silent);
  23904. }
  23905. };
  23906. /**
  23907. * @DEPRECATED
  23908. */
  23909. echartsProto.setTheme = function () {
  23910. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23911. };
  23912. /**
  23913. * @return {module:echarts/model/Global}
  23914. */
  23915. echartsProto.getModel = function () {
  23916. return this._model;
  23917. };
  23918. /**
  23919. * @return {Object}
  23920. */
  23921. echartsProto.getOption = function () {
  23922. return this._model && this._model.getOption();
  23923. };
  23924. /**
  23925. * @return {number}
  23926. */
  23927. echartsProto.getWidth = function () {
  23928. return this._zr.getWidth();
  23929. };
  23930. /**
  23931. * @return {number}
  23932. */
  23933. echartsProto.getHeight = function () {
  23934. return this._zr.getHeight();
  23935. };
  23936. /**
  23937. * @return {number}
  23938. */
  23939. echartsProto.getDevicePixelRatio = function () {
  23940. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23941. };
  23942. /**
  23943. * Get canvas which has all thing rendered
  23944. * @param {Object} opts
  23945. * @param {string} [opts.backgroundColor]
  23946. * @return {string}
  23947. */
  23948. echartsProto.getRenderedCanvas = function (opts) {
  23949. if (!env$1.canvasSupported) {
  23950. return;
  23951. }
  23952. opts = opts || {};
  23953. opts.pixelRatio = opts.pixelRatio || 1;
  23954. opts.backgroundColor = opts.backgroundColor
  23955. || this._model.get('backgroundColor');
  23956. var zr = this._zr;
  23957. // var list = zr.storage.getDisplayList();
  23958. // Stop animations
  23959. // Never works before in init animation, so remove it.
  23960. // zrUtil.each(list, function (el) {
  23961. // el.stopAnimation(true);
  23962. // });
  23963. return zr.painter.getRenderedCanvas(opts);
  23964. };
  23965. /**
  23966. * Get svg data url
  23967. * @return {string}
  23968. */
  23969. echartsProto.getSvgDataUrl = function () {
  23970. if (!env$1.svgSupported) {
  23971. return;
  23972. }
  23973. var zr = this._zr;
  23974. var list = zr.storage.getDisplayList();
  23975. // Stop animations
  23976. each$1(list, function (el) {
  23977. el.stopAnimation(true);
  23978. });
  23979. return zr.painter.pathToDataUrl();
  23980. };
  23981. /**
  23982. * @return {string}
  23983. * @param {Object} opts
  23984. * @param {string} [opts.type='png']
  23985. * @param {string} [opts.pixelRatio=1]
  23986. * @param {string} [opts.backgroundColor]
  23987. * @param {string} [opts.excludeComponents]
  23988. */
  23989. echartsProto.getDataURL = function (opts) {
  23990. if (this._disposed) {
  23991. disposedWarning(this.id);
  23992. return;
  23993. }
  23994. opts = opts || {};
  23995. var excludeComponents = opts.excludeComponents;
  23996. var ecModel = this._model;
  23997. var excludesComponentViews = [];
  23998. var self = this;
  23999. each(excludeComponents, function (componentType) {
  24000. ecModel.eachComponent({
  24001. mainType: componentType
  24002. }, function (component) {
  24003. var view = self._componentsMap[component.__viewId];
  24004. if (!view.group.ignore) {
  24005. excludesComponentViews.push(view);
  24006. view.group.ignore = true;
  24007. }
  24008. });
  24009. });
  24010. var url = this._zr.painter.getType() === 'svg'
  24011. ? this.getSvgDataUrl()
  24012. : this.getRenderedCanvas(opts).toDataURL(
  24013. 'image/' + (opts && opts.type || 'png')
  24014. );
  24015. each(excludesComponentViews, function (view) {
  24016. view.group.ignore = false;
  24017. });
  24018. return url;
  24019. };
  24020. /**
  24021. * @return {string}
  24022. * @param {Object} opts
  24023. * @param {string} [opts.type='png']
  24024. * @param {string} [opts.pixelRatio=1]
  24025. * @param {string} [opts.backgroundColor]
  24026. */
  24027. echartsProto.getConnectedDataURL = function (opts) {
  24028. if (this._disposed) {
  24029. disposedWarning(this.id);
  24030. return;
  24031. }
  24032. if (!env$1.canvasSupported) {
  24033. return;
  24034. }
  24035. var groupId = this.group;
  24036. var mathMin = Math.min;
  24037. var mathMax = Math.max;
  24038. var MAX_NUMBER = Infinity;
  24039. if (connectedGroups[groupId]) {
  24040. var left = MAX_NUMBER;
  24041. var top = MAX_NUMBER;
  24042. var right = -MAX_NUMBER;
  24043. var bottom = -MAX_NUMBER;
  24044. var canvasList = [];
  24045. var dpr = (opts && opts.pixelRatio) || 1;
  24046. each$1(instances, function (chart, id) {
  24047. if (chart.group === groupId) {
  24048. var canvas = chart.getRenderedCanvas(
  24049. clone(opts)
  24050. );
  24051. var boundingRect = chart.getDom().getBoundingClientRect();
  24052. left = mathMin(boundingRect.left, left);
  24053. top = mathMin(boundingRect.top, top);
  24054. right = mathMax(boundingRect.right, right);
  24055. bottom = mathMax(boundingRect.bottom, bottom);
  24056. canvasList.push({
  24057. dom: canvas,
  24058. left: boundingRect.left,
  24059. top: boundingRect.top
  24060. });
  24061. }
  24062. });
  24063. left *= dpr;
  24064. top *= dpr;
  24065. right *= dpr;
  24066. bottom *= dpr;
  24067. var width = right - left;
  24068. var height = bottom - top;
  24069. var targetCanvas = createCanvas();
  24070. targetCanvas.width = width;
  24071. targetCanvas.height = height;
  24072. var zr = init$1(targetCanvas);
  24073. // Background between the charts
  24074. if (opts.connectedBackgroundColor) {
  24075. zr.add(new Rect({
  24076. shape: {
  24077. x: 0,
  24078. y: 0,
  24079. width: width,
  24080. height: height
  24081. },
  24082. style: {
  24083. fill: opts.connectedBackgroundColor
  24084. }
  24085. }));
  24086. }
  24087. each(canvasList, function (item) {
  24088. var img = new ZImage({
  24089. style: {
  24090. x: item.left * dpr - left,
  24091. y: item.top * dpr - top,
  24092. image: item.dom
  24093. }
  24094. });
  24095. zr.add(img);
  24096. });
  24097. zr.refreshImmediately();
  24098. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  24099. }
  24100. else {
  24101. return this.getDataURL(opts);
  24102. }
  24103. };
  24104. /**
  24105. * Convert from logical coordinate system to pixel coordinate system.
  24106. * See CoordinateSystem#convertToPixel.
  24107. * @param {string|Object} finder
  24108. * If string, e.g., 'geo', means {geoIndex: 0}.
  24109. * If Object, could contain some of these properties below:
  24110. * {
  24111. * seriesIndex / seriesId / seriesName,
  24112. * geoIndex / geoId, geoName,
  24113. * bmapIndex / bmapId / bmapName,
  24114. * xAxisIndex / xAxisId / xAxisName,
  24115. * yAxisIndex / yAxisId / yAxisName,
  24116. * gridIndex / gridId / gridName,
  24117. * ... (can be extended)
  24118. * }
  24119. * @param {Array|number} value
  24120. * @return {Array|number} result
  24121. */
  24122. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  24123. /**
  24124. * Convert from pixel coordinate system to logical coordinate system.
  24125. * See CoordinateSystem#convertFromPixel.
  24126. * @param {string|Object} finder
  24127. * If string, e.g., 'geo', means {geoIndex: 0}.
  24128. * If Object, could contain some of these properties below:
  24129. * {
  24130. * seriesIndex / seriesId / seriesName,
  24131. * geoIndex / geoId / geoName,
  24132. * bmapIndex / bmapId / bmapName,
  24133. * xAxisIndex / xAxisId / xAxisName,
  24134. * yAxisIndex / yAxisId / yAxisName
  24135. * gridIndex / gridId / gridName,
  24136. * ... (can be extended)
  24137. * }
  24138. * @param {Array|number} value
  24139. * @return {Array|number} result
  24140. */
  24141. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24142. function doConvertPixel(methodName, finder, value) {
  24143. if (this._disposed) {
  24144. disposedWarning(this.id);
  24145. return;
  24146. }
  24147. var ecModel = this._model;
  24148. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24149. var result;
  24150. finder = parseFinder(ecModel, finder);
  24151. for (var i = 0; i < coordSysList.length; i++) {
  24152. var coordSys = coordSysList[i];
  24153. if (coordSys[methodName]
  24154. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24155. ) {
  24156. return result;
  24157. }
  24158. }
  24159. if (__DEV__) {
  24160. console.warn(
  24161. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24162. );
  24163. }
  24164. }
  24165. /**
  24166. * Is the specified coordinate systems or components contain the given pixel point.
  24167. * @param {string|Object} finder
  24168. * If string, e.g., 'geo', means {geoIndex: 0}.
  24169. * If Object, could contain some of these properties below:
  24170. * {
  24171. * seriesIndex / seriesId / seriesName,
  24172. * geoIndex / geoId / geoName,
  24173. * bmapIndex / bmapId / bmapName,
  24174. * xAxisIndex / xAxisId / xAxisName,
  24175. * yAxisIndex / yAxisId / yAxisName,
  24176. * gridIndex / gridId / gridName,
  24177. * ... (can be extended)
  24178. * }
  24179. * @param {Array|number} value
  24180. * @return {boolean} result
  24181. */
  24182. echartsProto.containPixel = function (finder, value) {
  24183. if (this._disposed) {
  24184. disposedWarning(this.id);
  24185. return;
  24186. }
  24187. var ecModel = this._model;
  24188. var result;
  24189. finder = parseFinder(ecModel, finder);
  24190. each$1(finder, function (models, key) {
  24191. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24192. var coordSys = model.coordinateSystem;
  24193. if (coordSys && coordSys.containPoint) {
  24194. result |= !!coordSys.containPoint(value);
  24195. }
  24196. else if (key === 'seriesModels') {
  24197. var view = this._chartsMap[model.__viewId];
  24198. if (view && view.containPoint) {
  24199. result |= view.containPoint(value, model);
  24200. }
  24201. else {
  24202. if (__DEV__) {
  24203. console.warn(key + ': ' + (view
  24204. ? 'The found component do not support containPoint.'
  24205. : 'No view mapping to the found component.'
  24206. ));
  24207. }
  24208. }
  24209. }
  24210. else {
  24211. if (__DEV__) {
  24212. console.warn(key + ': containPoint is not supported');
  24213. }
  24214. }
  24215. }, this);
  24216. }, this);
  24217. return !!result;
  24218. };
  24219. /**
  24220. * Get visual from series or data.
  24221. * @param {string|Object} finder
  24222. * If string, e.g., 'series', means {seriesIndex: 0}.
  24223. * If Object, could contain some of these properties below:
  24224. * {
  24225. * seriesIndex / seriesId / seriesName,
  24226. * dataIndex / dataIndexInside
  24227. * }
  24228. * If dataIndex is not specified, series visual will be fetched,
  24229. * but not data item visual.
  24230. * If all of seriesIndex, seriesId, seriesName are not specified,
  24231. * visual will be fetched from first series.
  24232. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24233. */
  24234. echartsProto.getVisual = function (finder, visualType) {
  24235. var ecModel = this._model;
  24236. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24237. var seriesModel = finder.seriesModel;
  24238. if (__DEV__) {
  24239. if (!seriesModel) {
  24240. console.warn('There is no specified seires model');
  24241. }
  24242. }
  24243. var data = seriesModel.getData();
  24244. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24245. ? finder.dataIndexInside
  24246. : finder.hasOwnProperty('dataIndex')
  24247. ? data.indexOfRawIndex(finder.dataIndex)
  24248. : null;
  24249. return dataIndexInside != null
  24250. ? data.getItemVisual(dataIndexInside, visualType)
  24251. : data.getVisual(visualType);
  24252. };
  24253. /**
  24254. * Get view of corresponding component model
  24255. * @param {module:echarts/model/Component} componentModel
  24256. * @return {module:echarts/view/Component}
  24257. */
  24258. echartsProto.getViewOfComponentModel = function (componentModel) {
  24259. return this._componentsMap[componentModel.__viewId];
  24260. };
  24261. /**
  24262. * Get view of corresponding series model
  24263. * @param {module:echarts/model/Series} seriesModel
  24264. * @return {module:echarts/view/Chart}
  24265. */
  24266. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24267. return this._chartsMap[seriesModel.__viewId];
  24268. };
  24269. var updateMethods = {
  24270. prepareAndUpdate: function (payload) {
  24271. prepare(this);
  24272. updateMethods.update.call(this, payload);
  24273. },
  24274. /**
  24275. * @param {Object} payload
  24276. * @private
  24277. */
  24278. update: function (payload) {
  24279. // console.profile && console.profile('update');
  24280. var ecModel = this._model;
  24281. var api = this._api;
  24282. var zr = this._zr;
  24283. var coordSysMgr = this._coordSysMgr;
  24284. var scheduler = this._scheduler;
  24285. // update before setOption
  24286. if (!ecModel) {
  24287. return;
  24288. }
  24289. scheduler.restoreData(ecModel, payload);
  24290. scheduler.performSeriesTasks(ecModel);
  24291. // TODO
  24292. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24293. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24294. // Create new coordinate system each update
  24295. // In LineView may save the old coordinate system and use it to get the orignal point
  24296. coordSysMgr.create(ecModel, api);
  24297. scheduler.performDataProcessorTasks(ecModel, payload);
  24298. // Current stream render is not supported in data process. So we can update
  24299. // stream modes after data processing, where the filtered data is used to
  24300. // deteming whether use progressive rendering.
  24301. updateStreamModes(this, ecModel);
  24302. // We update stream modes before coordinate system updated, then the modes info
  24303. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24304. // the drawback is the full coord info can not be fetched. Fortunately this full
  24305. // coord is not requied in stream mode updater currently.
  24306. coordSysMgr.update(ecModel, api);
  24307. clearColorPalette(ecModel);
  24308. scheduler.performVisualTasks(ecModel, payload);
  24309. render(this, ecModel, api, payload);
  24310. // Set background
  24311. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24312. // In IE8
  24313. if (!env$1.canvasSupported) {
  24314. var colorArr = parse(backgroundColor);
  24315. backgroundColor = stringify(colorArr, 'rgb');
  24316. if (colorArr[3] === 0) {
  24317. backgroundColor = 'transparent';
  24318. }
  24319. }
  24320. else {
  24321. zr.setBackgroundColor(backgroundColor);
  24322. }
  24323. performPostUpdateFuncs(ecModel, api);
  24324. // console.profile && console.profileEnd('update');
  24325. },
  24326. /**
  24327. * @param {Object} payload
  24328. * @private
  24329. */
  24330. updateTransform: function (payload) {
  24331. var ecModel = this._model;
  24332. var ecIns = this;
  24333. var api = this._api;
  24334. // update before setOption
  24335. if (!ecModel) {
  24336. return;
  24337. }
  24338. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24339. var componentDirtyList = [];
  24340. ecModel.eachComponent(function (componentType, componentModel) {
  24341. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24342. if (componentView && componentView.__alive) {
  24343. if (componentView.updateTransform) {
  24344. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24345. result && result.update && componentDirtyList.push(componentView);
  24346. }
  24347. else {
  24348. componentDirtyList.push(componentView);
  24349. }
  24350. }
  24351. });
  24352. var seriesDirtyMap = createHashMap();
  24353. ecModel.eachSeries(function (seriesModel) {
  24354. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24355. if (chartView.updateTransform) {
  24356. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24357. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24358. }
  24359. else {
  24360. seriesDirtyMap.set(seriesModel.uid, 1);
  24361. }
  24362. });
  24363. clearColorPalette(ecModel);
  24364. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24365. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24366. this._scheduler.performVisualTasks(
  24367. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24368. );
  24369. // Currently, not call render of components. Geo render cost a lot.
  24370. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24371. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24372. performPostUpdateFuncs(ecModel, this._api);
  24373. },
  24374. /**
  24375. * @param {Object} payload
  24376. * @private
  24377. */
  24378. updateView: function (payload) {
  24379. var ecModel = this._model;
  24380. // update before setOption
  24381. if (!ecModel) {
  24382. return;
  24383. }
  24384. Chart.markUpdateMethod(payload, 'updateView');
  24385. clearColorPalette(ecModel);
  24386. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24387. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24388. render(this, this._model, this._api, payload);
  24389. performPostUpdateFuncs(ecModel, this._api);
  24390. },
  24391. /**
  24392. * @param {Object} payload
  24393. * @private
  24394. */
  24395. updateVisual: function (payload) {
  24396. updateMethods.update.call(this, payload);
  24397. // var ecModel = this._model;
  24398. // // update before setOption
  24399. // if (!ecModel) {
  24400. // return;
  24401. // }
  24402. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24403. // clearColorPalette(ecModel);
  24404. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24405. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24406. // render(this, this._model, this._api, payload);
  24407. // performPostUpdateFuncs(ecModel, this._api);
  24408. },
  24409. /**
  24410. * @param {Object} payload
  24411. * @private
  24412. */
  24413. updateLayout: function (payload) {
  24414. updateMethods.update.call(this, payload);
  24415. // var ecModel = this._model;
  24416. // // update before setOption
  24417. // if (!ecModel) {
  24418. // return;
  24419. // }
  24420. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24421. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24422. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24423. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24424. // render(this, this._model, this._api, payload);
  24425. // performPostUpdateFuncs(ecModel, this._api);
  24426. }
  24427. };
  24428. function prepare(ecIns) {
  24429. var ecModel = ecIns._model;
  24430. var scheduler = ecIns._scheduler;
  24431. scheduler.restorePipelines(ecModel);
  24432. scheduler.prepareStageTasks();
  24433. prepareView(ecIns, 'component', ecModel, scheduler);
  24434. prepareView(ecIns, 'chart', ecModel, scheduler);
  24435. scheduler.plan();
  24436. }
  24437. /**
  24438. * @private
  24439. */
  24440. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24441. var ecModel = ecIns._model;
  24442. // broadcast
  24443. if (!mainType) {
  24444. // FIXME
  24445. // Chart will not be update directly here, except set dirty.
  24446. // But there is no such scenario now.
  24447. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24448. return;
  24449. }
  24450. var query = {};
  24451. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24452. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24453. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24454. var condition = {mainType: mainType, query: query};
  24455. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24456. var excludeSeriesId = payload.excludeSeriesId;
  24457. if (excludeSeriesId != null) {
  24458. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24459. }
  24460. // If dispatchAction before setOption, do nothing.
  24461. ecModel && ecModel.eachComponent(condition, function (model) {
  24462. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24463. callView(ecIns[
  24464. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24465. ][model.__viewId]);
  24466. }
  24467. }, ecIns);
  24468. function callView(view) {
  24469. view && view.__alive && view[method] && view[method](
  24470. view.__model, ecModel, ecIns._api, payload
  24471. );
  24472. }
  24473. }
  24474. /**
  24475. * Resize the chart
  24476. * @param {Object} opts
  24477. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24478. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24479. * @param {boolean} [opts.silent=false]
  24480. */
  24481. echartsProto.resize = function (opts) {
  24482. if (__DEV__) {
  24483. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24484. }
  24485. if (this._disposed) {
  24486. disposedWarning(this.id);
  24487. return;
  24488. }
  24489. this._zr.resize(opts);
  24490. var ecModel = this._model;
  24491. // Resize loading effect
  24492. this._loadingFX && this._loadingFX.resize();
  24493. if (!ecModel) {
  24494. return;
  24495. }
  24496. var optionChanged = ecModel.resetOption('media');
  24497. var silent = opts && opts.silent;
  24498. this[IN_MAIN_PROCESS] = true;
  24499. optionChanged && prepare(this);
  24500. updateMethods.update.call(this);
  24501. this[IN_MAIN_PROCESS] = false;
  24502. flushPendingActions.call(this, silent);
  24503. triggerUpdatedEvent.call(this, silent);
  24504. };
  24505. function updateStreamModes(ecIns, ecModel) {
  24506. var chartsMap = ecIns._chartsMap;
  24507. var scheduler = ecIns._scheduler;
  24508. ecModel.eachSeries(function (seriesModel) {
  24509. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24510. });
  24511. }
  24512. /**
  24513. * Show loading effect
  24514. * @param {string} [name='default']
  24515. * @param {Object} [cfg]
  24516. */
  24517. echartsProto.showLoading = function (name, cfg) {
  24518. if (this._disposed) {
  24519. disposedWarning(this.id);
  24520. return;
  24521. }
  24522. if (isObject(name)) {
  24523. cfg = name;
  24524. name = '';
  24525. }
  24526. name = name || 'default';
  24527. this.hideLoading();
  24528. if (!loadingEffects[name]) {
  24529. if (__DEV__) {
  24530. console.warn('Loading effects ' + name + ' not exists.');
  24531. }
  24532. return;
  24533. }
  24534. var el = loadingEffects[name](this._api, cfg);
  24535. var zr = this._zr;
  24536. this._loadingFX = el;
  24537. zr.add(el);
  24538. };
  24539. /**
  24540. * Hide loading effect
  24541. */
  24542. echartsProto.hideLoading = function () {
  24543. if (this._disposed) {
  24544. disposedWarning(this.id);
  24545. return;
  24546. }
  24547. this._loadingFX && this._zr.remove(this._loadingFX);
  24548. this._loadingFX = null;
  24549. };
  24550. /**
  24551. * @param {Object} eventObj
  24552. * @return {Object}
  24553. */
  24554. echartsProto.makeActionFromEvent = function (eventObj) {
  24555. var payload = extend({}, eventObj);
  24556. payload.type = eventActionMap[eventObj.type];
  24557. return payload;
  24558. };
  24559. /**
  24560. * @pubilc
  24561. * @param {Object} payload
  24562. * @param {string} [payload.type] Action type
  24563. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24564. * @param {boolean} [opt.silent=false] Whether trigger events.
  24565. * @param {boolean} [opt.flush=undefined]
  24566. * true: Flush immediately, and then pixel in canvas can be fetched
  24567. * immediately. Caution: it might affect performance.
  24568. * false: Not flush.
  24569. * undefined: Auto decide whether perform flush.
  24570. */
  24571. echartsProto.dispatchAction = function (payload, opt) {
  24572. if (this._disposed) {
  24573. disposedWarning(this.id);
  24574. return;
  24575. }
  24576. if (!isObject(opt)) {
  24577. opt = {silent: !!opt};
  24578. }
  24579. if (!actions[payload.type]) {
  24580. return;
  24581. }
  24582. // Avoid dispatch action before setOption. Especially in `connect`.
  24583. if (!this._model) {
  24584. return;
  24585. }
  24586. // May dispatchAction in rendering procedure
  24587. if (this[IN_MAIN_PROCESS]) {
  24588. this._pendingActions.push(payload);
  24589. return;
  24590. }
  24591. doDispatchAction.call(this, payload, opt.silent);
  24592. if (opt.flush) {
  24593. this._zr.flush(true);
  24594. }
  24595. else if (opt.flush !== false && env$1.browser.weChat) {
  24596. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24597. // hang when sliding page (on touch event), which cause that zr does not
  24598. // refresh util user interaction finished, which is not expected.
  24599. // But `dispatchAction` may be called too frequently when pan on touch
  24600. // screen, which impacts performance if do not throttle them.
  24601. this._throttledZrFlush();
  24602. }
  24603. flushPendingActions.call(this, opt.silent);
  24604. triggerUpdatedEvent.call(this, opt.silent);
  24605. };
  24606. function doDispatchAction(payload, silent) {
  24607. var payloadType = payload.type;
  24608. var escapeConnect = payload.escapeConnect;
  24609. var actionWrap = actions[payloadType];
  24610. var actionInfo = actionWrap.actionInfo;
  24611. var cptType = (actionInfo.update || 'update').split(':');
  24612. var updateMethod = cptType.pop();
  24613. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24614. this[IN_MAIN_PROCESS] = true;
  24615. var payloads = [payload];
  24616. var batched = false;
  24617. // Batch action
  24618. if (payload.batch) {
  24619. batched = true;
  24620. payloads = map(payload.batch, function (item) {
  24621. item = defaults(extend({}, item), payload);
  24622. item.batch = null;
  24623. return item;
  24624. });
  24625. }
  24626. var eventObjBatch = [];
  24627. var eventObj;
  24628. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24629. each(payloads, function (batchItem) {
  24630. // Action can specify the event by return it.
  24631. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24632. // Emit event outside
  24633. eventObj = eventObj || extend({}, batchItem);
  24634. // Convert type to eventType
  24635. eventObj.type = actionInfo.event || eventObj.type;
  24636. eventObjBatch.push(eventObj);
  24637. // light update does not perform data process, layout and visual.
  24638. if (isHighDown) {
  24639. // method, payload, mainType, subType
  24640. updateDirectly(this, updateMethod, batchItem, 'series');
  24641. }
  24642. else if (cptType) {
  24643. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24644. }
  24645. }, this);
  24646. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24647. // Still dirty
  24648. if (this[OPTION_UPDATED]) {
  24649. // FIXME Pass payload ?
  24650. prepare(this);
  24651. updateMethods.update.call(this, payload);
  24652. this[OPTION_UPDATED] = false;
  24653. }
  24654. else {
  24655. updateMethods[updateMethod].call(this, payload);
  24656. }
  24657. }
  24658. // Follow the rule of action batch
  24659. if (batched) {
  24660. eventObj = {
  24661. type: actionInfo.event || payloadType,
  24662. escapeConnect: escapeConnect,
  24663. batch: eventObjBatch
  24664. };
  24665. }
  24666. else {
  24667. eventObj = eventObjBatch[0];
  24668. }
  24669. this[IN_MAIN_PROCESS] = false;
  24670. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24671. }
  24672. function flushPendingActions(silent) {
  24673. var pendingActions = this._pendingActions;
  24674. while (pendingActions.length) {
  24675. var payload = pendingActions.shift();
  24676. doDispatchAction.call(this, payload, silent);
  24677. }
  24678. }
  24679. function triggerUpdatedEvent(silent) {
  24680. !silent && this.trigger('updated');
  24681. }
  24682. /**
  24683. * Event `rendered` is triggered when zr
  24684. * rendered. It is useful for realtime
  24685. * snapshot (reflect animation).
  24686. *
  24687. * Event `finished` is triggered when:
  24688. * (1) zrender rendering finished.
  24689. * (2) initial animation finished.
  24690. * (3) progressive rendering finished.
  24691. * (4) no pending action.
  24692. * (5) no delayed setOption needs to be processed.
  24693. */
  24694. function bindRenderedEvent(zr, ecIns) {
  24695. zr.on('rendered', function () {
  24696. ecIns.trigger('rendered');
  24697. // The `finished` event should not be triggered repeatly,
  24698. // so it should only be triggered when rendering indeed happend
  24699. // in zrender. (Consider the case that dipatchAction is keep
  24700. // triggering when mouse move).
  24701. if (
  24702. // Although zr is dirty if initial animation is not finished
  24703. // and this checking is called on frame, we also check
  24704. // animation finished for robustness.
  24705. zr.animation.isFinished()
  24706. && !ecIns[OPTION_UPDATED]
  24707. && !ecIns._scheduler.unfinished
  24708. && !ecIns._pendingActions.length
  24709. ) {
  24710. ecIns.trigger('finished');
  24711. }
  24712. });
  24713. }
  24714. /**
  24715. * @param {Object} params
  24716. * @param {number} params.seriesIndex
  24717. * @param {Array|TypedArray} params.data
  24718. */
  24719. echartsProto.appendData = function (params) {
  24720. if (this._disposed) {
  24721. disposedWarning(this.id);
  24722. return;
  24723. }
  24724. var seriesIndex = params.seriesIndex;
  24725. var ecModel = this.getModel();
  24726. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24727. if (__DEV__) {
  24728. assert(params.data && seriesModel);
  24729. }
  24730. seriesModel.appendData(params);
  24731. // Note: `appendData` does not support that update extent of coordinate
  24732. // system, util some scenario require that. In the expected usage of
  24733. // `appendData`, the initial extent of coordinate system should better
  24734. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24735. // the extent changed while `appendData`, the location of the painted
  24736. // graphic elements have to be changed, which make the usage of
  24737. // `appendData` meaningless.
  24738. this._scheduler.unfinished = true;
  24739. };
  24740. /**
  24741. * Register event
  24742. * @method
  24743. */
  24744. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  24745. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  24746. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  24747. /**
  24748. * Prepare view instances of charts and components
  24749. * @param {module:echarts/model/Global} ecModel
  24750. * @private
  24751. */
  24752. function prepareView(ecIns, type, ecModel, scheduler) {
  24753. var isComponent = type === 'component';
  24754. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24755. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24756. var zr = ecIns._zr;
  24757. var api = ecIns._api;
  24758. for (var i = 0; i < viewList.length; i++) {
  24759. viewList[i].__alive = false;
  24760. }
  24761. isComponent
  24762. ? ecModel.eachComponent(function (componentType, model) {
  24763. componentType !== 'series' && doPrepare(model);
  24764. })
  24765. : ecModel.eachSeries(doPrepare);
  24766. function doPrepare(model) {
  24767. // Consider: id same and type changed.
  24768. var viewId = '_ec_' + model.id + '_' + model.type;
  24769. var view = viewMap[viewId];
  24770. if (!view) {
  24771. var classType = parseClassType(model.type);
  24772. var Clazz = isComponent
  24773. ? Component.getClass(classType.main, classType.sub)
  24774. : Chart.getClass(classType.sub);
  24775. if (__DEV__) {
  24776. assert(Clazz, classType.sub + ' does not exist.');
  24777. }
  24778. view = new Clazz();
  24779. view.init(ecModel, api);
  24780. viewMap[viewId] = view;
  24781. viewList.push(view);
  24782. zr.add(view.group);
  24783. }
  24784. model.__viewId = view.__id = viewId;
  24785. view.__alive = true;
  24786. view.__model = model;
  24787. view.group.__ecComponentInfo = {
  24788. mainType: model.mainType,
  24789. index: model.componentIndex
  24790. };
  24791. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24792. }
  24793. for (var i = 0; i < viewList.length;) {
  24794. var view = viewList[i];
  24795. if (!view.__alive) {
  24796. !isComponent && view.renderTask.dispose();
  24797. zr.remove(view.group);
  24798. view.dispose(ecModel, api);
  24799. viewList.splice(i, 1);
  24800. delete viewMap[view.__id];
  24801. view.__id = view.group.__ecComponentInfo = null;
  24802. }
  24803. else {
  24804. i++;
  24805. }
  24806. }
  24807. }
  24808. // /**
  24809. // * Encode visual infomation from data after data processing
  24810. // *
  24811. // * @param {module:echarts/model/Global} ecModel
  24812. // * @param {object} layout
  24813. // * @param {boolean} [layoutFilter] `true`: only layout,
  24814. // * `false`: only not layout,
  24815. // * `null`/`undefined`: all.
  24816. // * @param {string} taskBaseTag
  24817. // * @private
  24818. // */
  24819. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24820. // each(visualFuncs, function (visual, index) {
  24821. // var isLayout = visual.isLayout;
  24822. // if (layoutFilter == null
  24823. // || (layoutFilter === false && !isLayout)
  24824. // || (layoutFilter === true && isLayout)
  24825. // ) {
  24826. // visual.func(ecModel, api, payload);
  24827. // }
  24828. // });
  24829. // }
  24830. function clearColorPalette(ecModel) {
  24831. ecModel.clearColorPalette();
  24832. ecModel.eachSeries(function (seriesModel) {
  24833. seriesModel.clearColorPalette();
  24834. });
  24835. }
  24836. function render(ecIns, ecModel, api, payload) {
  24837. renderComponents(ecIns, ecModel, api, payload);
  24838. each(ecIns._chartsViews, function (chart) {
  24839. chart.__alive = false;
  24840. });
  24841. renderSeries(ecIns, ecModel, api, payload);
  24842. // Remove groups of unrendered charts
  24843. each(ecIns._chartsViews, function (chart) {
  24844. if (!chart.__alive) {
  24845. chart.remove(ecModel, api);
  24846. }
  24847. });
  24848. }
  24849. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24850. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24851. var componentModel = componentView.__model;
  24852. componentView.render(componentModel, ecModel, api, payload);
  24853. updateZ(componentModel, componentView);
  24854. });
  24855. }
  24856. /**
  24857. * Render each chart and component
  24858. * @private
  24859. */
  24860. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24861. // Render all charts
  24862. var scheduler = ecIns._scheduler;
  24863. var unfinished;
  24864. ecModel.eachSeries(function (seriesModel) {
  24865. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24866. chartView.__alive = true;
  24867. var renderTask = chartView.renderTask;
  24868. scheduler.updatePayload(renderTask, payload);
  24869. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24870. renderTask.dirty();
  24871. }
  24872. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24873. chartView.group.silent = !!seriesModel.get('silent');
  24874. updateZ(seriesModel, chartView);
  24875. updateBlend(seriesModel, chartView);
  24876. });
  24877. scheduler.unfinished |= unfinished;
  24878. // If use hover layer
  24879. updateHoverLayerStatus(ecIns, ecModel);
  24880. // Add aria
  24881. aria(ecIns._zr.dom, ecModel);
  24882. }
  24883. function performPostUpdateFuncs(ecModel, api) {
  24884. each(postUpdateFuncs, function (func) {
  24885. func(ecModel, api);
  24886. });
  24887. }
  24888. var MOUSE_EVENT_NAMES = [
  24889. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24890. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24891. ];
  24892. /**
  24893. * @private
  24894. */
  24895. echartsProto._initEvents = function () {
  24896. each(MOUSE_EVENT_NAMES, function (eveName) {
  24897. var handler = function (e) {
  24898. var ecModel = this.getModel();
  24899. var el = e.target;
  24900. var params;
  24901. var isGlobalOut = eveName === 'globalout';
  24902. // no e.target when 'globalout'.
  24903. if (isGlobalOut) {
  24904. params = {};
  24905. }
  24906. else if (el && el.dataIndex != null) {
  24907. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24908. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24909. }
  24910. // If element has custom eventData of components
  24911. else if (el && el.eventData) {
  24912. params = extend({}, el.eventData);
  24913. }
  24914. // Contract: if params prepared in mouse event,
  24915. // these properties must be specified:
  24916. // {
  24917. // componentType: string (component main type)
  24918. // componentIndex: number
  24919. // }
  24920. // Otherwise event query can not work.
  24921. if (params) {
  24922. var componentType = params.componentType;
  24923. var componentIndex = params.componentIndex;
  24924. // Special handling for historic reason: when trigger by
  24925. // markLine/markPoint/markArea, the componentType is
  24926. // 'markLine'/'markPoint'/'markArea', but we should better
  24927. // enable them to be queried by seriesIndex, since their
  24928. // option is set in each series.
  24929. if (componentType === 'markLine'
  24930. || componentType === 'markPoint'
  24931. || componentType === 'markArea'
  24932. ) {
  24933. componentType = 'series';
  24934. componentIndex = params.seriesIndex;
  24935. }
  24936. var model = componentType && componentIndex != null
  24937. && ecModel.getComponent(componentType, componentIndex);
  24938. var view = model && this[
  24939. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24940. ][model.__viewId];
  24941. if (__DEV__) {
  24942. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24943. // be missed, otherwise there is no way to distinguish source component.
  24944. // See `dataFormat.getDataParams`.
  24945. if (!isGlobalOut && !(model && view)) {
  24946. console.warn('model or view can not be found by params');
  24947. }
  24948. }
  24949. params.event = e;
  24950. params.type = eveName;
  24951. this._ecEventProcessor.eventInfo = {
  24952. targetEl: el,
  24953. packedEvent: params,
  24954. model: model,
  24955. view: view
  24956. };
  24957. this.trigger(eveName, params);
  24958. }
  24959. };
  24960. // Consider that some component (like tooltip, brush, ...)
  24961. // register zr event handler, but user event handler might
  24962. // do anything, such as call `setOption` or `dispatchAction`,
  24963. // which probably update any of the content and probably
  24964. // cause problem if it is called previous other inner handlers.
  24965. handler.zrEventfulCallAtLast = true;
  24966. this._zr.on(eveName, handler, this);
  24967. }, this);
  24968. each(eventActionMap, function (actionType, eventType) {
  24969. this._messageCenter.on(eventType, function (event) {
  24970. this.trigger(eventType, event);
  24971. }, this);
  24972. }, this);
  24973. };
  24974. /**
  24975. * @return {boolean}
  24976. */
  24977. echartsProto.isDisposed = function () {
  24978. return this._disposed;
  24979. };
  24980. /**
  24981. * Clear
  24982. */
  24983. echartsProto.clear = function () {
  24984. if (this._disposed) {
  24985. disposedWarning(this.id);
  24986. return;
  24987. }
  24988. this.setOption({ series: [] }, true);
  24989. };
  24990. /**
  24991. * Dispose instance
  24992. */
  24993. echartsProto.dispose = function () {
  24994. if (this._disposed) {
  24995. disposedWarning(this.id);
  24996. return;
  24997. }
  24998. this._disposed = true;
  24999. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25000. var api = this._api;
  25001. var ecModel = this._model;
  25002. each(this._componentsViews, function (component) {
  25003. component.dispose(ecModel, api);
  25004. });
  25005. each(this._chartsViews, function (chart) {
  25006. chart.dispose(ecModel, api);
  25007. });
  25008. // Dispose after all views disposed
  25009. this._zr.dispose();
  25010. delete instances[this.id];
  25011. };
  25012. mixin(ECharts, Eventful);
  25013. function disposedWarning(id) {
  25014. if (__DEV__) {
  25015. console.warn('Instance ' + id + ' has been disposed');
  25016. }
  25017. }
  25018. function updateHoverLayerStatus(ecIns, ecModel) {
  25019. var zr = ecIns._zr;
  25020. var storage = zr.storage;
  25021. var elCount = 0;
  25022. storage.traverse(function (el) {
  25023. elCount++;
  25024. });
  25025. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  25026. ecModel.eachSeries(function (seriesModel) {
  25027. if (seriesModel.preventUsingHoverLayer) {
  25028. return;
  25029. }
  25030. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  25031. if (chartView.__alive) {
  25032. chartView.group.traverse(function (el) {
  25033. // Don't switch back.
  25034. el.useHoverLayer = true;
  25035. });
  25036. }
  25037. });
  25038. }
  25039. }
  25040. /**
  25041. * Update chart progressive and blend.
  25042. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25043. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25044. */
  25045. function updateBlend(seriesModel, chartView) {
  25046. var blendMode = seriesModel.get('blendMode') || null;
  25047. if (__DEV__) {
  25048. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  25049. console.warn('Only canvas support blendMode');
  25050. }
  25051. }
  25052. chartView.group.traverse(function (el) {
  25053. // FIXME marker and other components
  25054. if (!el.isGroup) {
  25055. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  25056. if (el.style.blend !== blendMode) {
  25057. el.setStyle('blend', blendMode);
  25058. }
  25059. }
  25060. if (el.eachPendingDisplayable) {
  25061. el.eachPendingDisplayable(function (displayable) {
  25062. displayable.setStyle('blend', blendMode);
  25063. });
  25064. }
  25065. });
  25066. }
  25067. /**
  25068. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  25069. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  25070. */
  25071. function updateZ(model, view) {
  25072. var z = model.get('z');
  25073. var zlevel = model.get('zlevel');
  25074. // Set z and zlevel
  25075. view.group.traverse(function (el) {
  25076. if (el.type !== 'group') {
  25077. z != null && (el.z = z);
  25078. zlevel != null && (el.zlevel = zlevel);
  25079. }
  25080. });
  25081. }
  25082. function createExtensionAPI(ecInstance) {
  25083. var coordSysMgr = ecInstance._coordSysMgr;
  25084. return extend(new ExtensionAPI(ecInstance), {
  25085. // Inject methods
  25086. getCoordinateSystems: bind(
  25087. coordSysMgr.getCoordinateSystems, coordSysMgr
  25088. ),
  25089. getComponentByElement: function (el) {
  25090. while (el) {
  25091. var modelInfo = el.__ecComponentInfo;
  25092. if (modelInfo != null) {
  25093. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  25094. }
  25095. el = el.parent;
  25096. }
  25097. }
  25098. });
  25099. }
  25100. /**
  25101. * @class
  25102. * Usage of query:
  25103. * `chart.on('click', query, handler);`
  25104. * The `query` can be:
  25105. * + The component type query string, only `mainType` or `mainType.subType`,
  25106. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  25107. * + The component query object, like:
  25108. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  25109. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  25110. * + The data query object, like:
  25111. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  25112. * + The other query object (cmponent customized query), like:
  25113. * `{element: 'some'}` (only available in custom series).
  25114. *
  25115. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  25116. * same as there is no such prop in the `query` object.
  25117. */
  25118. function EventProcessor() {
  25119. // These info required: targetEl, packedEvent, model, view
  25120. this.eventInfo;
  25121. }
  25122. EventProcessor.prototype = {
  25123. constructor: EventProcessor,
  25124. normalizeQuery: function (query) {
  25125. var cptQuery = {};
  25126. var dataQuery = {};
  25127. var otherQuery = {};
  25128. // `query` is `mainType` or `mainType.subType` of component.
  25129. if (isString(query)) {
  25130. var condCptType = parseClassType(query);
  25131. // `.main` and `.sub` may be ''.
  25132. cptQuery.mainType = condCptType.main || null;
  25133. cptQuery.subType = condCptType.sub || null;
  25134. }
  25135. // `query` is an object, convert to {mainType, index, name, id}.
  25136. else {
  25137. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25138. // can not be used in `compomentModel.filterForExposedEvent`.
  25139. var suffixes = ['Index', 'Name', 'Id'];
  25140. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25141. each$1(query, function (val, key) {
  25142. var reserved = false;
  25143. for (var i = 0; i < suffixes.length; i++) {
  25144. var propSuffix = suffixes[i];
  25145. var suffixPos = key.lastIndexOf(propSuffix);
  25146. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25147. var mainType = key.slice(0, suffixPos);
  25148. // Consider `dataIndex`.
  25149. if (mainType !== 'data') {
  25150. cptQuery.mainType = mainType;
  25151. cptQuery[propSuffix.toLowerCase()] = val;
  25152. reserved = true;
  25153. }
  25154. }
  25155. }
  25156. if (dataKeys.hasOwnProperty(key)) {
  25157. dataQuery[key] = val;
  25158. reserved = true;
  25159. }
  25160. if (!reserved) {
  25161. otherQuery[key] = val;
  25162. }
  25163. });
  25164. }
  25165. return {
  25166. cptQuery: cptQuery,
  25167. dataQuery: dataQuery,
  25168. otherQuery: otherQuery
  25169. };
  25170. },
  25171. filter: function (eventType, query, args) {
  25172. // They should be assigned before each trigger call.
  25173. var eventInfo = this.eventInfo;
  25174. if (!eventInfo) {
  25175. return true;
  25176. }
  25177. var targetEl = eventInfo.targetEl;
  25178. var packedEvent = eventInfo.packedEvent;
  25179. var model = eventInfo.model;
  25180. var view = eventInfo.view;
  25181. // For event like 'globalout'.
  25182. if (!model || !view) {
  25183. return true;
  25184. }
  25185. var cptQuery = query.cptQuery;
  25186. var dataQuery = query.dataQuery;
  25187. return check(cptQuery, model, 'mainType')
  25188. && check(cptQuery, model, 'subType')
  25189. && check(cptQuery, model, 'index', 'componentIndex')
  25190. && check(cptQuery, model, 'name')
  25191. && check(cptQuery, model, 'id')
  25192. && check(dataQuery, packedEvent, 'name')
  25193. && check(dataQuery, packedEvent, 'dataIndex')
  25194. && check(dataQuery, packedEvent, 'dataType')
  25195. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25196. eventType, query.otherQuery, targetEl, packedEvent
  25197. ));
  25198. function check(query, host, prop, propOnHost) {
  25199. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25200. }
  25201. },
  25202. afterTrigger: function () {
  25203. // Make sure the eventInfo wont be used in next trigger.
  25204. this.eventInfo = null;
  25205. }
  25206. };
  25207. /**
  25208. * @type {Object} key: actionType.
  25209. * @inner
  25210. */
  25211. var actions = {};
  25212. /**
  25213. * Map eventType to actionType
  25214. * @type {Object}
  25215. */
  25216. var eventActionMap = {};
  25217. /**
  25218. * Data processor functions of each stage
  25219. * @type {Array.<Object.<string, Function>>}
  25220. * @inner
  25221. */
  25222. var dataProcessorFuncs = [];
  25223. /**
  25224. * @type {Array.<Function>}
  25225. * @inner
  25226. */
  25227. var optionPreprocessorFuncs = [];
  25228. /**
  25229. * @type {Array.<Function>}
  25230. * @inner
  25231. */
  25232. var postUpdateFuncs = [];
  25233. /**
  25234. * Visual encoding functions of each stage
  25235. * @type {Array.<Object.<string, Function>>}
  25236. */
  25237. var visualFuncs = [];
  25238. /**
  25239. * Theme storage
  25240. * @type {Object.<key, Object>}
  25241. */
  25242. var themeStorage = {};
  25243. /**
  25244. * Loading effects
  25245. */
  25246. var loadingEffects = {};
  25247. var instances = {};
  25248. var connectedGroups = {};
  25249. var idBase = new Date() - 0;
  25250. var groupIdBase = new Date() - 0;
  25251. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25252. function enableConnect(chart) {
  25253. var STATUS_PENDING = 0;
  25254. var STATUS_UPDATING = 1;
  25255. var STATUS_UPDATED = 2;
  25256. var STATUS_KEY = '__connectUpdateStatus';
  25257. function updateConnectedChartsStatus(charts, status) {
  25258. for (var i = 0; i < charts.length; i++) {
  25259. var otherChart = charts[i];
  25260. otherChart[STATUS_KEY] = status;
  25261. }
  25262. }
  25263. each(eventActionMap, function (actionType, eventType) {
  25264. chart._messageCenter.on(eventType, function (event) {
  25265. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25266. if (event && event.escapeConnect) {
  25267. return;
  25268. }
  25269. var action = chart.makeActionFromEvent(event);
  25270. var otherCharts = [];
  25271. each(instances, function (otherChart) {
  25272. if (otherChart !== chart && otherChart.group === chart.group) {
  25273. otherCharts.push(otherChart);
  25274. }
  25275. });
  25276. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25277. each(otherCharts, function (otherChart) {
  25278. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25279. otherChart.dispatchAction(action);
  25280. }
  25281. });
  25282. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25283. }
  25284. });
  25285. });
  25286. }
  25287. /**
  25288. * @param {HTMLElement} dom
  25289. * @param {Object} [theme]
  25290. * @param {Object} opts
  25291. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25292. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25293. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25294. * Can be 'auto' (the same as null/undefined)
  25295. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25296. * Can be 'auto' (the same as null/undefined)
  25297. */
  25298. function init(dom, theme$$1, opts) {
  25299. if (__DEV__) {
  25300. // Check version
  25301. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25302. throw new Error(
  25303. 'zrender/src ' + version$1
  25304. + ' is too old for ECharts ' + version
  25305. + '. Current version need ZRender '
  25306. + dependencies.zrender + '+'
  25307. );
  25308. }
  25309. if (!dom) {
  25310. throw new Error('Initialize failed: invalid dom.');
  25311. }
  25312. }
  25313. var existInstance = getInstanceByDom(dom);
  25314. if (existInstance) {
  25315. if (__DEV__) {
  25316. console.warn('There is a chart instance already initialized on the dom.');
  25317. }
  25318. return existInstance;
  25319. }
  25320. if (__DEV__) {
  25321. if (isDom(dom)
  25322. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25323. && (
  25324. (!dom.clientWidth && (!opts || opts.width == null))
  25325. || (!dom.clientHeight && (!opts || opts.height == null))
  25326. )
  25327. ) {
  25328. console.warn('Can\'t get DOM width or height. Please check '
  25329. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25330. + 'For example, you may need to call this in the callback '
  25331. + 'of window.onload.');
  25332. }
  25333. }
  25334. var chart = new ECharts(dom, theme$$1, opts);
  25335. chart.id = 'ec_' + idBase++;
  25336. instances[chart.id] = chart;
  25337. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25338. enableConnect(chart);
  25339. return chart;
  25340. }
  25341. /**
  25342. * @return {string|Array.<module:echarts~ECharts>} groupId
  25343. */
  25344. function connect(groupId) {
  25345. // Is array of charts
  25346. if (isArray(groupId)) {
  25347. var charts = groupId;
  25348. groupId = null;
  25349. // If any chart has group
  25350. each(charts, function (chart) {
  25351. if (chart.group != null) {
  25352. groupId = chart.group;
  25353. }
  25354. });
  25355. groupId = groupId || ('g_' + groupIdBase++);
  25356. each(charts, function (chart) {
  25357. chart.group = groupId;
  25358. });
  25359. }
  25360. connectedGroups[groupId] = true;
  25361. return groupId;
  25362. }
  25363. /**
  25364. * @DEPRECATED
  25365. * @return {string} groupId
  25366. */
  25367. function disConnect(groupId) {
  25368. connectedGroups[groupId] = false;
  25369. }
  25370. /**
  25371. * @return {string} groupId
  25372. */
  25373. var disconnect = disConnect;
  25374. /**
  25375. * Dispose a chart instance
  25376. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25377. */
  25378. function dispose(chart) {
  25379. if (typeof chart === 'string') {
  25380. chart = instances[chart];
  25381. }
  25382. else if (!(chart instanceof ECharts)) {
  25383. // Try to treat as dom
  25384. chart = getInstanceByDom(chart);
  25385. }
  25386. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25387. chart.dispose();
  25388. }
  25389. }
  25390. /**
  25391. * @param {HTMLElement} dom
  25392. * @return {echarts~ECharts}
  25393. */
  25394. function getInstanceByDom(dom) {
  25395. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25396. }
  25397. /**
  25398. * @param {string} key
  25399. * @return {echarts~ECharts}
  25400. */
  25401. function getInstanceById(key) {
  25402. return instances[key];
  25403. }
  25404. /**
  25405. * Register theme
  25406. */
  25407. function registerTheme(name, theme$$1) {
  25408. themeStorage[name] = theme$$1;
  25409. }
  25410. /**
  25411. * Register option preprocessor
  25412. * @param {Function} preprocessorFunc
  25413. */
  25414. function registerPreprocessor(preprocessorFunc) {
  25415. optionPreprocessorFuncs.push(preprocessorFunc);
  25416. }
  25417. /**
  25418. * @param {number} [priority=1000]
  25419. * @param {Object|Function} processor
  25420. */
  25421. function registerProcessor(priority, processor) {
  25422. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25423. }
  25424. /**
  25425. * Register postUpdater
  25426. * @param {Function} postUpdateFunc
  25427. */
  25428. function registerPostUpdate(postUpdateFunc) {
  25429. postUpdateFuncs.push(postUpdateFunc);
  25430. }
  25431. /**
  25432. * Usage:
  25433. * registerAction('someAction', 'someEvent', function () { ... });
  25434. * registerAction('someAction', function () { ... });
  25435. * registerAction(
  25436. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25437. * function () { ... }
  25438. * );
  25439. *
  25440. * @param {(string|Object)} actionInfo
  25441. * @param {string} actionInfo.type
  25442. * @param {string} [actionInfo.event]
  25443. * @param {string} [actionInfo.update]
  25444. * @param {string} [eventName]
  25445. * @param {Function} action
  25446. */
  25447. function registerAction(actionInfo, eventName, action) {
  25448. if (typeof eventName === 'function') {
  25449. action = eventName;
  25450. eventName = '';
  25451. }
  25452. var actionType = isObject(actionInfo)
  25453. ? actionInfo.type
  25454. : ([actionInfo, actionInfo = {
  25455. event: eventName
  25456. }][0]);
  25457. // Event name is all lowercase
  25458. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25459. eventName = actionInfo.event;
  25460. // Validate action type and event name.
  25461. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25462. if (!actions[actionType]) {
  25463. actions[actionType] = {action: action, actionInfo: actionInfo};
  25464. }
  25465. eventActionMap[eventName] = actionType;
  25466. }
  25467. /**
  25468. * @param {string} type
  25469. * @param {*} CoordinateSystem
  25470. */
  25471. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25472. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25473. }
  25474. /**
  25475. * Get dimensions of specified coordinate system.
  25476. * @param {string} type
  25477. * @return {Array.<string|Object>}
  25478. */
  25479. function getCoordinateSystemDimensions(type) {
  25480. var coordSysCreator = CoordinateSystemManager.get(type);
  25481. if (coordSysCreator) {
  25482. return coordSysCreator.getDimensionsInfo
  25483. ? coordSysCreator.getDimensionsInfo()
  25484. : coordSysCreator.dimensions.slice();
  25485. }
  25486. }
  25487. /**
  25488. * Layout is a special stage of visual encoding
  25489. * Most visual encoding like color are common for different chart
  25490. * But each chart has it's own layout algorithm
  25491. *
  25492. * @param {number} [priority=1000]
  25493. * @param {Function} layoutTask
  25494. */
  25495. function registerLayout(priority, layoutTask) {
  25496. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25497. }
  25498. /**
  25499. * @param {number} [priority=3000]
  25500. * @param {module:echarts/stream/Task} visualTask
  25501. */
  25502. function registerVisual(priority, visualTask) {
  25503. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25504. }
  25505. /**
  25506. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25507. */
  25508. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25509. if (isFunction(priority) || isObject(priority)) {
  25510. fn = priority;
  25511. priority = defaultPriority;
  25512. }
  25513. if (__DEV__) {
  25514. if (isNaN(priority) || priority == null) {
  25515. throw new Error('Illegal priority');
  25516. }
  25517. // Check duplicate
  25518. each(targetList, function (wrap) {
  25519. assert(wrap.__raw !== fn);
  25520. });
  25521. }
  25522. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25523. stageHandler.__prio = priority;
  25524. stageHandler.__raw = fn;
  25525. targetList.push(stageHandler);
  25526. return stageHandler;
  25527. }
  25528. /**
  25529. * @param {string} name
  25530. */
  25531. function registerLoading(name, loadingFx) {
  25532. loadingEffects[name] = loadingFx;
  25533. }
  25534. /**
  25535. * @param {Object} opts
  25536. * @param {string} [superClass]
  25537. */
  25538. function extendComponentModel(opts/*, superClass*/) {
  25539. // var Clazz = ComponentModel;
  25540. // if (superClass) {
  25541. // var classType = parseClassType(superClass);
  25542. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25543. // }
  25544. return ComponentModel.extend(opts);
  25545. }
  25546. /**
  25547. * @param {Object} opts
  25548. * @param {string} [superClass]
  25549. */
  25550. function extendComponentView(opts/*, superClass*/) {
  25551. // var Clazz = ComponentView;
  25552. // if (superClass) {
  25553. // var classType = parseClassType(superClass);
  25554. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25555. // }
  25556. return Component.extend(opts);
  25557. }
  25558. /**
  25559. * @param {Object} opts
  25560. * @param {string} [superClass]
  25561. */
  25562. function extendSeriesModel(opts/*, superClass*/) {
  25563. // var Clazz = SeriesModel;
  25564. // if (superClass) {
  25565. // superClass = 'series.' + superClass.replace('series.', '');
  25566. // var classType = parseClassType(superClass);
  25567. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25568. // }
  25569. return SeriesModel.extend(opts);
  25570. }
  25571. /**
  25572. * @param {Object} opts
  25573. * @param {string} [superClass]
  25574. */
  25575. function extendChartView(opts/*, superClass*/) {
  25576. // var Clazz = ChartView;
  25577. // if (superClass) {
  25578. // superClass = superClass.replace('series.', '');
  25579. // var classType = parseClassType(superClass);
  25580. // Clazz = ChartView.getClass(classType.main, true);
  25581. // }
  25582. return Chart.extend(opts);
  25583. }
  25584. /**
  25585. * ZRender need a canvas context to do measureText.
  25586. * But in node environment canvas may be created by node-canvas.
  25587. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25588. *
  25589. * Be careful of using it in the browser.
  25590. *
  25591. * @param {Function} creator
  25592. * @example
  25593. * var Canvas = require('canvas');
  25594. * var echarts = require('echarts');
  25595. * echarts.setCanvasCreator(function () {
  25596. * // Small size is enough.
  25597. * return new Canvas(32, 32);
  25598. * });
  25599. */
  25600. function setCanvasCreator(creator) {
  25601. $override('createCanvas', creator);
  25602. }
  25603. /**
  25604. * @param {string} mapName
  25605. * @param {Array.<Object>|Object|string} geoJson
  25606. * @param {Object} [specialAreas]
  25607. *
  25608. * @example GeoJSON
  25609. * $.get('USA.json', function (geoJson) {
  25610. * echarts.registerMap('USA', geoJson);
  25611. * // Or
  25612. * echarts.registerMap('USA', {
  25613. * geoJson: geoJson,
  25614. * specialAreas: {}
  25615. * })
  25616. * });
  25617. *
  25618. * $.get('airport.svg', function (svg) {
  25619. * echarts.registerMap('airport', {
  25620. * svg: svg
  25621. * }
  25622. * });
  25623. *
  25624. * echarts.registerMap('eu', [
  25625. * {svg: eu-topographic.svg},
  25626. * {geoJSON: eu.json}
  25627. * ])
  25628. */
  25629. function registerMap(mapName, geoJson, specialAreas) {
  25630. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25631. }
  25632. /**
  25633. * @param {string} mapName
  25634. * @return {Object}
  25635. */
  25636. function getMap(mapName) {
  25637. // For backward compatibility, only return the first one.
  25638. var records = mapDataStorage.retrieveMap(mapName);
  25639. return records && records[0] && {
  25640. geoJson: records[0].geoJSON,
  25641. specialAreas: records[0].specialAreas
  25642. };
  25643. }
  25644. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25645. registerPreprocessor(backwardCompat);
  25646. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  25647. registerLoading('default', loadingDefault);
  25648. // Default actions
  25649. registerAction({
  25650. type: 'highlight',
  25651. event: 'highlight',
  25652. update: 'highlight'
  25653. }, noop);
  25654. registerAction({
  25655. type: 'downplay',
  25656. event: 'downplay',
  25657. update: 'downplay'
  25658. }, noop);
  25659. // Default theme
  25660. registerTheme('light', lightTheme);
  25661. registerTheme('dark', theme);
  25662. // For backward compatibility, where the namespace `dataTool` will
  25663. // be mounted on `echarts` is the extension `dataTool` is imported.
  25664. var dataTool = {};
  25665. /*
  25666. * Licensed to the Apache Software Foundation (ASF) under one
  25667. * or more contributor license agreements. See the NOTICE file
  25668. * distributed with this work for additional information
  25669. * regarding copyright ownership. The ASF licenses this file
  25670. * to you under the Apache License, Version 2.0 (the
  25671. * "License"); you may not use this file except in compliance
  25672. * with the License. You may obtain a copy of the License at
  25673. *
  25674. * http://www.apache.org/licenses/LICENSE-2.0
  25675. *
  25676. * Unless required by applicable law or agreed to in writing,
  25677. * software distributed under the License is distributed on an
  25678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25679. * KIND, either express or implied. See the License for the
  25680. * specific language governing permissions and limitations
  25681. * under the License.
  25682. */
  25683. function defaultKeyGetter(item) {
  25684. return item;
  25685. }
  25686. /**
  25687. * @param {Array} oldArr
  25688. * @param {Array} newArr
  25689. * @param {Function} oldKeyGetter
  25690. * @param {Function} newKeyGetter
  25691. * @param {Object} [context] Can be visited by this.context in callback.
  25692. */
  25693. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25694. this._old = oldArr;
  25695. this._new = newArr;
  25696. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25697. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25698. this.context = context;
  25699. }
  25700. DataDiffer.prototype = {
  25701. constructor: DataDiffer,
  25702. /**
  25703. * Callback function when add a data
  25704. */
  25705. add: function (func) {
  25706. this._add = func;
  25707. return this;
  25708. },
  25709. /**
  25710. * Callback function when update a data
  25711. */
  25712. update: function (func) {
  25713. this._update = func;
  25714. return this;
  25715. },
  25716. /**
  25717. * Callback function when remove a data
  25718. */
  25719. remove: function (func) {
  25720. this._remove = func;
  25721. return this;
  25722. },
  25723. execute: function () {
  25724. var oldArr = this._old;
  25725. var newArr = this._new;
  25726. var oldDataIndexMap = {};
  25727. var newDataIndexMap = {};
  25728. var oldDataKeyArr = [];
  25729. var newDataKeyArr = [];
  25730. var i;
  25731. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25732. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25733. for (i = 0; i < oldArr.length; i++) {
  25734. var key = oldDataKeyArr[i];
  25735. var idx = newDataIndexMap[key];
  25736. // idx can never be empty array here. see 'set null' logic below.
  25737. if (idx != null) {
  25738. // Consider there is duplicate key (for example, use dataItem.name as key).
  25739. // We should make sure every item in newArr and oldArr can be visited.
  25740. var len = idx.length;
  25741. if (len) {
  25742. len === 1 && (newDataIndexMap[key] = null);
  25743. idx = idx.shift();
  25744. }
  25745. else {
  25746. newDataIndexMap[key] = null;
  25747. }
  25748. this._update && this._update(idx, i);
  25749. }
  25750. else {
  25751. this._remove && this._remove(i);
  25752. }
  25753. }
  25754. for (var i = 0; i < newDataKeyArr.length; i++) {
  25755. var key = newDataKeyArr[i];
  25756. if (newDataIndexMap.hasOwnProperty(key)) {
  25757. var idx = newDataIndexMap[key];
  25758. if (idx == null) {
  25759. continue;
  25760. }
  25761. // idx can never be empty array here. see 'set null' logic above.
  25762. if (!idx.length) {
  25763. this._add && this._add(idx);
  25764. }
  25765. else {
  25766. for (var j = 0, len = idx.length; j < len; j++) {
  25767. this._add && this._add(idx[j]);
  25768. }
  25769. }
  25770. }
  25771. }
  25772. }
  25773. };
  25774. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25775. for (var i = 0; i < arr.length; i++) {
  25776. // Add prefix to avoid conflict with Object.prototype.
  25777. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25778. var existence = map[key];
  25779. if (existence == null) {
  25780. keyArr.push(key);
  25781. map[key] = i;
  25782. }
  25783. else {
  25784. if (!existence.length) {
  25785. map[key] = existence = [existence];
  25786. }
  25787. existence.push(i);
  25788. }
  25789. }
  25790. }
  25791. /*
  25792. * Licensed to the Apache Software Foundation (ASF) under one
  25793. * or more contributor license agreements. See the NOTICE file
  25794. * distributed with this work for additional information
  25795. * regarding copyright ownership. The ASF licenses this file
  25796. * to you under the Apache License, Version 2.0 (the
  25797. * "License"); you may not use this file except in compliance
  25798. * with the License. You may obtain a copy of the License at
  25799. *
  25800. * http://www.apache.org/licenses/LICENSE-2.0
  25801. *
  25802. * Unless required by applicable law or agreed to in writing,
  25803. * software distributed under the License is distributed on an
  25804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25805. * KIND, either express or implied. See the License for the
  25806. * specific language governing permissions and limitations
  25807. * under the License.
  25808. */
  25809. var OTHER_DIMENSIONS = createHashMap([
  25810. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25811. ]);
  25812. function summarizeDimensions(data) {
  25813. var summary = {};
  25814. var encode = summary.encode = {};
  25815. var notExtraCoordDimMap = createHashMap();
  25816. var defaultedLabel = [];
  25817. var defaultedTooltip = [];
  25818. // See the comment of `List.js#userOutput`.
  25819. var userOutput = summary.userOutput = {
  25820. dimensionNames: data.dimensions.slice(),
  25821. encode: {}
  25822. };
  25823. each$1(data.dimensions, function (dimName) {
  25824. var dimItem = data.getDimensionInfo(dimName);
  25825. var coordDim = dimItem.coordDim;
  25826. if (coordDim) {
  25827. if (__DEV__) {
  25828. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25829. }
  25830. var coordDimIndex = dimItem.coordDimIndex;
  25831. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  25832. if (!dimItem.isExtraCoord) {
  25833. notExtraCoordDimMap.set(coordDim, 1);
  25834. // Use the last coord dim (and label friendly) as default label,
  25835. // because when dataset is used, it is hard to guess which dimension
  25836. // can be value dimension. If both show x, y on label is not look good,
  25837. // and conventionally y axis is focused more.
  25838. if (mayLabelDimType(dimItem.type)) {
  25839. defaultedLabel[0] = dimName;
  25840. }
  25841. // User output encode do not contain generated coords.
  25842. // And it only has index. User can use index to retrieve value from the raw item array.
  25843. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  25844. }
  25845. if (dimItem.defaultTooltip) {
  25846. defaultedTooltip.push(dimName);
  25847. }
  25848. }
  25849. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25850. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  25851. var dimIndex = dimItem.otherDims[otherDim];
  25852. if (dimIndex != null && dimIndex !== false) {
  25853. encodeArr[dimIndex] = dimItem.name;
  25854. }
  25855. });
  25856. });
  25857. var dataDimsOnCoord = [];
  25858. var encodeFirstDimNotExtra = {};
  25859. notExtraCoordDimMap.each(function (v, coordDim) {
  25860. var dimArr = encode[coordDim];
  25861. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25862. // But should fix the case that radar axes: simplify the logic
  25863. // of `completeDimension`, remove `extraPrefix`.
  25864. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25865. // Not necessary to remove duplicate, because a data
  25866. // dim canot on more than one coordDim.
  25867. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25868. });
  25869. summary.dataDimsOnCoord = dataDimsOnCoord;
  25870. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25871. var encodeLabel = encode.label;
  25872. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25873. // in this way. Use label.formatter instead. May be remove this approach someday.
  25874. if (encodeLabel && encodeLabel.length) {
  25875. defaultedLabel = encodeLabel.slice();
  25876. }
  25877. var encodeTooltip = encode.tooltip;
  25878. if (encodeTooltip && encodeTooltip.length) {
  25879. defaultedTooltip = encodeTooltip.slice();
  25880. }
  25881. else if (!defaultedTooltip.length) {
  25882. defaultedTooltip = defaultedLabel.slice();
  25883. }
  25884. encode.defaultedLabel = defaultedLabel;
  25885. encode.defaultedTooltip = defaultedTooltip;
  25886. return summary;
  25887. }
  25888. function getOrCreateEncodeArr(encode, dim) {
  25889. if (!encode.hasOwnProperty(dim)) {
  25890. encode[dim] = [];
  25891. }
  25892. return encode[dim];
  25893. }
  25894. function getDimensionTypeByAxis(axisType) {
  25895. return axisType === 'category'
  25896. ? 'ordinal'
  25897. : axisType === 'time'
  25898. ? 'time'
  25899. : 'float';
  25900. }
  25901. function mayLabelDimType(dimType) {
  25902. // In most cases, ordinal and time do not suitable for label.
  25903. // Ordinal info can be displayed on axis. Time is too long.
  25904. return !(dimType === 'ordinal' || dimType === 'time');
  25905. }
  25906. // function findTheLastDimMayLabel(data) {
  25907. // // Get last value dim
  25908. // var dimensions = data.dimensions.slice();
  25909. // var valueType;
  25910. // var valueDim;
  25911. // while (dimensions.length && (
  25912. // valueDim = dimensions.pop(),
  25913. // valueType = data.getDimensionInfo(valueDim).type,
  25914. // valueType === 'ordinal' || valueType === 'time'
  25915. // )) {} // jshint ignore:line
  25916. // return valueDim;
  25917. // }
  25918. /*
  25919. * Licensed to the Apache Software Foundation (ASF) under one
  25920. * or more contributor license agreements. See the NOTICE file
  25921. * distributed with this work for additional information
  25922. * regarding copyright ownership. The ASF licenses this file
  25923. * to you under the Apache License, Version 2.0 (the
  25924. * "License"); you may not use this file except in compliance
  25925. * with the License. You may obtain a copy of the License at
  25926. *
  25927. * http://www.apache.org/licenses/LICENSE-2.0
  25928. *
  25929. * Unless required by applicable law or agreed to in writing,
  25930. * software distributed under the License is distributed on an
  25931. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25932. * KIND, either express or implied. See the License for the
  25933. * specific language governing permissions and limitations
  25934. * under the License.
  25935. */
  25936. /**
  25937. * @class
  25938. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  25939. */
  25940. function DataDimensionInfo(opt) {
  25941. if (opt != null) {
  25942. extend(this, opt);
  25943. }
  25944. /**
  25945. * Dimension name.
  25946. * Mandatory.
  25947. * @type {string}
  25948. */
  25949. // this.name;
  25950. /**
  25951. * The origin name in dimsDef, see source helper.
  25952. * If displayName given, the tooltip will displayed vertically.
  25953. * Optional.
  25954. * @type {string}
  25955. */
  25956. // this.displayName;
  25957. /**
  25958. * Which coordSys dimension this dimension mapped to.
  25959. * A `coordDim` can be a "coordSysDim" that the coordSys required
  25960. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  25961. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  25962. * (That is determined by whether `isExtraCoord` is `true`).
  25963. * Mandatory.
  25964. * @type {string}
  25965. */
  25966. // this.coordDim;
  25967. /**
  25968. * The index of this dimension in `series.encode[coordDim]`.
  25969. * Mandatory.
  25970. * @type {number}
  25971. */
  25972. // this.coordDimIndex;
  25973. /**
  25974. * Dimension type. The enumerable values are the key of
  25975. * `dataCtors` of `data/List`.
  25976. * Optional.
  25977. * @type {string}
  25978. */
  25979. // this.type;
  25980. /**
  25981. * This index of this dimension info in `data/List#_dimensionInfos`.
  25982. * Mandatory after added to `data/List`.
  25983. * @type {number}
  25984. */
  25985. // this.index;
  25986. /**
  25987. * The format of `otherDims` is:
  25988. * ```js
  25989. * {
  25990. * tooltip: number optional,
  25991. * label: number optional,
  25992. * itemName: number optional,
  25993. * seriesName: number optional,
  25994. * }
  25995. * ```
  25996. *
  25997. * A `series.encode` can specified these fields:
  25998. * ```js
  25999. * encode: {
  26000. * // "3, 1, 5" is the index of data dimension.
  26001. * tooltip: [3, 1, 5],
  26002. * label: [0, 3],
  26003. * ...
  26004. * }
  26005. * ```
  26006. * `otherDims` is the parse result of the `series.encode` above, like:
  26007. * ```js
  26008. * // Suppose the index of this data dimension is `3`.
  26009. * this.otherDims = {
  26010. * // `3` is at the index `0` of the `encode.tooltip`
  26011. * tooltip: 0,
  26012. * // `3` is at the index `1` of the `encode.tooltip`
  26013. * label: 1
  26014. * };
  26015. * ```
  26016. *
  26017. * This prop should never be `null`/`undefined` after initialized.
  26018. * @type {Object}
  26019. */
  26020. this.otherDims = {};
  26021. /**
  26022. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  26023. * "coordSys" required.
  26024. * Mandatory.
  26025. * @type {boolean}
  26026. */
  26027. // this.isExtraCoord;
  26028. /**
  26029. * @type {module:data/OrdinalMeta}
  26030. */
  26031. // this.ordinalMeta;
  26032. /**
  26033. * Whether to create inverted indices.
  26034. * @type {boolean}
  26035. */
  26036. // this.createInvertedIndices;
  26037. }
  26038. /*
  26039. * Licensed to the Apache Software Foundation (ASF) under one
  26040. * or more contributor license agreements. See the NOTICE file
  26041. * distributed with this work for additional information
  26042. * regarding copyright ownership. The ASF licenses this file
  26043. * to you under the Apache License, Version 2.0 (the
  26044. * "License"); you may not use this file except in compliance
  26045. * with the License. You may obtain a copy of the License at
  26046. *
  26047. * http://www.apache.org/licenses/LICENSE-2.0
  26048. *
  26049. * Unless required by applicable law or agreed to in writing,
  26050. * software distributed under the License is distributed on an
  26051. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26052. * KIND, either express or implied. See the License for the
  26053. * specific language governing permissions and limitations
  26054. * under the License.
  26055. */
  26056. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  26057. /**
  26058. * List for data storage
  26059. * @module echarts/data/List
  26060. */
  26061. var isObject$4 = isObject$1;
  26062. var UNDEFINED = 'undefined';
  26063. var INDEX_NOT_FOUND = -1;
  26064. // Use prefix to avoid index to be the same as otherIdList[idx],
  26065. // which will cause weird udpate animation.
  26066. var ID_PREFIX = 'e\0\0';
  26067. var dataCtors = {
  26068. 'float': typeof Float64Array === UNDEFINED
  26069. ? Array : Float64Array,
  26070. 'int': typeof Int32Array === UNDEFINED
  26071. ? Array : Int32Array,
  26072. // Ordinal data type can be string or int
  26073. 'ordinal': Array,
  26074. 'number': Array,
  26075. 'time': Array
  26076. };
  26077. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  26078. // different from the Ctor of typed array.
  26079. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  26080. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  26081. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  26082. function getIndicesCtor(list) {
  26083. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  26084. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  26085. }
  26086. function cloneChunk(originalChunk) {
  26087. var Ctor = originalChunk.constructor;
  26088. // Only shallow clone is enough when Array.
  26089. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  26090. }
  26091. var TRANSFERABLE_PROPERTIES = [
  26092. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  26093. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  26094. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  26095. ];
  26096. var CLONE_PROPERTIES = [
  26097. '_extent', '_approximateExtent', '_rawExtent'
  26098. ];
  26099. function transferProperties(target, source) {
  26100. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  26101. if (source.hasOwnProperty(propName)) {
  26102. target[propName] = source[propName];
  26103. }
  26104. });
  26105. target.__wrappedMethods = source.__wrappedMethods;
  26106. each$1(CLONE_PROPERTIES, function (propName) {
  26107. target[propName] = clone(source[propName]);
  26108. });
  26109. target._calculationInfo = extend(source._calculationInfo);
  26110. }
  26111. /**
  26112. * @constructor
  26113. * @alias module:echarts/data/List
  26114. *
  26115. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  26116. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  26117. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  26118. * @param {module:echarts/model/Model} hostModel
  26119. */
  26120. var List = function (dimensions, hostModel) {
  26121. dimensions = dimensions || ['x', 'y'];
  26122. var dimensionInfos = {};
  26123. var dimensionNames = [];
  26124. var invertedIndicesMap = {};
  26125. for (var i = 0; i < dimensions.length; i++) {
  26126. // Use the original dimensions[i], where other flag props may exists.
  26127. var dimensionInfo = dimensions[i];
  26128. if (isString(dimensionInfo)) {
  26129. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26130. }
  26131. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26132. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26133. }
  26134. var dimensionName = dimensionInfo.name;
  26135. dimensionInfo.type = dimensionInfo.type || 'float';
  26136. if (!dimensionInfo.coordDim) {
  26137. dimensionInfo.coordDim = dimensionName;
  26138. dimensionInfo.coordDimIndex = 0;
  26139. }
  26140. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26141. dimensionNames.push(dimensionName);
  26142. dimensionInfos[dimensionName] = dimensionInfo;
  26143. dimensionInfo.index = i;
  26144. if (dimensionInfo.createInvertedIndices) {
  26145. invertedIndicesMap[dimensionName] = [];
  26146. }
  26147. }
  26148. /**
  26149. * @readOnly
  26150. * @type {Array.<string>}
  26151. */
  26152. this.dimensions = dimensionNames;
  26153. /**
  26154. * Infomation of each data dimension, like data type.
  26155. * @type {Object}
  26156. */
  26157. this._dimensionInfos = dimensionInfos;
  26158. /**
  26159. * @type {module:echarts/model/Model}
  26160. */
  26161. this.hostModel = hostModel;
  26162. /**
  26163. * @type {module:echarts/model/Model}
  26164. */
  26165. this.dataType;
  26166. /**
  26167. * Indices stores the indices of data subset after filtered.
  26168. * This data subset will be used in chart.
  26169. * @type {Array.<number>}
  26170. * @readOnly
  26171. */
  26172. this._indices = null;
  26173. this._count = 0;
  26174. this._rawCount = 0;
  26175. /**
  26176. * Data storage
  26177. * @type {Object.<key, Array.<TypedArray|Array>>}
  26178. * @private
  26179. */
  26180. this._storage = {};
  26181. /**
  26182. * @type {Array.<string>}
  26183. */
  26184. this._nameList = [];
  26185. /**
  26186. * @type {Array.<string>}
  26187. */
  26188. this._idList = [];
  26189. /**
  26190. * Models of data option is stored sparse for optimizing memory cost
  26191. * @type {Array.<module:echarts/model/Model>}
  26192. * @private
  26193. */
  26194. this._optionModels = [];
  26195. /**
  26196. * Global visual properties after visual coding
  26197. * @type {Object}
  26198. * @private
  26199. */
  26200. this._visual = {};
  26201. /**
  26202. * Globel layout properties.
  26203. * @type {Object}
  26204. * @private
  26205. */
  26206. this._layout = {};
  26207. /**
  26208. * Item visual properties after visual coding
  26209. * @type {Array.<Object>}
  26210. * @private
  26211. */
  26212. this._itemVisuals = [];
  26213. /**
  26214. * Key: visual type, Value: boolean
  26215. * @type {Object}
  26216. * @readOnly
  26217. */
  26218. this.hasItemVisual = {};
  26219. /**
  26220. * Item layout properties after layout
  26221. * @type {Array.<Object>}
  26222. * @private
  26223. */
  26224. this._itemLayouts = [];
  26225. /**
  26226. * Graphic elemnents
  26227. * @type {Array.<module:zrender/Element>}
  26228. * @private
  26229. */
  26230. this._graphicEls = [];
  26231. /**
  26232. * Max size of each chunk.
  26233. * @type {number}
  26234. * @private
  26235. */
  26236. this._chunkSize = 1e5;
  26237. /**
  26238. * @type {number}
  26239. * @private
  26240. */
  26241. this._chunkCount = 0;
  26242. /**
  26243. * @type {Array.<Array|Object>}
  26244. * @private
  26245. */
  26246. this._rawData;
  26247. /**
  26248. * Raw extent will not be cloned, but only transfered.
  26249. * It will not be calculated util needed.
  26250. * key: dim,
  26251. * value: {end: number, extent: Array.<number>}
  26252. * @type {Object}
  26253. * @private
  26254. */
  26255. this._rawExtent = {};
  26256. /**
  26257. * @type {Object}
  26258. * @private
  26259. */
  26260. this._extent = {};
  26261. /**
  26262. * key: dim
  26263. * value: extent
  26264. * @type {Object}
  26265. * @private
  26266. */
  26267. this._approximateExtent = {};
  26268. /**
  26269. * Cache summary info for fast visit. See "dimensionHelper".
  26270. * @type {Object}
  26271. * @private
  26272. */
  26273. this._dimensionsSummary = summarizeDimensions(this);
  26274. /**
  26275. * @type {Object.<Array|TypedArray>}
  26276. * @private
  26277. */
  26278. this._invertedIndicesMap = invertedIndicesMap;
  26279. /**
  26280. * @type {Object}
  26281. * @private
  26282. */
  26283. this._calculationInfo = {};
  26284. /**
  26285. * User output info of this data.
  26286. * DO NOT use it in other places!
  26287. *
  26288. * When preparing user params for user callbacks, we have
  26289. * to clone these inner data structures to prevent users
  26290. * from modifying them to effect built-in logic. And for
  26291. * performance consideration we make this `userOutput` to
  26292. * avoid clone them too many times.
  26293. *
  26294. * @type {Object}
  26295. * @readOnly
  26296. */
  26297. this.userOutput = this._dimensionsSummary.userOutput;
  26298. };
  26299. var listProto = List.prototype;
  26300. listProto.type = 'list';
  26301. /**
  26302. * If each data item has it's own option
  26303. * @type {boolean}
  26304. */
  26305. listProto.hasItemOption = true;
  26306. /**
  26307. * The meanings of the input parameter `dim`:
  26308. *
  26309. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26310. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26311. * + If dim is a number-like string (e.g., `"1"`):
  26312. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26313. * + If not, it will be converted to a number, which means the index of the dimension.
  26314. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26315. * dimension setting, although now it seems that it is not a good idea.)
  26316. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26317. * if no dimension name is defined as `"1"`.
  26318. * + If dim is a not-number-like string, it means the concrete dim name.
  26319. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26320. * or customized in `dimensions` property of option like `"age"`.
  26321. *
  26322. * Get dimension name
  26323. * @param {string|number} dim See above.
  26324. * @return {string} Concrete dim name.
  26325. */
  26326. listProto.getDimension = function (dim) {
  26327. if (typeof dim === 'number'
  26328. // If being a number-like string but not being defined a dimension name.
  26329. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26330. ) {
  26331. dim = this.dimensions[dim];
  26332. }
  26333. return dim;
  26334. };
  26335. /**
  26336. * Get type and calculation info of particular dimension
  26337. * @param {string|number} dim
  26338. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26339. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26340. */
  26341. listProto.getDimensionInfo = function (dim) {
  26342. // Do not clone, because there may be categories in dimInfo.
  26343. return this._dimensionInfos[this.getDimension(dim)];
  26344. };
  26345. /**
  26346. * @return {Array.<string>} concrete dimension name list on coord.
  26347. */
  26348. listProto.getDimensionsOnCoord = function () {
  26349. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26350. };
  26351. /**
  26352. * @param {string} coordDim
  26353. * @param {number} [idx] A coordDim may map to more than one data dim.
  26354. * If idx is `true`, return a array of all mapped dims.
  26355. * If idx is not specified, return the first dim not extra.
  26356. * @return {string|Array.<string>} concrete data dim.
  26357. * If idx is number, and not found, return null/undefined.
  26358. * If idx is `true`, and not found, return empty array (always return array).
  26359. */
  26360. listProto.mapDimension = function (coordDim, idx) {
  26361. var dimensionsSummary = this._dimensionsSummary;
  26362. if (idx == null) {
  26363. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26364. }
  26365. var dims = dimensionsSummary.encode[coordDim];
  26366. return idx === true
  26367. // always return array if idx is `true`
  26368. ? (dims || []).slice()
  26369. : (dims && dims[idx]);
  26370. };
  26371. /**
  26372. * Initialize from data
  26373. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26374. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26375. * defualt label/tooltip.
  26376. * A name can be specified in encode.itemName,
  26377. * or dataItem.name (only for series option data),
  26378. * or provided in nameList from outside.
  26379. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26380. */
  26381. listProto.initData = function (data, nameList, dimValueGetter) {
  26382. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26383. if (notProvider) {
  26384. data = new DefaultDataProvider(data, this.dimensions.length);
  26385. }
  26386. if (__DEV__) {
  26387. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26388. throw new Error('Inavlid data provider.');
  26389. }
  26390. }
  26391. this._rawData = data;
  26392. // Clear
  26393. this._storage = {};
  26394. this._indices = null;
  26395. this._nameList = nameList || [];
  26396. this._idList = [];
  26397. this._nameRepeatCount = {};
  26398. if (!dimValueGetter) {
  26399. this.hasItemOption = false;
  26400. }
  26401. /**
  26402. * @readOnly
  26403. */
  26404. this.defaultDimValueGetter = defaultDimValueGetters[
  26405. this._rawData.getSource().sourceFormat
  26406. ];
  26407. // Default dim value getter
  26408. this._dimValueGetter = dimValueGetter = dimValueGetter
  26409. || this.defaultDimValueGetter;
  26410. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26411. // Reset raw extent.
  26412. this._rawExtent = {};
  26413. this._initDataFromProvider(0, data.count());
  26414. // If data has no item option.
  26415. if (data.pure) {
  26416. this.hasItemOption = false;
  26417. }
  26418. };
  26419. listProto.getProvider = function () {
  26420. return this._rawData;
  26421. };
  26422. /**
  26423. * Caution: Can be only called on raw data (before `this._indices` created).
  26424. */
  26425. listProto.appendData = function (data) {
  26426. if (__DEV__) {
  26427. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26428. }
  26429. var rawData = this._rawData;
  26430. var start = this.count();
  26431. rawData.appendData(data);
  26432. var end = rawData.count();
  26433. if (!rawData.persistent) {
  26434. end += start;
  26435. }
  26436. this._initDataFromProvider(start, end);
  26437. };
  26438. /**
  26439. * Caution: Can be only called on raw data (before `this._indices` created).
  26440. * This method does not modify `rawData` (`dataProvider`), but only
  26441. * add values to storage.
  26442. *
  26443. * The final count will be increased by `Math.max(values.length, names.length)`.
  26444. *
  26445. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26446. * [
  26447. * [12, 33, 44],
  26448. * [NaN, 43, 1],
  26449. * ['-', 'asdf', 0]
  26450. * ]
  26451. * Each item is exaclty cooresponding to a dimension.
  26452. * @param {Array.<string>} [names]
  26453. */
  26454. listProto.appendValues = function (values, names) {
  26455. var chunkSize = this._chunkSize;
  26456. var storage = this._storage;
  26457. var dimensions = this.dimensions;
  26458. var dimLen = dimensions.length;
  26459. var rawExtent = this._rawExtent;
  26460. var start = this.count();
  26461. var end = start + Math.max(values.length, names ? names.length : 0);
  26462. var originalChunkCount = this._chunkCount;
  26463. for (var i = 0; i < dimLen; i++) {
  26464. var dim = dimensions[i];
  26465. if (!rawExtent[dim]) {
  26466. rawExtent[dim] = getInitialExtent();
  26467. }
  26468. if (!storage[dim]) {
  26469. storage[dim] = [];
  26470. }
  26471. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26472. this._chunkCount = storage[dim].length;
  26473. }
  26474. var emptyDataItem = new Array(dimLen);
  26475. for (var idx = start; idx < end; idx++) {
  26476. var sourceIdx = idx - start;
  26477. var chunkIndex = Math.floor(idx / chunkSize);
  26478. var chunkOffset = idx % chunkSize;
  26479. // Store the data by dimensions
  26480. for (var k = 0; k < dimLen; k++) {
  26481. var dim = dimensions[k];
  26482. var val = this._dimValueGetterArrayRows(
  26483. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26484. );
  26485. storage[dim][chunkIndex][chunkOffset] = val;
  26486. var dimRawExtent = rawExtent[dim];
  26487. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26488. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26489. }
  26490. if (names) {
  26491. this._nameList[idx] = names[sourceIdx];
  26492. }
  26493. }
  26494. this._rawCount = this._count = end;
  26495. // Reset data extent
  26496. this._extent = {};
  26497. prepareInvertedIndex(this);
  26498. };
  26499. listProto._initDataFromProvider = function (start, end) {
  26500. // Optimize.
  26501. if (start >= end) {
  26502. return;
  26503. }
  26504. var chunkSize = this._chunkSize;
  26505. var rawData = this._rawData;
  26506. var storage = this._storage;
  26507. var dimensions = this.dimensions;
  26508. var dimLen = dimensions.length;
  26509. var dimensionInfoMap = this._dimensionInfos;
  26510. var nameList = this._nameList;
  26511. var idList = this._idList;
  26512. var rawExtent = this._rawExtent;
  26513. var nameRepeatCount = this._nameRepeatCount = {};
  26514. var nameDimIdx;
  26515. var originalChunkCount = this._chunkCount;
  26516. for (var i = 0; i < dimLen; i++) {
  26517. var dim = dimensions[i];
  26518. if (!rawExtent[dim]) {
  26519. rawExtent[dim] = getInitialExtent();
  26520. }
  26521. var dimInfo = dimensionInfoMap[dim];
  26522. if (dimInfo.otherDims.itemName === 0) {
  26523. nameDimIdx = this._nameDimIdx = i;
  26524. }
  26525. if (dimInfo.otherDims.itemId === 0) {
  26526. this._idDimIdx = i;
  26527. }
  26528. if (!storage[dim]) {
  26529. storage[dim] = [];
  26530. }
  26531. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26532. this._chunkCount = storage[dim].length;
  26533. }
  26534. var dataItem = new Array(dimLen);
  26535. for (var idx = start; idx < end; idx++) {
  26536. // NOTICE: Try not to write things into dataItem
  26537. dataItem = rawData.getItem(idx, dataItem);
  26538. // Each data item is value
  26539. // [1, 2]
  26540. // 2
  26541. // Bar chart, line chart which uses category axis
  26542. // only gives the 'y' value. 'x' value is the indices of category
  26543. // Use a tempValue to normalize the value to be a (x, y) value
  26544. var chunkIndex = Math.floor(idx / chunkSize);
  26545. var chunkOffset = idx % chunkSize;
  26546. // Store the data by dimensions
  26547. for (var k = 0; k < dimLen; k++) {
  26548. var dim = dimensions[k];
  26549. var dimStorage = storage[dim][chunkIndex];
  26550. // PENDING NULL is empty or zero
  26551. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26552. dimStorage[chunkOffset] = val;
  26553. var dimRawExtent = rawExtent[dim];
  26554. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26555. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26556. }
  26557. // ??? FIXME not check by pure but sourceFormat?
  26558. // TODO refactor these logic.
  26559. if (!rawData.pure) {
  26560. var name = nameList[idx];
  26561. if (dataItem && name == null) {
  26562. // If dataItem is {name: ...}, it has highest priority.
  26563. // That is appropriate for many common cases.
  26564. if (dataItem.name != null) {
  26565. // There is no other place to persistent dataItem.name,
  26566. // so save it to nameList.
  26567. nameList[idx] = name = dataItem.name;
  26568. }
  26569. else if (nameDimIdx != null) {
  26570. var nameDim = dimensions[nameDimIdx];
  26571. var nameDimChunk = storage[nameDim][chunkIndex];
  26572. if (nameDimChunk) {
  26573. name = nameDimChunk[chunkOffset];
  26574. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26575. if (ordinalMeta && ordinalMeta.categories.length) {
  26576. name = ordinalMeta.categories[name];
  26577. }
  26578. }
  26579. }
  26580. }
  26581. // Try using the id in option
  26582. // id or name is used on dynamical data, mapping old and new items.
  26583. var id = dataItem == null ? null : dataItem.id;
  26584. if (id == null && name != null) {
  26585. // Use name as id and add counter to avoid same name
  26586. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26587. id = name;
  26588. if (nameRepeatCount[name] > 0) {
  26589. id += '__ec__' + nameRepeatCount[name];
  26590. }
  26591. nameRepeatCount[name]++;
  26592. }
  26593. id != null && (idList[idx] = id);
  26594. }
  26595. }
  26596. if (!rawData.persistent && rawData.clean) {
  26597. // Clean unused data if data source is typed array.
  26598. rawData.clean();
  26599. }
  26600. this._rawCount = this._count = end;
  26601. // Reset data extent
  26602. this._extent = {};
  26603. prepareInvertedIndex(this);
  26604. };
  26605. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26606. var DataCtor = dataCtors[dimInfo.type];
  26607. var lastChunkIndex = chunkCount - 1;
  26608. var dim = dimInfo.name;
  26609. var resizeChunkArray = storage[dim][lastChunkIndex];
  26610. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26611. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26612. // The cost of the copy is probably inconsiderable
  26613. // within the initial chunkSize.
  26614. for (var j = 0; j < resizeChunkArray.length; j++) {
  26615. newStore[j] = resizeChunkArray[j];
  26616. }
  26617. storage[dim][lastChunkIndex] = newStore;
  26618. }
  26619. // Create new chunks.
  26620. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26621. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26622. }
  26623. }
  26624. function prepareInvertedIndex(list) {
  26625. var invertedIndicesMap = list._invertedIndicesMap;
  26626. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26627. var dimInfo = list._dimensionInfos[dim];
  26628. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26629. var ordinalMeta = dimInfo.ordinalMeta;
  26630. if (ordinalMeta) {
  26631. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26632. ordinalMeta.categories.length
  26633. );
  26634. // The default value of TypedArray is 0. To avoid miss
  26635. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26636. for (var i = 0; i < invertedIndices.length; i++) {
  26637. invertedIndices[i] = INDEX_NOT_FOUND;
  26638. }
  26639. for (var i = 0; i < list._count; i++) {
  26640. // Only support the case that all values are distinct.
  26641. invertedIndices[list.get(dim, i)] = i;
  26642. }
  26643. }
  26644. });
  26645. }
  26646. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26647. var val;
  26648. if (dimIndex != null) {
  26649. var chunkSize = list._chunkSize;
  26650. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26651. var chunkOffset = rawIndex % chunkSize;
  26652. var dim = list.dimensions[dimIndex];
  26653. var chunk = list._storage[dim][chunkIndex];
  26654. if (chunk) {
  26655. val = chunk[chunkOffset];
  26656. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26657. if (ordinalMeta && ordinalMeta.categories.length) {
  26658. val = ordinalMeta.categories[val];
  26659. }
  26660. }
  26661. }
  26662. return val;
  26663. }
  26664. /**
  26665. * @return {number}
  26666. */
  26667. listProto.count = function () {
  26668. return this._count;
  26669. };
  26670. listProto.getIndices = function () {
  26671. var newIndices;
  26672. var indices = this._indices;
  26673. if (indices) {
  26674. var Ctor = indices.constructor;
  26675. var thisCount = this._count;
  26676. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26677. if (Ctor === Array) {
  26678. newIndices = new Ctor(thisCount);
  26679. for (var i = 0; i < thisCount; i++) {
  26680. newIndices[i] = indices[i];
  26681. }
  26682. }
  26683. else {
  26684. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26685. }
  26686. }
  26687. else {
  26688. var Ctor = getIndicesCtor(this);
  26689. var newIndices = new Ctor(this.count());
  26690. for (var i = 0; i < newIndices.length; i++) {
  26691. newIndices[i] = i;
  26692. }
  26693. }
  26694. return newIndices;
  26695. };
  26696. /**
  26697. * Get value. Return NaN if idx is out of range.
  26698. * @param {string} dim Dim must be concrete name.
  26699. * @param {number} idx
  26700. * @param {boolean} stack
  26701. * @return {number}
  26702. */
  26703. listProto.get = function (dim, idx /*, stack */) {
  26704. if (!(idx >= 0 && idx < this._count)) {
  26705. return NaN;
  26706. }
  26707. var storage = this._storage;
  26708. if (!storage[dim]) {
  26709. // TODO Warn ?
  26710. return NaN;
  26711. }
  26712. idx = this.getRawIndex(idx);
  26713. var chunkIndex = Math.floor(idx / this._chunkSize);
  26714. var chunkOffset = idx % this._chunkSize;
  26715. var chunkStore = storage[dim][chunkIndex];
  26716. var value = chunkStore[chunkOffset];
  26717. // FIXME ordinal data type is not stackable
  26718. // if (stack) {
  26719. // var dimensionInfo = this._dimensionInfos[dim];
  26720. // if (dimensionInfo && dimensionInfo.stackable) {
  26721. // var stackedOn = this.stackedOn;
  26722. // while (stackedOn) {
  26723. // // Get no stacked data of stacked on
  26724. // var stackedValue = stackedOn.get(dim, idx);
  26725. // // Considering positive stack, negative stack and empty data
  26726. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26727. // || (value <= 0 && stackedValue < 0) // Negative stack
  26728. // ) {
  26729. // value += stackedValue;
  26730. // }
  26731. // stackedOn = stackedOn.stackedOn;
  26732. // }
  26733. // }
  26734. // }
  26735. return value;
  26736. };
  26737. /**
  26738. * @param {string} dim concrete dim
  26739. * @param {number} rawIndex
  26740. * @return {number|string}
  26741. */
  26742. listProto.getByRawIndex = function (dim, rawIdx) {
  26743. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26744. return NaN;
  26745. }
  26746. var dimStore = this._storage[dim];
  26747. if (!dimStore) {
  26748. // TODO Warn ?
  26749. return NaN;
  26750. }
  26751. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26752. var chunkOffset = rawIdx % this._chunkSize;
  26753. var chunkStore = dimStore[chunkIndex];
  26754. return chunkStore[chunkOffset];
  26755. };
  26756. /**
  26757. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26758. * Hack a much simpler _getFast
  26759. * @private
  26760. */
  26761. listProto._getFast = function (dim, rawIdx) {
  26762. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26763. var chunkOffset = rawIdx % this._chunkSize;
  26764. var chunkStore = this._storage[dim][chunkIndex];
  26765. return chunkStore[chunkOffset];
  26766. };
  26767. /**
  26768. * Get value for multi dimensions.
  26769. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26770. * @param {number} idx
  26771. * @return {number}
  26772. */
  26773. listProto.getValues = function (dimensions, idx /*, stack */) {
  26774. var values = [];
  26775. if (!isArray(dimensions)) {
  26776. // stack = idx;
  26777. idx = dimensions;
  26778. dimensions = this.dimensions;
  26779. }
  26780. for (var i = 0, len = dimensions.length; i < len; i++) {
  26781. values.push(this.get(dimensions[i], idx /*, stack */));
  26782. }
  26783. return values;
  26784. };
  26785. /**
  26786. * If value is NaN. Inlcuding '-'
  26787. * Only check the coord dimensions.
  26788. * @param {string} dim
  26789. * @param {number} idx
  26790. * @return {number}
  26791. */
  26792. listProto.hasValue = function (idx) {
  26793. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26794. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26795. // Ordinal type originally can be string or number.
  26796. // But when an ordinal type is used on coord, it can
  26797. // not be string but only number. So we can also use isNaN.
  26798. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  26799. return false;
  26800. }
  26801. }
  26802. return true;
  26803. };
  26804. /**
  26805. * Get extent of data in one dimension
  26806. * @param {string} dim
  26807. * @param {boolean} stack
  26808. */
  26809. listProto.getDataExtent = function (dim /*, stack */) {
  26810. // Make sure use concrete dim as cache name.
  26811. dim = this.getDimension(dim);
  26812. var dimData = this._storage[dim];
  26813. var initialExtent = getInitialExtent();
  26814. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26815. if (!dimData) {
  26816. return initialExtent;
  26817. }
  26818. // Make more strict checkings to ensure hitting cache.
  26819. var currEnd = this.count();
  26820. // var cacheName = [dim, !!stack].join('_');
  26821. // var cacheName = dim;
  26822. // Consider the most cases when using data zoom, `getDataExtent`
  26823. // happened before filtering. We cache raw extent, which is not
  26824. // necessary to be cleared and recalculated when restore data.
  26825. var useRaw = !this._indices; // && !stack;
  26826. var dimExtent;
  26827. if (useRaw) {
  26828. return this._rawExtent[dim].slice();
  26829. }
  26830. dimExtent = this._extent[dim];
  26831. if (dimExtent) {
  26832. return dimExtent.slice();
  26833. }
  26834. dimExtent = initialExtent;
  26835. var min = dimExtent[0];
  26836. var max = dimExtent[1];
  26837. for (var i = 0; i < currEnd; i++) {
  26838. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26839. var value = this._getFast(dim, this.getRawIndex(i));
  26840. value < min && (min = value);
  26841. value > max && (max = value);
  26842. }
  26843. dimExtent = [min, max];
  26844. this._extent[dim] = dimExtent;
  26845. return dimExtent;
  26846. };
  26847. /**
  26848. * Optimize for the scenario that data is filtered by a given extent.
  26849. * Consider that if data amount is more than hundreds of thousand,
  26850. * extent calculation will cost more than 10ms and the cache will
  26851. * be erased because of the filtering.
  26852. */
  26853. listProto.getApproximateExtent = function (dim /*, stack */) {
  26854. dim = this.getDimension(dim);
  26855. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26856. };
  26857. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26858. dim = this.getDimension(dim);
  26859. this._approximateExtent[dim] = extent.slice();
  26860. };
  26861. /**
  26862. * @param {string} key
  26863. * @return {*}
  26864. */
  26865. listProto.getCalculationInfo = function (key) {
  26866. return this._calculationInfo[key];
  26867. };
  26868. /**
  26869. * @param {string|Object} key or k-v object
  26870. * @param {*} [value]
  26871. */
  26872. listProto.setCalculationInfo = function (key, value) {
  26873. isObject$4(key)
  26874. ? extend(this._calculationInfo, key)
  26875. : (this._calculationInfo[key] = value);
  26876. };
  26877. /**
  26878. * Get sum of data in one dimension
  26879. * @param {string} dim
  26880. */
  26881. listProto.getSum = function (dim /*, stack */) {
  26882. var dimData = this._storage[dim];
  26883. var sum = 0;
  26884. if (dimData) {
  26885. for (var i = 0, len = this.count(); i < len; i++) {
  26886. var value = this.get(dim, i /*, stack */);
  26887. if (!isNaN(value)) {
  26888. sum += value;
  26889. }
  26890. }
  26891. }
  26892. return sum;
  26893. };
  26894. /**
  26895. * Get median of data in one dimension
  26896. * @param {string} dim
  26897. */
  26898. listProto.getMedian = function (dim /*, stack */) {
  26899. var dimDataArray = [];
  26900. // map all data of one dimension
  26901. this.each(dim, function (val, idx) {
  26902. if (!isNaN(val)) {
  26903. dimDataArray.push(val);
  26904. }
  26905. });
  26906. // TODO
  26907. // Use quick select?
  26908. // immutability & sort
  26909. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26910. return a - b;
  26911. });
  26912. var len = this.count();
  26913. // calculate median
  26914. return len === 0
  26915. ? 0
  26916. : len % 2 === 1
  26917. ? sortedDimDataArray[(len - 1) / 2]
  26918. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26919. };
  26920. // /**
  26921. // * Retreive the index with given value
  26922. // * @param {string} dim Concrete dimension.
  26923. // * @param {number} value
  26924. // * @return {number}
  26925. // */
  26926. // Currently incorrect: should return dataIndex but not rawIndex.
  26927. // Do not fix it until this method is to be used somewhere.
  26928. // FIXME Precision of float value
  26929. // listProto.indexOf = function (dim, value) {
  26930. // var storage = this._storage;
  26931. // var dimData = storage[dim];
  26932. // var chunkSize = this._chunkSize;
  26933. // if (dimData) {
  26934. // for (var i = 0, len = this.count(); i < len; i++) {
  26935. // var chunkIndex = Math.floor(i / chunkSize);
  26936. // var chunkOffset = i % chunkSize;
  26937. // if (dimData[chunkIndex][chunkOffset] === value) {
  26938. // return i;
  26939. // }
  26940. // }
  26941. // }
  26942. // return -1;
  26943. // };
  26944. /**
  26945. * Only support the dimension which inverted index created.
  26946. * Do not support other cases until required.
  26947. * @param {string} concrete dim
  26948. * @param {number|string} value
  26949. * @return {number} rawIndex
  26950. */
  26951. listProto.rawIndexOf = function (dim, value) {
  26952. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26953. if (__DEV__) {
  26954. if (!invertedIndices) {
  26955. throw new Error('Do not supported yet');
  26956. }
  26957. }
  26958. var rawIndex = invertedIndices[value];
  26959. if (rawIndex == null || isNaN(rawIndex)) {
  26960. return INDEX_NOT_FOUND;
  26961. }
  26962. return rawIndex;
  26963. };
  26964. /**
  26965. * Retreive the index with given name
  26966. * @param {number} idx
  26967. * @param {number} name
  26968. * @return {number}
  26969. */
  26970. listProto.indexOfName = function (name) {
  26971. for (var i = 0, len = this.count(); i < len; i++) {
  26972. if (this.getName(i) === name) {
  26973. return i;
  26974. }
  26975. }
  26976. return -1;
  26977. };
  26978. /**
  26979. * Retreive the index with given raw data index
  26980. * @param {number} idx
  26981. * @param {number} name
  26982. * @return {number}
  26983. */
  26984. listProto.indexOfRawIndex = function (rawIndex) {
  26985. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26986. return -1;
  26987. }
  26988. if (!this._indices) {
  26989. return rawIndex;
  26990. }
  26991. // Indices are ascending
  26992. var indices = this._indices;
  26993. // If rawIndex === dataIndex
  26994. var rawDataIndex = indices[rawIndex];
  26995. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26996. return rawIndex;
  26997. }
  26998. var left = 0;
  26999. var right = this._count - 1;
  27000. while (left <= right) {
  27001. var mid = (left + right) / 2 | 0;
  27002. if (indices[mid] < rawIndex) {
  27003. left = mid + 1;
  27004. }
  27005. else if (indices[mid] > rawIndex) {
  27006. right = mid - 1;
  27007. }
  27008. else {
  27009. return mid;
  27010. }
  27011. }
  27012. return -1;
  27013. };
  27014. /**
  27015. * Retreive the index of nearest value
  27016. * @param {string} dim
  27017. * @param {number} value
  27018. * @param {number} [maxDistance=Infinity]
  27019. * @return {Array.<number>} If and only if multiple indices has
  27020. * the same value, they are put to the result.
  27021. */
  27022. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  27023. var storage = this._storage;
  27024. var dimData = storage[dim];
  27025. var nearestIndices = [];
  27026. if (!dimData) {
  27027. return nearestIndices;
  27028. }
  27029. if (maxDistance == null) {
  27030. maxDistance = Infinity;
  27031. }
  27032. var minDist = Infinity;
  27033. var minDiff = -1;
  27034. var nearestIndicesLen = 0;
  27035. // Check the test case of `test/ut/spec/data/List.js`.
  27036. for (var i = 0, len = this.count(); i < len; i++) {
  27037. var diff = value - this.get(dim, i);
  27038. var dist = Math.abs(diff);
  27039. if (dist <= maxDistance) {
  27040. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  27041. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  27042. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  27043. // So we chose the one that `diff >= 0` in this csae.
  27044. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  27045. // should be push to `nearestIndices`.
  27046. if (dist < minDist
  27047. || (dist === minDist && diff >= 0 && minDiff < 0)
  27048. ) {
  27049. minDist = dist;
  27050. minDiff = diff;
  27051. nearestIndicesLen = 0;
  27052. }
  27053. if (diff === minDiff) {
  27054. nearestIndices[nearestIndicesLen++] = i;
  27055. }
  27056. }
  27057. }
  27058. nearestIndices.length = nearestIndicesLen;
  27059. return nearestIndices;
  27060. };
  27061. /**
  27062. * Get raw data index
  27063. * @param {number} idx
  27064. * @return {number}
  27065. */
  27066. listProto.getRawIndex = getRawIndexWithoutIndices;
  27067. function getRawIndexWithoutIndices(idx) {
  27068. return idx;
  27069. }
  27070. function getRawIndexWithIndices(idx) {
  27071. if (idx < this._count && idx >= 0) {
  27072. return this._indices[idx];
  27073. }
  27074. return -1;
  27075. }
  27076. /**
  27077. * Get raw data item
  27078. * @param {number} idx
  27079. * @return {number}
  27080. */
  27081. listProto.getRawDataItem = function (idx) {
  27082. if (!this._rawData.persistent) {
  27083. var val = [];
  27084. for (var i = 0; i < this.dimensions.length; i++) {
  27085. var dim = this.dimensions[i];
  27086. val.push(this.get(dim, idx));
  27087. }
  27088. return val;
  27089. }
  27090. else {
  27091. return this._rawData.getItem(this.getRawIndex(idx));
  27092. }
  27093. };
  27094. /**
  27095. * @param {number} idx
  27096. * @param {boolean} [notDefaultIdx=false]
  27097. * @return {string}
  27098. */
  27099. listProto.getName = function (idx) {
  27100. var rawIndex = this.getRawIndex(idx);
  27101. return this._nameList[rawIndex]
  27102. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  27103. || '';
  27104. };
  27105. /**
  27106. * @param {number} idx
  27107. * @param {boolean} [notDefaultIdx=false]
  27108. * @return {string}
  27109. */
  27110. listProto.getId = function (idx) {
  27111. return getId(this, this.getRawIndex(idx));
  27112. };
  27113. function getId(list, rawIndex) {
  27114. var id = list._idList[rawIndex];
  27115. if (id == null) {
  27116. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  27117. }
  27118. if (id == null) {
  27119. // FIXME Check the usage in graph, should not use prefix.
  27120. id = ID_PREFIX + rawIndex;
  27121. }
  27122. return id;
  27123. }
  27124. function normalizeDimensions(dimensions) {
  27125. if (!isArray(dimensions)) {
  27126. dimensions = [dimensions];
  27127. }
  27128. return dimensions;
  27129. }
  27130. function validateDimensions(list, dims) {
  27131. for (var i = 0; i < dims.length; i++) {
  27132. // stroage may be empty when no data, so use
  27133. // dimensionInfos to check.
  27134. if (!list._dimensionInfos[dims[i]]) {
  27135. console.error('Unkown dimension ' + dims[i]);
  27136. }
  27137. }
  27138. }
  27139. /**
  27140. * Data iteration
  27141. * @param {string|Array.<string>}
  27142. * @param {Function} cb
  27143. * @param {*} [context=this]
  27144. *
  27145. * @example
  27146. * list.each('x', function (x, idx) {});
  27147. * list.each(['x', 'y'], function (x, y, idx) {});
  27148. * list.each(function (idx) {})
  27149. */
  27150. listProto.each = function (dims, cb, context, contextCompat) {
  27151. 'use strict';
  27152. if (!this._count) {
  27153. return;
  27154. }
  27155. if (typeof dims === 'function') {
  27156. contextCompat = context;
  27157. context = cb;
  27158. cb = dims;
  27159. dims = [];
  27160. }
  27161. // contextCompat just for compat echarts3
  27162. context = context || contextCompat || this;
  27163. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27164. if (__DEV__) {
  27165. validateDimensions(this, dims);
  27166. }
  27167. var dimSize = dims.length;
  27168. for (var i = 0; i < this.count(); i++) {
  27169. // Simple optimization
  27170. switch (dimSize) {
  27171. case 0:
  27172. cb.call(context, i);
  27173. break;
  27174. case 1:
  27175. cb.call(context, this.get(dims[0], i), i);
  27176. break;
  27177. case 2:
  27178. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27179. break;
  27180. default:
  27181. var k = 0;
  27182. var value = [];
  27183. for (; k < dimSize; k++) {
  27184. value[k] = this.get(dims[k], i);
  27185. }
  27186. // Index
  27187. value[k] = i;
  27188. cb.apply(context, value);
  27189. }
  27190. }
  27191. };
  27192. /**
  27193. * Data filter
  27194. * @param {string|Array.<string>}
  27195. * @param {Function} cb
  27196. * @param {*} [context=this]
  27197. */
  27198. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27199. 'use strict';
  27200. if (!this._count) {
  27201. return;
  27202. }
  27203. if (typeof dimensions === 'function') {
  27204. contextCompat = context;
  27205. context = cb;
  27206. cb = dimensions;
  27207. dimensions = [];
  27208. }
  27209. // contextCompat just for compat echarts3
  27210. context = context || contextCompat || this;
  27211. dimensions = map(
  27212. normalizeDimensions(dimensions), this.getDimension, this
  27213. );
  27214. if (__DEV__) {
  27215. validateDimensions(this, dimensions);
  27216. }
  27217. var count = this.count();
  27218. var Ctor = getIndicesCtor(this);
  27219. var newIndices = new Ctor(count);
  27220. var value = [];
  27221. var dimSize = dimensions.length;
  27222. var offset = 0;
  27223. var dim0 = dimensions[0];
  27224. for (var i = 0; i < count; i++) {
  27225. var keep;
  27226. var rawIdx = this.getRawIndex(i);
  27227. // Simple optimization
  27228. if (dimSize === 0) {
  27229. keep = cb.call(context, i);
  27230. }
  27231. else if (dimSize === 1) {
  27232. var val = this._getFast(dim0, rawIdx);
  27233. keep = cb.call(context, val, i);
  27234. }
  27235. else {
  27236. for (var k = 0; k < dimSize; k++) {
  27237. value[k] = this._getFast(dim0, rawIdx);
  27238. }
  27239. value[k] = i;
  27240. keep = cb.apply(context, value);
  27241. }
  27242. if (keep) {
  27243. newIndices[offset++] = rawIdx;
  27244. }
  27245. }
  27246. // Set indices after filtered.
  27247. if (offset < count) {
  27248. this._indices = newIndices;
  27249. }
  27250. this._count = offset;
  27251. // Reset data extent
  27252. this._extent = {};
  27253. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27254. return this;
  27255. };
  27256. /**
  27257. * Select data in range. (For optimization of filter)
  27258. * (Manually inline code, support 5 million data filtering in data zoom.)
  27259. */
  27260. listProto.selectRange = function (range) {
  27261. 'use strict';
  27262. if (!this._count) {
  27263. return;
  27264. }
  27265. var dimensions = [];
  27266. for (var dim in range) {
  27267. if (range.hasOwnProperty(dim)) {
  27268. dimensions.push(dim);
  27269. }
  27270. }
  27271. if (__DEV__) {
  27272. validateDimensions(this, dimensions);
  27273. }
  27274. var dimSize = dimensions.length;
  27275. if (!dimSize) {
  27276. return;
  27277. }
  27278. var originalCount = this.count();
  27279. var Ctor = getIndicesCtor(this);
  27280. var newIndices = new Ctor(originalCount);
  27281. var offset = 0;
  27282. var dim0 = dimensions[0];
  27283. var min = range[dim0][0];
  27284. var max = range[dim0][1];
  27285. var quickFinished = false;
  27286. if (!this._indices) {
  27287. // Extreme optimization for common case. About 2x faster in chrome.
  27288. var idx = 0;
  27289. if (dimSize === 1) {
  27290. var dimStorage = this._storage[dimensions[0]];
  27291. for (var k = 0; k < this._chunkCount; k++) {
  27292. var chunkStorage = dimStorage[k];
  27293. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27294. for (var i = 0; i < len; i++) {
  27295. var val = chunkStorage[i];
  27296. // NaN will not be filtered. Consider the case, in line chart, empty
  27297. // value indicates the line should be broken. But for the case like
  27298. // scatter plot, a data item with empty value will not be rendered,
  27299. // but the axis extent may be effected if some other dim of the data
  27300. // item has value. Fortunately it is not a significant negative effect.
  27301. if (
  27302. (val >= min && val <= max) || isNaN(val)
  27303. ) {
  27304. newIndices[offset++] = idx;
  27305. }
  27306. idx++;
  27307. }
  27308. }
  27309. quickFinished = true;
  27310. }
  27311. else if (dimSize === 2) {
  27312. var dimStorage = this._storage[dim0];
  27313. var dimStorage2 = this._storage[dimensions[1]];
  27314. var min2 = range[dimensions[1]][0];
  27315. var max2 = range[dimensions[1]][1];
  27316. for (var k = 0; k < this._chunkCount; k++) {
  27317. var chunkStorage = dimStorage[k];
  27318. var chunkStorage2 = dimStorage2[k];
  27319. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27320. for (var i = 0; i < len; i++) {
  27321. var val = chunkStorage[i];
  27322. var val2 = chunkStorage2[i];
  27323. // Do not filter NaN, see comment above.
  27324. if ((
  27325. (val >= min && val <= max) || isNaN(val)
  27326. )
  27327. && (
  27328. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27329. )
  27330. ) {
  27331. newIndices[offset++] = idx;
  27332. }
  27333. idx++;
  27334. }
  27335. }
  27336. quickFinished = true;
  27337. }
  27338. }
  27339. if (!quickFinished) {
  27340. if (dimSize === 1) {
  27341. for (var i = 0; i < originalCount; i++) {
  27342. var rawIndex = this.getRawIndex(i);
  27343. var val = this._getFast(dim0, rawIndex);
  27344. // Do not filter NaN, see comment above.
  27345. if (
  27346. (val >= min && val <= max) || isNaN(val)
  27347. ) {
  27348. newIndices[offset++] = rawIndex;
  27349. }
  27350. }
  27351. }
  27352. else {
  27353. for (var i = 0; i < originalCount; i++) {
  27354. var keep = true;
  27355. var rawIndex = this.getRawIndex(i);
  27356. for (var k = 0; k < dimSize; k++) {
  27357. var dimk = dimensions[k];
  27358. var val = this._getFast(dim, rawIndex);
  27359. // Do not filter NaN, see comment above.
  27360. if (val < range[dimk][0] || val > range[dimk][1]) {
  27361. keep = false;
  27362. }
  27363. }
  27364. if (keep) {
  27365. newIndices[offset++] = this.getRawIndex(i);
  27366. }
  27367. }
  27368. }
  27369. }
  27370. // Set indices after filtered.
  27371. if (offset < originalCount) {
  27372. this._indices = newIndices;
  27373. }
  27374. this._count = offset;
  27375. // Reset data extent
  27376. this._extent = {};
  27377. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27378. return this;
  27379. };
  27380. /**
  27381. * Data mapping to a plain array
  27382. * @param {string|Array.<string>} [dimensions]
  27383. * @param {Function} cb
  27384. * @param {*} [context=this]
  27385. * @return {Array}
  27386. */
  27387. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27388. 'use strict';
  27389. if (typeof dimensions === 'function') {
  27390. contextCompat = context;
  27391. context = cb;
  27392. cb = dimensions;
  27393. dimensions = [];
  27394. }
  27395. // contextCompat just for compat echarts3
  27396. context = context || contextCompat || this;
  27397. var result = [];
  27398. this.each(dimensions, function () {
  27399. result.push(cb && cb.apply(this, arguments));
  27400. }, context);
  27401. return result;
  27402. };
  27403. // Data in excludeDimensions is copied, otherwise transfered.
  27404. function cloneListForMapAndSample(original, excludeDimensions) {
  27405. var allDimensions = original.dimensions;
  27406. var list = new List(
  27407. map(allDimensions, original.getDimensionInfo, original),
  27408. original.hostModel
  27409. );
  27410. // FIXME If needs stackedOn, value may already been stacked
  27411. transferProperties(list, original);
  27412. var storage = list._storage = {};
  27413. var originalStorage = original._storage;
  27414. // Init storage
  27415. for (var i = 0; i < allDimensions.length; i++) {
  27416. var dim = allDimensions[i];
  27417. if (originalStorage[dim]) {
  27418. // Notice that we do not reset invertedIndicesMap here, becuase
  27419. // there is no scenario of mapping or sampling ordinal dimension.
  27420. if (indexOf(excludeDimensions, dim) >= 0) {
  27421. storage[dim] = cloneDimStore(originalStorage[dim]);
  27422. list._rawExtent[dim] = getInitialExtent();
  27423. list._extent[dim] = null;
  27424. }
  27425. else {
  27426. // Direct reference for other dimensions
  27427. storage[dim] = originalStorage[dim];
  27428. }
  27429. }
  27430. }
  27431. return list;
  27432. }
  27433. function cloneDimStore(originalDimStore) {
  27434. var newDimStore = new Array(originalDimStore.length);
  27435. for (var j = 0; j < originalDimStore.length; j++) {
  27436. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27437. }
  27438. return newDimStore;
  27439. }
  27440. function getInitialExtent() {
  27441. return [Infinity, -Infinity];
  27442. }
  27443. /**
  27444. * Data mapping to a new List with given dimensions
  27445. * @param {string|Array.<string>} dimensions
  27446. * @param {Function} cb
  27447. * @param {*} [context=this]
  27448. * @return {Array}
  27449. */
  27450. listProto.map = function (dimensions, cb, context, contextCompat) {
  27451. 'use strict';
  27452. // contextCompat just for compat echarts3
  27453. context = context || contextCompat || this;
  27454. dimensions = map(
  27455. normalizeDimensions(dimensions), this.getDimension, this
  27456. );
  27457. if (__DEV__) {
  27458. validateDimensions(this, dimensions);
  27459. }
  27460. var list = cloneListForMapAndSample(this, dimensions);
  27461. // Following properties are all immutable.
  27462. // So we can reference to the same value
  27463. list._indices = this._indices;
  27464. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27465. var storage = list._storage;
  27466. var tmpRetValue = [];
  27467. var chunkSize = this._chunkSize;
  27468. var dimSize = dimensions.length;
  27469. var dataCount = this.count();
  27470. var values = [];
  27471. var rawExtent = list._rawExtent;
  27472. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27473. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27474. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27475. }
  27476. values[dimSize] = dataIndex;
  27477. var retValue = cb && cb.apply(context, values);
  27478. if (retValue != null) {
  27479. // a number or string (in oridinal dimension)?
  27480. if (typeof retValue !== 'object') {
  27481. tmpRetValue[0] = retValue;
  27482. retValue = tmpRetValue;
  27483. }
  27484. var rawIndex = this.getRawIndex(dataIndex);
  27485. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27486. var chunkOffset = rawIndex % chunkSize;
  27487. for (var i = 0; i < retValue.length; i++) {
  27488. var dim = dimensions[i];
  27489. var val = retValue[i];
  27490. var rawExtentOnDim = rawExtent[dim];
  27491. var dimStore = storage[dim];
  27492. if (dimStore) {
  27493. dimStore[chunkIndex][chunkOffset] = val;
  27494. }
  27495. if (val < rawExtentOnDim[0]) {
  27496. rawExtentOnDim[0] = val;
  27497. }
  27498. if (val > rawExtentOnDim[1]) {
  27499. rawExtentOnDim[1] = val;
  27500. }
  27501. }
  27502. }
  27503. }
  27504. return list;
  27505. };
  27506. /**
  27507. * Large data down sampling on given dimension
  27508. * @param {string} dimension
  27509. * @param {number} rate
  27510. * @param {Function} sampleValue
  27511. * @param {Function} sampleIndex Sample index for name and id
  27512. */
  27513. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27514. var list = cloneListForMapAndSample(this, [dimension]);
  27515. var targetStorage = list._storage;
  27516. var frameValues = [];
  27517. var frameSize = Math.floor(1 / rate);
  27518. var dimStore = targetStorage[dimension];
  27519. var len = this.count();
  27520. var chunkSize = this._chunkSize;
  27521. var rawExtentOnDim = list._rawExtent[dimension];
  27522. var newIndices = new (getIndicesCtor(this))(len);
  27523. var offset = 0;
  27524. for (var i = 0; i < len; i += frameSize) {
  27525. // Last frame
  27526. if (frameSize > len - i) {
  27527. frameSize = len - i;
  27528. frameValues.length = frameSize;
  27529. }
  27530. for (var k = 0; k < frameSize; k++) {
  27531. var dataIdx = this.getRawIndex(i + k);
  27532. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27533. var originalChunkOffset = dataIdx % chunkSize;
  27534. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27535. }
  27536. var value = sampleValue(frameValues);
  27537. var sampleFrameIdx = this.getRawIndex(
  27538. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27539. );
  27540. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27541. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27542. // Only write value on the filtered data
  27543. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27544. if (value < rawExtentOnDim[0]) {
  27545. rawExtentOnDim[0] = value;
  27546. }
  27547. if (value > rawExtentOnDim[1]) {
  27548. rawExtentOnDim[1] = value;
  27549. }
  27550. newIndices[offset++] = sampleFrameIdx;
  27551. }
  27552. list._count = offset;
  27553. list._indices = newIndices;
  27554. list.getRawIndex = getRawIndexWithIndices;
  27555. return list;
  27556. };
  27557. /**
  27558. * Get model of one data item.
  27559. *
  27560. * @param {number} idx
  27561. */
  27562. // FIXME Model proxy ?
  27563. listProto.getItemModel = function (idx) {
  27564. var hostModel = this.hostModel;
  27565. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27566. };
  27567. /**
  27568. * Create a data differ
  27569. * @param {module:echarts/data/List} otherList
  27570. * @return {module:echarts/data/DataDiffer}
  27571. */
  27572. listProto.diff = function (otherList) {
  27573. var thisList = this;
  27574. return new DataDiffer(
  27575. otherList ? otherList.getIndices() : [],
  27576. this.getIndices(),
  27577. function (idx) {
  27578. return getId(otherList, idx);
  27579. },
  27580. function (idx) {
  27581. return getId(thisList, idx);
  27582. }
  27583. );
  27584. };
  27585. /**
  27586. * Get visual property.
  27587. * @param {string} key
  27588. */
  27589. listProto.getVisual = function (key) {
  27590. var visual = this._visual;
  27591. return visual && visual[key];
  27592. };
  27593. /**
  27594. * Set visual property
  27595. * @param {string|Object} key
  27596. * @param {*} [value]
  27597. *
  27598. * @example
  27599. * setVisual('color', color);
  27600. * setVisual({
  27601. * 'color': color
  27602. * });
  27603. */
  27604. listProto.setVisual = function (key, val) {
  27605. if (isObject$4(key)) {
  27606. for (var name in key) {
  27607. if (key.hasOwnProperty(name)) {
  27608. this.setVisual(name, key[name]);
  27609. }
  27610. }
  27611. return;
  27612. }
  27613. this._visual = this._visual || {};
  27614. this._visual[key] = val;
  27615. };
  27616. /**
  27617. * Set layout property.
  27618. * @param {string|Object} key
  27619. * @param {*} [val]
  27620. */
  27621. listProto.setLayout = function (key, val) {
  27622. if (isObject$4(key)) {
  27623. for (var name in key) {
  27624. if (key.hasOwnProperty(name)) {
  27625. this.setLayout(name, key[name]);
  27626. }
  27627. }
  27628. return;
  27629. }
  27630. this._layout[key] = val;
  27631. };
  27632. /**
  27633. * Get layout property.
  27634. * @param {string} key.
  27635. * @return {*}
  27636. */
  27637. listProto.getLayout = function (key) {
  27638. return this._layout[key];
  27639. };
  27640. /**
  27641. * Get layout of single data item
  27642. * @param {number} idx
  27643. */
  27644. listProto.getItemLayout = function (idx) {
  27645. return this._itemLayouts[idx];
  27646. };
  27647. /**
  27648. * Set layout of single data item
  27649. * @param {number} idx
  27650. * @param {Object} layout
  27651. * @param {boolean=} [merge=false]
  27652. */
  27653. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27654. this._itemLayouts[idx] = merge$$1
  27655. ? extend(this._itemLayouts[idx] || {}, layout)
  27656. : layout;
  27657. };
  27658. /**
  27659. * Clear all layout of single data item
  27660. */
  27661. listProto.clearItemLayouts = function () {
  27662. this._itemLayouts.length = 0;
  27663. };
  27664. /**
  27665. * Get visual property of single data item
  27666. * @param {number} idx
  27667. * @param {string} key
  27668. * @param {boolean} [ignoreParent=false]
  27669. */
  27670. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27671. var itemVisual = this._itemVisuals[idx];
  27672. var val = itemVisual && itemVisual[key];
  27673. if (val == null && !ignoreParent) {
  27674. // Use global visual property
  27675. return this.getVisual(key);
  27676. }
  27677. return val;
  27678. };
  27679. /**
  27680. * Set visual property of single data item
  27681. *
  27682. * @param {number} idx
  27683. * @param {string|Object} key
  27684. * @param {*} [value]
  27685. *
  27686. * @example
  27687. * setItemVisual(0, 'color', color);
  27688. * setItemVisual(0, {
  27689. * 'color': color
  27690. * });
  27691. */
  27692. listProto.setItemVisual = function (idx, key, value) {
  27693. var itemVisual = this._itemVisuals[idx] || {};
  27694. var hasItemVisual = this.hasItemVisual;
  27695. this._itemVisuals[idx] = itemVisual;
  27696. if (isObject$4(key)) {
  27697. for (var name in key) {
  27698. if (key.hasOwnProperty(name)) {
  27699. itemVisual[name] = key[name];
  27700. hasItemVisual[name] = true;
  27701. }
  27702. }
  27703. return;
  27704. }
  27705. itemVisual[key] = value;
  27706. hasItemVisual[key] = true;
  27707. };
  27708. /**
  27709. * Clear itemVisuals and list visual.
  27710. */
  27711. listProto.clearAllVisual = function () {
  27712. this._visual = {};
  27713. this._itemVisuals = [];
  27714. this.hasItemVisual = {};
  27715. };
  27716. var setItemDataAndSeriesIndex = function (child) {
  27717. child.seriesIndex = this.seriesIndex;
  27718. child.dataIndex = this.dataIndex;
  27719. child.dataType = this.dataType;
  27720. };
  27721. /**
  27722. * Set graphic element relative to data. It can be set as null
  27723. * @param {number} idx
  27724. * @param {module:zrender/Element} [el]
  27725. */
  27726. listProto.setItemGraphicEl = function (idx, el) {
  27727. var hostModel = this.hostModel;
  27728. if (el) {
  27729. // Add data index and series index for indexing the data by element
  27730. // Useful in tooltip
  27731. el.dataIndex = idx;
  27732. el.dataType = this.dataType;
  27733. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27734. if (el.type === 'group') {
  27735. el.traverse(setItemDataAndSeriesIndex, el);
  27736. }
  27737. }
  27738. this._graphicEls[idx] = el;
  27739. };
  27740. /**
  27741. * @param {number} idx
  27742. * @return {module:zrender/Element}
  27743. */
  27744. listProto.getItemGraphicEl = function (idx) {
  27745. return this._graphicEls[idx];
  27746. };
  27747. /**
  27748. * @param {Function} cb
  27749. * @param {*} context
  27750. */
  27751. listProto.eachItemGraphicEl = function (cb, context) {
  27752. each$1(this._graphicEls, function (el, idx) {
  27753. if (el) {
  27754. cb && cb.call(context, el, idx);
  27755. }
  27756. });
  27757. };
  27758. /**
  27759. * Shallow clone a new list except visual and layout properties, and graph elements.
  27760. * New list only change the indices.
  27761. */
  27762. listProto.cloneShallow = function (list) {
  27763. if (!list) {
  27764. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27765. list = new List(dimensionInfoList, this.hostModel);
  27766. }
  27767. // FIXME
  27768. list._storage = this._storage;
  27769. transferProperties(list, this);
  27770. // Clone will not change the data extent and indices
  27771. if (this._indices) {
  27772. var Ctor = this._indices.constructor;
  27773. list._indices = new Ctor(this._indices);
  27774. }
  27775. else {
  27776. list._indices = null;
  27777. }
  27778. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27779. return list;
  27780. };
  27781. /**
  27782. * Wrap some method to add more feature
  27783. * @param {string} methodName
  27784. * @param {Function} injectFunction
  27785. */
  27786. listProto.wrapMethod = function (methodName, injectFunction) {
  27787. var originalMethod = this[methodName];
  27788. if (typeof originalMethod !== 'function') {
  27789. return;
  27790. }
  27791. this.__wrappedMethods = this.__wrappedMethods || [];
  27792. this.__wrappedMethods.push(methodName);
  27793. this[methodName] = function () {
  27794. var res = originalMethod.apply(this, arguments);
  27795. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27796. };
  27797. };
  27798. // Methods that create a new list based on this list should be listed here.
  27799. // Notice that those method should `RETURN` the new list.
  27800. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27801. // Methods that change indices of this list should be listed here.
  27802. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27803. /*
  27804. * Licensed to the Apache Software Foundation (ASF) under one
  27805. * or more contributor license agreements. See the NOTICE file
  27806. * distributed with this work for additional information
  27807. * regarding copyright ownership. The ASF licenses this file
  27808. * to you under the Apache License, Version 2.0 (the
  27809. * "License"); you may not use this file except in compliance
  27810. * with the License. You may obtain a copy of the License at
  27811. *
  27812. * http://www.apache.org/licenses/LICENSE-2.0
  27813. *
  27814. * Unless required by applicable law or agreed to in writing,
  27815. * software distributed under the License is distributed on an
  27816. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27817. * KIND, either express or implied. See the License for the
  27818. * specific language governing permissions and limitations
  27819. * under the License.
  27820. */
  27821. /**
  27822. * @deprecated
  27823. * Use `echarts/data/helper/createDimensions` instead.
  27824. */
  27825. /**
  27826. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27827. *
  27828. * This method builds the relationship between:
  27829. * + "what the coord sys or series requires (see `sysDims`)",
  27830. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  27831. * + "what the data source provids (see `source`)".
  27832. *
  27833. * Some guess strategy will be adapted if user does not define something.
  27834. * If no 'value' dimension specified, the first no-named dimension will be
  27835. * named as 'value'.
  27836. *
  27837. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27838. * provides not only dim template, but also default order.
  27839. * properties: 'name', 'type', 'displayName'.
  27840. * `name` of each item provides default coord name.
  27841. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27842. * provide dims count that the sysDim required.
  27843. * [{ordinalMeta}] can be specified.
  27844. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27845. * @param {Object} [opt]
  27846. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27847. * For example: ['asdf', {name, type}, ...].
  27848. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27849. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  27850. * If not specified, auto find the next available data dim.
  27851. * param source {module:data/Source}
  27852. * param dimCount {number}
  27853. * return {Object} encode Never be `null/undefined`.
  27854. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27855. * If not specified, extra dim names will be:
  27856. * 'value', 'value0', 'value1', ...
  27857. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27858. * If `generateCoordCount` specified, the generated dim names will be:
  27859. * `generateCoord` + 0, `generateCoord` + 1, ...
  27860. * can be Infinity, indicate that use all of the remain columns.
  27861. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27862. * @return {Array.<module:data/DataDimensionInfo>}
  27863. */
  27864. function completeDimensions(sysDims, source, opt) {
  27865. if (!Source.isInstance(source)) {
  27866. source = Source.seriesDataToSource(source);
  27867. }
  27868. opt = opt || {};
  27869. sysDims = (sysDims || []).slice();
  27870. var dimsDef = (opt.dimsDef || []).slice();
  27871. var dataDimNameMap = createHashMap();
  27872. var coordDimNameMap = createHashMap();
  27873. // var valueCandidate;
  27874. var result = [];
  27875. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27876. // Apply user defined dims (`name` and `type`) and init result.
  27877. for (var i = 0; i < dimCount; i++) {
  27878. var dimDefItem = dimsDef[i] = extend(
  27879. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27880. );
  27881. var userDimName = dimDefItem.name;
  27882. var resultItem = result[i] = new DataDimensionInfo();
  27883. // Name will be applied later for avoiding duplication.
  27884. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27885. // Only if `series.dimensions` is defined in option
  27886. // displayName, will be set, and dimension will be diplayed vertically in
  27887. // tooltip by default.
  27888. resultItem.name = resultItem.displayName = userDimName;
  27889. dataDimNameMap.set(userDimName, i);
  27890. }
  27891. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27892. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27893. }
  27894. var encodeDef = opt.encodeDef;
  27895. if (!encodeDef && opt.encodeDefaulter) {
  27896. encodeDef = opt.encodeDefaulter(source, dimCount);
  27897. }
  27898. encodeDef = createHashMap(encodeDef);
  27899. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27900. encodeDef.each(function (dataDims, coordDim) {
  27901. dataDims = normalizeToArray(dataDims).slice();
  27902. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27903. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27904. // this case.
  27905. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  27906. encodeDef.set(coordDim, false);
  27907. return;
  27908. }
  27909. var validDataDims = encodeDef.set(coordDim, []);
  27910. each$1(dataDims, function (resultDimIdx, idx) {
  27911. // The input resultDimIdx can be dim name or index.
  27912. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27913. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27914. validDataDims[idx] = resultDimIdx;
  27915. applyDim(result[resultDimIdx], coordDim, idx);
  27916. }
  27917. });
  27918. });
  27919. // Apply templetes and default order from `sysDims`.
  27920. var availDimIdx = 0;
  27921. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27922. var coordDim;
  27923. var sysDimItem;
  27924. var sysDimItemDimsDef;
  27925. var sysDimItemOtherDims;
  27926. if (isString(sysDimItem)) {
  27927. coordDim = sysDimItem;
  27928. sysDimItem = {};
  27929. }
  27930. else {
  27931. coordDim = sysDimItem.name;
  27932. var ordinalMeta = sysDimItem.ordinalMeta;
  27933. sysDimItem.ordinalMeta = null;
  27934. sysDimItem = clone(sysDimItem);
  27935. sysDimItem.ordinalMeta = ordinalMeta;
  27936. // `coordDimIndex` should not be set directly.
  27937. sysDimItemDimsDef = sysDimItem.dimsDef;
  27938. sysDimItemOtherDims = sysDimItem.otherDims;
  27939. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  27940. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27941. }
  27942. var dataDims = encodeDef.get(coordDim);
  27943. // negative resultDimIdx means no need to mapping.
  27944. if (dataDims === false) {
  27945. return;
  27946. }
  27947. var dataDims = normalizeToArray(dataDims);
  27948. // dimensions provides default dim sequences.
  27949. if (!dataDims.length) {
  27950. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27951. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27952. availDimIdx++;
  27953. }
  27954. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27955. }
  27956. }
  27957. // Apply templates.
  27958. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27959. var resultItem = result[resultDimIdx];
  27960. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27961. if (resultItem.name == null && sysDimItemDimsDef) {
  27962. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27963. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27964. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27965. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27966. }
  27967. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27968. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27969. });
  27970. });
  27971. function applyDim(resultItem, coordDim, coordDimIndex) {
  27972. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27973. resultItem.otherDims[coordDim] = coordDimIndex;
  27974. }
  27975. else {
  27976. resultItem.coordDim = coordDim;
  27977. resultItem.coordDimIndex = coordDimIndex;
  27978. coordDimNameMap.set(coordDim, true);
  27979. }
  27980. }
  27981. // Make sure the first extra dim is 'value'.
  27982. var generateCoord = opt.generateCoord;
  27983. var generateCoordCount = opt.generateCoordCount;
  27984. var fromZero = generateCoordCount != null;
  27985. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27986. var extra = generateCoord || 'value';
  27987. // Set dim `name` and other `coordDim` and other props.
  27988. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27989. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  27990. var coordDim = resultItem.coordDim;
  27991. if (coordDim == null) {
  27992. resultItem.coordDim = genName(
  27993. extra, coordDimNameMap, fromZero
  27994. );
  27995. resultItem.coordDimIndex = 0;
  27996. if (!generateCoord || generateCoordCount <= 0) {
  27997. resultItem.isExtraCoord = true;
  27998. }
  27999. generateCoordCount--;
  28000. }
  28001. resultItem.name == null && (resultItem.name = genName(
  28002. resultItem.coordDim,
  28003. dataDimNameMap
  28004. ));
  28005. if (resultItem.type == null
  28006. && (
  28007. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  28008. // Consider the case:
  28009. // {
  28010. // dataset: {source: [
  28011. // ['2001', 123],
  28012. // ['2002', 456],
  28013. // ...
  28014. // ['The others', 987],
  28015. // ]},
  28016. // series: {type: 'pie'}
  28017. // }
  28018. // The first colum should better be treated as a "ordinal" although it
  28019. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  28020. || (resultItem.isExtraCoord
  28021. && (resultItem.otherDims.itemName != null
  28022. || resultItem.otherDims.seriesName != null
  28023. )
  28024. )
  28025. )
  28026. ) {
  28027. resultItem.type = 'ordinal';
  28028. }
  28029. }
  28030. return result;
  28031. }
  28032. // ??? TODO
  28033. // Originally detect dimCount by data[0]. Should we
  28034. // optimize it to only by sysDims and dimensions and encode.
  28035. // So only necessary dims will be initialized.
  28036. // But
  28037. // (1) custom series should be considered. where other dims
  28038. // may be visited.
  28039. // (2) sometimes user need to calcualte bubble size or use visualMap
  28040. // on other dimensions besides coordSys needed.
  28041. // So, dims that is not used by system, should be shared in storage?
  28042. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  28043. // Note that the result dimCount should not small than columns count
  28044. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  28045. var dimCount = Math.max(
  28046. source.dimensionsDetectCount || 1,
  28047. sysDims.length,
  28048. dimsDef.length,
  28049. optDimCount || 0
  28050. );
  28051. each$1(sysDims, function (sysDimItem) {
  28052. var sysDimItemDimsDef = sysDimItem.dimsDef;
  28053. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  28054. });
  28055. return dimCount;
  28056. }
  28057. function genName(name, map$$1, fromZero) {
  28058. if (fromZero || map$$1.get(name) != null) {
  28059. var i = 0;
  28060. while (map$$1.get(name + i) != null) {
  28061. i++;
  28062. }
  28063. name += i;
  28064. }
  28065. map$$1.set(name, true);
  28066. return name;
  28067. }
  28068. /*
  28069. * Licensed to the Apache Software Foundation (ASF) under one
  28070. * or more contributor license agreements. See the NOTICE file
  28071. * distributed with this work for additional information
  28072. * regarding copyright ownership. The ASF licenses this file
  28073. * to you under the Apache License, Version 2.0 (the
  28074. * "License"); you may not use this file except in compliance
  28075. * with the License. You may obtain a copy of the License at
  28076. *
  28077. * http://www.apache.org/licenses/LICENSE-2.0
  28078. *
  28079. * Unless required by applicable law or agreed to in writing,
  28080. * software distributed under the License is distributed on an
  28081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28082. * KIND, either express or implied. See the License for the
  28083. * specific language governing permissions and limitations
  28084. * under the License.
  28085. */
  28086. /**
  28087. * Substitute `completeDimensions`.
  28088. * `completeDimensions` is to be deprecated.
  28089. */
  28090. /**
  28091. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  28092. * @param {Object|Array} [opt]
  28093. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  28094. * @param {number} [opt.dimensionsCount]
  28095. * @param {string} [opt.generateCoord]
  28096. * @param {string} [opt.generateCoordCount]
  28097. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  28098. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  28099. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  28100. * @return {Array.<Object>} dimensionsInfo
  28101. */
  28102. var createDimensions = function (source, opt) {
  28103. opt = opt || {};
  28104. return completeDimensions(opt.coordDimensions || [], source, {
  28105. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  28106. encodeDef: opt.encodeDefine || source.encodeDefine,
  28107. dimCount: opt.dimensionsCount,
  28108. encodeDefaulter: opt.encodeDefaulter,
  28109. generateCoord: opt.generateCoord,
  28110. generateCoordCount: opt.generateCoordCount
  28111. });
  28112. };
  28113. /*
  28114. * Licensed to the Apache Software Foundation (ASF) under one
  28115. * or more contributor license agreements. See the NOTICE file
  28116. * distributed with this work for additional information
  28117. * regarding copyright ownership. The ASF licenses this file
  28118. * to you under the Apache License, Version 2.0 (the
  28119. * "License"); you may not use this file except in compliance
  28120. * with the License. You may obtain a copy of the License at
  28121. *
  28122. * http://www.apache.org/licenses/LICENSE-2.0
  28123. *
  28124. * Unless required by applicable law or agreed to in writing,
  28125. * software distributed under the License is distributed on an
  28126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28127. * KIND, either express or implied. See the License for the
  28128. * specific language governing permissions and limitations
  28129. * under the License.
  28130. */
  28131. /**
  28132. * Helper for model references.
  28133. * There are many manners to refer axis/coordSys.
  28134. */
  28135. // TODO
  28136. // merge relevant logic to this file?
  28137. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28138. /**
  28139. * @class
  28140. * For example:
  28141. * {
  28142. * coordSysName: 'cartesian2d',
  28143. * coordSysDims: ['x', 'y', ...],
  28144. * axisMap: HashMap({
  28145. * x: xAxisModel,
  28146. * y: yAxisModel
  28147. * }),
  28148. * categoryAxisMap: HashMap({
  28149. * x: xAxisModel,
  28150. * y: undefined
  28151. * }),
  28152. * // The index of the first category axis in `coordSysDims`.
  28153. * // `null/undefined` means no category axis exists.
  28154. * firstCategoryDimIndex: 1,
  28155. * // To replace user specified encode.
  28156. * }
  28157. */
  28158. function CoordSysInfo(coordSysName) {
  28159. /**
  28160. * @type {string}
  28161. */
  28162. this.coordSysName = coordSysName;
  28163. /**
  28164. * @type {Array.<string>}
  28165. */
  28166. this.coordSysDims = [];
  28167. /**
  28168. * @type {module:zrender/core/util#HashMap}
  28169. */
  28170. this.axisMap = createHashMap();
  28171. /**
  28172. * @type {module:zrender/core/util#HashMap}
  28173. */
  28174. this.categoryAxisMap = createHashMap();
  28175. /**
  28176. * @type {number}
  28177. */
  28178. this.firstCategoryDimIndex = null;
  28179. }
  28180. /**
  28181. * @return {module:model/referHelper#CoordSysInfo}
  28182. */
  28183. function getCoordSysInfoBySeries(seriesModel) {
  28184. var coordSysName = seriesModel.get('coordinateSystem');
  28185. var result = new CoordSysInfo(coordSysName);
  28186. var fetch = fetchers[coordSysName];
  28187. if (fetch) {
  28188. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28189. return result;
  28190. }
  28191. }
  28192. var fetchers = {
  28193. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28194. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28195. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28196. if (__DEV__) {
  28197. if (!xAxisModel) {
  28198. throw new Error('xAxis "' + retrieve(
  28199. seriesModel.get('xAxisIndex'),
  28200. seriesModel.get('xAxisId'),
  28201. 0
  28202. ) + '" not found');
  28203. }
  28204. if (!yAxisModel) {
  28205. throw new Error('yAxis "' + retrieve(
  28206. seriesModel.get('xAxisIndex'),
  28207. seriesModel.get('yAxisId'),
  28208. 0
  28209. ) + '" not found');
  28210. }
  28211. }
  28212. result.coordSysDims = ['x', 'y'];
  28213. axisMap.set('x', xAxisModel);
  28214. axisMap.set('y', yAxisModel);
  28215. if (isCategory(xAxisModel)) {
  28216. categoryAxisMap.set('x', xAxisModel);
  28217. result.firstCategoryDimIndex = 0;
  28218. }
  28219. if (isCategory(yAxisModel)) {
  28220. categoryAxisMap.set('y', yAxisModel);
  28221. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28222. }
  28223. },
  28224. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28225. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28226. if (__DEV__) {
  28227. if (!singleAxisModel) {
  28228. throw new Error('singleAxis should be specified.');
  28229. }
  28230. }
  28231. result.coordSysDims = ['single'];
  28232. axisMap.set('single', singleAxisModel);
  28233. if (isCategory(singleAxisModel)) {
  28234. categoryAxisMap.set('single', singleAxisModel);
  28235. result.firstCategoryDimIndex = 0;
  28236. }
  28237. },
  28238. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28239. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28240. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28241. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28242. if (__DEV__) {
  28243. if (!angleAxisModel) {
  28244. throw new Error('angleAxis option not found');
  28245. }
  28246. if (!radiusAxisModel) {
  28247. throw new Error('radiusAxis option not found');
  28248. }
  28249. }
  28250. result.coordSysDims = ['radius', 'angle'];
  28251. axisMap.set('radius', radiusAxisModel);
  28252. axisMap.set('angle', angleAxisModel);
  28253. if (isCategory(radiusAxisModel)) {
  28254. categoryAxisMap.set('radius', radiusAxisModel);
  28255. result.firstCategoryDimIndex = 0;
  28256. }
  28257. if (isCategory(angleAxisModel)) {
  28258. categoryAxisMap.set('angle', angleAxisModel);
  28259. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28260. }
  28261. },
  28262. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28263. result.coordSysDims = ['lng', 'lat'];
  28264. },
  28265. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28266. var ecModel = seriesModel.ecModel;
  28267. var parallelModel = ecModel.getComponent(
  28268. 'parallel', seriesModel.get('parallelIndex')
  28269. );
  28270. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28271. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28272. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28273. var axisDim = coordSysDims[index];
  28274. axisMap.set(axisDim, axisModel);
  28275. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28276. categoryAxisMap.set(axisDim, axisModel);
  28277. result.firstCategoryDimIndex = index;
  28278. }
  28279. });
  28280. }
  28281. };
  28282. function isCategory(axisModel) {
  28283. return axisModel.get('type') === 'category';
  28284. }
  28285. /*
  28286. * Licensed to the Apache Software Foundation (ASF) under one
  28287. * or more contributor license agreements. See the NOTICE file
  28288. * distributed with this work for additional information
  28289. * regarding copyright ownership. The ASF licenses this file
  28290. * to you under the Apache License, Version 2.0 (the
  28291. * "License"); you may not use this file except in compliance
  28292. * with the License. You may obtain a copy of the License at
  28293. *
  28294. * http://www.apache.org/licenses/LICENSE-2.0
  28295. *
  28296. * Unless required by applicable law or agreed to in writing,
  28297. * software distributed under the License is distributed on an
  28298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28299. * KIND, either express or implied. See the License for the
  28300. * specific language governing permissions and limitations
  28301. * under the License.
  28302. */
  28303. /**
  28304. * Note that it is too complicated to support 3d stack by value
  28305. * (have to create two-dimension inverted index), so in 3d case
  28306. * we just support that stacked by index.
  28307. *
  28308. * @param {module:echarts/model/Series} seriesModel
  28309. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28310. * The input dimensionInfoList will be modified.
  28311. * @param {Object} [opt]
  28312. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28313. * @param {boolean} [opt.byIndex=false]
  28314. * @return {Object} calculationInfo
  28315. * {
  28316. * stackedDimension: string
  28317. * stackedByDimension: string
  28318. * isStackedByIndex: boolean
  28319. * stackedOverDimension: string
  28320. * stackResultDimension: string
  28321. * }
  28322. */
  28323. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28324. opt = opt || {};
  28325. var byIndex = opt.byIndex;
  28326. var stackedCoordDimension = opt.stackedCoordDimension;
  28327. // Compatibal: when `stack` is set as '', do not stack.
  28328. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28329. var stackedByDimInfo;
  28330. var stackedDimInfo;
  28331. var stackResultDimension;
  28332. var stackedOverDimension;
  28333. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28334. if (isString(dimensionInfo)) {
  28335. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28336. }
  28337. if (mayStack && !dimensionInfo.isExtraCoord) {
  28338. // Find the first ordinal dimension as the stackedByDimInfo.
  28339. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28340. stackedByDimInfo = dimensionInfo;
  28341. }
  28342. // Find the first stackable dimension as the stackedDimInfo.
  28343. if (!stackedDimInfo
  28344. && dimensionInfo.type !== 'ordinal'
  28345. && dimensionInfo.type !== 'time'
  28346. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28347. ) {
  28348. stackedDimInfo = dimensionInfo;
  28349. }
  28350. }
  28351. });
  28352. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28353. // Compatible with previous design, value axis (time axis) only stack by index.
  28354. // It may make sense if the user provides elaborately constructed data.
  28355. byIndex = true;
  28356. }
  28357. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28358. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28359. // might not be a good way.
  28360. if (stackedDimInfo) {
  28361. // Use a weird name that not duplicated with other names.
  28362. stackResultDimension = '__\0ecstackresult';
  28363. stackedOverDimension = '__\0ecstackedover';
  28364. // Create inverted index to fast query index by value.
  28365. if (stackedByDimInfo) {
  28366. stackedByDimInfo.createInvertedIndices = true;
  28367. }
  28368. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28369. var stackedDimType = stackedDimInfo.type;
  28370. var stackedDimCoordIndex = 0;
  28371. each$1(dimensionInfoList, function (dimensionInfo) {
  28372. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28373. stackedDimCoordIndex++;
  28374. }
  28375. });
  28376. dimensionInfoList.push({
  28377. name: stackResultDimension,
  28378. coordDim: stackedDimCoordDim,
  28379. coordDimIndex: stackedDimCoordIndex,
  28380. type: stackedDimType,
  28381. isExtraCoord: true,
  28382. isCalculationCoord: true
  28383. });
  28384. stackedDimCoordIndex++;
  28385. dimensionInfoList.push({
  28386. name: stackedOverDimension,
  28387. // This dimension contains stack base (generally, 0), so do not set it as
  28388. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28389. coordDim: stackedOverDimension,
  28390. coordDimIndex: stackedDimCoordIndex,
  28391. type: stackedDimType,
  28392. isExtraCoord: true,
  28393. isCalculationCoord: true
  28394. });
  28395. }
  28396. return {
  28397. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28398. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28399. isStackedByIndex: byIndex,
  28400. stackedOverDimension: stackedOverDimension,
  28401. stackResultDimension: stackResultDimension
  28402. };
  28403. }
  28404. /**
  28405. * @param {module:echarts/data/List} data
  28406. * @param {string} stackedDim
  28407. */
  28408. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28409. // Each single series only maps to one pair of axis. So we do not need to
  28410. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28411. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28412. // && (
  28413. // stackedByDim != null
  28414. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28415. // : data.getCalculationInfo('isStackedByIndex')
  28416. // );
  28417. }
  28418. /**
  28419. * @param {module:echarts/data/List} data
  28420. * @param {string} targetDim
  28421. * @param {string} [stackedByDim] If not input this parameter, check whether
  28422. * stacked by index.
  28423. * @return {string} dimension
  28424. */
  28425. function getStackedDimension(data, targetDim) {
  28426. return isDimensionStacked(data, targetDim)
  28427. ? data.getCalculationInfo('stackResultDimension')
  28428. : targetDim;
  28429. }
  28430. /*
  28431. * Licensed to the Apache Software Foundation (ASF) under one
  28432. * or more contributor license agreements. See the NOTICE file
  28433. * distributed with this work for additional information
  28434. * regarding copyright ownership. The ASF licenses this file
  28435. * to you under the Apache License, Version 2.0 (the
  28436. * "License"); you may not use this file except in compliance
  28437. * with the License. You may obtain a copy of the License at
  28438. *
  28439. * http://www.apache.org/licenses/LICENSE-2.0
  28440. *
  28441. * Unless required by applicable law or agreed to in writing,
  28442. * software distributed under the License is distributed on an
  28443. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28444. * KIND, either express or implied. See the License for the
  28445. * specific language governing permissions and limitations
  28446. * under the License.
  28447. */
  28448. /**
  28449. * @param {module:echarts/data/Source|Array} source Or raw data.
  28450. * @param {module:echarts/model/Series} seriesModel
  28451. * @param {Object} [opt]
  28452. * @param {string} [opt.generateCoord]
  28453. * @param {boolean} [opt.useEncodeDefaulter]
  28454. */
  28455. function createListFromArray(source, seriesModel, opt) {
  28456. opt = opt || {};
  28457. if (!Source.isInstance(source)) {
  28458. source = Source.seriesDataToSource(source);
  28459. }
  28460. var coordSysName = seriesModel.get('coordinateSystem');
  28461. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28462. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28463. var coordSysDimDefs;
  28464. if (coordSysInfo) {
  28465. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28466. var dimInfo = {name: dim};
  28467. var axisModel = coordSysInfo.axisMap.get(dim);
  28468. if (axisModel) {
  28469. var axisType = axisModel.get('type');
  28470. dimInfo.type = getDimensionTypeByAxis(axisType);
  28471. // dimInfo.stackable = isStackable(axisType);
  28472. }
  28473. return dimInfo;
  28474. });
  28475. }
  28476. if (!coordSysDimDefs) {
  28477. // Get dimensions from registered coordinate system
  28478. coordSysDimDefs = (registeredCoordSys && (
  28479. registeredCoordSys.getDimensionsInfo
  28480. ? registeredCoordSys.getDimensionsInfo()
  28481. : registeredCoordSys.dimensions.slice()
  28482. )) || ['x', 'y'];
  28483. }
  28484. var dimInfoList = createDimensions(source, {
  28485. coordDimensions: coordSysDimDefs,
  28486. generateCoord: opt.generateCoord,
  28487. encodeDefaulter: opt.useEncodeDefaulter
  28488. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28489. : null
  28490. });
  28491. var firstCategoryDimIndex;
  28492. var hasNameEncode;
  28493. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  28494. var coordDim = dimInfo.coordDim;
  28495. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28496. if (categoryAxisModel) {
  28497. if (firstCategoryDimIndex == null) {
  28498. firstCategoryDimIndex = dimIndex;
  28499. }
  28500. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28501. }
  28502. if (dimInfo.otherDims.itemName != null) {
  28503. hasNameEncode = true;
  28504. }
  28505. });
  28506. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28507. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28508. }
  28509. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28510. var list = new List(dimInfoList, seriesModel);
  28511. list.setCalculationInfo(stackCalculationInfo);
  28512. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  28513. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28514. // Use dataIndex as ordinal value in categoryAxis
  28515. return dimIndex === firstCategoryDimIndex
  28516. ? dataIndex
  28517. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28518. }
  28519. : null;
  28520. list.hasItemOption = false;
  28521. list.initData(source, null, dimValueGetter);
  28522. return list;
  28523. }
  28524. function isNeedCompleteOrdinalData(source) {
  28525. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28526. var sampleItem = firstDataNotNull(source.data || []);
  28527. return sampleItem != null
  28528. && !isArray(getDataItemValue(sampleItem));
  28529. }
  28530. }
  28531. function firstDataNotNull(data) {
  28532. var i = 0;
  28533. while (i < data.length && data[i] == null) {
  28534. i++;
  28535. }
  28536. return data[i];
  28537. }
  28538. /*
  28539. * Licensed to the Apache Software Foundation (ASF) under one
  28540. * or more contributor license agreements. See the NOTICE file
  28541. * distributed with this work for additional information
  28542. * regarding copyright ownership. The ASF licenses this file
  28543. * to you under the Apache License, Version 2.0 (the
  28544. * "License"); you may not use this file except in compliance
  28545. * with the License. You may obtain a copy of the License at
  28546. *
  28547. * http://www.apache.org/licenses/LICENSE-2.0
  28548. *
  28549. * Unless required by applicable law or agreed to in writing,
  28550. * software distributed under the License is distributed on an
  28551. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28552. * KIND, either express or implied. See the License for the
  28553. * specific language governing permissions and limitations
  28554. * under the License.
  28555. */
  28556. SeriesModel.extend({
  28557. type: 'series.line',
  28558. dependencies: ['grid', 'polar'],
  28559. getInitialData: function (option, ecModel) {
  28560. if (__DEV__) {
  28561. var coordSys = option.coordinateSystem;
  28562. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  28563. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  28564. }
  28565. }
  28566. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  28567. },
  28568. defaultOption: {
  28569. zlevel: 0,
  28570. z: 2,
  28571. coordinateSystem: 'cartesian2d',
  28572. legendHoverLink: true,
  28573. hoverAnimation: true,
  28574. // stack: null
  28575. // xAxisIndex: 0,
  28576. // yAxisIndex: 0,
  28577. // polarIndex: 0,
  28578. // If clip the overflow value
  28579. clip: true,
  28580. // cursor: null,
  28581. label: {
  28582. position: 'top'
  28583. },
  28584. // itemStyle: {
  28585. // },
  28586. lineStyle: {
  28587. width: 2,
  28588. type: 'solid'
  28589. },
  28590. // areaStyle: {
  28591. // origin of areaStyle. Valid values:
  28592. // `'auto'/null/undefined`: from axisLine to data
  28593. // `'start'`: from min to data
  28594. // `'end'`: from data to max
  28595. // origin: 'auto'
  28596. // },
  28597. // false, 'start', 'end', 'middle'
  28598. step: false,
  28599. // Disabled if step is true
  28600. smooth: false,
  28601. smoothMonotone: null,
  28602. symbol: 'emptyCircle',
  28603. symbolSize: 4,
  28604. symbolRotate: null,
  28605. showSymbol: true,
  28606. // `false`: follow the label interval strategy.
  28607. // `true`: show all symbols.
  28608. // `'auto'`: If possible, show all symbols, otherwise
  28609. // follow the label interval strategy.
  28610. showAllSymbol: 'auto',
  28611. // Whether to connect break point.
  28612. connectNulls: false,
  28613. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  28614. sampling: 'none',
  28615. animationEasing: 'linear',
  28616. // Disable progressive
  28617. progressive: 0,
  28618. hoverLayerThreshold: Infinity
  28619. }
  28620. });
  28621. /*
  28622. * Licensed to the Apache Software Foundation (ASF) under one
  28623. * or more contributor license agreements. See the NOTICE file
  28624. * distributed with this work for additional information
  28625. * regarding copyright ownership. The ASF licenses this file
  28626. * to you under the Apache License, Version 2.0 (the
  28627. * "License"); you may not use this file except in compliance
  28628. * with the License. You may obtain a copy of the License at
  28629. *
  28630. * http://www.apache.org/licenses/LICENSE-2.0
  28631. *
  28632. * Unless required by applicable law or agreed to in writing,
  28633. * software distributed under the License is distributed on an
  28634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28635. * KIND, either express or implied. See the License for the
  28636. * specific language governing permissions and limitations
  28637. * under the License.
  28638. */
  28639. // Symbol factory
  28640. /**
  28641. * Triangle shape
  28642. * @inner
  28643. */
  28644. var Triangle = extendShape({
  28645. type: 'triangle',
  28646. shape: {
  28647. cx: 0,
  28648. cy: 0,
  28649. width: 0,
  28650. height: 0
  28651. },
  28652. buildPath: function (path, shape) {
  28653. var cx = shape.cx;
  28654. var cy = shape.cy;
  28655. var width = shape.width / 2;
  28656. var height = shape.height / 2;
  28657. path.moveTo(cx, cy - height);
  28658. path.lineTo(cx + width, cy + height);
  28659. path.lineTo(cx - width, cy + height);
  28660. path.closePath();
  28661. }
  28662. });
  28663. /**
  28664. * Diamond shape
  28665. * @inner
  28666. */
  28667. var Diamond = extendShape({
  28668. type: 'diamond',
  28669. shape: {
  28670. cx: 0,
  28671. cy: 0,
  28672. width: 0,
  28673. height: 0
  28674. },
  28675. buildPath: function (path, shape) {
  28676. var cx = shape.cx;
  28677. var cy = shape.cy;
  28678. var width = shape.width / 2;
  28679. var height = shape.height / 2;
  28680. path.moveTo(cx, cy - height);
  28681. path.lineTo(cx + width, cy);
  28682. path.lineTo(cx, cy + height);
  28683. path.lineTo(cx - width, cy);
  28684. path.closePath();
  28685. }
  28686. });
  28687. /**
  28688. * Pin shape
  28689. * @inner
  28690. */
  28691. var Pin = extendShape({
  28692. type: 'pin',
  28693. shape: {
  28694. // x, y on the cusp
  28695. x: 0,
  28696. y: 0,
  28697. width: 0,
  28698. height: 0
  28699. },
  28700. buildPath: function (path, shape) {
  28701. var x = shape.x;
  28702. var y = shape.y;
  28703. var w = shape.width / 5 * 3;
  28704. // Height must be larger than width
  28705. var h = Math.max(w, shape.height);
  28706. var r = w / 2;
  28707. // Dist on y with tangent point and circle center
  28708. var dy = r * r / (h - r);
  28709. var cy = y - h + r + dy;
  28710. var angle = Math.asin(dy / r);
  28711. // Dist on x with tangent point and circle center
  28712. var dx = Math.cos(angle) * r;
  28713. var tanX = Math.sin(angle);
  28714. var tanY = Math.cos(angle);
  28715. var cpLen = r * 0.6;
  28716. var cpLen2 = r * 0.7;
  28717. path.moveTo(x - dx, cy + dy);
  28718. path.arc(
  28719. x, cy, r,
  28720. Math.PI - angle,
  28721. Math.PI * 2 + angle
  28722. );
  28723. path.bezierCurveTo(
  28724. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28725. x, y - cpLen2,
  28726. x, y
  28727. );
  28728. path.bezierCurveTo(
  28729. x, y - cpLen2,
  28730. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28731. x - dx, cy + dy
  28732. );
  28733. path.closePath();
  28734. }
  28735. });
  28736. /**
  28737. * Arrow shape
  28738. * @inner
  28739. */
  28740. var Arrow = extendShape({
  28741. type: 'arrow',
  28742. shape: {
  28743. x: 0,
  28744. y: 0,
  28745. width: 0,
  28746. height: 0
  28747. },
  28748. buildPath: function (ctx, shape) {
  28749. var height = shape.height;
  28750. var width = shape.width;
  28751. var x = shape.x;
  28752. var y = shape.y;
  28753. var dx = width / 3 * 2;
  28754. ctx.moveTo(x, y);
  28755. ctx.lineTo(x + dx, y + height);
  28756. ctx.lineTo(x, y + height / 4 * 3);
  28757. ctx.lineTo(x - dx, y + height);
  28758. ctx.lineTo(x, y);
  28759. ctx.closePath();
  28760. }
  28761. });
  28762. /**
  28763. * Map of path contructors
  28764. * @type {Object.<string, module:zrender/graphic/Path>}
  28765. */
  28766. var symbolCtors = {
  28767. line: Line,
  28768. rect: Rect,
  28769. roundRect: Rect,
  28770. square: Rect,
  28771. circle: Circle,
  28772. diamond: Diamond,
  28773. pin: Pin,
  28774. arrow: Arrow,
  28775. triangle: Triangle
  28776. };
  28777. var symbolShapeMakers = {
  28778. line: function (x, y, w, h, shape) {
  28779. // FIXME
  28780. shape.x1 = x;
  28781. shape.y1 = y + h / 2;
  28782. shape.x2 = x + w;
  28783. shape.y2 = y + h / 2;
  28784. },
  28785. rect: function (x, y, w, h, shape) {
  28786. shape.x = x;
  28787. shape.y = y;
  28788. shape.width = w;
  28789. shape.height = h;
  28790. },
  28791. roundRect: function (x, y, w, h, shape) {
  28792. shape.x = x;
  28793. shape.y = y;
  28794. shape.width = w;
  28795. shape.height = h;
  28796. shape.r = Math.min(w, h) / 4;
  28797. },
  28798. square: function (x, y, w, h, shape) {
  28799. var size = Math.min(w, h);
  28800. shape.x = x;
  28801. shape.y = y;
  28802. shape.width = size;
  28803. shape.height = size;
  28804. },
  28805. circle: function (x, y, w, h, shape) {
  28806. // Put circle in the center of square
  28807. shape.cx = x + w / 2;
  28808. shape.cy = y + h / 2;
  28809. shape.r = Math.min(w, h) / 2;
  28810. },
  28811. diamond: function (x, y, w, h, shape) {
  28812. shape.cx = x + w / 2;
  28813. shape.cy = y + h / 2;
  28814. shape.width = w;
  28815. shape.height = h;
  28816. },
  28817. pin: function (x, y, w, h, shape) {
  28818. shape.x = x + w / 2;
  28819. shape.y = y + h / 2;
  28820. shape.width = w;
  28821. shape.height = h;
  28822. },
  28823. arrow: function (x, y, w, h, shape) {
  28824. shape.x = x + w / 2;
  28825. shape.y = y + h / 2;
  28826. shape.width = w;
  28827. shape.height = h;
  28828. },
  28829. triangle: function (x, y, w, h, shape) {
  28830. shape.cx = x + w / 2;
  28831. shape.cy = y + h / 2;
  28832. shape.width = w;
  28833. shape.height = h;
  28834. }
  28835. };
  28836. var symbolBuildProxies = {};
  28837. each$1(symbolCtors, function (Ctor, name) {
  28838. symbolBuildProxies[name] = new Ctor();
  28839. });
  28840. var SymbolClz$2 = extendShape({
  28841. type: 'symbol',
  28842. shape: {
  28843. symbolType: '',
  28844. x: 0,
  28845. y: 0,
  28846. width: 0,
  28847. height: 0
  28848. },
  28849. calculateTextPosition: function (out, style, rect) {
  28850. var res = calculateTextPosition(out, style, rect);
  28851. var shape = this.shape;
  28852. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28853. res.y = rect.y + rect.height * 0.4;
  28854. }
  28855. return res;
  28856. },
  28857. buildPath: function (ctx, shape, inBundle) {
  28858. var symbolType = shape.symbolType;
  28859. if (symbolType !== 'none') {
  28860. var proxySymbol = symbolBuildProxies[symbolType];
  28861. if (!proxySymbol) {
  28862. // Default rect
  28863. symbolType = 'rect';
  28864. proxySymbol = symbolBuildProxies[symbolType];
  28865. }
  28866. symbolShapeMakers[symbolType](
  28867. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28868. );
  28869. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28870. }
  28871. }
  28872. });
  28873. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28874. function symbolPathSetColor(color, innerColor) {
  28875. if (this.type !== 'image') {
  28876. var symbolStyle = this.style;
  28877. var symbolShape = this.shape;
  28878. if (symbolShape && symbolShape.symbolType === 'line') {
  28879. symbolStyle.stroke = color;
  28880. }
  28881. else if (this.__isEmptyBrush) {
  28882. symbolStyle.stroke = color;
  28883. symbolStyle.fill = innerColor || '#fff';
  28884. }
  28885. else {
  28886. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28887. symbolStyle.fill && (symbolStyle.fill = color);
  28888. symbolStyle.stroke && (symbolStyle.stroke = color);
  28889. }
  28890. this.dirty(false);
  28891. }
  28892. }
  28893. /**
  28894. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28895. * @param {string} symbolType
  28896. * @param {number} x
  28897. * @param {number} y
  28898. * @param {number} w
  28899. * @param {number} h
  28900. * @param {string} color
  28901. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28902. * for path and image only.
  28903. */
  28904. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28905. // TODO Support image object, DynamicImage.
  28906. var isEmpty = symbolType.indexOf('empty') === 0;
  28907. if (isEmpty) {
  28908. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28909. }
  28910. var symbolPath;
  28911. if (symbolType.indexOf('image://') === 0) {
  28912. symbolPath = makeImage(
  28913. symbolType.slice(8),
  28914. new BoundingRect(x, y, w, h),
  28915. keepAspect ? 'center' : 'cover'
  28916. );
  28917. }
  28918. else if (symbolType.indexOf('path://') === 0) {
  28919. symbolPath = makePath(
  28920. symbolType.slice(7),
  28921. {},
  28922. new BoundingRect(x, y, w, h),
  28923. keepAspect ? 'center' : 'cover'
  28924. );
  28925. }
  28926. else {
  28927. symbolPath = new SymbolClz$2({
  28928. shape: {
  28929. symbolType: symbolType,
  28930. x: x,
  28931. y: y,
  28932. width: w,
  28933. height: h
  28934. }
  28935. });
  28936. }
  28937. symbolPath.__isEmptyBrush = isEmpty;
  28938. symbolPath.setColor = symbolPathSetColor;
  28939. symbolPath.setColor(color);
  28940. return symbolPath;
  28941. }
  28942. /*
  28943. * Licensed to the Apache Software Foundation (ASF) under one
  28944. * or more contributor license agreements. See the NOTICE file
  28945. * distributed with this work for additional information
  28946. * regarding copyright ownership. The ASF licenses this file
  28947. * to you under the Apache License, Version 2.0 (the
  28948. * "License"); you may not use this file except in compliance
  28949. * with the License. You may obtain a copy of the License at
  28950. *
  28951. * http://www.apache.org/licenses/LICENSE-2.0
  28952. *
  28953. * Unless required by applicable law or agreed to in writing,
  28954. * software distributed under the License is distributed on an
  28955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28956. * KIND, either express or implied. See the License for the
  28957. * specific language governing permissions and limitations
  28958. * under the License.
  28959. */
  28960. /**
  28961. * @param {module:echarts/data/List} data
  28962. * @param {number} dataIndex
  28963. * @return {string} label string. Not null/undefined
  28964. */
  28965. function getDefaultLabel(data, dataIndex) {
  28966. var labelDims = data.mapDimension('defaultedLabel', true);
  28967. var len = labelDims.length;
  28968. // Simple optimization (in lots of cases, label dims length is 1)
  28969. if (len === 1) {
  28970. return retrieveRawValue(data, dataIndex, labelDims[0]);
  28971. }
  28972. else if (len) {
  28973. var vals = [];
  28974. for (var i = 0; i < labelDims.length; i++) {
  28975. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  28976. vals.push(val);
  28977. }
  28978. return vals.join(' ');
  28979. }
  28980. }
  28981. /*
  28982. * Licensed to the Apache Software Foundation (ASF) under one
  28983. * or more contributor license agreements. See the NOTICE file
  28984. * distributed with this work for additional information
  28985. * regarding copyright ownership. The ASF licenses this file
  28986. * to you under the Apache License, Version 2.0 (the
  28987. * "License"); you may not use this file except in compliance
  28988. * with the License. You may obtain a copy of the License at
  28989. *
  28990. * http://www.apache.org/licenses/LICENSE-2.0
  28991. *
  28992. * Unless required by applicable law or agreed to in writing,
  28993. * software distributed under the License is distributed on an
  28994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28995. * KIND, either express or implied. See the License for the
  28996. * specific language governing permissions and limitations
  28997. * under the License.
  28998. */
  28999. /**
  29000. * @module echarts/chart/helper/Symbol
  29001. */
  29002. /**
  29003. * @constructor
  29004. * @alias {module:echarts/chart/helper/Symbol}
  29005. * @param {module:echarts/data/List} data
  29006. * @param {number} idx
  29007. * @extends {module:zrender/graphic/Group}
  29008. */
  29009. function SymbolClz(data, idx, seriesScope) {
  29010. Group.call(this);
  29011. this.updateData(data, idx, seriesScope);
  29012. }
  29013. var symbolProto = SymbolClz.prototype;
  29014. /**
  29015. * @public
  29016. * @static
  29017. * @param {module:echarts/data/List} data
  29018. * @param {number} dataIndex
  29019. * @return {Array.<number>} [width, height]
  29020. */
  29021. var getSymbolSize = SymbolClz.getSymbolSize = function (data, idx) {
  29022. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  29023. return symbolSize instanceof Array
  29024. ? symbolSize.slice()
  29025. : [+symbolSize, +symbolSize];
  29026. };
  29027. function getScale(symbolSize) {
  29028. return [symbolSize[0] / 2, symbolSize[1] / 2];
  29029. }
  29030. function driftSymbol(dx, dy) {
  29031. this.parent.drift(dx, dy);
  29032. }
  29033. symbolProto._createSymbol = function (
  29034. symbolType,
  29035. data,
  29036. idx,
  29037. symbolSize,
  29038. keepAspect
  29039. ) {
  29040. // Remove paths created before
  29041. this.removeAll();
  29042. var color = data.getItemVisual(idx, 'color');
  29043. // var symbolPath = createSymbol(
  29044. // symbolType, -0.5, -0.5, 1, 1, color
  29045. // );
  29046. // If width/height are set too small (e.g., set to 1) on ios10
  29047. // and macOS Sierra, a circle stroke become a rect, no matter what
  29048. // the scale is set. So we set width/height as 2. See #4150.
  29049. var symbolPath = createSymbol(
  29050. symbolType, -1, -1, 2, 2, color, keepAspect
  29051. );
  29052. symbolPath.attr({
  29053. z2: 100,
  29054. culling: true,
  29055. scale: getScale(symbolSize)
  29056. });
  29057. // Rewrite drift method
  29058. symbolPath.drift = driftSymbol;
  29059. this._symbolType = symbolType;
  29060. this.add(symbolPath);
  29061. };
  29062. /**
  29063. * Stop animation
  29064. * @param {boolean} toLastFrame
  29065. */
  29066. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  29067. this.childAt(0).stopAnimation(toLastFrame);
  29068. };
  29069. /**
  29070. * FIXME:
  29071. * Caution: This method breaks the encapsulation of this module,
  29072. * but it indeed brings convenience. So do not use the method
  29073. * unless you detailedly know all the implements of `Symbol`,
  29074. * especially animation.
  29075. *
  29076. * Get symbol path element.
  29077. */
  29078. symbolProto.getSymbolPath = function () {
  29079. return this.childAt(0);
  29080. };
  29081. /**
  29082. * Get scale(aka, current symbol size).
  29083. * Including the change caused by animation
  29084. */
  29085. symbolProto.getScale = function () {
  29086. return this.childAt(0).scale;
  29087. };
  29088. /**
  29089. * Highlight symbol
  29090. */
  29091. symbolProto.highlight = function () {
  29092. this.childAt(0).trigger('emphasis');
  29093. };
  29094. /**
  29095. * Downplay symbol
  29096. */
  29097. symbolProto.downplay = function () {
  29098. this.childAt(0).trigger('normal');
  29099. };
  29100. /**
  29101. * @param {number} zlevel
  29102. * @param {number} z
  29103. */
  29104. symbolProto.setZ = function (zlevel, z) {
  29105. var symbolPath = this.childAt(0);
  29106. symbolPath.zlevel = zlevel;
  29107. symbolPath.z = z;
  29108. };
  29109. symbolProto.setDraggable = function (draggable) {
  29110. var symbolPath = this.childAt(0);
  29111. symbolPath.draggable = draggable;
  29112. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  29113. };
  29114. /**
  29115. * Update symbol properties
  29116. * @param {module:echarts/data/List} data
  29117. * @param {number} idx
  29118. * @param {Object} [seriesScope]
  29119. * @param {Object} [seriesScope.itemStyle]
  29120. * @param {Object} [seriesScope.hoverItemStyle]
  29121. * @param {Object} [seriesScope.symbolRotate]
  29122. * @param {Object} [seriesScope.symbolOffset]
  29123. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  29124. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  29125. * @param {boolean} [seriesScope.hoverAnimation]
  29126. * @param {Object} [seriesScope.cursorStyle]
  29127. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29128. * @param {string} [seriesScope.symbolInnerColor]
  29129. * @param {Object} [seriesScope.fadeIn=false]
  29130. */
  29131. symbolProto.updateData = function (data, idx, seriesScope) {
  29132. this.silent = false;
  29133. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29134. var seriesModel = data.hostModel;
  29135. var symbolSize = getSymbolSize(data, idx);
  29136. var isInit = symbolType !== this._symbolType;
  29137. if (isInit) {
  29138. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29139. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29140. }
  29141. else {
  29142. var symbolPath = this.childAt(0);
  29143. symbolPath.silent = false;
  29144. updateProps(symbolPath, {
  29145. scale: getScale(symbolSize)
  29146. }, seriesModel, idx);
  29147. }
  29148. this._updateCommon(data, idx, symbolSize, seriesScope);
  29149. if (isInit) {
  29150. var symbolPath = this.childAt(0);
  29151. var fadeIn = seriesScope && seriesScope.fadeIn;
  29152. var target = {scale: symbolPath.scale.slice()};
  29153. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29154. symbolPath.scale = [0, 0];
  29155. fadeIn && (symbolPath.style.opacity = 0);
  29156. initProps(symbolPath, target, seriesModel, idx);
  29157. }
  29158. this._seriesModel = seriesModel;
  29159. };
  29160. // Update common properties
  29161. var normalStyleAccessPath = ['itemStyle'];
  29162. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29163. var normalLabelAccessPath = ['label'];
  29164. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29165. /**
  29166. * @param {module:echarts/data/List} data
  29167. * @param {number} idx
  29168. * @param {Array.<number>} symbolSize
  29169. * @param {Object} [seriesScope]
  29170. */
  29171. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29172. var symbolPath = this.childAt(0);
  29173. var seriesModel = data.hostModel;
  29174. var color = data.getItemVisual(idx, 'color');
  29175. // Reset style
  29176. if (symbolPath.type !== 'image') {
  29177. symbolPath.useStyle({
  29178. strokeNoScale: true
  29179. });
  29180. }
  29181. else {
  29182. symbolPath.setStyle({
  29183. opacity: null,
  29184. shadowBlur: null,
  29185. shadowOffsetX: null,
  29186. shadowOffsetY: null,
  29187. shadowColor: null
  29188. });
  29189. }
  29190. var itemStyle = seriesScope && seriesScope.itemStyle;
  29191. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29192. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29193. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29194. var labelModel = seriesScope && seriesScope.labelModel;
  29195. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29196. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29197. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29198. if (!seriesScope || data.hasItemOption) {
  29199. var itemModel = (seriesScope && seriesScope.itemModel)
  29200. ? seriesScope.itemModel : data.getItemModel(idx);
  29201. // Color must be excluded.
  29202. // Because symbol provide setColor individually to set fill and stroke
  29203. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29204. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29205. symbolRotate = itemModel.getShallow('symbolRotate');
  29206. symbolOffset = itemModel.getShallow('symbolOffset');
  29207. labelModel = itemModel.getModel(normalLabelAccessPath);
  29208. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29209. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29210. cursorStyle = itemModel.getShallow('cursor');
  29211. }
  29212. else {
  29213. hoverItemStyle = extend({}, hoverItemStyle);
  29214. }
  29215. var elStyle = symbolPath.style;
  29216. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29217. if (symbolOffset) {
  29218. symbolPath.attr('position', [
  29219. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29220. parsePercent$1(symbolOffset[1], symbolSize[1])
  29221. ]);
  29222. }
  29223. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29224. // PENDING setColor before setStyle!!!
  29225. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29226. symbolPath.setStyle(itemStyle);
  29227. var opacity = data.getItemVisual(idx, 'opacity');
  29228. if (opacity != null) {
  29229. elStyle.opacity = opacity;
  29230. }
  29231. var liftZ = data.getItemVisual(idx, 'liftZ');
  29232. var z2Origin = symbolPath.__z2Origin;
  29233. if (liftZ != null) {
  29234. if (z2Origin == null) {
  29235. symbolPath.__z2Origin = symbolPath.z2;
  29236. symbolPath.z2 += liftZ;
  29237. }
  29238. }
  29239. else if (z2Origin != null) {
  29240. symbolPath.z2 = z2Origin;
  29241. symbolPath.__z2Origin = null;
  29242. }
  29243. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29244. setLabelStyle(
  29245. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29246. {
  29247. labelFetcher: seriesModel,
  29248. labelDataIndex: idx,
  29249. defaultText: getLabelDefaultText,
  29250. isRectText: true,
  29251. autoColor: color
  29252. }
  29253. );
  29254. // Do not execute util needed.
  29255. function getLabelDefaultText(idx, opt) {
  29256. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29257. }
  29258. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  29259. symbolPath.hoverStyle = hoverItemStyle;
  29260. symbolPath.highDownOnUpdate = (
  29261. hoverAnimation && seriesModel.isAnimationEnabled()
  29262. ) ? highDownOnUpdate : null;
  29263. setHoverStyle(symbolPath);
  29264. };
  29265. function highDownOnUpdate(fromState, toState) {
  29266. // Do not support this hover animation util some scenario required.
  29267. // Animation can only be supported in hover layer when using `el.incremetal`.
  29268. if (this.incremental || this.useHoverLayer) {
  29269. return;
  29270. }
  29271. if (toState === 'emphasis') {
  29272. var scale = this.__symbolOriginalScale;
  29273. var ratio = scale[1] / scale[0];
  29274. var emphasisOpt = {
  29275. scale: [
  29276. Math.max(scale[0] * 1.1, scale[0] + 3),
  29277. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29278. ]
  29279. };
  29280. // FIXME
  29281. // modify it after support stop specified animation.
  29282. // toState === fromState
  29283. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  29284. this.animateTo(emphasisOpt, 400, 'elasticOut');
  29285. }
  29286. else if (toState === 'normal') {
  29287. this.animateTo({
  29288. scale: this.__symbolOriginalScale
  29289. }, 400, 'elasticOut');
  29290. }
  29291. }
  29292. /**
  29293. * @param {Function} cb
  29294. * @param {Object} [opt]
  29295. * @param {Object} [opt.keepLabel=true]
  29296. */
  29297. symbolProto.fadeOut = function (cb, opt) {
  29298. var symbolPath = this.childAt(0);
  29299. // Avoid mistaken hover when fading out
  29300. this.silent = symbolPath.silent = true;
  29301. // Not show text when animating
  29302. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29303. updateProps(
  29304. symbolPath,
  29305. {
  29306. style: {opacity: 0},
  29307. scale: [0, 0]
  29308. },
  29309. this._seriesModel,
  29310. this.dataIndex,
  29311. cb
  29312. );
  29313. };
  29314. inherits(SymbolClz, Group);
  29315. /*
  29316. * Licensed to the Apache Software Foundation (ASF) under one
  29317. * or more contributor license agreements. See the NOTICE file
  29318. * distributed with this work for additional information
  29319. * regarding copyright ownership. The ASF licenses this file
  29320. * to you under the Apache License, Version 2.0 (the
  29321. * "License"); you may not use this file except in compliance
  29322. * with the License. You may obtain a copy of the License at
  29323. *
  29324. * http://www.apache.org/licenses/LICENSE-2.0
  29325. *
  29326. * Unless required by applicable law or agreed to in writing,
  29327. * software distributed under the License is distributed on an
  29328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29329. * KIND, either express or implied. See the License for the
  29330. * specific language governing permissions and limitations
  29331. * under the License.
  29332. */
  29333. /**
  29334. * @module echarts/chart/helper/SymbolDraw
  29335. */
  29336. /**
  29337. * @constructor
  29338. * @alias module:echarts/chart/helper/SymbolDraw
  29339. * @param {module:zrender/graphic/Group} [symbolCtor]
  29340. */
  29341. function SymbolDraw(symbolCtor) {
  29342. this.group = new Group();
  29343. this._symbolCtor = symbolCtor || SymbolClz;
  29344. }
  29345. var symbolDrawProto = SymbolDraw.prototype;
  29346. function symbolNeedsDraw(data, point, idx, opt) {
  29347. return point && !isNaN(point[0]) && !isNaN(point[1])
  29348. && !(opt.isIgnore && opt.isIgnore(idx))
  29349. // We do not set clipShape on group, because it will cut part of
  29350. // the symbol element shape. We use the same clip shape here as
  29351. // the line clip.
  29352. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29353. && data.getItemVisual(idx, 'symbol') !== 'none';
  29354. }
  29355. /**
  29356. * Update symbols draw by new data
  29357. * @param {module:echarts/data/List} data
  29358. * @param {Object} [opt] Or isIgnore
  29359. * @param {Function} [opt.isIgnore]
  29360. * @param {Object} [opt.clipShape]
  29361. */
  29362. symbolDrawProto.updateData = function (data, opt) {
  29363. opt = normalizeUpdateOpt(opt);
  29364. var group = this.group;
  29365. var seriesModel = data.hostModel;
  29366. var oldData = this._data;
  29367. var SymbolCtor = this._symbolCtor;
  29368. var seriesScope = makeSeriesScope(data);
  29369. // There is no oldLineData only when first rendering or switching from
  29370. // stream mode to normal mode, where previous elements should be removed.
  29371. if (!oldData) {
  29372. group.removeAll();
  29373. }
  29374. data.diff(oldData)
  29375. .add(function (newIdx) {
  29376. var point = data.getItemLayout(newIdx);
  29377. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29378. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29379. symbolEl.attr('position', point);
  29380. data.setItemGraphicEl(newIdx, symbolEl);
  29381. group.add(symbolEl);
  29382. }
  29383. })
  29384. .update(function (newIdx, oldIdx) {
  29385. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29386. var point = data.getItemLayout(newIdx);
  29387. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29388. group.remove(symbolEl);
  29389. return;
  29390. }
  29391. if (!symbolEl) {
  29392. symbolEl = new SymbolCtor(data, newIdx);
  29393. symbolEl.attr('position', point);
  29394. }
  29395. else {
  29396. symbolEl.updateData(data, newIdx, seriesScope);
  29397. updateProps(symbolEl, {
  29398. position: point
  29399. }, seriesModel);
  29400. }
  29401. // Add back
  29402. group.add(symbolEl);
  29403. data.setItemGraphicEl(newIdx, symbolEl);
  29404. })
  29405. .remove(function (oldIdx) {
  29406. var el = oldData.getItemGraphicEl(oldIdx);
  29407. el && el.fadeOut(function () {
  29408. group.remove(el);
  29409. });
  29410. })
  29411. .execute();
  29412. this._data = data;
  29413. };
  29414. symbolDrawProto.isPersistent = function () {
  29415. return true;
  29416. };
  29417. symbolDrawProto.updateLayout = function () {
  29418. var data = this._data;
  29419. if (data) {
  29420. // Not use animation
  29421. data.eachItemGraphicEl(function (el, idx) {
  29422. var point = data.getItemLayout(idx);
  29423. el.attr('position', point);
  29424. });
  29425. }
  29426. };
  29427. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29428. this._seriesScope = makeSeriesScope(data);
  29429. this._data = null;
  29430. this.group.removeAll();
  29431. };
  29432. /**
  29433. * Update symbols draw by new data
  29434. * @param {module:echarts/data/List} data
  29435. * @param {Object} [opt] Or isIgnore
  29436. * @param {Function} [opt.isIgnore]
  29437. * @param {Object} [opt.clipShape]
  29438. */
  29439. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29440. opt = normalizeUpdateOpt(opt);
  29441. function updateIncrementalAndHover(el) {
  29442. if (!el.isGroup) {
  29443. el.incremental = el.useHoverLayer = true;
  29444. }
  29445. }
  29446. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29447. var point = data.getItemLayout(idx);
  29448. if (symbolNeedsDraw(data, point, idx, opt)) {
  29449. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29450. el.traverse(updateIncrementalAndHover);
  29451. el.attr('position', point);
  29452. this.group.add(el);
  29453. data.setItemGraphicEl(idx, el);
  29454. }
  29455. }
  29456. };
  29457. function normalizeUpdateOpt(opt) {
  29458. if (opt != null && !isObject$1(opt)) {
  29459. opt = {isIgnore: opt};
  29460. }
  29461. return opt || {};
  29462. }
  29463. symbolDrawProto.remove = function (enableAnimation) {
  29464. var group = this.group;
  29465. var data = this._data;
  29466. // Incremental model do not have this._data.
  29467. if (data && enableAnimation) {
  29468. data.eachItemGraphicEl(function (el) {
  29469. el.fadeOut(function () {
  29470. group.remove(el);
  29471. });
  29472. });
  29473. }
  29474. else {
  29475. group.removeAll();
  29476. }
  29477. };
  29478. function makeSeriesScope(data) {
  29479. var seriesModel = data.hostModel;
  29480. return {
  29481. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29482. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29483. symbolRotate: seriesModel.get('symbolRotate'),
  29484. symbolOffset: seriesModel.get('symbolOffset'),
  29485. hoverAnimation: seriesModel.get('hoverAnimation'),
  29486. labelModel: seriesModel.getModel('label'),
  29487. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29488. cursorStyle: seriesModel.get('cursor')
  29489. };
  29490. }
  29491. /*
  29492. * Licensed to the Apache Software Foundation (ASF) under one
  29493. * or more contributor license agreements. See the NOTICE file
  29494. * distributed with this work for additional information
  29495. * regarding copyright ownership. The ASF licenses this file
  29496. * to you under the Apache License, Version 2.0 (the
  29497. * "License"); you may not use this file except in compliance
  29498. * with the License. You may obtain a copy of the License at
  29499. *
  29500. * http://www.apache.org/licenses/LICENSE-2.0
  29501. *
  29502. * Unless required by applicable law or agreed to in writing,
  29503. * software distributed under the License is distributed on an
  29504. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29505. * KIND, either express or implied. See the License for the
  29506. * specific language governing permissions and limitations
  29507. * under the License.
  29508. */
  29509. /**
  29510. * @param {Object} coordSys
  29511. * @param {module:echarts/data/List} data
  29512. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29513. */
  29514. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29515. var baseAxis = coordSys.getBaseAxis();
  29516. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29517. var valueStart = getValueStart(valueAxis, valueOrigin);
  29518. var baseAxisDim = baseAxis.dim;
  29519. var valueAxisDim = valueAxis.dim;
  29520. var valueDim = data.mapDimension(valueAxisDim);
  29521. var baseDim = data.mapDimension(baseAxisDim);
  29522. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29523. var dims = map(coordSys.dimensions, function (coordDim) {
  29524. return data.mapDimension(coordDim);
  29525. });
  29526. var stacked;
  29527. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29528. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  29529. dims[0] = stackResultDim;
  29530. }
  29531. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  29532. dims[1] = stackResultDim;
  29533. }
  29534. return {
  29535. dataDimsForPoint: dims,
  29536. valueStart: valueStart,
  29537. valueAxisDim: valueAxisDim,
  29538. baseAxisDim: baseAxisDim,
  29539. stacked: !!stacked,
  29540. valueDim: valueDim,
  29541. baseDim: baseDim,
  29542. baseDataOffset: baseDataOffset,
  29543. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29544. };
  29545. }
  29546. function getValueStart(valueAxis, valueOrigin) {
  29547. var valueStart = 0;
  29548. var extent = valueAxis.scale.getExtent();
  29549. if (valueOrigin === 'start') {
  29550. valueStart = extent[0];
  29551. }
  29552. else if (valueOrigin === 'end') {
  29553. valueStart = extent[1];
  29554. }
  29555. // auto
  29556. else {
  29557. // Both positive
  29558. if (extent[0] > 0) {
  29559. valueStart = extent[0];
  29560. }
  29561. // Both negative
  29562. else if (extent[1] < 0) {
  29563. valueStart = extent[1];
  29564. }
  29565. // If is one positive, and one negative, onZero shall be true
  29566. }
  29567. return valueStart;
  29568. }
  29569. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  29570. var value = NaN;
  29571. if (dataCoordInfo.stacked) {
  29572. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  29573. }
  29574. if (isNaN(value)) {
  29575. value = dataCoordInfo.valueStart;
  29576. }
  29577. var baseDataOffset = dataCoordInfo.baseDataOffset;
  29578. var stackedData = [];
  29579. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  29580. stackedData[1 - baseDataOffset] = value;
  29581. return coordSys.dataToPoint(stackedData);
  29582. }
  29583. /*
  29584. * Licensed to the Apache Software Foundation (ASF) under one
  29585. * or more contributor license agreements. See the NOTICE file
  29586. * distributed with this work for additional information
  29587. * regarding copyright ownership. The ASF licenses this file
  29588. * to you under the Apache License, Version 2.0 (the
  29589. * "License"); you may not use this file except in compliance
  29590. * with the License. You may obtain a copy of the License at
  29591. *
  29592. * http://www.apache.org/licenses/LICENSE-2.0
  29593. *
  29594. * Unless required by applicable law or agreed to in writing,
  29595. * software distributed under the License is distributed on an
  29596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29597. * KIND, either express or implied. See the License for the
  29598. * specific language governing permissions and limitations
  29599. * under the License.
  29600. */
  29601. // var arrayDiff = require('zrender/src/core/arrayDiff');
  29602. // 'zrender/src/core/arrayDiff' has been used before, but it did
  29603. // not do well in performance when roam with fixed dataZoom window.
  29604. // function convertToIntId(newIdList, oldIdList) {
  29605. // // Generate int id instead of string id.
  29606. // // Compare string maybe slow in score function of arrDiff
  29607. // // Assume id in idList are all unique
  29608. // var idIndicesMap = {};
  29609. // var idx = 0;
  29610. // for (var i = 0; i < newIdList.length; i++) {
  29611. // idIndicesMap[newIdList[i]] = idx;
  29612. // newIdList[i] = idx++;
  29613. // }
  29614. // for (var i = 0; i < oldIdList.length; i++) {
  29615. // var oldId = oldIdList[i];
  29616. // // Same with newIdList
  29617. // if (idIndicesMap[oldId]) {
  29618. // oldIdList[i] = idIndicesMap[oldId];
  29619. // }
  29620. // else {
  29621. // oldIdList[i] = idx++;
  29622. // }
  29623. // }
  29624. // }
  29625. function diffData(oldData, newData) {
  29626. var diffResult = [];
  29627. newData.diff(oldData)
  29628. .add(function (idx) {
  29629. diffResult.push({cmd: '+', idx: idx});
  29630. })
  29631. .update(function (newIdx, oldIdx) {
  29632. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  29633. })
  29634. .remove(function (idx) {
  29635. diffResult.push({cmd: '-', idx: idx});
  29636. })
  29637. .execute();
  29638. return diffResult;
  29639. }
  29640. var lineAnimationDiff = function (
  29641. oldData, newData,
  29642. oldStackedOnPoints, newStackedOnPoints,
  29643. oldCoordSys, newCoordSys,
  29644. oldValueOrigin, newValueOrigin
  29645. ) {
  29646. var diff = diffData(oldData, newData);
  29647. // var newIdList = newData.mapArray(newData.getId);
  29648. // var oldIdList = oldData.mapArray(oldData.getId);
  29649. // convertToIntId(newIdList, oldIdList);
  29650. // // FIXME One data ?
  29651. // diff = arrayDiff(oldIdList, newIdList);
  29652. var currPoints = [];
  29653. var nextPoints = [];
  29654. // Points for stacking base line
  29655. var currStackedPoints = [];
  29656. var nextStackedPoints = [];
  29657. var status = [];
  29658. var sortedIndices = [];
  29659. var rawIndices = [];
  29660. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  29661. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  29662. for (var i = 0; i < diff.length; i++) {
  29663. var diffItem = diff[i];
  29664. var pointAdded = true;
  29665. // FIXME, animation is not so perfect when dataZoom window moves fast
  29666. // Which is in case remvoing or add more than one data in the tail or head
  29667. switch (diffItem.cmd) {
  29668. case '=':
  29669. var currentPt = oldData.getItemLayout(diffItem.idx);
  29670. var nextPt = newData.getItemLayout(diffItem.idx1);
  29671. // If previous data is NaN, use next point directly
  29672. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  29673. currentPt = nextPt.slice();
  29674. }
  29675. currPoints.push(currentPt);
  29676. nextPoints.push(nextPt);
  29677. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  29678. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  29679. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  29680. break;
  29681. case '+':
  29682. var idx = diffItem.idx;
  29683. currPoints.push(
  29684. oldCoordSys.dataToPoint([
  29685. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  29686. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  29687. ])
  29688. );
  29689. nextPoints.push(newData.getItemLayout(idx).slice());
  29690. currStackedPoints.push(
  29691. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  29692. );
  29693. nextStackedPoints.push(newStackedOnPoints[idx]);
  29694. rawIndices.push(newData.getRawIndex(idx));
  29695. break;
  29696. case '-':
  29697. var idx = diffItem.idx;
  29698. var rawIndex = oldData.getRawIndex(idx);
  29699. // Data is replaced. In the case of dynamic data queue
  29700. // FIXME FIXME FIXME
  29701. if (rawIndex !== idx) {
  29702. currPoints.push(oldData.getItemLayout(idx));
  29703. nextPoints.push(newCoordSys.dataToPoint([
  29704. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  29705. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  29706. ]));
  29707. currStackedPoints.push(oldStackedOnPoints[idx]);
  29708. nextStackedPoints.push(
  29709. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  29710. );
  29711. rawIndices.push(rawIndex);
  29712. }
  29713. else {
  29714. pointAdded = false;
  29715. }
  29716. }
  29717. // Original indices
  29718. if (pointAdded) {
  29719. status.push(diffItem);
  29720. sortedIndices.push(sortedIndices.length);
  29721. }
  29722. }
  29723. // Diff result may be crossed if all items are changed
  29724. // Sort by data index
  29725. sortedIndices.sort(function (a, b) {
  29726. return rawIndices[a] - rawIndices[b];
  29727. });
  29728. var sortedCurrPoints = [];
  29729. var sortedNextPoints = [];
  29730. var sortedCurrStackedPoints = [];
  29731. var sortedNextStackedPoints = [];
  29732. var sortedStatus = [];
  29733. for (var i = 0; i < sortedIndices.length; i++) {
  29734. var idx = sortedIndices[i];
  29735. sortedCurrPoints[i] = currPoints[idx];
  29736. sortedNextPoints[i] = nextPoints[idx];
  29737. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  29738. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  29739. sortedStatus[i] = status[idx];
  29740. }
  29741. return {
  29742. current: sortedCurrPoints,
  29743. next: sortedNextPoints,
  29744. stackedOnCurrent: sortedCurrStackedPoints,
  29745. stackedOnNext: sortedNextStackedPoints,
  29746. status: sortedStatus
  29747. };
  29748. };
  29749. /*
  29750. * Licensed to the Apache Software Foundation (ASF) under one
  29751. * or more contributor license agreements. See the NOTICE file
  29752. * distributed with this work for additional information
  29753. * regarding copyright ownership. The ASF licenses this file
  29754. * to you under the Apache License, Version 2.0 (the
  29755. * "License"); you may not use this file except in compliance
  29756. * with the License. You may obtain a copy of the License at
  29757. *
  29758. * http://www.apache.org/licenses/LICENSE-2.0
  29759. *
  29760. * Unless required by applicable law or agreed to in writing,
  29761. * software distributed under the License is distributed on an
  29762. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29763. * KIND, either express or implied. See the License for the
  29764. * specific language governing permissions and limitations
  29765. * under the License.
  29766. */
  29767. // Poly path support NaN point
  29768. var vec2Min = min;
  29769. var vec2Max = max;
  29770. var scaleAndAdd$1 = scaleAndAdd;
  29771. var v2Copy = copy;
  29772. // Temporary variable
  29773. var v = [];
  29774. var cp0 = [];
  29775. var cp1 = [];
  29776. function isPointNull(p) {
  29777. return isNaN(p[0]) || isNaN(p[1]);
  29778. }
  29779. function drawSegment(
  29780. ctx, points, start, segLen, allLen,
  29781. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29782. ) {
  29783. // if (smoothMonotone == null) {
  29784. // if (isMono(points, 'x')) {
  29785. // return drawMono(ctx, points, start, segLen, allLen,
  29786. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  29787. // }
  29788. // else if (isMono(points, 'y')) {
  29789. // return drawMono(ctx, points, start, segLen, allLen,
  29790. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  29791. // }
  29792. // else {
  29793. // return drawNonMono.apply(this, arguments);
  29794. // }
  29795. // }
  29796. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  29797. // return drawMono.apply(this, arguments);
  29798. // }
  29799. // else {
  29800. // return drawNonMono.apply(this, arguments);
  29801. // }
  29802. if (smoothMonotone === 'none' || !smoothMonotone) {
  29803. return drawNonMono.apply(this, arguments);
  29804. }
  29805. else {
  29806. return drawMono.apply(this, arguments);
  29807. }
  29808. }
  29809. /**
  29810. * Check if points is in monotone.
  29811. *
  29812. * @param {number[][]} points Array of points which is in [x, y] form
  29813. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  29814. * dimension that is checking.
  29815. * If is 'none', `drawNonMono` should be
  29816. * called.
  29817. * If is undefined, either being monotone
  29818. * in 'x' or 'y' will call `drawMono`.
  29819. */
  29820. // function isMono(points, smoothMonotone) {
  29821. // if (points.length <= 1) {
  29822. // return true;
  29823. // }
  29824. // var dim = smoothMonotone === 'x' ? 0 : 1;
  29825. // var last = points[0][dim];
  29826. // var lastDiff = 0;
  29827. // for (var i = 1; i < points.length; ++i) {
  29828. // var diff = points[i][dim] - last;
  29829. // if (!isNaN(diff) && !isNaN(lastDiff)
  29830. // && diff !== 0 && lastDiff !== 0
  29831. // && ((diff >= 0) !== (lastDiff >= 0))
  29832. // ) {
  29833. // return false;
  29834. // }
  29835. // if (!isNaN(diff) && diff !== 0) {
  29836. // lastDiff = diff;
  29837. // last = points[i][dim];
  29838. // }
  29839. // }
  29840. // return true;
  29841. // }
  29842. /**
  29843. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  29844. * control points will be used. This should be used when points are monotone
  29845. * either in x or y dimension.
  29846. */
  29847. function drawMono(
  29848. ctx, points, start, segLen, allLen,
  29849. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29850. ) {
  29851. var prevIdx = 0;
  29852. var idx = start;
  29853. for (var k = 0; k < segLen; k++) {
  29854. var p = points[idx];
  29855. if (idx >= allLen || idx < 0) {
  29856. break;
  29857. }
  29858. if (isPointNull(p)) {
  29859. if (connectNulls) {
  29860. idx += dir;
  29861. continue;
  29862. }
  29863. break;
  29864. }
  29865. if (idx === start) {
  29866. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29867. }
  29868. else {
  29869. if (smooth > 0) {
  29870. var prevP = points[prevIdx];
  29871. var dim = smoothMonotone === 'y' ? 1 : 0;
  29872. // Length of control point to p, either in x or y, but not both
  29873. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  29874. v2Copy(cp0, prevP);
  29875. cp0[dim] = prevP[dim] + ctrlLen;
  29876. v2Copy(cp1, p);
  29877. cp1[dim] = p[dim] - ctrlLen;
  29878. ctx.bezierCurveTo(
  29879. cp0[0], cp0[1],
  29880. cp1[0], cp1[1],
  29881. p[0], p[1]
  29882. );
  29883. }
  29884. else {
  29885. ctx.lineTo(p[0], p[1]);
  29886. }
  29887. }
  29888. prevIdx = idx;
  29889. idx += dir;
  29890. }
  29891. return k;
  29892. }
  29893. /**
  29894. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  29895. * situations. This should be used when points are non-monotone neither in x or
  29896. * y dimension.
  29897. */
  29898. function drawNonMono(
  29899. ctx, points, start, segLen, allLen,
  29900. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29901. ) {
  29902. var prevIdx = 0;
  29903. var idx = start;
  29904. for (var k = 0; k < segLen; k++) {
  29905. var p = points[idx];
  29906. if (idx >= allLen || idx < 0) {
  29907. break;
  29908. }
  29909. if (isPointNull(p)) {
  29910. if (connectNulls) {
  29911. idx += dir;
  29912. continue;
  29913. }
  29914. break;
  29915. }
  29916. if (idx === start) {
  29917. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29918. v2Copy(cp0, p);
  29919. }
  29920. else {
  29921. if (smooth > 0) {
  29922. var nextIdx = idx + dir;
  29923. var nextP = points[nextIdx];
  29924. if (connectNulls) {
  29925. // Find next point not null
  29926. while (nextP && isPointNull(points[nextIdx])) {
  29927. nextIdx += dir;
  29928. nextP = points[nextIdx];
  29929. }
  29930. }
  29931. var ratioNextSeg = 0.5;
  29932. var prevP = points[prevIdx];
  29933. var nextP = points[nextIdx];
  29934. // Last point
  29935. if (!nextP || isPointNull(nextP)) {
  29936. v2Copy(cp1, p);
  29937. }
  29938. else {
  29939. // If next data is null in not connect case
  29940. if (isPointNull(nextP) && !connectNulls) {
  29941. nextP = p;
  29942. }
  29943. sub(v, nextP, prevP);
  29944. var lenPrevSeg;
  29945. var lenNextSeg;
  29946. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  29947. var dim = smoothMonotone === 'x' ? 0 : 1;
  29948. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  29949. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  29950. }
  29951. else {
  29952. lenPrevSeg = dist(p, prevP);
  29953. lenNextSeg = dist(p, nextP);
  29954. }
  29955. // Use ratio of seg length
  29956. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  29957. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  29958. }
  29959. // Smooth constraint
  29960. vec2Min(cp0, cp0, smoothMax);
  29961. vec2Max(cp0, cp0, smoothMin);
  29962. vec2Min(cp1, cp1, smoothMax);
  29963. vec2Max(cp1, cp1, smoothMin);
  29964. ctx.bezierCurveTo(
  29965. cp0[0], cp0[1],
  29966. cp1[0], cp1[1],
  29967. p[0], p[1]
  29968. );
  29969. // cp0 of next segment
  29970. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  29971. }
  29972. else {
  29973. ctx.lineTo(p[0], p[1]);
  29974. }
  29975. }
  29976. prevIdx = idx;
  29977. idx += dir;
  29978. }
  29979. return k;
  29980. }
  29981. function getBoundingBox(points, smoothConstraint) {
  29982. var ptMin = [Infinity, Infinity];
  29983. var ptMax = [-Infinity, -Infinity];
  29984. if (smoothConstraint) {
  29985. for (var i = 0; i < points.length; i++) {
  29986. var pt = points[i];
  29987. if (pt[0] < ptMin[0]) {
  29988. ptMin[0] = pt[0];
  29989. }
  29990. if (pt[1] < ptMin[1]) {
  29991. ptMin[1] = pt[1];
  29992. }
  29993. if (pt[0] > ptMax[0]) {
  29994. ptMax[0] = pt[0];
  29995. }
  29996. if (pt[1] > ptMax[1]) {
  29997. ptMax[1] = pt[1];
  29998. }
  29999. }
  30000. }
  30001. return {
  30002. min: smoothConstraint ? ptMin : ptMax,
  30003. max: smoothConstraint ? ptMax : ptMin
  30004. };
  30005. }
  30006. var Polyline$1 = Path.extend({
  30007. type: 'ec-polyline',
  30008. shape: {
  30009. points: [],
  30010. smooth: 0,
  30011. smoothConstraint: true,
  30012. smoothMonotone: null,
  30013. connectNulls: false
  30014. },
  30015. style: {
  30016. fill: null,
  30017. stroke: '#000'
  30018. },
  30019. brush: fixClipWithShadow(Path.prototype.brush),
  30020. buildPath: function (ctx, shape) {
  30021. var points = shape.points;
  30022. var i = 0;
  30023. var len$$1 = points.length;
  30024. var result = getBoundingBox(points, shape.smoothConstraint);
  30025. if (shape.connectNulls) {
  30026. // Must remove first and last null values avoid draw error in polygon
  30027. for (; len$$1 > 0; len$$1--) {
  30028. if (!isPointNull(points[len$$1 - 1])) {
  30029. break;
  30030. }
  30031. }
  30032. for (; i < len$$1; i++) {
  30033. if (!isPointNull(points[i])) {
  30034. break;
  30035. }
  30036. }
  30037. }
  30038. while (i < len$$1) {
  30039. i += drawSegment(
  30040. ctx, points, i, len$$1, len$$1,
  30041. 1, result.min, result.max, shape.smooth,
  30042. shape.smoothMonotone, shape.connectNulls
  30043. ) + 1;
  30044. }
  30045. }
  30046. });
  30047. var Polygon$1 = Path.extend({
  30048. type: 'ec-polygon',
  30049. shape: {
  30050. points: [],
  30051. // Offset between stacked base points and points
  30052. stackedOnPoints: [],
  30053. smooth: 0,
  30054. stackedOnSmooth: 0,
  30055. smoothConstraint: true,
  30056. smoothMonotone: null,
  30057. connectNulls: false
  30058. },
  30059. brush: fixClipWithShadow(Path.prototype.brush),
  30060. buildPath: function (ctx, shape) {
  30061. var points = shape.points;
  30062. var stackedOnPoints = shape.stackedOnPoints;
  30063. var i = 0;
  30064. var len$$1 = points.length;
  30065. var smoothMonotone = shape.smoothMonotone;
  30066. var bbox = getBoundingBox(points, shape.smoothConstraint);
  30067. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  30068. if (shape.connectNulls) {
  30069. // Must remove first and last null values avoid draw error in polygon
  30070. for (; len$$1 > 0; len$$1--) {
  30071. if (!isPointNull(points[len$$1 - 1])) {
  30072. break;
  30073. }
  30074. }
  30075. for (; i < len$$1; i++) {
  30076. if (!isPointNull(points[i])) {
  30077. break;
  30078. }
  30079. }
  30080. }
  30081. while (i < len$$1) {
  30082. var k = drawSegment(
  30083. ctx, points, i, len$$1, len$$1,
  30084. 1, bbox.min, bbox.max, shape.smooth,
  30085. smoothMonotone, shape.connectNulls
  30086. );
  30087. drawSegment(
  30088. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  30089. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  30090. smoothMonotone, shape.connectNulls
  30091. );
  30092. i += k + 1;
  30093. ctx.closePath();
  30094. }
  30095. }
  30096. });
  30097. /*
  30098. * Licensed to the Apache Software Foundation (ASF) under one
  30099. * or more contributor license agreements. See the NOTICE file
  30100. * distributed with this work for additional information
  30101. * regarding copyright ownership. The ASF licenses this file
  30102. * to you under the Apache License, Version 2.0 (the
  30103. * "License"); you may not use this file except in compliance
  30104. * with the License. You may obtain a copy of the License at
  30105. *
  30106. * http://www.apache.org/licenses/LICENSE-2.0
  30107. *
  30108. * Unless required by applicable law or agreed to in writing,
  30109. * software distributed under the License is distributed on an
  30110. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30111. * KIND, either express or implied. See the License for the
  30112. * specific language governing permissions and limitations
  30113. * under the License.
  30114. */
  30115. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  30116. var rect = cartesian.getArea();
  30117. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  30118. var x = rect.x;
  30119. var y = rect.y;
  30120. var width = rect.width;
  30121. var height = rect.height;
  30122. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  30123. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  30124. x -= lineWidth / 2;
  30125. y -= lineWidth / 2;
  30126. width += lineWidth;
  30127. height += lineWidth;
  30128. var clipPath = new Rect({
  30129. shape: {
  30130. x: x,
  30131. y: y,
  30132. width: width,
  30133. height: height
  30134. }
  30135. });
  30136. if (hasAnimation) {
  30137. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30138. initProps(clipPath, {
  30139. shape: {
  30140. width: width,
  30141. height: height
  30142. }
  30143. }, seriesModel);
  30144. }
  30145. return clipPath;
  30146. }
  30147. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  30148. var sectorArea = polar.getArea();
  30149. // Avoid float number rounding error for symbol on the edge of axis extent.
  30150. var clipPath = new Sector({
  30151. shape: {
  30152. cx: round$1(polar.cx, 1),
  30153. cy: round$1(polar.cy, 1),
  30154. r0: round$1(sectorArea.r0, 1),
  30155. r: round$1(sectorArea.r, 1),
  30156. startAngle: sectorArea.startAngle,
  30157. endAngle: sectorArea.endAngle,
  30158. clockwise: sectorArea.clockwise
  30159. }
  30160. });
  30161. if (hasAnimation) {
  30162. clipPath.shape.endAngle = sectorArea.startAngle;
  30163. initProps(clipPath, {
  30164. shape: {
  30165. endAngle: sectorArea.endAngle
  30166. }
  30167. }, seriesModel);
  30168. }
  30169. return clipPath;
  30170. }
  30171. function createClipPath(coordSys, hasAnimation, seriesModel) {
  30172. if (!coordSys) {
  30173. return null;
  30174. }
  30175. else if (coordSys.type === 'polar') {
  30176. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30177. }
  30178. else if (coordSys.type === 'cartesian2d') {
  30179. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  30180. }
  30181. return null;
  30182. }
  30183. /*
  30184. * Licensed to the Apache Software Foundation (ASF) under one
  30185. * or more contributor license agreements. See the NOTICE file
  30186. * distributed with this work for additional information
  30187. * regarding copyright ownership. The ASF licenses this file
  30188. * to you under the Apache License, Version 2.0 (the
  30189. * "License"); you may not use this file except in compliance
  30190. * with the License. You may obtain a copy of the License at
  30191. *
  30192. * http://www.apache.org/licenses/LICENSE-2.0
  30193. *
  30194. * Unless required by applicable law or agreed to in writing,
  30195. * software distributed under the License is distributed on an
  30196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30197. * KIND, either express or implied. See the License for the
  30198. * specific language governing permissions and limitations
  30199. * under the License.
  30200. */
  30201. // FIXME step not support polar
  30202. function isPointsSame(points1, points2) {
  30203. if (points1.length !== points2.length) {
  30204. return;
  30205. }
  30206. for (var i = 0; i < points1.length; i++) {
  30207. var p1 = points1[i];
  30208. var p2 = points2[i];
  30209. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30210. return;
  30211. }
  30212. }
  30213. return true;
  30214. }
  30215. function getSmooth(smooth) {
  30216. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30217. }
  30218. /**
  30219. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30220. * @param {module:echarts/data/List} data
  30221. * @param {Object} dataCoordInfo
  30222. * @param {Array.<Array.<number>>} points
  30223. */
  30224. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30225. if (!dataCoordInfo.valueDim) {
  30226. return [];
  30227. }
  30228. var points = [];
  30229. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30230. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30231. }
  30232. return points;
  30233. }
  30234. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30235. var baseAxis = coordSys.getBaseAxis();
  30236. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30237. var stepPoints = [];
  30238. for (var i = 0; i < points.length - 1; i++) {
  30239. var nextPt = points[i + 1];
  30240. var pt = points[i];
  30241. stepPoints.push(pt);
  30242. var stepPt = [];
  30243. switch (stepTurnAt) {
  30244. case 'end':
  30245. stepPt[baseIndex] = nextPt[baseIndex];
  30246. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30247. // default is start
  30248. stepPoints.push(stepPt);
  30249. break;
  30250. case 'middle':
  30251. // default is start
  30252. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30253. var stepPt2 = [];
  30254. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30255. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30256. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30257. stepPoints.push(stepPt);
  30258. stepPoints.push(stepPt2);
  30259. break;
  30260. default:
  30261. stepPt[baseIndex] = pt[baseIndex];
  30262. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30263. // default is start
  30264. stepPoints.push(stepPt);
  30265. }
  30266. }
  30267. // Last points
  30268. points[i] && stepPoints.push(points[i]);
  30269. return stepPoints;
  30270. }
  30271. function getVisualGradient(data, coordSys) {
  30272. var visualMetaList = data.getVisual('visualMeta');
  30273. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30274. // When data.count() is 0, gradient range can not be calculated.
  30275. return;
  30276. }
  30277. if (coordSys.type !== 'cartesian2d') {
  30278. if (__DEV__) {
  30279. console.warn('Visual map on line style is only supported on cartesian2d.');
  30280. }
  30281. return;
  30282. }
  30283. var coordDim;
  30284. var visualMeta;
  30285. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30286. var dimIndex = visualMetaList[i].dimension;
  30287. var dimName = data.dimensions[dimIndex];
  30288. var dimInfo = data.getDimensionInfo(dimName);
  30289. coordDim = dimInfo && dimInfo.coordDim;
  30290. // Can only be x or y
  30291. if (coordDim === 'x' || coordDim === 'y') {
  30292. visualMeta = visualMetaList[i];
  30293. break;
  30294. }
  30295. }
  30296. if (!visualMeta) {
  30297. if (__DEV__) {
  30298. console.warn('Visual map on line style only support x or y dimension.');
  30299. }
  30300. return;
  30301. }
  30302. // If the area to be rendered is bigger than area defined by LinearGradient,
  30303. // the canvas spec prescribes that the color of the first stop and the last
  30304. // stop should be used. But if two stops are added at offset 0, in effect
  30305. // browsers use the color of the second stop to render area outside
  30306. // LinearGradient. So we can only infinitesimally extend area defined in
  30307. // LinearGradient to render `outerColors`.
  30308. var axis = coordSys.getAxis(coordDim);
  30309. // dataToCoor mapping may not be linear, but must be monotonic.
  30310. var colorStops = map(visualMeta.stops, function (stop) {
  30311. return {
  30312. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30313. color: stop.color
  30314. };
  30315. });
  30316. var stopLen = colorStops.length;
  30317. var outerColors = visualMeta.outerColors.slice();
  30318. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30319. colorStops.reverse();
  30320. outerColors.reverse();
  30321. }
  30322. var tinyExtent = 10; // Arbitrary value: 10px
  30323. var minCoord = colorStops[0].coord - tinyExtent;
  30324. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30325. var coordSpan = maxCoord - minCoord;
  30326. if (coordSpan < 1e-3) {
  30327. return 'transparent';
  30328. }
  30329. each$1(colorStops, function (stop) {
  30330. stop.offset = (stop.coord - minCoord) / coordSpan;
  30331. });
  30332. colorStops.push({
  30333. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30334. color: outerColors[1] || 'transparent'
  30335. });
  30336. colorStops.unshift({ // notice colorStops.length have been changed.
  30337. offset: stopLen ? colorStops[0].offset : 0.5,
  30338. color: outerColors[0] || 'transparent'
  30339. });
  30340. // zrUtil.each(colorStops, function (colorStop) {
  30341. // // Make sure each offset has rounded px to avoid not sharp edge
  30342. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30343. // });
  30344. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30345. gradient[coordDim] = minCoord;
  30346. gradient[coordDim + '2'] = maxCoord;
  30347. return gradient;
  30348. }
  30349. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30350. var showAllSymbol = seriesModel.get('showAllSymbol');
  30351. var isAuto = showAllSymbol === 'auto';
  30352. if (showAllSymbol && !isAuto) {
  30353. return;
  30354. }
  30355. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30356. if (!categoryAxis) {
  30357. return;
  30358. }
  30359. // Note that category label interval strategy might bring some weird effect
  30360. // in some scenario: users may wonder why some of the symbols are not
  30361. // displayed. So we show all symbols as possible as we can.
  30362. if (isAuto
  30363. // Simplify the logic, do not determine label overlap here.
  30364. && canShowAllSymbolForCategory(categoryAxis, data)
  30365. ) {
  30366. return;
  30367. }
  30368. // Otherwise follow the label interval strategy on category axis.
  30369. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30370. var labelMap = {};
  30371. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30372. labelMap[labelItem.tickValue] = 1;
  30373. });
  30374. return function (dataIndex) {
  30375. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30376. };
  30377. }
  30378. function canShowAllSymbolForCategory(categoryAxis, data) {
  30379. // In mose cases, line is monotonous on category axis, and the label size
  30380. // is close with each other. So we check the symbol size and some of the
  30381. // label size alone with the category axis to estimate whether all symbol
  30382. // can be shown without overlap.
  30383. var axisExtent = categoryAxis.getExtent();
  30384. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30385. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30386. // Sampling some points, max 5.
  30387. var dataLen = data.count();
  30388. var step = Math.max(1, Math.round(dataLen / 5));
  30389. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30390. if (SymbolClz.getSymbolSize(
  30391. data, dataIndex
  30392. // Only for cartesian, where `isHorizontal` exists.
  30393. )[categoryAxis.isHorizontal() ? 1 : 0]
  30394. // Empirical number
  30395. * 1.5 > availSize
  30396. ) {
  30397. return false;
  30398. }
  30399. }
  30400. return true;
  30401. }
  30402. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  30403. if (coordSys.type === 'cartesian2d') {
  30404. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  30405. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  30406. // Expand clip shape to avoid clipping when line value exceeds axis
  30407. if (!seriesModel.get('clip', true)) {
  30408. var rectShape = clipPath.shape;
  30409. var expandSize = Math.max(rectShape.width, rectShape.height);
  30410. if (isHorizontal) {
  30411. rectShape.y -= expandSize;
  30412. rectShape.height += expandSize * 2;
  30413. }
  30414. else {
  30415. rectShape.x -= expandSize;
  30416. rectShape.width += expandSize * 2;
  30417. }
  30418. }
  30419. return clipPath;
  30420. }
  30421. else {
  30422. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30423. }
  30424. }
  30425. Chart.extend({
  30426. type: 'line',
  30427. init: function () {
  30428. var lineGroup = new Group();
  30429. var symbolDraw = new SymbolDraw();
  30430. this.group.add(symbolDraw.group);
  30431. this._symbolDraw = symbolDraw;
  30432. this._lineGroup = lineGroup;
  30433. },
  30434. render: function (seriesModel, ecModel, api) {
  30435. var coordSys = seriesModel.coordinateSystem;
  30436. var group = this.group;
  30437. var data = seriesModel.getData();
  30438. var lineStyleModel = seriesModel.getModel('lineStyle');
  30439. var areaStyleModel = seriesModel.getModel('areaStyle');
  30440. var points = data.mapArray(data.getItemLayout);
  30441. var isCoordSysPolar = coordSys.type === 'polar';
  30442. var prevCoordSys = this._coordSys;
  30443. var symbolDraw = this._symbolDraw;
  30444. var polyline = this._polyline;
  30445. var polygon = this._polygon;
  30446. var lineGroup = this._lineGroup;
  30447. var hasAnimation = seriesModel.get('animation');
  30448. var isAreaChart = !areaStyleModel.isEmpty();
  30449. var valueOrigin = areaStyleModel.get('origin');
  30450. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30451. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30452. var showSymbol = seriesModel.get('showSymbol');
  30453. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30454. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30455. // Remove temporary symbols
  30456. var oldData = this._data;
  30457. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30458. if (el.__temp) {
  30459. group.remove(el);
  30460. oldData.setItemGraphicEl(idx, null);
  30461. }
  30462. });
  30463. // Remove previous created symbols if showSymbol changed to false
  30464. if (!showSymbol) {
  30465. symbolDraw.remove();
  30466. }
  30467. group.add(lineGroup);
  30468. // FIXME step not support polar
  30469. var step = !isCoordSysPolar && seriesModel.get('step');
  30470. var clipShapeForSymbol;
  30471. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  30472. clipShapeForSymbol = coordSys.getArea();
  30473. // Avoid float number rounding error for symbol on the edge of axis extent.
  30474. // See #7913 and `test/dataZoom-clip.html`.
  30475. if (clipShapeForSymbol.width != null) {
  30476. clipShapeForSymbol.x -= 0.1;
  30477. clipShapeForSymbol.y -= 0.1;
  30478. clipShapeForSymbol.width += 0.2;
  30479. clipShapeForSymbol.height += 0.2;
  30480. }
  30481. else if (clipShapeForSymbol.r0) {
  30482. clipShapeForSymbol.r0 -= 0.5;
  30483. clipShapeForSymbol.r1 += 0.5;
  30484. }
  30485. }
  30486. this._clipShapeForSymbol = clipShapeForSymbol;
  30487. // Initialization animation or coordinate system changed
  30488. if (
  30489. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30490. ) {
  30491. showSymbol && symbolDraw.updateData(data, {
  30492. isIgnore: isIgnoreFunc,
  30493. clipShape: clipShapeForSymbol
  30494. });
  30495. if (step) {
  30496. // TODO If stacked series is not step
  30497. points = turnPointsIntoStep(points, coordSys, step);
  30498. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30499. }
  30500. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30501. if (isAreaChart) {
  30502. polygon = this._newPolygon(
  30503. points, stackedOnPoints,
  30504. coordSys, hasAnimation
  30505. );
  30506. }
  30507. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  30508. }
  30509. else {
  30510. if (isAreaChart && !polygon) {
  30511. // If areaStyle is added
  30512. polygon = this._newPolygon(
  30513. points, stackedOnPoints,
  30514. coordSys, hasAnimation
  30515. );
  30516. }
  30517. else if (polygon && !isAreaChart) {
  30518. // If areaStyle is removed
  30519. lineGroup.remove(polygon);
  30520. polygon = this._polygon = null;
  30521. }
  30522. // Update clipPath
  30523. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  30524. // Always update, or it is wrong in the case turning on legend
  30525. // because points are not changed
  30526. showSymbol && symbolDraw.updateData(data, {
  30527. isIgnore: isIgnoreFunc,
  30528. clipShape: clipShapeForSymbol
  30529. });
  30530. // Stop symbol animation and sync with line points
  30531. // FIXME performance?
  30532. data.eachItemGraphicEl(function (el) {
  30533. el.stopAnimation(true);
  30534. });
  30535. // In the case data zoom triggerred refreshing frequently
  30536. // Data may not change if line has a category axis. So it should animate nothing
  30537. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30538. || !isPointsSame(this._points, points)
  30539. ) {
  30540. if (hasAnimation) {
  30541. this._updateAnimation(
  30542. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30543. );
  30544. }
  30545. else {
  30546. // Not do it in update with animation
  30547. if (step) {
  30548. // TODO If stacked series is not step
  30549. points = turnPointsIntoStep(points, coordSys, step);
  30550. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30551. }
  30552. polyline.setShape({
  30553. points: points
  30554. });
  30555. polygon && polygon.setShape({
  30556. points: points,
  30557. stackedOnPoints: stackedOnPoints
  30558. });
  30559. }
  30560. }
  30561. }
  30562. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30563. polyline.useStyle(defaults(
  30564. // Use color in lineStyle first
  30565. lineStyleModel.getLineStyle(),
  30566. {
  30567. fill: 'none',
  30568. stroke: visualColor,
  30569. lineJoin: 'bevel'
  30570. }
  30571. ));
  30572. var smooth = seriesModel.get('smooth');
  30573. smooth = getSmooth(seriesModel.get('smooth'));
  30574. polyline.setShape({
  30575. smooth: smooth,
  30576. smoothMonotone: seriesModel.get('smoothMonotone'),
  30577. connectNulls: seriesModel.get('connectNulls')
  30578. });
  30579. if (polygon) {
  30580. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30581. var stackedOnSmooth = 0;
  30582. polygon.useStyle(defaults(
  30583. areaStyleModel.getAreaStyle(),
  30584. {
  30585. fill: visualColor,
  30586. opacity: 0.7,
  30587. lineJoin: 'bevel'
  30588. }
  30589. ));
  30590. if (stackedOnSeries) {
  30591. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30592. }
  30593. polygon.setShape({
  30594. smooth: smooth,
  30595. stackedOnSmooth: stackedOnSmooth,
  30596. smoothMonotone: seriesModel.get('smoothMonotone'),
  30597. connectNulls: seriesModel.get('connectNulls')
  30598. });
  30599. }
  30600. this._data = data;
  30601. // Save the coordinate system for transition animation when data changed
  30602. this._coordSys = coordSys;
  30603. this._stackedOnPoints = stackedOnPoints;
  30604. this._points = points;
  30605. this._step = step;
  30606. this._valueOrigin = valueOrigin;
  30607. },
  30608. dispose: function () {},
  30609. highlight: function (seriesModel, ecModel, api, payload) {
  30610. var data = seriesModel.getData();
  30611. var dataIndex = queryDataIndex(data, payload);
  30612. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  30613. var symbol = data.getItemGraphicEl(dataIndex);
  30614. if (!symbol) {
  30615. // Create a temporary symbol if it is not exists
  30616. var pt = data.getItemLayout(dataIndex);
  30617. if (!pt) {
  30618. // Null data
  30619. return;
  30620. }
  30621. // fix #11360: should't draw symbol outside clipShapeForSymbol
  30622. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  30623. return;
  30624. }
  30625. symbol = new SymbolClz(data, dataIndex);
  30626. symbol.position = pt;
  30627. symbol.setZ(
  30628. seriesModel.get('zlevel'),
  30629. seriesModel.get('z')
  30630. );
  30631. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  30632. symbol.__temp = true;
  30633. data.setItemGraphicEl(dataIndex, symbol);
  30634. // Stop scale animation
  30635. symbol.stopSymbolAnimation(true);
  30636. this.group.add(symbol);
  30637. }
  30638. symbol.highlight();
  30639. }
  30640. else {
  30641. // Highlight whole series
  30642. Chart.prototype.highlight.call(
  30643. this, seriesModel, ecModel, api, payload
  30644. );
  30645. }
  30646. },
  30647. downplay: function (seriesModel, ecModel, api, payload) {
  30648. var data = seriesModel.getData();
  30649. var dataIndex = queryDataIndex(data, payload);
  30650. if (dataIndex != null && dataIndex >= 0) {
  30651. var symbol = data.getItemGraphicEl(dataIndex);
  30652. if (symbol) {
  30653. if (symbol.__temp) {
  30654. data.setItemGraphicEl(dataIndex, null);
  30655. this.group.remove(symbol);
  30656. }
  30657. else {
  30658. symbol.downplay();
  30659. }
  30660. }
  30661. }
  30662. else {
  30663. // FIXME
  30664. // can not downplay completely.
  30665. // Downplay whole series
  30666. Chart.prototype.downplay.call(
  30667. this, seriesModel, ecModel, api, payload
  30668. );
  30669. }
  30670. },
  30671. /**
  30672. * @param {module:zrender/container/Group} group
  30673. * @param {Array.<Array.<number>>} points
  30674. * @private
  30675. */
  30676. _newPolyline: function (points) {
  30677. var polyline = this._polyline;
  30678. // Remove previous created polyline
  30679. if (polyline) {
  30680. this._lineGroup.remove(polyline);
  30681. }
  30682. polyline = new Polyline$1({
  30683. shape: {
  30684. points: points
  30685. },
  30686. silent: true,
  30687. z2: 10
  30688. });
  30689. this._lineGroup.add(polyline);
  30690. this._polyline = polyline;
  30691. return polyline;
  30692. },
  30693. /**
  30694. * @param {module:zrender/container/Group} group
  30695. * @param {Array.<Array.<number>>} stackedOnPoints
  30696. * @param {Array.<Array.<number>>} points
  30697. * @private
  30698. */
  30699. _newPolygon: function (points, stackedOnPoints) {
  30700. var polygon = this._polygon;
  30701. // Remove previous created polygon
  30702. if (polygon) {
  30703. this._lineGroup.remove(polygon);
  30704. }
  30705. polygon = new Polygon$1({
  30706. shape: {
  30707. points: points,
  30708. stackedOnPoints: stackedOnPoints
  30709. },
  30710. silent: true
  30711. });
  30712. this._lineGroup.add(polygon);
  30713. this._polygon = polygon;
  30714. return polygon;
  30715. },
  30716. /**
  30717. * @private
  30718. */
  30719. // FIXME Two value axis
  30720. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  30721. var polyline = this._polyline;
  30722. var polygon = this._polygon;
  30723. var seriesModel = data.hostModel;
  30724. var diff = lineAnimationDiff(
  30725. this._data, data,
  30726. this._stackedOnPoints, stackedOnPoints,
  30727. this._coordSys, coordSys,
  30728. this._valueOrigin, valueOrigin
  30729. );
  30730. var current = diff.current;
  30731. var stackedOnCurrent = diff.stackedOnCurrent;
  30732. var next = diff.next;
  30733. var stackedOnNext = diff.stackedOnNext;
  30734. if (step) {
  30735. // TODO If stacked series is not step
  30736. current = turnPointsIntoStep(diff.current, coordSys, step);
  30737. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  30738. next = turnPointsIntoStep(diff.next, coordSys, step);
  30739. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  30740. }
  30741. // `diff.current` is subset of `current` (which should be ensured by
  30742. // turnPointsIntoStep), so points in `__points` can be updated when
  30743. // points in `current` are update during animation.
  30744. polyline.shape.__points = diff.current;
  30745. polyline.shape.points = current;
  30746. updateProps(polyline, {
  30747. shape: {
  30748. points: next
  30749. }
  30750. }, seriesModel);
  30751. if (polygon) {
  30752. polygon.setShape({
  30753. points: current,
  30754. stackedOnPoints: stackedOnCurrent
  30755. });
  30756. updateProps(polygon, {
  30757. shape: {
  30758. points: next,
  30759. stackedOnPoints: stackedOnNext
  30760. }
  30761. }, seriesModel);
  30762. }
  30763. var updatedDataInfo = [];
  30764. var diffStatus = diff.status;
  30765. for (var i = 0; i < diffStatus.length; i++) {
  30766. var cmd = diffStatus[i].cmd;
  30767. if (cmd === '=') {
  30768. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  30769. if (el) {
  30770. updatedDataInfo.push({
  30771. el: el,
  30772. ptIdx: i // Index of points
  30773. });
  30774. }
  30775. }
  30776. }
  30777. if (polyline.animators && polyline.animators.length) {
  30778. polyline.animators[0].during(function () {
  30779. for (var i = 0; i < updatedDataInfo.length; i++) {
  30780. var el = updatedDataInfo[i].el;
  30781. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  30782. }
  30783. });
  30784. }
  30785. },
  30786. remove: function (ecModel) {
  30787. var group = this.group;
  30788. var oldData = this._data;
  30789. this._lineGroup.removeAll();
  30790. this._symbolDraw.remove(true);
  30791. // Remove temporary created elements when highlighting
  30792. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30793. if (el.__temp) {
  30794. group.remove(el);
  30795. oldData.setItemGraphicEl(idx, null);
  30796. }
  30797. });
  30798. this._polyline =
  30799. this._polygon =
  30800. this._coordSys =
  30801. this._points =
  30802. this._stackedOnPoints =
  30803. this._data = null;
  30804. }
  30805. });
  30806. /*
  30807. * Licensed to the Apache Software Foundation (ASF) under one
  30808. * or more contributor license agreements. See the NOTICE file
  30809. * distributed with this work for additional information
  30810. * regarding copyright ownership. The ASF licenses this file
  30811. * to you under the Apache License, Version 2.0 (the
  30812. * "License"); you may not use this file except in compliance
  30813. * with the License. You may obtain a copy of the License at
  30814. *
  30815. * http://www.apache.org/licenses/LICENSE-2.0
  30816. *
  30817. * Unless required by applicable law or agreed to in writing,
  30818. * software distributed under the License is distributed on an
  30819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30820. * KIND, either express or implied. See the License for the
  30821. * specific language governing permissions and limitations
  30822. * under the License.
  30823. */
  30824. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  30825. // Encoding visual for all series include which is filtered for legend drawing
  30826. return {
  30827. seriesType: seriesType,
  30828. // For legend.
  30829. performRawSeries: true,
  30830. reset: function (seriesModel, ecModel, api) {
  30831. var data = seriesModel.getData();
  30832. var symbolType = seriesModel.get('symbol');
  30833. var symbolSize = seriesModel.get('symbolSize');
  30834. var keepAspect = seriesModel.get('symbolKeepAspect');
  30835. var hasSymbolTypeCallback = isFunction$1(symbolType);
  30836. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  30837. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  30838. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  30839. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  30840. data.setVisual({
  30841. legendSymbol: legendSymbol || seriesSymbol,
  30842. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  30843. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  30844. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  30845. // some cases but generally it is not recommanded.
  30846. symbol: seriesSymbol,
  30847. symbolSize: seriesSymbolSize,
  30848. symbolKeepAspect: keepAspect
  30849. });
  30850. // Only visible series has each data be visual encoded
  30851. if (ecModel.isSeriesFiltered(seriesModel)) {
  30852. return;
  30853. }
  30854. function dataEach(data, idx) {
  30855. if (hasCallback) {
  30856. var rawValue = seriesModel.getRawValue(idx);
  30857. var params = seriesModel.getDataParams(idx);
  30858. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  30859. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  30860. }
  30861. if (data.hasItemOption) {
  30862. var itemModel = data.getItemModel(idx);
  30863. var itemSymbolType = itemModel.getShallow('symbol', true);
  30864. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  30865. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  30866. // If has item symbol
  30867. if (itemSymbolType != null) {
  30868. data.setItemVisual(idx, 'symbol', itemSymbolType);
  30869. }
  30870. if (itemSymbolSize != null) {
  30871. // PENDING Transform symbolSize ?
  30872. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  30873. }
  30874. if (itemSymbolKeepAspect != null) {
  30875. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  30876. }
  30877. }
  30878. }
  30879. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  30880. }
  30881. };
  30882. };
  30883. /*
  30884. * Licensed to the Apache Software Foundation (ASF) under one
  30885. * or more contributor license agreements. See the NOTICE file
  30886. * distributed with this work for additional information
  30887. * regarding copyright ownership. The ASF licenses this file
  30888. * to you under the Apache License, Version 2.0 (the
  30889. * "License"); you may not use this file except in compliance
  30890. * with the License. You may obtain a copy of the License at
  30891. *
  30892. * http://www.apache.org/licenses/LICENSE-2.0
  30893. *
  30894. * Unless required by applicable law or agreed to in writing,
  30895. * software distributed under the License is distributed on an
  30896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30897. * KIND, either express or implied. See the License for the
  30898. * specific language governing permissions and limitations
  30899. * under the License.
  30900. */
  30901. /* global Float32Array */
  30902. var layoutPoints = function (seriesType) {
  30903. return {
  30904. seriesType: seriesType,
  30905. plan: createRenderPlanner(),
  30906. reset: function (seriesModel) {
  30907. var data = seriesModel.getData();
  30908. var coordSys = seriesModel.coordinateSystem;
  30909. var pipelineContext = seriesModel.pipelineContext;
  30910. var isLargeRender = pipelineContext.large;
  30911. if (!coordSys) {
  30912. return;
  30913. }
  30914. var dims = map(coordSys.dimensions, function (dim) {
  30915. return data.mapDimension(dim);
  30916. }).slice(0, 2);
  30917. var dimLen = dims.length;
  30918. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30919. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  30920. dims[0] = stackResultDim;
  30921. }
  30922. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  30923. dims[1] = stackResultDim;
  30924. }
  30925. function progress(params, data) {
  30926. var segCount = params.end - params.start;
  30927. var points = isLargeRender && new Float32Array(segCount * dimLen);
  30928. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  30929. var point;
  30930. if (dimLen === 1) {
  30931. var x = data.get(dims[0], i);
  30932. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  30933. }
  30934. else {
  30935. var x = tmpIn[0] = data.get(dims[0], i);
  30936. var y = tmpIn[1] = data.get(dims[1], i);
  30937. // Also {Array.<number>}, not undefined to avoid if...else... statement
  30938. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  30939. }
  30940. if (isLargeRender) {
  30941. points[offset++] = point ? point[0] : NaN;
  30942. points[offset++] = point ? point[1] : NaN;
  30943. }
  30944. else {
  30945. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  30946. }
  30947. }
  30948. isLargeRender && data.setLayout('symbolPoints', points);
  30949. }
  30950. return dimLen && {progress: progress};
  30951. }
  30952. };
  30953. };
  30954. /*
  30955. * Licensed to the Apache Software Foundation (ASF) under one
  30956. * or more contributor license agreements. See the NOTICE file
  30957. * distributed with this work for additional information
  30958. * regarding copyright ownership. The ASF licenses this file
  30959. * to you under the Apache License, Version 2.0 (the
  30960. * "License"); you may not use this file except in compliance
  30961. * with the License. You may obtain a copy of the License at
  30962. *
  30963. * http://www.apache.org/licenses/LICENSE-2.0
  30964. *
  30965. * Unless required by applicable law or agreed to in writing,
  30966. * software distributed under the License is distributed on an
  30967. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30968. * KIND, either express or implied. See the License for the
  30969. * specific language governing permissions and limitations
  30970. * under the License.
  30971. */
  30972. var samplers = {
  30973. average: function (frame) {
  30974. var sum = 0;
  30975. var count = 0;
  30976. for (var i = 0; i < frame.length; i++) {
  30977. if (!isNaN(frame[i])) {
  30978. sum += frame[i];
  30979. count++;
  30980. }
  30981. }
  30982. // Return NaN if count is 0
  30983. return count === 0 ? NaN : sum / count;
  30984. },
  30985. sum: function (frame) {
  30986. var sum = 0;
  30987. for (var i = 0; i < frame.length; i++) {
  30988. // Ignore NaN
  30989. sum += frame[i] || 0;
  30990. }
  30991. return sum;
  30992. },
  30993. max: function (frame) {
  30994. var max = -Infinity;
  30995. for (var i = 0; i < frame.length; i++) {
  30996. frame[i] > max && (max = frame[i]);
  30997. }
  30998. // NaN will cause illegal axis extent.
  30999. return isFinite(max) ? max : NaN;
  31000. },
  31001. min: function (frame) {
  31002. var min = Infinity;
  31003. for (var i = 0; i < frame.length; i++) {
  31004. frame[i] < min && (min = frame[i]);
  31005. }
  31006. // NaN will cause illegal axis extent.
  31007. return isFinite(min) ? min : NaN;
  31008. },
  31009. // TODO
  31010. // Median
  31011. nearest: function (frame) {
  31012. return frame[0];
  31013. }
  31014. };
  31015. var indexSampler = function (frame, value) {
  31016. return Math.round(frame.length / 2);
  31017. };
  31018. var dataSample = function (seriesType) {
  31019. return {
  31020. seriesType: seriesType,
  31021. modifyOutputEnd: true,
  31022. reset: function (seriesModel, ecModel, api) {
  31023. var data = seriesModel.getData();
  31024. var sampling = seriesModel.get('sampling');
  31025. var coordSys = seriesModel.coordinateSystem;
  31026. // Only cartesian2d support down sampling
  31027. if (coordSys.type === 'cartesian2d' && sampling) {
  31028. var baseAxis = coordSys.getBaseAxis();
  31029. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31030. var extent = baseAxis.getExtent();
  31031. // Coordinste system has been resized
  31032. var size = extent[1] - extent[0];
  31033. var rate = Math.round(data.count() / size);
  31034. if (rate > 1) {
  31035. var sampler;
  31036. if (typeof sampling === 'string') {
  31037. sampler = samplers[sampling];
  31038. }
  31039. else if (typeof sampling === 'function') {
  31040. sampler = sampling;
  31041. }
  31042. if (sampler) {
  31043. // Only support sample the first dim mapped from value axis.
  31044. seriesModel.setData(data.downSample(
  31045. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  31046. ));
  31047. }
  31048. }
  31049. }
  31050. }
  31051. };
  31052. };
  31053. /*
  31054. * Licensed to the Apache Software Foundation (ASF) under one
  31055. * or more contributor license agreements. See the NOTICE file
  31056. * distributed with this work for additional information
  31057. * regarding copyright ownership. The ASF licenses this file
  31058. * to you under the Apache License, Version 2.0 (the
  31059. * "License"); you may not use this file except in compliance
  31060. * with the License. You may obtain a copy of the License at
  31061. *
  31062. * http://www.apache.org/licenses/LICENSE-2.0
  31063. *
  31064. * Unless required by applicable law or agreed to in writing,
  31065. * software distributed under the License is distributed on an
  31066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31067. * KIND, either express or implied. See the License for the
  31068. * specific language governing permissions and limitations
  31069. * under the License.
  31070. */
  31071. /**
  31072. * // Scale class management
  31073. * @module echarts/scale/Scale
  31074. */
  31075. /**
  31076. * @param {Object} [setting]
  31077. */
  31078. function Scale(setting) {
  31079. this._setting = setting || {};
  31080. /**
  31081. * Extent
  31082. * @type {Array.<number>}
  31083. * @protected
  31084. */
  31085. this._extent = [Infinity, -Infinity];
  31086. /**
  31087. * Step is calculated in adjustExtent
  31088. * @type {Array.<number>}
  31089. * @protected
  31090. */
  31091. this._interval = 0;
  31092. this.init && this.init.apply(this, arguments);
  31093. }
  31094. /**
  31095. * Parse input val to valid inner number.
  31096. * @param {*} val
  31097. * @return {number}
  31098. */
  31099. Scale.prototype.parse = function (val) {
  31100. // Notice: This would be a trap here, If the implementation
  31101. // of this method depends on extent, and this method is used
  31102. // before extent set (like in dataZoom), it would be wrong.
  31103. // Nevertheless, parse does not depend on extent generally.
  31104. return val;
  31105. };
  31106. Scale.prototype.getSetting = function (name) {
  31107. return this._setting[name];
  31108. };
  31109. Scale.prototype.contain = function (val) {
  31110. var extent = this._extent;
  31111. return val >= extent[0] && val <= extent[1];
  31112. };
  31113. /**
  31114. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  31115. * @param {number} val
  31116. * @return {number}
  31117. */
  31118. Scale.prototype.normalize = function (val) {
  31119. var extent = this._extent;
  31120. if (extent[1] === extent[0]) {
  31121. return 0.5;
  31122. }
  31123. return (val - extent[0]) / (extent[1] - extent[0]);
  31124. };
  31125. /**
  31126. * Scale normalized value
  31127. * @param {number} val
  31128. * @return {number}
  31129. */
  31130. Scale.prototype.scale = function (val) {
  31131. var extent = this._extent;
  31132. return val * (extent[1] - extent[0]) + extent[0];
  31133. };
  31134. /**
  31135. * Set extent from data
  31136. * @param {Array.<number>} other
  31137. */
  31138. Scale.prototype.unionExtent = function (other) {
  31139. var extent = this._extent;
  31140. other[0] < extent[0] && (extent[0] = other[0]);
  31141. other[1] > extent[1] && (extent[1] = other[1]);
  31142. // not setExtent because in log axis it may transformed to power
  31143. // this.setExtent(extent[0], extent[1]);
  31144. };
  31145. /**
  31146. * Set extent from data
  31147. * @param {module:echarts/data/List} data
  31148. * @param {string} dim
  31149. */
  31150. Scale.prototype.unionExtentFromData = function (data, dim) {
  31151. this.unionExtent(data.getApproximateExtent(dim));
  31152. };
  31153. /**
  31154. * Get extent
  31155. * @return {Array.<number>}
  31156. */
  31157. Scale.prototype.getExtent = function () {
  31158. return this._extent.slice();
  31159. };
  31160. /**
  31161. * Set extent
  31162. * @param {number} start
  31163. * @param {number} end
  31164. */
  31165. Scale.prototype.setExtent = function (start, end) {
  31166. var thisExtent = this._extent;
  31167. if (!isNaN(start)) {
  31168. thisExtent[0] = start;
  31169. }
  31170. if (!isNaN(end)) {
  31171. thisExtent[1] = end;
  31172. }
  31173. };
  31174. /**
  31175. * When axis extent depends on data and no data exists,
  31176. * axis ticks should not be drawn, which is named 'blank'.
  31177. */
  31178. Scale.prototype.isBlank = function () {
  31179. return this._isBlank;
  31180. },
  31181. /**
  31182. * When axis extent depends on data and no data exists,
  31183. * axis ticks should not be drawn, which is named 'blank'.
  31184. */
  31185. Scale.prototype.setBlank = function (isBlank) {
  31186. this._isBlank = isBlank;
  31187. };
  31188. /**
  31189. * @abstract
  31190. * @param {*} tick
  31191. * @return {string} label of the tick.
  31192. */
  31193. Scale.prototype.getLabel = null;
  31194. enableClassExtend(Scale);
  31195. enableClassManagement(Scale, {
  31196. registerWhenExtend: true
  31197. });
  31198. /*
  31199. * Licensed to the Apache Software Foundation (ASF) under one
  31200. * or more contributor license agreements. See the NOTICE file
  31201. * distributed with this work for additional information
  31202. * regarding copyright ownership. The ASF licenses this file
  31203. * to you under the Apache License, Version 2.0 (the
  31204. * "License"); you may not use this file except in compliance
  31205. * with the License. You may obtain a copy of the License at
  31206. *
  31207. * http://www.apache.org/licenses/LICENSE-2.0
  31208. *
  31209. * Unless required by applicable law or agreed to in writing,
  31210. * software distributed under the License is distributed on an
  31211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31212. * KIND, either express or implied. See the License for the
  31213. * specific language governing permissions and limitations
  31214. * under the License.
  31215. */
  31216. /**
  31217. * @constructor
  31218. * @param {Object} [opt]
  31219. * @param {Object} [opt.categories=[]]
  31220. * @param {Object} [opt.needCollect=false]
  31221. * @param {Object} [opt.deduplication=false]
  31222. */
  31223. function OrdinalMeta(opt) {
  31224. /**
  31225. * @readOnly
  31226. * @type {Array.<string>}
  31227. */
  31228. this.categories = opt.categories || [];
  31229. /**
  31230. * @private
  31231. * @type {boolean}
  31232. */
  31233. this._needCollect = opt.needCollect;
  31234. /**
  31235. * @private
  31236. * @type {boolean}
  31237. */
  31238. this._deduplication = opt.deduplication;
  31239. /**
  31240. * @private
  31241. * @type {boolean}
  31242. */
  31243. this._map;
  31244. }
  31245. /**
  31246. * @param {module:echarts/model/Model} axisModel
  31247. * @return {module:echarts/data/OrdinalMeta}
  31248. */
  31249. OrdinalMeta.createByAxisModel = function (axisModel) {
  31250. var option = axisModel.option;
  31251. var data = option.data;
  31252. var categories = data && map(data, getName);
  31253. return new OrdinalMeta({
  31254. categories: categories,
  31255. needCollect: !categories,
  31256. // deduplication is default in axis.
  31257. deduplication: option.dedplication !== false
  31258. });
  31259. };
  31260. var proto$1 = OrdinalMeta.prototype;
  31261. /**
  31262. * @param {string} category
  31263. * @return {number} ordinal
  31264. */
  31265. proto$1.getOrdinal = function (category) {
  31266. return getOrCreateMap(this).get(category);
  31267. };
  31268. /**
  31269. * @param {*} category
  31270. * @return {number} The ordinal. If not found, return NaN.
  31271. */
  31272. proto$1.parseAndCollect = function (category) {
  31273. var index;
  31274. var needCollect = this._needCollect;
  31275. // The value of category dim can be the index of the given category set.
  31276. // This feature is only supported when !needCollect, because we should
  31277. // consider a common case: a value is 2017, which is a number but is
  31278. // expected to be tread as a category. This case usually happen in dataset,
  31279. // where it happent to be no need of the index feature.
  31280. if (typeof category !== 'string' && !needCollect) {
  31281. return category;
  31282. }
  31283. // Optimize for the scenario:
  31284. // category is ['2012-01-01', '2012-01-02', ...], where the input
  31285. // data has been ensured not duplicate and is large data.
  31286. // Notice, if a dataset dimension provide categroies, usually echarts
  31287. // should remove duplication except user tell echarts dont do that
  31288. // (set axis.deduplication = false), because echarts do not know whether
  31289. // the values in the category dimension has duplication (consider the
  31290. // parallel-aqi example)
  31291. if (needCollect && !this._deduplication) {
  31292. index = this.categories.length;
  31293. this.categories[index] = category;
  31294. return index;
  31295. }
  31296. var map$$1 = getOrCreateMap(this);
  31297. index = map$$1.get(category);
  31298. if (index == null) {
  31299. if (needCollect) {
  31300. index = this.categories.length;
  31301. this.categories[index] = category;
  31302. map$$1.set(category, index);
  31303. }
  31304. else {
  31305. index = NaN;
  31306. }
  31307. }
  31308. return index;
  31309. };
  31310. // Consider big data, do not create map until needed.
  31311. function getOrCreateMap(ordinalMeta) {
  31312. return ordinalMeta._map || (
  31313. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  31314. );
  31315. }
  31316. function getName(obj) {
  31317. if (isObject$1(obj) && obj.value != null) {
  31318. return obj.value;
  31319. }
  31320. else {
  31321. return obj + '';
  31322. }
  31323. }
  31324. /*
  31325. * Licensed to the Apache Software Foundation (ASF) under one
  31326. * or more contributor license agreements. See the NOTICE file
  31327. * distributed with this work for additional information
  31328. * regarding copyright ownership. The ASF licenses this file
  31329. * to you under the Apache License, Version 2.0 (the
  31330. * "License"); you may not use this file except in compliance
  31331. * with the License. You may obtain a copy of the License at
  31332. *
  31333. * http://www.apache.org/licenses/LICENSE-2.0
  31334. *
  31335. * Unless required by applicable law or agreed to in writing,
  31336. * software distributed under the License is distributed on an
  31337. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31338. * KIND, either express or implied. See the License for the
  31339. * specific language governing permissions and limitations
  31340. * under the License.
  31341. */
  31342. /**
  31343. * Linear continuous scale
  31344. * @module echarts/coord/scale/Ordinal
  31345. *
  31346. * http://en.wikipedia.org/wiki/Level_of_measurement
  31347. */
  31348. // FIXME only one data
  31349. var scaleProto = Scale.prototype;
  31350. var OrdinalScale = Scale.extend({
  31351. type: 'ordinal',
  31352. /**
  31353. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  31354. */
  31355. init: function (ordinalMeta, extent) {
  31356. // Caution: Should not use instanceof, consider ec-extensions using
  31357. // import approach to get OrdinalMeta class.
  31358. if (!ordinalMeta || isArray(ordinalMeta)) {
  31359. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  31360. }
  31361. this._ordinalMeta = ordinalMeta;
  31362. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  31363. },
  31364. parse: function (val) {
  31365. return typeof val === 'string'
  31366. ? this._ordinalMeta.getOrdinal(val)
  31367. // val might be float.
  31368. : Math.round(val);
  31369. },
  31370. contain: function (rank) {
  31371. rank = this.parse(rank);
  31372. return scaleProto.contain.call(this, rank)
  31373. && this._ordinalMeta.categories[rank] != null;
  31374. },
  31375. /**
  31376. * Normalize given rank or name to linear [0, 1]
  31377. * @param {number|string} [val]
  31378. * @return {number}
  31379. */
  31380. normalize: function (val) {
  31381. return scaleProto.normalize.call(this, this.parse(val));
  31382. },
  31383. scale: function (val) {
  31384. return Math.round(scaleProto.scale.call(this, val));
  31385. },
  31386. /**
  31387. * @return {Array}
  31388. */
  31389. getTicks: function () {
  31390. var ticks = [];
  31391. var extent = this._extent;
  31392. var rank = extent[0];
  31393. while (rank <= extent[1]) {
  31394. ticks.push(rank);
  31395. rank++;
  31396. }
  31397. return ticks;
  31398. },
  31399. /**
  31400. * Get item on rank n
  31401. * @param {number} n
  31402. * @return {string}
  31403. */
  31404. getLabel: function (n) {
  31405. if (!this.isBlank()) {
  31406. // Note that if no data, ordinalMeta.categories is an empty array.
  31407. return this._ordinalMeta.categories[n];
  31408. }
  31409. },
  31410. /**
  31411. * @return {number}
  31412. */
  31413. count: function () {
  31414. return this._extent[1] - this._extent[0] + 1;
  31415. },
  31416. /**
  31417. * @override
  31418. */
  31419. unionExtentFromData: function (data, dim) {
  31420. this.unionExtent(data.getApproximateExtent(dim));
  31421. },
  31422. getOrdinalMeta: function () {
  31423. return this._ordinalMeta;
  31424. },
  31425. niceTicks: noop,
  31426. niceExtent: noop
  31427. });
  31428. /**
  31429. * @return {module:echarts/scale/Time}
  31430. */
  31431. OrdinalScale.create = function () {
  31432. return new OrdinalScale();
  31433. };
  31434. /*
  31435. * Licensed to the Apache Software Foundation (ASF) under one
  31436. * or more contributor license agreements. See the NOTICE file
  31437. * distributed with this work for additional information
  31438. * regarding copyright ownership. The ASF licenses this file
  31439. * to you under the Apache License, Version 2.0 (the
  31440. * "License"); you may not use this file except in compliance
  31441. * with the License. You may obtain a copy of the License at
  31442. *
  31443. * http://www.apache.org/licenses/LICENSE-2.0
  31444. *
  31445. * Unless required by applicable law or agreed to in writing,
  31446. * software distributed under the License is distributed on an
  31447. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31448. * KIND, either express or implied. See the License for the
  31449. * specific language governing permissions and limitations
  31450. * under the License.
  31451. */
  31452. /**
  31453. * For testable.
  31454. */
  31455. var roundNumber$1 = round$1;
  31456. /**
  31457. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  31458. * Should be extent[0] < extent[1].
  31459. * @param {number} splitNumber splitNumber should be >= 1.
  31460. * @param {number} [minInterval]
  31461. * @param {number} [maxInterval]
  31462. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  31463. */
  31464. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  31465. var result = {};
  31466. var span = extent[1] - extent[0];
  31467. var interval = result.interval = nice(span / splitNumber, true);
  31468. if (minInterval != null && interval < minInterval) {
  31469. interval = result.interval = minInterval;
  31470. }
  31471. if (maxInterval != null && interval > maxInterval) {
  31472. interval = result.interval = maxInterval;
  31473. }
  31474. // Tow more digital for tick.
  31475. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  31476. // Niced extent inside original extent
  31477. var niceTickExtent = result.niceTickExtent = [
  31478. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  31479. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  31480. ];
  31481. fixExtent(niceTickExtent, extent);
  31482. return result;
  31483. }
  31484. /**
  31485. * @param {number} interval
  31486. * @return {number} interval precision
  31487. */
  31488. function getIntervalPrecision(interval) {
  31489. // Tow more digital for tick.
  31490. return getPrecisionSafe(interval) + 2;
  31491. }
  31492. function clamp(niceTickExtent, idx, extent) {
  31493. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  31494. }
  31495. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  31496. function fixExtent(niceTickExtent, extent) {
  31497. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  31498. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  31499. clamp(niceTickExtent, 0, extent);
  31500. clamp(niceTickExtent, 1, extent);
  31501. if (niceTickExtent[0] > niceTickExtent[1]) {
  31502. niceTickExtent[0] = niceTickExtent[1];
  31503. }
  31504. }
  31505. /*
  31506. * Licensed to the Apache Software Foundation (ASF) under one
  31507. * or more contributor license agreements. See the NOTICE file
  31508. * distributed with this work for additional information
  31509. * regarding copyright ownership. The ASF licenses this file
  31510. * to you under the Apache License, Version 2.0 (the
  31511. * "License"); you may not use this file except in compliance
  31512. * with the License. You may obtain a copy of the License at
  31513. *
  31514. * http://www.apache.org/licenses/LICENSE-2.0
  31515. *
  31516. * Unless required by applicable law or agreed to in writing,
  31517. * software distributed under the License is distributed on an
  31518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31519. * KIND, either express or implied. See the License for the
  31520. * specific language governing permissions and limitations
  31521. * under the License.
  31522. */
  31523. /**
  31524. * Interval scale
  31525. * @module echarts/scale/Interval
  31526. */
  31527. var roundNumber = round$1;
  31528. /**
  31529. * @alias module:echarts/coord/scale/Interval
  31530. * @constructor
  31531. */
  31532. var IntervalScale = Scale.extend({
  31533. type: 'interval',
  31534. _interval: 0,
  31535. _intervalPrecision: 2,
  31536. setExtent: function (start, end) {
  31537. var thisExtent = this._extent;
  31538. //start,end may be a Number like '25',so...
  31539. if (!isNaN(start)) {
  31540. thisExtent[0] = parseFloat(start);
  31541. }
  31542. if (!isNaN(end)) {
  31543. thisExtent[1] = parseFloat(end);
  31544. }
  31545. },
  31546. unionExtent: function (other) {
  31547. var extent = this._extent;
  31548. other[0] < extent[0] && (extent[0] = other[0]);
  31549. other[1] > extent[1] && (extent[1] = other[1]);
  31550. // unionExtent may called by it's sub classes
  31551. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  31552. },
  31553. /**
  31554. * Get interval
  31555. */
  31556. getInterval: function () {
  31557. return this._interval;
  31558. },
  31559. /**
  31560. * Set interval
  31561. */
  31562. setInterval: function (interval) {
  31563. this._interval = interval;
  31564. // Dropped auto calculated niceExtent and use user setted extent
  31565. // We assume user wan't to set both interval, min, max to get a better result
  31566. this._niceExtent = this._extent.slice();
  31567. this._intervalPrecision = getIntervalPrecision(interval);
  31568. },
  31569. /**
  31570. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  31571. * @return {Array.<number>}
  31572. */
  31573. getTicks: function (expandToNicedExtent) {
  31574. var interval = this._interval;
  31575. var extent = this._extent;
  31576. var niceTickExtent = this._niceExtent;
  31577. var intervalPrecision = this._intervalPrecision;
  31578. var ticks = [];
  31579. // If interval is 0, return [];
  31580. if (!interval) {
  31581. return ticks;
  31582. }
  31583. // Consider this case: using dataZoom toolbox, zoom and zoom.
  31584. var safeLimit = 10000;
  31585. if (extent[0] < niceTickExtent[0]) {
  31586. if (expandToNicedExtent) {
  31587. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  31588. }
  31589. else {
  31590. ticks.push(extent[0]);
  31591. }
  31592. }
  31593. var tick = niceTickExtent[0];
  31594. while (tick <= niceTickExtent[1]) {
  31595. ticks.push(tick);
  31596. // Avoid rounding error
  31597. tick = roundNumber(tick + interval, intervalPrecision);
  31598. if (tick === ticks[ticks.length - 1]) {
  31599. // Consider out of safe float point, e.g.,
  31600. // -3711126.9907707 + 2e-10 === -3711126.9907707
  31601. break;
  31602. }
  31603. if (ticks.length > safeLimit) {
  31604. return [];
  31605. }
  31606. }
  31607. // Consider this case: the last item of ticks is smaller
  31608. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  31609. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  31610. if (extent[1] > lastNiceTick) {
  31611. if (expandToNicedExtent) {
  31612. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  31613. }
  31614. else {
  31615. ticks.push(extent[1]);
  31616. }
  31617. }
  31618. return ticks;
  31619. },
  31620. /**
  31621. * @param {number} [splitNumber=5]
  31622. * @return {Array.<Array.<number>>}
  31623. */
  31624. getMinorTicks: function (splitNumber) {
  31625. var ticks = this.getTicks(true);
  31626. var minorTicks = [];
  31627. var extent = this.getExtent();
  31628. for (var i = 1; i < ticks.length; i++) {
  31629. var nextTick = ticks[i];
  31630. var prevTick = ticks[i - 1];
  31631. var count = 0;
  31632. var minorTicksGroup = [];
  31633. var interval = nextTick - prevTick;
  31634. var minorInterval = interval / splitNumber;
  31635. while (count < splitNumber - 1) {
  31636. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  31637. // For the first and last interval. The count may be less than splitNumber.
  31638. if (minorTick > extent[0] && minorTick < extent[1]) {
  31639. minorTicksGroup.push(minorTick);
  31640. }
  31641. count++;
  31642. }
  31643. minorTicks.push(minorTicksGroup);
  31644. }
  31645. return minorTicks;
  31646. },
  31647. /**
  31648. * @param {number} data
  31649. * @param {Object} [opt]
  31650. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  31651. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  31652. * @return {string}
  31653. */
  31654. getLabel: function (data, opt) {
  31655. if (data == null) {
  31656. return '';
  31657. }
  31658. var precision = opt && opt.precision;
  31659. if (precision == null) {
  31660. precision = getPrecisionSafe(data) || 0;
  31661. }
  31662. else if (precision === 'auto') {
  31663. // Should be more precise then tick.
  31664. precision = this._intervalPrecision;
  31665. }
  31666. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  31667. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  31668. data = roundNumber(data, precision, true);
  31669. return addCommas(data);
  31670. },
  31671. /**
  31672. * Update interval and extent of intervals for nice ticks
  31673. *
  31674. * @param {number} [splitNumber = 5] Desired number of ticks
  31675. * @param {number} [minInterval]
  31676. * @param {number} [maxInterval]
  31677. */
  31678. niceTicks: function (splitNumber, minInterval, maxInterval) {
  31679. splitNumber = splitNumber || 5;
  31680. var extent = this._extent;
  31681. var span = extent[1] - extent[0];
  31682. if (!isFinite(span)) {
  31683. return;
  31684. }
  31685. // User may set axis min 0 and data are all negative
  31686. // FIXME If it needs to reverse ?
  31687. if (span < 0) {
  31688. span = -span;
  31689. extent.reverse();
  31690. }
  31691. var result = intervalScaleNiceTicks(
  31692. extent, splitNumber, minInterval, maxInterval
  31693. );
  31694. this._intervalPrecision = result.intervalPrecision;
  31695. this._interval = result.interval;
  31696. this._niceExtent = result.niceTickExtent;
  31697. },
  31698. /**
  31699. * Nice extent.
  31700. * @param {Object} opt
  31701. * @param {number} [opt.splitNumber = 5] Given approx tick number
  31702. * @param {boolean} [opt.fixMin=false]
  31703. * @param {boolean} [opt.fixMax=false]
  31704. * @param {boolean} [opt.minInterval]
  31705. * @param {boolean} [opt.maxInterval]
  31706. */
  31707. niceExtent: function (opt) {
  31708. var extent = this._extent;
  31709. // If extent start and end are same, expand them
  31710. if (extent[0] === extent[1]) {
  31711. if (extent[0] !== 0) {
  31712. // Expand extent
  31713. var expandSize = extent[0];
  31714. // In the fowllowing case
  31715. // Axis has been fixed max 100
  31716. // Plus data are all 100 and axis extent are [100, 100].
  31717. // Extend to the both side will cause expanded max is larger than fixed max.
  31718. // So only expand to the smaller side.
  31719. if (!opt.fixMax) {
  31720. extent[1] += expandSize / 2;
  31721. extent[0] -= expandSize / 2;
  31722. }
  31723. else {
  31724. extent[0] -= expandSize / 2;
  31725. }
  31726. }
  31727. else {
  31728. extent[1] = 1;
  31729. }
  31730. }
  31731. var span = extent[1] - extent[0];
  31732. // If there are no data and extent are [Infinity, -Infinity]
  31733. if (!isFinite(span)) {
  31734. extent[0] = 0;
  31735. extent[1] = 1;
  31736. }
  31737. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31738. // var extent = this._extent;
  31739. var interval = this._interval;
  31740. if (!opt.fixMin) {
  31741. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  31742. }
  31743. if (!opt.fixMax) {
  31744. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  31745. }
  31746. }
  31747. });
  31748. /**
  31749. * @return {module:echarts/scale/Time}
  31750. */
  31751. IntervalScale.create = function () {
  31752. return new IntervalScale();
  31753. };
  31754. /*
  31755. * Licensed to the Apache Software Foundation (ASF) under one
  31756. * or more contributor license agreements. See the NOTICE file
  31757. * distributed with this work for additional information
  31758. * regarding copyright ownership. The ASF licenses this file
  31759. * to you under the Apache License, Version 2.0 (the
  31760. * "License"); you may not use this file except in compliance
  31761. * with the License. You may obtain a copy of the License at
  31762. *
  31763. * http://www.apache.org/licenses/LICENSE-2.0
  31764. *
  31765. * Unless required by applicable law or agreed to in writing,
  31766. * software distributed under the License is distributed on an
  31767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31768. * KIND, either express or implied. See the License for the
  31769. * specific language governing permissions and limitations
  31770. * under the License.
  31771. */
  31772. /* global Float32Array */
  31773. var STACK_PREFIX = '__ec_stack_';
  31774. var LARGE_BAR_MIN_WIDTH = 0.5;
  31775. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  31776. function getSeriesStackId(seriesModel) {
  31777. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  31778. }
  31779. function getAxisKey(axis) {
  31780. return axis.dim + axis.index;
  31781. }
  31782. /**
  31783. * @param {Object} opt
  31784. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  31785. * @param {number} opt.count Positive interger.
  31786. * @param {number} [opt.barWidth]
  31787. * @param {number} [opt.barMaxWidth]
  31788. * @param {number} [opt.barMinWidth]
  31789. * @param {number} [opt.barGap]
  31790. * @param {number} [opt.barCategoryGap]
  31791. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  31792. */
  31793. function prepareLayoutBarSeries(seriesType, ecModel) {
  31794. var seriesModels = [];
  31795. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31796. // Check series coordinate, do layout for cartesian2d only
  31797. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  31798. seriesModels.push(seriesModel);
  31799. }
  31800. });
  31801. return seriesModels;
  31802. }
  31803. /**
  31804. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  31805. * values.
  31806. * This works for time axes, value axes, and log axes.
  31807. * For a single time axis, return value is in the form like
  31808. * {'x_0': [1000000]}.
  31809. * The value of 1000000 is in milliseconds.
  31810. */
  31811. function getValueAxesMinGaps(barSeries) {
  31812. /**
  31813. * Map from axis.index to values.
  31814. * For a single time axis, axisValues is in the form like
  31815. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  31816. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  31817. * series.
  31818. */
  31819. var axisValues = {};
  31820. each$1(barSeries, function (seriesModel) {
  31821. var cartesian = seriesModel.coordinateSystem;
  31822. var baseAxis = cartesian.getBaseAxis();
  31823. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  31824. return;
  31825. }
  31826. var data = seriesModel.getData();
  31827. var key = baseAxis.dim + '_' + baseAxis.index;
  31828. var dim = data.mapDimension(baseAxis.dim);
  31829. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  31830. var value = data.get(dim, i);
  31831. if (!axisValues[key]) {
  31832. // No previous data for the axis
  31833. axisValues[key] = [value];
  31834. }
  31835. else {
  31836. // No value in previous series
  31837. axisValues[key].push(value);
  31838. }
  31839. // Ignore duplicated time values in the same axis
  31840. }
  31841. });
  31842. var axisMinGaps = [];
  31843. for (var key in axisValues) {
  31844. if (axisValues.hasOwnProperty(key)) {
  31845. var valuesInAxis = axisValues[key];
  31846. if (valuesInAxis) {
  31847. // Sort axis values into ascending order to calculate gaps
  31848. valuesInAxis.sort(function (a, b) {
  31849. return a - b;
  31850. });
  31851. var min = null;
  31852. for (var j = 1; j < valuesInAxis.length; ++j) {
  31853. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  31854. if (delta > 0) {
  31855. // Ignore 0 delta because they are of the same axis value
  31856. min = min === null ? delta : Math.min(min, delta);
  31857. }
  31858. }
  31859. // Set to null if only have one data
  31860. axisMinGaps[key] = min;
  31861. }
  31862. }
  31863. }
  31864. return axisMinGaps;
  31865. }
  31866. function makeColumnLayout(barSeries) {
  31867. var axisMinGaps = getValueAxesMinGaps(barSeries);
  31868. var seriesInfoList = [];
  31869. each$1(barSeries, function (seriesModel) {
  31870. var cartesian = seriesModel.coordinateSystem;
  31871. var baseAxis = cartesian.getBaseAxis();
  31872. var axisExtent = baseAxis.getExtent();
  31873. var bandWidth;
  31874. if (baseAxis.type === 'category') {
  31875. bandWidth = baseAxis.getBandWidth();
  31876. }
  31877. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  31878. var key = baseAxis.dim + '_' + baseAxis.index;
  31879. var minGap = axisMinGaps[key];
  31880. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  31881. var scale = baseAxis.scale.getExtent();
  31882. var scaleSpan = Math.abs(scale[1] - scale[0]);
  31883. bandWidth = minGap
  31884. ? extentSpan / scaleSpan * minGap
  31885. : extentSpan; // When there is only one data value
  31886. }
  31887. else {
  31888. var data = seriesModel.getData();
  31889. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  31890. }
  31891. var barWidth = parsePercent$1(
  31892. seriesModel.get('barWidth'), bandWidth
  31893. );
  31894. var barMaxWidth = parsePercent$1(
  31895. seriesModel.get('barMaxWidth'), bandWidth
  31896. );
  31897. var barMinWidth = parsePercent$1(
  31898. // barMinWidth by default is 1 in cartesian. Because in value axis,
  31899. // the auto-calculated bar width might be less than 1.
  31900. seriesModel.get('barMinWidth') || 1, bandWidth
  31901. );
  31902. var barGap = seriesModel.get('barGap');
  31903. var barCategoryGap = seriesModel.get('barCategoryGap');
  31904. seriesInfoList.push({
  31905. bandWidth: bandWidth,
  31906. barWidth: barWidth,
  31907. barMaxWidth: barMaxWidth,
  31908. barMinWidth: barMinWidth,
  31909. barGap: barGap,
  31910. barCategoryGap: barCategoryGap,
  31911. axisKey: getAxisKey(baseAxis),
  31912. stackId: getSeriesStackId(seriesModel)
  31913. });
  31914. });
  31915. return doCalBarWidthAndOffset(seriesInfoList);
  31916. }
  31917. function doCalBarWidthAndOffset(seriesInfoList) {
  31918. // Columns info on each category axis. Key is cartesian name
  31919. var columnsMap = {};
  31920. each$1(seriesInfoList, function (seriesInfo, idx) {
  31921. var axisKey = seriesInfo.axisKey;
  31922. var bandWidth = seriesInfo.bandWidth;
  31923. var columnsOnAxis = columnsMap[axisKey] || {
  31924. bandWidth: bandWidth,
  31925. remainedWidth: bandWidth,
  31926. autoWidthCount: 0,
  31927. categoryGap: '20%',
  31928. gap: '30%',
  31929. stacks: {}
  31930. };
  31931. var stacks = columnsOnAxis.stacks;
  31932. columnsMap[axisKey] = columnsOnAxis;
  31933. var stackId = seriesInfo.stackId;
  31934. if (!stacks[stackId]) {
  31935. columnsOnAxis.autoWidthCount++;
  31936. }
  31937. stacks[stackId] = stacks[stackId] || {
  31938. width: 0,
  31939. maxWidth: 0
  31940. };
  31941. // Caution: In a single coordinate system, these barGrid attributes
  31942. // will be shared by series. Consider that they have default values,
  31943. // only the attributes set on the last series will work.
  31944. // Do not change this fact unless there will be a break change.
  31945. var barWidth = seriesInfo.barWidth;
  31946. if (barWidth && !stacks[stackId].width) {
  31947. // See #6312, do not restrict width.
  31948. stacks[stackId].width = barWidth;
  31949. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  31950. columnsOnAxis.remainedWidth -= barWidth;
  31951. }
  31952. var barMaxWidth = seriesInfo.barMaxWidth;
  31953. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  31954. var barMinWidth = seriesInfo.barMinWidth;
  31955. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  31956. var barGap = seriesInfo.barGap;
  31957. (barGap != null) && (columnsOnAxis.gap = barGap);
  31958. var barCategoryGap = seriesInfo.barCategoryGap;
  31959. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  31960. });
  31961. var result = {};
  31962. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  31963. result[coordSysName] = {};
  31964. var stacks = columnsOnAxis.stacks;
  31965. var bandWidth = columnsOnAxis.bandWidth;
  31966. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  31967. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  31968. var remainedWidth = columnsOnAxis.remainedWidth;
  31969. var autoWidthCount = columnsOnAxis.autoWidthCount;
  31970. var autoWidth = (remainedWidth - categoryGap)
  31971. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31972. autoWidth = Math.max(autoWidth, 0);
  31973. // Find if any auto calculated bar exceeded maxBarWidth
  31974. each$1(stacks, function (column) {
  31975. var maxWidth = column.maxWidth;
  31976. var minWidth = column.minWidth;
  31977. if (!column.width) {
  31978. var finalWidth = autoWidth;
  31979. if (maxWidth && maxWidth < finalWidth) {
  31980. finalWidth = Math.min(maxWidth, remainedWidth);
  31981. }
  31982. // `minWidth` has higher priority. `minWidth` decide that wheter the
  31983. // bar is able to be visible. So `minWidth` should not be restricted
  31984. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  31985. // the extreme cases for `value` axis, bars are allowed to overlap
  31986. // with each other if `minWidth` specified.
  31987. if (minWidth && minWidth > finalWidth) {
  31988. finalWidth = minWidth;
  31989. }
  31990. if (finalWidth !== autoWidth) {
  31991. column.width = finalWidth;
  31992. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31993. autoWidthCount--;
  31994. }
  31995. }
  31996. else {
  31997. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  31998. // CSS does. Becuase barWidth can be a percent value, where
  31999. // `barMaxWidth` can be used to restrict the final width.
  32000. var finalWidth = column.width;
  32001. if (maxWidth) {
  32002. finalWidth = Math.min(finalWidth, maxWidth);
  32003. }
  32004. // `minWidth` has higher priority, as described above
  32005. if (minWidth) {
  32006. finalWidth = Math.max(finalWidth, minWidth);
  32007. }
  32008. column.width = finalWidth;
  32009. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  32010. autoWidthCount--;
  32011. }
  32012. });
  32013. // Recalculate width again
  32014. autoWidth = (remainedWidth - categoryGap)
  32015. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  32016. autoWidth = Math.max(autoWidth, 0);
  32017. var widthSum = 0;
  32018. var lastColumn;
  32019. each$1(stacks, function (column, idx) {
  32020. if (!column.width) {
  32021. column.width = autoWidth;
  32022. }
  32023. lastColumn = column;
  32024. widthSum += column.width * (1 + barGapPercent);
  32025. });
  32026. if (lastColumn) {
  32027. widthSum -= lastColumn.width * barGapPercent;
  32028. }
  32029. var offset = -widthSum / 2;
  32030. each$1(stacks, function (column, stackId) {
  32031. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  32032. bandWidth: bandWidth,
  32033. offset: offset,
  32034. width: column.width
  32035. };
  32036. offset += column.width * (1 + barGapPercent);
  32037. });
  32038. });
  32039. return result;
  32040. }
  32041. /**
  32042. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  32043. * @param {module:echarts/coord/Axis} axis
  32044. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  32045. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  32046. */
  32047. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  32048. if (barWidthAndOffset && axis) {
  32049. var result = barWidthAndOffset[getAxisKey(axis)];
  32050. if (result != null && seriesModel != null) {
  32051. result = result[getSeriesStackId(seriesModel)];
  32052. }
  32053. return result;
  32054. }
  32055. }
  32056. /**
  32057. * @param {string} seriesType
  32058. * @param {module:echarts/model/Global} ecModel
  32059. */
  32060. function layout(seriesType, ecModel) {
  32061. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  32062. var barWidthAndOffset = makeColumnLayout(seriesModels);
  32063. var lastStackCoords = {};
  32064. each$1(seriesModels, function (seriesModel) {
  32065. var data = seriesModel.getData();
  32066. var cartesian = seriesModel.coordinateSystem;
  32067. var baseAxis = cartesian.getBaseAxis();
  32068. var stackId = getSeriesStackId(seriesModel);
  32069. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  32070. var columnOffset = columnLayoutInfo.offset;
  32071. var columnWidth = columnLayoutInfo.width;
  32072. var valueAxis = cartesian.getOtherAxis(baseAxis);
  32073. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  32074. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  32075. data.setLayout({
  32076. bandWidth: columnLayoutInfo.bandWidth,
  32077. offset: columnOffset,
  32078. size: columnWidth
  32079. });
  32080. var valueDim = data.mapDimension(valueAxis.dim);
  32081. var baseDim = data.mapDimension(baseAxis.dim);
  32082. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  32083. var isValueAxisH = valueAxis.isHorizontal();
  32084. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  32085. for (var idx = 0, len = data.count(); idx < len; idx++) {
  32086. var value = data.get(valueDim, idx);
  32087. var baseValue = data.get(baseDim, idx);
  32088. var sign = value >= 0 ? 'p' : 'n';
  32089. var baseCoord = valueAxisStart;
  32090. // Because of the barMinHeight, we can not use the value in
  32091. // stackResultDimension directly.
  32092. if (stacked) {
  32093. // Only ordinal axis can be stacked.
  32094. if (!lastStackCoords[stackId][baseValue]) {
  32095. lastStackCoords[stackId][baseValue] = {
  32096. p: valueAxisStart, // Positive stack
  32097. n: valueAxisStart // Negative stack
  32098. };
  32099. }
  32100. // Should also consider #4243
  32101. baseCoord = lastStackCoords[stackId][baseValue][sign];
  32102. }
  32103. var x;
  32104. var y;
  32105. var width;
  32106. var height;
  32107. if (isValueAxisH) {
  32108. var coord = cartesian.dataToPoint([value, baseValue]);
  32109. x = baseCoord;
  32110. y = coord[1] + columnOffset;
  32111. width = coord[0] - valueAxisStart;
  32112. height = columnWidth;
  32113. if (Math.abs(width) < barMinHeight) {
  32114. width = (width < 0 ? -1 : 1) * barMinHeight;
  32115. }
  32116. // Ignore stack from NaN value
  32117. if (!isNaN(width)) {
  32118. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  32119. }
  32120. }
  32121. else {
  32122. var coord = cartesian.dataToPoint([baseValue, value]);
  32123. x = coord[0] + columnOffset;
  32124. y = baseCoord;
  32125. width = columnWidth;
  32126. height = coord[1] - valueAxisStart;
  32127. if (Math.abs(height) < barMinHeight) {
  32128. // Include zero to has a positive bar
  32129. height = (height <= 0 ? -1 : 1) * barMinHeight;
  32130. }
  32131. // Ignore stack from NaN value
  32132. if (!isNaN(height)) {
  32133. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  32134. }
  32135. }
  32136. data.setItemLayout(idx, {
  32137. x: x,
  32138. y: y,
  32139. width: width,
  32140. height: height
  32141. });
  32142. }
  32143. }, this);
  32144. }
  32145. // TODO: Do not support stack in large mode yet.
  32146. var largeLayout = {
  32147. seriesType: 'bar',
  32148. plan: createRenderPlanner(),
  32149. reset: function (seriesModel) {
  32150. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  32151. return;
  32152. }
  32153. var data = seriesModel.getData();
  32154. var cartesian = seriesModel.coordinateSystem;
  32155. var coordLayout = cartesian.grid.getRect();
  32156. var baseAxis = cartesian.getBaseAxis();
  32157. var valueAxis = cartesian.getOtherAxis(baseAxis);
  32158. var valueDim = data.mapDimension(valueAxis.dim);
  32159. var baseDim = data.mapDimension(baseAxis.dim);
  32160. var valueAxisHorizontal = valueAxis.isHorizontal();
  32161. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  32162. var barWidth = retrieveColumnLayout(
  32163. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  32164. ).width;
  32165. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  32166. barWidth = LARGE_BAR_MIN_WIDTH;
  32167. }
  32168. return {progress: progress};
  32169. function progress(params, data) {
  32170. var count = params.count;
  32171. var largePoints = new LargeArr(count * 2);
  32172. var largeBackgroundPoints = new LargeArr(count * 2);
  32173. var largeDataIndices = new LargeArr(count);
  32174. var dataIndex;
  32175. var coord = [];
  32176. var valuePair = [];
  32177. var pointsOffset = 0;
  32178. var idxOffset = 0;
  32179. while ((dataIndex = params.next()) != null) {
  32180. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  32181. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  32182. coord = cartesian.dataToPoint(valuePair, null, coord);
  32183. // Data index might not be in order, depends on `progressiveChunkMode`.
  32184. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  32185. largePoints[pointsOffset++] = coord[0];
  32186. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  32187. largePoints[pointsOffset++] = coord[1];
  32188. largeDataIndices[idxOffset++] = dataIndex;
  32189. }
  32190. data.setLayout({
  32191. largePoints: largePoints,
  32192. largeDataIndices: largeDataIndices,
  32193. largeBackgroundPoints: largeBackgroundPoints,
  32194. barWidth: barWidth,
  32195. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  32196. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  32197. valueAxisHorizontal: valueAxisHorizontal
  32198. });
  32199. }
  32200. }
  32201. };
  32202. function isOnCartesian(seriesModel) {
  32203. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  32204. }
  32205. function isInLargeMode(seriesModel) {
  32206. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  32207. }
  32208. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  32209. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  32210. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  32211. }
  32212. /*
  32213. * Licensed to the Apache Software Foundation (ASF) under one
  32214. * or more contributor license agreements. See the NOTICE file
  32215. * distributed with this work for additional information
  32216. * regarding copyright ownership. The ASF licenses this file
  32217. * to you under the Apache License, Version 2.0 (the
  32218. * "License"); you may not use this file except in compliance
  32219. * with the License. You may obtain a copy of the License at
  32220. *
  32221. * http://www.apache.org/licenses/LICENSE-2.0
  32222. *
  32223. * Unless required by applicable law or agreed to in writing,
  32224. * software distributed under the License is distributed on an
  32225. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32226. * KIND, either express or implied. See the License for the
  32227. * specific language governing permissions and limitations
  32228. * under the License.
  32229. */
  32230. /*
  32231. * A third-party license is embeded for some of the code in this file:
  32232. * The "scaleLevels" was originally copied from "d3.js" with some
  32233. * modifications made for this project.
  32234. * (See more details in the comment on the definition of "scaleLevels" below.)
  32235. * The use of the source code of this file is also subject to the terms
  32236. * and consitions of the license of "d3.js" (BSD-3Clause, see
  32237. * </licenses/LICENSE-d3>).
  32238. */
  32239. // [About UTC and local time zone]:
  32240. // In most cases, `number.parseDate` will treat input data string as local time
  32241. // (except time zone is specified in time string). And `format.formateTime` returns
  32242. // local time by default. option.useUTC is false by default. This design have
  32243. // concidered these common case:
  32244. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  32245. // in local time by default.
  32246. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  32247. // as its original time, without any time difference.
  32248. var intervalScaleProto = IntervalScale.prototype;
  32249. var mathCeil = Math.ceil;
  32250. var mathFloor = Math.floor;
  32251. var ONE_SECOND = 1000;
  32252. var ONE_MINUTE = ONE_SECOND * 60;
  32253. var ONE_HOUR = ONE_MINUTE * 60;
  32254. var ONE_DAY = ONE_HOUR * 24;
  32255. // FIXME 公用?
  32256. var bisect = function (a, x, lo, hi) {
  32257. while (lo < hi) {
  32258. var mid = lo + hi >>> 1;
  32259. if (a[mid][1] < x) {
  32260. lo = mid + 1;
  32261. }
  32262. else {
  32263. hi = mid;
  32264. }
  32265. }
  32266. return lo;
  32267. };
  32268. /**
  32269. * @alias module:echarts/coord/scale/Time
  32270. * @constructor
  32271. */
  32272. var TimeScale = IntervalScale.extend({
  32273. type: 'time',
  32274. /**
  32275. * @override
  32276. */
  32277. getLabel: function (val) {
  32278. var stepLvl = this._stepLvl;
  32279. var date = new Date(val);
  32280. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  32281. },
  32282. /**
  32283. * @override
  32284. */
  32285. niceExtent: function (opt) {
  32286. var extent = this._extent;
  32287. // If extent start and end are same, expand them
  32288. if (extent[0] === extent[1]) {
  32289. // Expand extent
  32290. extent[0] -= ONE_DAY;
  32291. extent[1] += ONE_DAY;
  32292. }
  32293. // If there are no data and extent are [Infinity, -Infinity]
  32294. if (extent[1] === -Infinity && extent[0] === Infinity) {
  32295. var d = new Date();
  32296. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  32297. extent[0] = extent[1] - ONE_DAY;
  32298. }
  32299. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  32300. // var extent = this._extent;
  32301. var interval = this._interval;
  32302. if (!opt.fixMin) {
  32303. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  32304. }
  32305. if (!opt.fixMax) {
  32306. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  32307. }
  32308. },
  32309. /**
  32310. * @override
  32311. */
  32312. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  32313. approxTickNum = approxTickNum || 10;
  32314. var extent = this._extent;
  32315. var span = extent[1] - extent[0];
  32316. var approxInterval = span / approxTickNum;
  32317. if (minInterval != null && approxInterval < minInterval) {
  32318. approxInterval = minInterval;
  32319. }
  32320. if (maxInterval != null && approxInterval > maxInterval) {
  32321. approxInterval = maxInterval;
  32322. }
  32323. var scaleLevelsLen = scaleLevels.length;
  32324. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  32325. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  32326. var interval = level[1];
  32327. // Same with interval scale if span is much larger than 1 year
  32328. if (level[0] === 'year') {
  32329. var yearSpan = span / interval;
  32330. // From "Nice Numbers for Graph Labels" of Graphic Gems
  32331. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  32332. var yearStep = nice(yearSpan / approxTickNum, true);
  32333. interval *= yearStep;
  32334. }
  32335. var timezoneOffset = this.getSetting('useUTC')
  32336. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  32337. var niceExtent = [
  32338. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  32339. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  32340. ];
  32341. fixExtent(niceExtent, extent);
  32342. this._stepLvl = level;
  32343. // Interval will be used in getTicks
  32344. this._interval = interval;
  32345. this._niceExtent = niceExtent;
  32346. },
  32347. parse: function (val) {
  32348. // val might be float.
  32349. return +parseDate(val);
  32350. }
  32351. });
  32352. each$1(['contain', 'normalize'], function (methodName) {
  32353. TimeScale.prototype[methodName] = function (val) {
  32354. return intervalScaleProto[methodName].call(this, this.parse(val));
  32355. };
  32356. });
  32357. /**
  32358. * This implementation was originally copied from "d3.js"
  32359. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  32360. * with some modifications made for this program.
  32361. * See the license statement at the head of this file.
  32362. */
  32363. var scaleLevels = [
  32364. // Format interval
  32365. ['hh:mm:ss', ONE_SECOND], // 1s
  32366. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  32367. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  32368. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  32369. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  32370. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  32371. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  32372. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  32373. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  32374. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  32375. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  32376. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  32377. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  32378. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  32379. ['MM-dd\nyyyy', ONE_DAY], // 1d
  32380. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  32381. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  32382. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  32383. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  32384. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  32385. ['week', ONE_DAY * 7], // 7d
  32386. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  32387. ['week', ONE_DAY * 14], // 2w
  32388. ['week', ONE_DAY * 21], // 3w
  32389. ['month', ONE_DAY * 31], // 1M
  32390. ['week', ONE_DAY * 42], // 6w
  32391. ['month', ONE_DAY * 62], // 2M
  32392. ['week', ONE_DAY * 70], // 10w
  32393. ['quarter', ONE_DAY * 95], // 3M
  32394. ['month', ONE_DAY * 31 * 4], // 4M
  32395. ['month', ONE_DAY * 31 * 5], // 5M
  32396. ['half-year', ONE_DAY * 380 / 2], // 6M
  32397. ['month', ONE_DAY * 31 * 8], // 8M
  32398. ['month', ONE_DAY * 31 * 10], // 10M
  32399. ['year', ONE_DAY * 380] // 1Y
  32400. ];
  32401. /**
  32402. * @param {module:echarts/model/Model}
  32403. * @return {module:echarts/scale/Time}
  32404. */
  32405. TimeScale.create = function (model) {
  32406. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  32407. };
  32408. /*
  32409. * Licensed to the Apache Software Foundation (ASF) under one
  32410. * or more contributor license agreements. See the NOTICE file
  32411. * distributed with this work for additional information
  32412. * regarding copyright ownership. The ASF licenses this file
  32413. * to you under the Apache License, Version 2.0 (the
  32414. * "License"); you may not use this file except in compliance
  32415. * with the License. You may obtain a copy of the License at
  32416. *
  32417. * http://www.apache.org/licenses/LICENSE-2.0
  32418. *
  32419. * Unless required by applicable law or agreed to in writing,
  32420. * software distributed under the License is distributed on an
  32421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32422. * KIND, either express or implied. See the License for the
  32423. * specific language governing permissions and limitations
  32424. * under the License.
  32425. */
  32426. /**
  32427. * Log scale
  32428. * @module echarts/scale/Log
  32429. */
  32430. // Use some method of IntervalScale
  32431. var scaleProto$1 = Scale.prototype;
  32432. var intervalScaleProto$1 = IntervalScale.prototype;
  32433. var getPrecisionSafe$1 = getPrecisionSafe;
  32434. var roundingErrorFix = round$1;
  32435. var mathFloor$1 = Math.floor;
  32436. var mathCeil$1 = Math.ceil;
  32437. var mathPow$1 = Math.pow;
  32438. var mathLog = Math.log;
  32439. var LogScale = Scale.extend({
  32440. type: 'log',
  32441. base: 10,
  32442. $constructor: function () {
  32443. Scale.apply(this, arguments);
  32444. this._originalScale = new IntervalScale();
  32445. },
  32446. /**
  32447. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  32448. * @return {Array.<number>}
  32449. */
  32450. getTicks: function (expandToNicedExtent) {
  32451. var originalScale = this._originalScale;
  32452. var extent = this._extent;
  32453. var originalExtent = originalScale.getExtent();
  32454. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  32455. var powVal = round$1(mathPow$1(this.base, val));
  32456. // Fix #4158
  32457. powVal = (val === extent[0] && originalScale.__fixMin)
  32458. ? fixRoundingError(powVal, originalExtent[0])
  32459. : powVal;
  32460. powVal = (val === extent[1] && originalScale.__fixMax)
  32461. ? fixRoundingError(powVal, originalExtent[1])
  32462. : powVal;
  32463. return powVal;
  32464. }, this);
  32465. },
  32466. /**
  32467. * @param {number} splitNumber
  32468. * @return {Array.<Array.<number>>}
  32469. */
  32470. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  32471. /**
  32472. * @param {number} val
  32473. * @return {string}
  32474. */
  32475. getLabel: intervalScaleProto$1.getLabel,
  32476. /**
  32477. * @param {number} val
  32478. * @return {number}
  32479. */
  32480. scale: function (val) {
  32481. val = scaleProto$1.scale.call(this, val);
  32482. return mathPow$1(this.base, val);
  32483. },
  32484. /**
  32485. * @param {number} start
  32486. * @param {number} end
  32487. */
  32488. setExtent: function (start, end) {
  32489. var base = this.base;
  32490. start = mathLog(start) / mathLog(base);
  32491. end = mathLog(end) / mathLog(base);
  32492. intervalScaleProto$1.setExtent.call(this, start, end);
  32493. },
  32494. /**
  32495. * @return {number} end
  32496. */
  32497. getExtent: function () {
  32498. var base = this.base;
  32499. var extent = scaleProto$1.getExtent.call(this);
  32500. extent[0] = mathPow$1(base, extent[0]);
  32501. extent[1] = mathPow$1(base, extent[1]);
  32502. // Fix #4158
  32503. var originalScale = this._originalScale;
  32504. var originalExtent = originalScale.getExtent();
  32505. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  32506. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  32507. return extent;
  32508. },
  32509. /**
  32510. * @param {Array.<number>} extent
  32511. */
  32512. unionExtent: function (extent) {
  32513. this._originalScale.unionExtent(extent);
  32514. var base = this.base;
  32515. extent[0] = mathLog(extent[0]) / mathLog(base);
  32516. extent[1] = mathLog(extent[1]) / mathLog(base);
  32517. scaleProto$1.unionExtent.call(this, extent);
  32518. },
  32519. /**
  32520. * @override
  32521. */
  32522. unionExtentFromData: function (data, dim) {
  32523. // TODO
  32524. // filter value that <= 0
  32525. this.unionExtent(data.getApproximateExtent(dim));
  32526. },
  32527. /**
  32528. * Update interval and extent of intervals for nice ticks
  32529. * @param {number} [approxTickNum = 10] Given approx tick number
  32530. */
  32531. niceTicks: function (approxTickNum) {
  32532. approxTickNum = approxTickNum || 10;
  32533. var extent = this._extent;
  32534. var span = extent[1] - extent[0];
  32535. if (span === Infinity || span <= 0) {
  32536. return;
  32537. }
  32538. var interval = quantity(span);
  32539. var err = approxTickNum / span * interval;
  32540. // Filter ticks to get closer to the desired count.
  32541. if (err <= 0.5) {
  32542. interval *= 10;
  32543. }
  32544. // Interval should be integer
  32545. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  32546. interval *= 10;
  32547. }
  32548. var niceExtent = [
  32549. round$1(mathCeil$1(extent[0] / interval) * interval),
  32550. round$1(mathFloor$1(extent[1] / interval) * interval)
  32551. ];
  32552. this._interval = interval;
  32553. this._niceExtent = niceExtent;
  32554. },
  32555. /**
  32556. * Nice extent.
  32557. * @override
  32558. */
  32559. niceExtent: function (opt) {
  32560. intervalScaleProto$1.niceExtent.call(this, opt);
  32561. var originalScale = this._originalScale;
  32562. originalScale.__fixMin = opt.fixMin;
  32563. originalScale.__fixMax = opt.fixMax;
  32564. }
  32565. });
  32566. each$1(['contain', 'normalize'], function (methodName) {
  32567. LogScale.prototype[methodName] = function (val) {
  32568. val = mathLog(val) / mathLog(this.base);
  32569. return scaleProto$1[methodName].call(this, val);
  32570. };
  32571. });
  32572. LogScale.create = function () {
  32573. return new LogScale();
  32574. };
  32575. function fixRoundingError(val, originalVal) {
  32576. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  32577. }
  32578. /*
  32579. * Licensed to the Apache Software Foundation (ASF) under one
  32580. * or more contributor license agreements. See the NOTICE file
  32581. * distributed with this work for additional information
  32582. * regarding copyright ownership. The ASF licenses this file
  32583. * to you under the Apache License, Version 2.0 (the
  32584. * "License"); you may not use this file except in compliance
  32585. * with the License. You may obtain a copy of the License at
  32586. *
  32587. * http://www.apache.org/licenses/LICENSE-2.0
  32588. *
  32589. * Unless required by applicable law or agreed to in writing,
  32590. * software distributed under the License is distributed on an
  32591. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32592. * KIND, either express or implied. See the License for the
  32593. * specific language governing permissions and limitations
  32594. * under the License.
  32595. */
  32596. /**
  32597. * Get axis scale extent before niced.
  32598. * Item of returned array can only be number (including Infinity and NaN).
  32599. */
  32600. function getScaleExtent(scale, model) {
  32601. var scaleType = scale.type;
  32602. var min = model.getMin();
  32603. var max = model.getMax();
  32604. var fixMin = min != null;
  32605. var fixMax = max != null;
  32606. var originalExtent = scale.getExtent();
  32607. var axisDataLen;
  32608. var boundaryGap;
  32609. var span;
  32610. if (scaleType === 'ordinal') {
  32611. axisDataLen = model.getCategories().length;
  32612. }
  32613. else {
  32614. boundaryGap = model.get('boundaryGap');
  32615. if (!isArray(boundaryGap)) {
  32616. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  32617. }
  32618. if (typeof boundaryGap[0] === 'boolean') {
  32619. if (__DEV__) {
  32620. console.warn('Boolean type for boundaryGap is only '
  32621. + 'allowed for ordinal axis. Please use string in '
  32622. + 'percentage instead, e.g., "20%". Currently, '
  32623. + 'boundaryGap is set to be 0.');
  32624. }
  32625. boundaryGap = [0, 0];
  32626. }
  32627. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  32628. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  32629. span = (originalExtent[1] - originalExtent[0])
  32630. || Math.abs(originalExtent[0]);
  32631. }
  32632. // Notice: When min/max is not set (that is, when there are null/undefined,
  32633. // which is the most common case), these cases should be ensured:
  32634. // (1) For 'ordinal', show all axis.data.
  32635. // (2) For others:
  32636. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  32637. // disabled).
  32638. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  32639. // be the result that originalExtent enlarged by boundaryGap.
  32640. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  32641. // FIXME
  32642. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  32643. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  32644. // that the results processed by boundaryGap are positive/negative?
  32645. if (min == null) {
  32646. min = scaleType === 'ordinal'
  32647. ? (axisDataLen ? 0 : NaN)
  32648. : originalExtent[0] - boundaryGap[0] * span;
  32649. }
  32650. if (max == null) {
  32651. max = scaleType === 'ordinal'
  32652. ? (axisDataLen ? axisDataLen - 1 : NaN)
  32653. : originalExtent[1] + boundaryGap[1] * span;
  32654. }
  32655. if (min === 'dataMin') {
  32656. min = originalExtent[0];
  32657. }
  32658. else if (typeof min === 'function') {
  32659. min = min({
  32660. min: originalExtent[0],
  32661. max: originalExtent[1]
  32662. });
  32663. }
  32664. if (max === 'dataMax') {
  32665. max = originalExtent[1];
  32666. }
  32667. else if (typeof max === 'function') {
  32668. max = max({
  32669. min: originalExtent[0],
  32670. max: originalExtent[1]
  32671. });
  32672. }
  32673. (min == null || !isFinite(min)) && (min = NaN);
  32674. (max == null || !isFinite(max)) && (max = NaN);
  32675. scale.setBlank(
  32676. eqNaN(min)
  32677. || eqNaN(max)
  32678. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  32679. );
  32680. // Evaluate if axis needs cross zero
  32681. if (model.getNeedCrossZero()) {
  32682. // Axis is over zero and min is not set
  32683. if (min > 0 && max > 0 && !fixMin) {
  32684. min = 0;
  32685. }
  32686. // Axis is under zero and max is not set
  32687. if (min < 0 && max < 0 && !fixMax) {
  32688. max = 0;
  32689. }
  32690. }
  32691. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  32692. // is base axis
  32693. // FIXME
  32694. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  32695. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  32696. // Should not depend on series type `bar`?
  32697. // (3) Fix that might overlap when using dataZoom.
  32698. // (4) Consider other chart types using `barGrid`?
  32699. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  32700. var ecModel = model.ecModel;
  32701. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  32702. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  32703. var isBaseAxisAndHasBarSeries;
  32704. each$1(barSeriesModels, function (seriesModel) {
  32705. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  32706. });
  32707. if (isBaseAxisAndHasBarSeries) {
  32708. // Calculate placement of bars on axis
  32709. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  32710. // Adjust axis min and max to account for overflow
  32711. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  32712. min = adjustedScale.min;
  32713. max = adjustedScale.max;
  32714. }
  32715. }
  32716. return [min, max];
  32717. }
  32718. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  32719. // Get Axis Length
  32720. var axisExtent = model.axis.getExtent();
  32721. var axisLength = axisExtent[1] - axisExtent[0];
  32722. // Get bars on current base axis and calculate min and max overflow
  32723. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  32724. if (barsOnCurrentAxis === undefined) {
  32725. return {min: min, max: max};
  32726. }
  32727. var minOverflow = Infinity;
  32728. each$1(barsOnCurrentAxis, function (item) {
  32729. minOverflow = Math.min(item.offset, minOverflow);
  32730. });
  32731. var maxOverflow = -Infinity;
  32732. each$1(barsOnCurrentAxis, function (item) {
  32733. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  32734. });
  32735. minOverflow = Math.abs(minOverflow);
  32736. maxOverflow = Math.abs(maxOverflow);
  32737. var totalOverFlow = minOverflow + maxOverflow;
  32738. // Calulate required buffer based on old range and overflow
  32739. var oldRange = max - min;
  32740. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  32741. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  32742. max += overflowBuffer * (maxOverflow / totalOverFlow);
  32743. min -= overflowBuffer * (minOverflow / totalOverFlow);
  32744. return {min: min, max: max};
  32745. }
  32746. function niceScaleExtent(scale, model) {
  32747. var extent = getScaleExtent(scale, model);
  32748. var fixMin = model.getMin() != null;
  32749. var fixMax = model.getMax() != null;
  32750. var splitNumber = model.get('splitNumber');
  32751. if (scale.type === 'log') {
  32752. scale.base = model.get('logBase');
  32753. }
  32754. var scaleType = scale.type;
  32755. scale.setExtent(extent[0], extent[1]);
  32756. scale.niceExtent({
  32757. splitNumber: splitNumber,
  32758. fixMin: fixMin,
  32759. fixMax: fixMax,
  32760. minInterval: (scaleType === 'interval' || scaleType === 'time')
  32761. ? model.get('minInterval') : null,
  32762. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  32763. ? model.get('maxInterval') : null
  32764. });
  32765. // If some one specified the min, max. And the default calculated interval
  32766. // is not good enough. He can specify the interval. It is often appeared
  32767. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32768. // to be 60.
  32769. // FIXME
  32770. var interval = model.get('interval');
  32771. if (interval != null) {
  32772. scale.setInterval && scale.setInterval(interval);
  32773. }
  32774. }
  32775. /**
  32776. * @param {module:echarts/model/Model} model
  32777. * @param {string} [axisType] Default retrieve from model.type
  32778. * @return {module:echarts/scale/*}
  32779. */
  32780. function createScaleByModel(model, axisType) {
  32781. axisType = axisType || model.get('type');
  32782. if (axisType) {
  32783. switch (axisType) {
  32784. // Buildin scale
  32785. case 'category':
  32786. return new OrdinalScale(
  32787. model.getOrdinalMeta
  32788. ? model.getOrdinalMeta()
  32789. : model.getCategories(),
  32790. [Infinity, -Infinity]
  32791. );
  32792. case 'value':
  32793. return new IntervalScale();
  32794. // Extended scale, like time and log
  32795. default:
  32796. return (Scale.getClass(axisType) || IntervalScale).create(model);
  32797. }
  32798. }
  32799. }
  32800. /**
  32801. * Check if the axis corss 0
  32802. */
  32803. function ifAxisCrossZero(axis) {
  32804. var dataExtent = axis.scale.getExtent();
  32805. var min = dataExtent[0];
  32806. var max = dataExtent[1];
  32807. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  32808. }
  32809. /**
  32810. * @param {module:echarts/coord/Axis} axis
  32811. * @return {Function} Label formatter function.
  32812. * param: {number} tickValue,
  32813. * param: {number} idx, the index in all ticks.
  32814. * If category axis, this param is not requied.
  32815. * return: {string} label string.
  32816. */
  32817. function makeLabelFormatter(axis) {
  32818. var labelFormatter = axis.getLabelModel().get('formatter');
  32819. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32820. if (typeof labelFormatter === 'string') {
  32821. labelFormatter = (function (tpl) {
  32822. return function (val) {
  32823. // For category axis, get raw value; for numeric axis,
  32824. // get foramtted label like '1,333,444'.
  32825. val = axis.scale.getLabel(val);
  32826. return tpl.replace('{value}', val != null ? val : '');
  32827. };
  32828. })(labelFormatter);
  32829. // Consider empty array
  32830. return labelFormatter;
  32831. }
  32832. else if (typeof labelFormatter === 'function') {
  32833. return function (tickValue, idx) {
  32834. // The original intention of `idx` is "the index of the tick in all ticks".
  32835. // But the previous implementation of category axis do not consider the
  32836. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32837. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32838. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32839. // the definition here for back compatibility.
  32840. if (categoryTickStart != null) {
  32841. idx = tickValue - categoryTickStart;
  32842. }
  32843. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  32844. };
  32845. }
  32846. else {
  32847. return function (tick) {
  32848. return axis.scale.getLabel(tick);
  32849. };
  32850. }
  32851. }
  32852. function getAxisRawValue(axis, value) {
  32853. // In category axis with data zoom, tick is not the original
  32854. // index of axis.data. So tick should not be exposed to user
  32855. // in category axis.
  32856. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  32857. }
  32858. /**
  32859. * @param {module:echarts/coord/Axis} axis
  32860. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  32861. */
  32862. function estimateLabelUnionRect(axis) {
  32863. var axisModel = axis.model;
  32864. var scale = axis.scale;
  32865. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  32866. return;
  32867. }
  32868. var isCategory = axis.type === 'category';
  32869. var realNumberScaleTicks;
  32870. var tickCount;
  32871. var categoryScaleExtent = scale.getExtent();
  32872. // Optimize for large category data, avoid call `getTicks()`.
  32873. if (isCategory) {
  32874. tickCount = scale.count();
  32875. }
  32876. else {
  32877. realNumberScaleTicks = scale.getTicks();
  32878. tickCount = realNumberScaleTicks.length;
  32879. }
  32880. var axisLabelModel = axis.getLabelModel();
  32881. var labelFormatter = makeLabelFormatter(axis);
  32882. var rect;
  32883. var step = 1;
  32884. // Simple optimization for large amount of labels
  32885. if (tickCount > 40) {
  32886. step = Math.ceil(tickCount / 40);
  32887. }
  32888. for (var i = 0; i < tickCount; i += step) {
  32889. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  32890. var label = labelFormatter(tickValue);
  32891. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32892. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32893. rect ? rect.union(singleRect) : (rect = singleRect);
  32894. }
  32895. return rect;
  32896. }
  32897. function rotateTextRect(textRect, rotate) {
  32898. var rotateRadians = rotate * Math.PI / 180;
  32899. var boundingBox = textRect.plain();
  32900. var beforeWidth = boundingBox.width;
  32901. var beforeHeight = boundingBox.height;
  32902. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  32903. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  32904. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  32905. return rotatedRect;
  32906. }
  32907. /**
  32908. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  32909. * @return {number|String} Can be null|'auto'|number|function
  32910. */
  32911. function getOptionCategoryInterval(model) {
  32912. var interval = model.get('interval');
  32913. return interval == null ? 'auto' : interval;
  32914. }
  32915. /**
  32916. * Set `categoryInterval` as 0 implicitly indicates that
  32917. * show all labels reguardless of overlap.
  32918. * @param {Object} axis axisModel.axis
  32919. * @return {boolean}
  32920. */
  32921. function shouldShowAllLabels(axis) {
  32922. return axis.type === 'category'
  32923. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32924. }
  32925. /*
  32926. * Licensed to the Apache Software Foundation (ASF) under one
  32927. * or more contributor license agreements. See the NOTICE file
  32928. * distributed with this work for additional information
  32929. * regarding copyright ownership. The ASF licenses this file
  32930. * to you under the Apache License, Version 2.0 (the
  32931. * "License"); you may not use this file except in compliance
  32932. * with the License. You may obtain a copy of the License at
  32933. *
  32934. * http://www.apache.org/licenses/LICENSE-2.0
  32935. *
  32936. * Unless required by applicable law or agreed to in writing,
  32937. * software distributed under the License is distributed on an
  32938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32939. * KIND, either express or implied. See the License for the
  32940. * specific language governing permissions and limitations
  32941. * under the License.
  32942. */
  32943. /**
  32944. * Cartesian coordinate system
  32945. * @module echarts/coord/Cartesian
  32946. *
  32947. */
  32948. function dimAxisMapper(dim) {
  32949. return this._axes[dim];
  32950. }
  32951. /**
  32952. * @alias module:echarts/coord/Cartesian
  32953. * @constructor
  32954. */
  32955. var Cartesian = function (name) {
  32956. this._axes = {};
  32957. this._dimList = [];
  32958. /**
  32959. * @type {string}
  32960. */
  32961. this.name = name || '';
  32962. };
  32963. Cartesian.prototype = {
  32964. constructor: Cartesian,
  32965. type: 'cartesian',
  32966. /**
  32967. * Get axis
  32968. * @param {number|string} dim
  32969. * @return {module:echarts/coord/Cartesian~Axis}
  32970. */
  32971. getAxis: function (dim) {
  32972. return this._axes[dim];
  32973. },
  32974. /**
  32975. * Get axes list
  32976. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  32977. */
  32978. getAxes: function () {
  32979. return map(this._dimList, dimAxisMapper, this);
  32980. },
  32981. /**
  32982. * Get axes list by given scale type
  32983. */
  32984. getAxesByScale: function (scaleType) {
  32985. scaleType = scaleType.toLowerCase();
  32986. return filter(
  32987. this.getAxes(),
  32988. function (axis) {
  32989. return axis.scale.type === scaleType;
  32990. }
  32991. );
  32992. },
  32993. /**
  32994. * Add axis
  32995. * @param {module:echarts/coord/Cartesian.Axis}
  32996. */
  32997. addAxis: function (axis) {
  32998. var dim = axis.dim;
  32999. this._axes[dim] = axis;
  33000. this._dimList.push(dim);
  33001. },
  33002. /**
  33003. * Convert data to coord in nd space
  33004. * @param {Array.<number>|Object.<string, number>} val
  33005. * @return {Array.<number>|Object.<string, number>}
  33006. */
  33007. dataToCoord: function (val) {
  33008. return this._dataCoordConvert(val, 'dataToCoord');
  33009. },
  33010. /**
  33011. * Convert coord in nd space to data
  33012. * @param {Array.<number>|Object.<string, number>} val
  33013. * @return {Array.<number>|Object.<string, number>}
  33014. */
  33015. coordToData: function (val) {
  33016. return this._dataCoordConvert(val, 'coordToData');
  33017. },
  33018. _dataCoordConvert: function (input, method) {
  33019. var dimList = this._dimList;
  33020. var output = input instanceof Array ? [] : {};
  33021. for (var i = 0; i < dimList.length; i++) {
  33022. var dim = dimList[i];
  33023. var axis = this._axes[dim];
  33024. output[dim] = axis[method](input[dim]);
  33025. }
  33026. return output;
  33027. }
  33028. };
  33029. /*
  33030. * Licensed to the Apache Software Foundation (ASF) under one
  33031. * or more contributor license agreements. See the NOTICE file
  33032. * distributed with this work for additional information
  33033. * regarding copyright ownership. The ASF licenses this file
  33034. * to you under the Apache License, Version 2.0 (the
  33035. * "License"); you may not use this file except in compliance
  33036. * with the License. You may obtain a copy of the License at
  33037. *
  33038. * http://www.apache.org/licenses/LICENSE-2.0
  33039. *
  33040. * Unless required by applicable law or agreed to in writing,
  33041. * software distributed under the License is distributed on an
  33042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33043. * KIND, either express or implied. See the License for the
  33044. * specific language governing permissions and limitations
  33045. * under the License.
  33046. */
  33047. function Cartesian2D(name) {
  33048. Cartesian.call(this, name);
  33049. }
  33050. Cartesian2D.prototype = {
  33051. constructor: Cartesian2D,
  33052. type: 'cartesian2d',
  33053. /**
  33054. * @type {Array.<string>}
  33055. * @readOnly
  33056. */
  33057. dimensions: ['x', 'y'],
  33058. /**
  33059. * Base axis will be used on stacking.
  33060. *
  33061. * @return {module:echarts/coord/cartesian/Axis2D}
  33062. */
  33063. getBaseAxis: function () {
  33064. return this.getAxesByScale('ordinal')[0]
  33065. || this.getAxesByScale('time')[0]
  33066. || this.getAxis('x');
  33067. },
  33068. /**
  33069. * If contain point
  33070. * @param {Array.<number>} point
  33071. * @return {boolean}
  33072. */
  33073. containPoint: function (point) {
  33074. var axisX = this.getAxis('x');
  33075. var axisY = this.getAxis('y');
  33076. return axisX.contain(axisX.toLocalCoord(point[0]))
  33077. && axisY.contain(axisY.toLocalCoord(point[1]));
  33078. },
  33079. /**
  33080. * If contain data
  33081. * @param {Array.<number>} data
  33082. * @return {boolean}
  33083. */
  33084. containData: function (data) {
  33085. return this.getAxis('x').containData(data[0])
  33086. && this.getAxis('y').containData(data[1]);
  33087. },
  33088. /**
  33089. * @param {Array.<number>} data
  33090. * @param {Array.<number>} out
  33091. * @return {Array.<number>}
  33092. */
  33093. dataToPoint: function (data, reserved, out) {
  33094. var xAxis = this.getAxis('x');
  33095. var yAxis = this.getAxis('y');
  33096. out = out || [];
  33097. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  33098. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  33099. return out;
  33100. },
  33101. /**
  33102. * @param {Array.<number>} data
  33103. * @param {Array.<number>} out
  33104. * @return {Array.<number>}
  33105. */
  33106. clampData: function (data, out) {
  33107. var xScale = this.getAxis('x').scale;
  33108. var yScale = this.getAxis('y').scale;
  33109. var xAxisExtent = xScale.getExtent();
  33110. var yAxisExtent = yScale.getExtent();
  33111. var x = xScale.parse(data[0]);
  33112. var y = yScale.parse(data[1]);
  33113. out = out || [];
  33114. out[0] = Math.min(
  33115. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  33116. Math.max(xAxisExtent[0], xAxisExtent[1])
  33117. );
  33118. out[1] = Math.min(
  33119. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  33120. Math.max(yAxisExtent[0], yAxisExtent[1])
  33121. );
  33122. return out;
  33123. },
  33124. /**
  33125. * @param {Array.<number>} point
  33126. * @param {Array.<number>} out
  33127. * @return {Array.<number>}
  33128. */
  33129. pointToData: function (point, out) {
  33130. var xAxis = this.getAxis('x');
  33131. var yAxis = this.getAxis('y');
  33132. out = out || [];
  33133. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33134. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33135. return out;
  33136. },
  33137. /**
  33138. * Get other axis
  33139. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33140. */
  33141. getOtherAxis: function (axis) {
  33142. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33143. },
  33144. /**
  33145. * Get rect area of cartesian.
  33146. * Area will have a contain function to determine if a point is in the coordinate system.
  33147. * @return {BoundingRect}
  33148. */
  33149. getArea: function () {
  33150. var xExtent = this.getAxis('x').getGlobalExtent();
  33151. var yExtent = this.getAxis('y').getGlobalExtent();
  33152. var x = Math.min(xExtent[0], xExtent[1]);
  33153. var y = Math.min(yExtent[0], yExtent[1]);
  33154. var width = Math.max(xExtent[0], xExtent[1]) - x;
  33155. var height = Math.max(yExtent[0], yExtent[1]) - y;
  33156. var rect = new BoundingRect(x, y, width, height);
  33157. return rect;
  33158. }
  33159. };
  33160. inherits(Cartesian2D, Cartesian);
  33161. /*
  33162. * Licensed to the Apache Software Foundation (ASF) under one
  33163. * or more contributor license agreements. See the NOTICE file
  33164. * distributed with this work for additional information
  33165. * regarding copyright ownership. The ASF licenses this file
  33166. * to you under the Apache License, Version 2.0 (the
  33167. * "License"); you may not use this file except in compliance
  33168. * with the License. You may obtain a copy of the License at
  33169. *
  33170. * http://www.apache.org/licenses/LICENSE-2.0
  33171. *
  33172. * Unless required by applicable law or agreed to in writing,
  33173. * software distributed under the License is distributed on an
  33174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33175. * KIND, either express or implied. See the License for the
  33176. * specific language governing permissions and limitations
  33177. * under the License.
  33178. */
  33179. var inner$6 = makeInner();
  33180. /**
  33181. * @param {module:echats/coord/Axis} axis
  33182. * @return {Object} {
  33183. * labels: [{
  33184. * formattedLabel: string,
  33185. * rawLabel: string,
  33186. * tickValue: number
  33187. * }, ...],
  33188. * labelCategoryInterval: number
  33189. * }
  33190. */
  33191. function createAxisLabels(axis) {
  33192. // Only ordinal scale support tick interval
  33193. return axis.type === 'category'
  33194. ? makeCategoryLabels(axis)
  33195. : makeRealNumberLabels(axis);
  33196. }
  33197. /**
  33198. * @param {module:echats/coord/Axis} axis
  33199. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  33200. * @return {Object} {
  33201. * ticks: Array.<number>
  33202. * tickCategoryInterval: number
  33203. * }
  33204. */
  33205. function createAxisTicks(axis, tickModel) {
  33206. // Only ordinal scale support tick interval
  33207. return axis.type === 'category'
  33208. ? makeCategoryTicks(axis, tickModel)
  33209. : {ticks: axis.scale.getTicks()};
  33210. }
  33211. function makeCategoryLabels(axis) {
  33212. var labelModel = axis.getLabelModel();
  33213. var result = makeCategoryLabelsActually(axis, labelModel);
  33214. return (!labelModel.get('show') || axis.scale.isBlank())
  33215. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  33216. : result;
  33217. }
  33218. function makeCategoryLabelsActually(axis, labelModel) {
  33219. var labelsCache = getListCache(axis, 'labels');
  33220. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  33221. var result = listCacheGet(labelsCache, optionLabelInterval);
  33222. if (result) {
  33223. return result;
  33224. }
  33225. var labels;
  33226. var numericLabelInterval;
  33227. if (isFunction$1(optionLabelInterval)) {
  33228. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  33229. }
  33230. else {
  33231. numericLabelInterval = optionLabelInterval === 'auto'
  33232. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  33233. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  33234. }
  33235. // Cache to avoid calling interval function repeatly.
  33236. return listCacheSet(labelsCache, optionLabelInterval, {
  33237. labels: labels, labelCategoryInterval: numericLabelInterval
  33238. });
  33239. }
  33240. function makeCategoryTicks(axis, tickModel) {
  33241. var ticksCache = getListCache(axis, 'ticks');
  33242. var optionTickInterval = getOptionCategoryInterval(tickModel);
  33243. var result = listCacheGet(ticksCache, optionTickInterval);
  33244. if (result) {
  33245. return result;
  33246. }
  33247. var ticks;
  33248. var tickCategoryInterval;
  33249. // Optimize for the case that large category data and no label displayed,
  33250. // we should not return all ticks.
  33251. if (!tickModel.get('show') || axis.scale.isBlank()) {
  33252. ticks = [];
  33253. }
  33254. if (isFunction$1(optionTickInterval)) {
  33255. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  33256. }
  33257. // Always use label interval by default despite label show. Consider this
  33258. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  33259. // labels. `splitLine` and `axisTick` should be consistent in this case.
  33260. else if (optionTickInterval === 'auto') {
  33261. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  33262. tickCategoryInterval = labelsResult.labelCategoryInterval;
  33263. ticks = map(labelsResult.labels, function (labelItem) {
  33264. return labelItem.tickValue;
  33265. });
  33266. }
  33267. else {
  33268. tickCategoryInterval = optionTickInterval;
  33269. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  33270. }
  33271. // Cache to avoid calling interval function repeatly.
  33272. return listCacheSet(ticksCache, optionTickInterval, {
  33273. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  33274. });
  33275. }
  33276. function makeRealNumberLabels(axis) {
  33277. var ticks = axis.scale.getTicks();
  33278. var labelFormatter = makeLabelFormatter(axis);
  33279. return {
  33280. labels: map(ticks, function (tickValue, idx) {
  33281. return {
  33282. formattedLabel: labelFormatter(tickValue, idx),
  33283. rawLabel: axis.scale.getLabel(tickValue),
  33284. tickValue: tickValue
  33285. };
  33286. })
  33287. };
  33288. }
  33289. // Large category data calculation is performence sensitive, and ticks and label
  33290. // probably be fetched by multiple times. So we cache the result.
  33291. // axis is created each time during a ec process, so we do not need to clear cache.
  33292. function getListCache(axis, prop) {
  33293. // Because key can be funciton, and cache size always be small, we use array cache.
  33294. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  33295. }
  33296. function listCacheGet(cache, key) {
  33297. for (var i = 0; i < cache.length; i++) {
  33298. if (cache[i].key === key) {
  33299. return cache[i].value;
  33300. }
  33301. }
  33302. }
  33303. function listCacheSet(cache, key, value) {
  33304. cache.push({key: key, value: value});
  33305. return value;
  33306. }
  33307. function makeAutoCategoryInterval(axis) {
  33308. var result = inner$6(axis).autoInterval;
  33309. return result != null
  33310. ? result
  33311. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  33312. }
  33313. /**
  33314. * Calculate interval for category axis ticks and labels.
  33315. * To get precise result, at least one of `getRotate` and `isHorizontal`
  33316. * should be implemented in axis.
  33317. */
  33318. function calculateCategoryInterval(axis) {
  33319. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  33320. var labelFormatter = makeLabelFormatter(axis);
  33321. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  33322. var ordinalScale = axis.scale;
  33323. var ordinalExtent = ordinalScale.getExtent();
  33324. // Providing this method is for optimization:
  33325. // avoid generating a long array by `getTicks`
  33326. // in large category data case.
  33327. var tickCount = ordinalScale.count();
  33328. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  33329. return 0;
  33330. }
  33331. var step = 1;
  33332. // Simple optimization. Empirical value: tick count should less than 40.
  33333. if (tickCount > 40) {
  33334. step = Math.max(1, Math.floor(tickCount / 40));
  33335. }
  33336. var tickValue = ordinalExtent[0];
  33337. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  33338. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  33339. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  33340. var maxW = 0;
  33341. var maxH = 0;
  33342. // Caution: Performance sensitive for large category data.
  33343. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  33344. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33345. var width = 0;
  33346. var height = 0;
  33347. // Not precise, do not consider align and vertical align
  33348. // and each distance from axis line yet.
  33349. var rect = getBoundingRect(
  33350. labelFormatter(tickValue), params.font, 'center', 'top'
  33351. );
  33352. // Magic number
  33353. width = rect.width * 1.3;
  33354. height = rect.height * 1.3;
  33355. // Min size, void long loop.
  33356. maxW = Math.max(maxW, width, 7);
  33357. maxH = Math.max(maxH, height, 7);
  33358. }
  33359. var dw = maxW / unitW;
  33360. var dh = maxH / unitH;
  33361. // 0/0 is NaN, 1/0 is Infinity.
  33362. isNaN(dw) && (dw = Infinity);
  33363. isNaN(dh) && (dh = Infinity);
  33364. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  33365. var cache = inner$6(axis.model);
  33366. var axisExtent = axis.getExtent();
  33367. var lastAutoInterval = cache.lastAutoInterval;
  33368. var lastTickCount = cache.lastTickCount;
  33369. // Use cache to keep interval stable while moving zoom window,
  33370. // otherwise the calculated interval might jitter when the zoom
  33371. // window size is close to the interval-changing size.
  33372. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  33373. // The jitter will cause that sometimes the displayed labels are
  33374. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  33375. if (lastAutoInterval != null
  33376. && lastTickCount != null
  33377. && Math.abs(lastAutoInterval - interval) <= 1
  33378. && Math.abs(lastTickCount - tickCount) <= 1
  33379. // Always choose the bigger one, otherwise the critical
  33380. // point is not the same when zooming in or zooming out.
  33381. && lastAutoInterval > interval
  33382. // If the axis change is caused by chart resize, the cache should not
  33383. // be used. Otherwise some hiden labels might not be shown again.
  33384. && cache.axisExtend0 === axisExtent[0]
  33385. && cache.axisExtend1 === axisExtent[1]
  33386. ) {
  33387. interval = lastAutoInterval;
  33388. }
  33389. // Only update cache if cache not used, otherwise the
  33390. // changing of interval is too insensitive.
  33391. else {
  33392. cache.lastTickCount = tickCount;
  33393. cache.lastAutoInterval = interval;
  33394. cache.axisExtend0 = axisExtent[0];
  33395. cache.axisExtend1 = axisExtent[1];
  33396. }
  33397. return interval;
  33398. }
  33399. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33400. var labelModel = axis.getLabelModel();
  33401. return {
  33402. axisRotate: axis.getRotate
  33403. ? axis.getRotate()
  33404. : (axis.isHorizontal && !axis.isHorizontal())
  33405. ? 90
  33406. : 0,
  33407. labelRotate: labelModel.get('rotate') || 0,
  33408. font: labelModel.getFont()
  33409. };
  33410. }
  33411. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33412. var labelFormatter = makeLabelFormatter(axis);
  33413. var ordinalScale = axis.scale;
  33414. var ordinalExtent = ordinalScale.getExtent();
  33415. var labelModel = axis.getLabelModel();
  33416. var result = [];
  33417. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33418. var step = Math.max((categoryInterval || 0) + 1, 1);
  33419. var startTick = ordinalExtent[0];
  33420. var tickCount = ordinalScale.count();
  33421. // Calculate start tick based on zero if possible to keep label consistent
  33422. // while zooming and moving while interval > 0. Otherwise the selection
  33423. // of displayable ticks and symbols probably keep changing.
  33424. // 3 is empirical value.
  33425. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33426. startTick = Math.round(Math.ceil(startTick / step) * step);
  33427. }
  33428. // (1) Only add min max label here but leave overlap checking
  33429. // to render stage, which also ensure the returned list
  33430. // suitable for splitLine and splitArea rendering.
  33431. // (2) Scales except category always contain min max label so
  33432. // do not need to perform this process.
  33433. var showAllLabel = shouldShowAllLabels(axis);
  33434. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33435. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33436. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33437. addItem(ordinalExtent[0]);
  33438. }
  33439. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33440. var tickValue = startTick;
  33441. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33442. addItem(tickValue);
  33443. }
  33444. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33445. addItem(ordinalExtent[1]);
  33446. }
  33447. function addItem(tVal) {
  33448. result.push(onlyTick
  33449. ? tVal
  33450. : {
  33451. formattedLabel: labelFormatter(tVal),
  33452. rawLabel: ordinalScale.getLabel(tVal),
  33453. tickValue: tVal
  33454. }
  33455. );
  33456. }
  33457. return result;
  33458. }
  33459. // When interval is function, the result `false` means ignore the tick.
  33460. // It is time consuming for large category data.
  33461. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33462. var ordinalScale = axis.scale;
  33463. var labelFormatter = makeLabelFormatter(axis);
  33464. var result = [];
  33465. each$1(ordinalScale.getTicks(), function (tickValue) {
  33466. var rawLabel = ordinalScale.getLabel(tickValue);
  33467. if (categoryInterval(tickValue, rawLabel)) {
  33468. result.push(onlyTick
  33469. ? tickValue
  33470. : {
  33471. formattedLabel: labelFormatter(tickValue),
  33472. rawLabel: rawLabel,
  33473. tickValue: tickValue
  33474. }
  33475. );
  33476. }
  33477. });
  33478. return result;
  33479. }
  33480. /*
  33481. * Licensed to the Apache Software Foundation (ASF) under one
  33482. * or more contributor license agreements. See the NOTICE file
  33483. * distributed with this work for additional information
  33484. * regarding copyright ownership. The ASF licenses this file
  33485. * to you under the Apache License, Version 2.0 (the
  33486. * "License"); you may not use this file except in compliance
  33487. * with the License. You may obtain a copy of the License at
  33488. *
  33489. * http://www.apache.org/licenses/LICENSE-2.0
  33490. *
  33491. * Unless required by applicable law or agreed to in writing,
  33492. * software distributed under the License is distributed on an
  33493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33494. * KIND, either express or implied. See the License for the
  33495. * specific language governing permissions and limitations
  33496. * under the License.
  33497. */
  33498. var NORMALIZED_EXTENT = [0, 1];
  33499. /**
  33500. * Base class of Axis.
  33501. * @constructor
  33502. */
  33503. var Axis = function (dim, scale, extent) {
  33504. /**
  33505. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  33506. * @type {string}
  33507. */
  33508. this.dim = dim;
  33509. /**
  33510. * Axis scale
  33511. * @type {module:echarts/coord/scale/*}
  33512. */
  33513. this.scale = scale;
  33514. /**
  33515. * @type {Array.<number>}
  33516. * @private
  33517. */
  33518. this._extent = extent || [0, 0];
  33519. /**
  33520. * @type {boolean}
  33521. */
  33522. this.inverse = false;
  33523. /**
  33524. * Usually true when axis has a ordinal scale
  33525. * @type {boolean}
  33526. */
  33527. this.onBand = false;
  33528. };
  33529. Axis.prototype = {
  33530. constructor: Axis,
  33531. /**
  33532. * If axis extent contain given coord
  33533. * @param {number} coord
  33534. * @return {boolean}
  33535. */
  33536. contain: function (coord) {
  33537. var extent = this._extent;
  33538. var min = Math.min(extent[0], extent[1]);
  33539. var max = Math.max(extent[0], extent[1]);
  33540. return coord >= min && coord <= max;
  33541. },
  33542. /**
  33543. * If axis extent contain given data
  33544. * @param {number} data
  33545. * @return {boolean}
  33546. */
  33547. containData: function (data) {
  33548. return this.scale.contain(data);
  33549. },
  33550. /**
  33551. * Get coord extent.
  33552. * @return {Array.<number>}
  33553. */
  33554. getExtent: function () {
  33555. return this._extent.slice();
  33556. },
  33557. /**
  33558. * Get precision used for formatting
  33559. * @param {Array.<number>} [dataExtent]
  33560. * @return {number}
  33561. */
  33562. getPixelPrecision: function (dataExtent) {
  33563. return getPixelPrecision(
  33564. dataExtent || this.scale.getExtent(),
  33565. this._extent
  33566. );
  33567. },
  33568. /**
  33569. * Set coord extent
  33570. * @param {number} start
  33571. * @param {number} end
  33572. */
  33573. setExtent: function (start, end) {
  33574. var extent = this._extent;
  33575. extent[0] = start;
  33576. extent[1] = end;
  33577. },
  33578. /**
  33579. * Convert data to coord. Data is the rank if it has an ordinal scale
  33580. * @param {number} data
  33581. * @param {boolean} clamp
  33582. * @return {number}
  33583. */
  33584. dataToCoord: function (data, clamp) {
  33585. var extent = this._extent;
  33586. var scale = this.scale;
  33587. data = scale.normalize(data);
  33588. if (this.onBand && scale.type === 'ordinal') {
  33589. extent = extent.slice();
  33590. fixExtentWithBands(extent, scale.count());
  33591. }
  33592. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33593. },
  33594. /**
  33595. * Convert coord to data. Data is the rank if it has an ordinal scale
  33596. * @param {number} coord
  33597. * @param {boolean} clamp
  33598. * @return {number}
  33599. */
  33600. coordToData: function (coord, clamp) {
  33601. var extent = this._extent;
  33602. var scale = this.scale;
  33603. if (this.onBand && scale.type === 'ordinal') {
  33604. extent = extent.slice();
  33605. fixExtentWithBands(extent, scale.count());
  33606. }
  33607. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33608. return this.scale.scale(t);
  33609. },
  33610. /**
  33611. * Convert pixel point to data in axis
  33612. * @param {Array.<number>} point
  33613. * @param {boolean} clamp
  33614. * @return {number} data
  33615. */
  33616. pointToData: function (point, clamp) {
  33617. // Should be implemented in derived class if necessary.
  33618. },
  33619. /**
  33620. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33621. * `axis.getTicksCoords` considers `onBand`, which is used by
  33622. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33623. * @param {Object} [opt]
  33624. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  33625. * @param {boolean} [opt.clamp] If `true`, the first and the last
  33626. * tick must be at the axis end points. Otherwise, clip ticks
  33627. * that outside the axis extent.
  33628. * @return {Array.<Object>} [{
  33629. * coord: ...,
  33630. * tickValue: ...
  33631. * }, ...]
  33632. */
  33633. getTicksCoords: function (opt) {
  33634. opt = opt || {};
  33635. var tickModel = opt.tickModel || this.getTickModel();
  33636. var result = createAxisTicks(this, tickModel);
  33637. var ticks = result.ticks;
  33638. var ticksCoords = map(ticks, function (tickValue) {
  33639. return {
  33640. coord: this.dataToCoord(tickValue),
  33641. tickValue: tickValue
  33642. };
  33643. }, this);
  33644. var alignWithLabel = tickModel.get('alignWithLabel');
  33645. fixOnBandTicksCoords(
  33646. this, ticksCoords, alignWithLabel, opt.clamp
  33647. );
  33648. return ticksCoords;
  33649. },
  33650. /**
  33651. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  33652. */
  33653. getMinorTicksCoords: function () {
  33654. if (this.scale.type === 'ordinal') {
  33655. // Category axis doesn't support minor ticks
  33656. return [];
  33657. }
  33658. var minorTickModel = this.model.getModel('minorTick');
  33659. var splitNumber = minorTickModel.get('splitNumber');
  33660. // Protection.
  33661. if (!(splitNumber > 0 && splitNumber < 100)) {
  33662. splitNumber = 5;
  33663. }
  33664. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33665. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33666. return map(minorTicksGroup, function (minorTick) {
  33667. return {
  33668. coord: this.dataToCoord(minorTick),
  33669. tickValue: minorTick
  33670. };
  33671. }, this);
  33672. }, this);
  33673. return minorTicksCoords;
  33674. },
  33675. /**
  33676. * @return {Array.<Object>} [{
  33677. * formattedLabel: string,
  33678. * rawLabel: axis.scale.getLabel(tickValue)
  33679. * tickValue: number
  33680. * }, ...]
  33681. */
  33682. getViewLabels: function () {
  33683. return createAxisLabels(this).labels;
  33684. },
  33685. /**
  33686. * @return {module:echarts/coord/model/Model}
  33687. */
  33688. getLabelModel: function () {
  33689. return this.model.getModel('axisLabel');
  33690. },
  33691. /**
  33692. * Notice here we only get the default tick model. For splitLine
  33693. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33694. * manually when calling `getTicksCoords`.
  33695. * In GL, this method may be overrided to:
  33696. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33697. * @return {module:echarts/coord/model/Model}
  33698. */
  33699. getTickModel: function () {
  33700. return this.model.getModel('axisTick');
  33701. },
  33702. /**
  33703. * Get width of band
  33704. * @return {number}
  33705. */
  33706. getBandWidth: function () {
  33707. var axisExtent = this._extent;
  33708. var dataExtent = this.scale.getExtent();
  33709. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  33710. // Fix #2728, avoid NaN when only one data.
  33711. len === 0 && (len = 1);
  33712. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33713. return Math.abs(size) / len;
  33714. },
  33715. /**
  33716. * @abstract
  33717. * @return {boolean} Is horizontal
  33718. */
  33719. isHorizontal: null,
  33720. /**
  33721. * @abstract
  33722. * @return {number} Get axis rotate, by degree.
  33723. */
  33724. getRotate: null,
  33725. /**
  33726. * Only be called in category axis.
  33727. * Can be overrided, consider other axes like in 3D.
  33728. * @return {number} Auto interval for cateogry axis tick and label
  33729. */
  33730. calculateCategoryInterval: function () {
  33731. return calculateCategoryInterval(this);
  33732. }
  33733. };
  33734. function fixExtentWithBands(extent, nTick) {
  33735. var size = extent[1] - extent[0];
  33736. var len = nTick;
  33737. var margin = size / len / 2;
  33738. extent[0] += margin;
  33739. extent[1] -= margin;
  33740. }
  33741. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33742. // |---1---|---2---|---3---|---4---|.
  33743. // So the displayed ticks and splitLine/splitArea should between
  33744. // each data item, otherwise cause misleading (e.g., split tow bars
  33745. // of a single data item when there are two bar series).
  33746. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33747. // splitLine/spliteArea should layout appropriately corresponding
  33748. // to displayed labels. (So we should not use `getBandWidth` in this
  33749. // case).
  33750. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33751. var ticksLen = ticksCoords.length;
  33752. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33753. return;
  33754. }
  33755. var axisExtent = axis.getExtent();
  33756. var last;
  33757. var diffSize;
  33758. if (ticksLen === 1) {
  33759. ticksCoords[0].coord = axisExtent[0];
  33760. last = ticksCoords[1] = {coord: axisExtent[0]};
  33761. }
  33762. else {
  33763. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33764. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33765. each$1(ticksCoords, function (ticksItem) {
  33766. ticksItem.coord -= shift / 2;
  33767. });
  33768. var dataExtent = axis.scale.getExtent();
  33769. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33770. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  33771. ticksCoords.push(last);
  33772. }
  33773. var inverse = axisExtent[0] > axisExtent[1];
  33774. // Handling clamp.
  33775. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33776. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  33777. }
  33778. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33779. ticksCoords.unshift({coord: axisExtent[0]});
  33780. }
  33781. if (littleThan(axisExtent[1], last.coord)) {
  33782. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  33783. }
  33784. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33785. ticksCoords.push({coord: axisExtent[1]});
  33786. }
  33787. function littleThan(a, b) {
  33788. // Avoid rounding error cause calculated tick coord different with extent.
  33789. // It may cause an extra unecessary tick added.
  33790. a = round$1(a);
  33791. b = round$1(b);
  33792. return inverse ? a > b : a < b;
  33793. }
  33794. }
  33795. /*
  33796. * Licensed to the Apache Software Foundation (ASF) under one
  33797. * or more contributor license agreements. See the NOTICE file
  33798. * distributed with this work for additional information
  33799. * regarding copyright ownership. The ASF licenses this file
  33800. * to you under the Apache License, Version 2.0 (the
  33801. * "License"); you may not use this file except in compliance
  33802. * with the License. You may obtain a copy of the License at
  33803. *
  33804. * http://www.apache.org/licenses/LICENSE-2.0
  33805. *
  33806. * Unless required by applicable law or agreed to in writing,
  33807. * software distributed under the License is distributed on an
  33808. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33809. * KIND, either express or implied. See the License for the
  33810. * specific language governing permissions and limitations
  33811. * under the License.
  33812. */
  33813. /**
  33814. * Extend axis 2d
  33815. * @constructor module:echarts/coord/cartesian/Axis2D
  33816. * @extends {module:echarts/coord/cartesian/Axis}
  33817. * @param {string} dim
  33818. * @param {*} scale
  33819. * @param {Array.<number>} coordExtent
  33820. * @param {string} axisType
  33821. * @param {string} position
  33822. */
  33823. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33824. Axis.call(this, dim, scale, coordExtent);
  33825. /**
  33826. * Axis type
  33827. * - 'category'
  33828. * - 'value'
  33829. * - 'time'
  33830. * - 'log'
  33831. * @type {string}
  33832. */
  33833. this.type = axisType || 'value';
  33834. /**
  33835. * Axis position
  33836. * - 'top'
  33837. * - 'bottom'
  33838. * - 'left'
  33839. * - 'right'
  33840. */
  33841. this.position = position || 'bottom';
  33842. };
  33843. Axis2D.prototype = {
  33844. constructor: Axis2D,
  33845. /**
  33846. * Index of axis, can be used as key
  33847. */
  33848. index: 0,
  33849. /**
  33850. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33851. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33852. * If not on zero of other axis, return null/undefined.
  33853. * If no axes, return an empty array.
  33854. */
  33855. getAxesOnZeroOf: null,
  33856. /**
  33857. * Axis model
  33858. * @param {module:echarts/coord/cartesian/AxisModel}
  33859. */
  33860. model: null,
  33861. isHorizontal: function () {
  33862. var position = this.position;
  33863. return position === 'top' || position === 'bottom';
  33864. },
  33865. /**
  33866. * Each item cooresponds to this.getExtent(), which
  33867. * means globalExtent[0] may greater than globalExtent[1],
  33868. * unless `asc` is input.
  33869. *
  33870. * @param {boolean} [asc]
  33871. * @return {Array.<number>}
  33872. */
  33873. getGlobalExtent: function (asc) {
  33874. var ret = this.getExtent();
  33875. ret[0] = this.toGlobalCoord(ret[0]);
  33876. ret[1] = this.toGlobalCoord(ret[1]);
  33877. asc && ret[0] > ret[1] && ret.reverse();
  33878. return ret;
  33879. },
  33880. getOtherAxis: function () {
  33881. this.grid.getOtherAxis();
  33882. },
  33883. /**
  33884. * @override
  33885. */
  33886. pointToData: function (point, clamp) {
  33887. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33888. },
  33889. /**
  33890. * Transform global coord to local coord,
  33891. * i.e. var localCoord = axis.toLocalCoord(80);
  33892. * designate by module:echarts/coord/cartesian/Grid.
  33893. * @type {Function}
  33894. */
  33895. toLocalCoord: null,
  33896. /**
  33897. * Transform global coord to local coord,
  33898. * i.e. var globalCoord = axis.toLocalCoord(40);
  33899. * designate by module:echarts/coord/cartesian/Grid.
  33900. * @type {Function}
  33901. */
  33902. toGlobalCoord: null
  33903. };
  33904. inherits(Axis2D, Axis);
  33905. /*
  33906. * Licensed to the Apache Software Foundation (ASF) under one
  33907. * or more contributor license agreements. See the NOTICE file
  33908. * distributed with this work for additional information
  33909. * regarding copyright ownership. The ASF licenses this file
  33910. * to you under the Apache License, Version 2.0 (the
  33911. * "License"); you may not use this file except in compliance
  33912. * with the License. You may obtain a copy of the License at
  33913. *
  33914. * http://www.apache.org/licenses/LICENSE-2.0
  33915. *
  33916. * Unless required by applicable law or agreed to in writing,
  33917. * software distributed under the License is distributed on an
  33918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33919. * KIND, either express or implied. See the License for the
  33920. * specific language governing permissions and limitations
  33921. * under the License.
  33922. */
  33923. var defaultOption = {
  33924. show: true,
  33925. zlevel: 0,
  33926. z: 0,
  33927. // Inverse the axis.
  33928. inverse: false,
  33929. // Axis name displayed.
  33930. name: '',
  33931. // 'start' | 'middle' | 'end'
  33932. nameLocation: 'end',
  33933. // By degree. By defualt auto rotate by nameLocation.
  33934. nameRotate: null,
  33935. nameTruncate: {
  33936. maxWidth: null,
  33937. ellipsis: '...',
  33938. placeholder: '.'
  33939. },
  33940. // Use global text style by default.
  33941. nameTextStyle: {},
  33942. // The gap between axisName and axisLine.
  33943. nameGap: 15,
  33944. // Default `false` to support tooltip.
  33945. silent: false,
  33946. // Default `false` to avoid legacy user event listener fail.
  33947. triggerEvent: false,
  33948. tooltip: {
  33949. show: false
  33950. },
  33951. axisPointer: {},
  33952. axisLine: {
  33953. show: true,
  33954. onZero: true,
  33955. onZeroAxisIndex: null,
  33956. lineStyle: {
  33957. color: '#333',
  33958. width: 1,
  33959. type: 'solid'
  33960. },
  33961. // The arrow at both ends the the axis.
  33962. symbol: ['none', 'none'],
  33963. symbolSize: [10, 15]
  33964. },
  33965. axisTick: {
  33966. show: true,
  33967. // Whether axisTick is inside the grid or outside the grid.
  33968. inside: false,
  33969. // The length of axisTick.
  33970. length: 5,
  33971. lineStyle: {
  33972. width: 1
  33973. }
  33974. },
  33975. axisLabel: {
  33976. show: true,
  33977. // Whether axisLabel is inside the grid or outside the grid.
  33978. inside: false,
  33979. rotate: 0,
  33980. // true | false | null/undefined (auto)
  33981. showMinLabel: null,
  33982. // true | false | null/undefined (auto)
  33983. showMaxLabel: null,
  33984. margin: 8,
  33985. // formatter: null,
  33986. fontSize: 12
  33987. },
  33988. splitLine: {
  33989. show: true,
  33990. lineStyle: {
  33991. color: ['#ccc'],
  33992. width: 1,
  33993. type: 'solid'
  33994. }
  33995. },
  33996. splitArea: {
  33997. show: false,
  33998. areaStyle: {
  33999. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  34000. }
  34001. }
  34002. };
  34003. var axisDefault = {};
  34004. axisDefault.categoryAxis = merge({
  34005. // The gap at both ends of the axis. For categoryAxis, boolean.
  34006. boundaryGap: true,
  34007. // Set false to faster category collection.
  34008. // Only usefull in the case like: category is
  34009. // ['2012-01-01', '2012-01-02', ...], where the input
  34010. // data has been ensured not duplicate and is large data.
  34011. // null means "auto":
  34012. // if axis.data provided, do not deduplication,
  34013. // else do deduplication.
  34014. deduplication: null,
  34015. // splitArea: {
  34016. // show: false
  34017. // },
  34018. splitLine: {
  34019. show: false
  34020. },
  34021. axisTick: {
  34022. // If tick is align with label when boundaryGap is true
  34023. alignWithLabel: false,
  34024. interval: 'auto'
  34025. },
  34026. axisLabel: {
  34027. interval: 'auto'
  34028. }
  34029. }, defaultOption);
  34030. axisDefault.valueAxis = merge({
  34031. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  34032. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  34033. boundaryGap: [0, 0],
  34034. // TODO
  34035. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  34036. // Min value of the axis. can be:
  34037. // + a number
  34038. // + 'dataMin': use the min value in data.
  34039. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  34040. // min: null,
  34041. // Max value of the axis. can be:
  34042. // + a number
  34043. // + 'dataMax': use the max value in data.
  34044. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  34045. // max: null,
  34046. // Readonly prop, specifies start value of the range when using data zoom.
  34047. // rangeStart: null
  34048. // Readonly prop, specifies end value of the range when using data zoom.
  34049. // rangeEnd: null
  34050. // Optional value can be:
  34051. // + `false`: always include value 0.
  34052. // + `true`: the extent do not consider value 0.
  34053. // scale: false,
  34054. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  34055. splitNumber: 5,
  34056. // Interval specifies the span of the ticks is mandatorily.
  34057. // interval: null
  34058. // Specify min interval when auto calculate tick interval.
  34059. // minInterval: null
  34060. // Specify max interval when auto calculate tick interval.
  34061. // maxInterval: null
  34062. minorTick: {
  34063. // Minor tick, not available for cateogry axis.
  34064. show: false,
  34065. // Split number of minor ticks. The value should be in range of (0, 100)
  34066. splitNumber: 5,
  34067. // Lenght of minor tick
  34068. length: 3,
  34069. // Same inside with axisTick
  34070. // Line style
  34071. lineStyle: {
  34072. // Default to be same with axisTick
  34073. }
  34074. },
  34075. minorSplitLine: {
  34076. show: false,
  34077. lineStyle: {
  34078. color: '#eee',
  34079. width: 1
  34080. }
  34081. }
  34082. }, defaultOption);
  34083. axisDefault.timeAxis = defaults({
  34084. scale: true,
  34085. min: 'dataMin',
  34086. max: 'dataMax'
  34087. }, axisDefault.valueAxis);
  34088. axisDefault.logAxis = defaults({
  34089. scale: true,
  34090. logBase: 10
  34091. }, axisDefault.valueAxis);
  34092. /*
  34093. * Licensed to the Apache Software Foundation (ASF) under one
  34094. * or more contributor license agreements. See the NOTICE file
  34095. * distributed with this work for additional information
  34096. * regarding copyright ownership. The ASF licenses this file
  34097. * to you under the Apache License, Version 2.0 (the
  34098. * "License"); you may not use this file except in compliance
  34099. * with the License. You may obtain a copy of the License at
  34100. *
  34101. * http://www.apache.org/licenses/LICENSE-2.0
  34102. *
  34103. * Unless required by applicable law or agreed to in writing,
  34104. * software distributed under the License is distributed on an
  34105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34106. * KIND, either express or implied. See the License for the
  34107. * specific language governing permissions and limitations
  34108. * under the License.
  34109. */
  34110. // FIXME axisType is fixed ?
  34111. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  34112. /**
  34113. * Generate sub axis model class
  34114. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  34115. * @param {module:echarts/model/Component} BaseAxisModelClass
  34116. * @param {Function} axisTypeDefaulter
  34117. * @param {Object} [extraDefaultOption]
  34118. */
  34119. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  34120. each$1(AXIS_TYPES, function (axisType) {
  34121. BaseAxisModelClass.extend({
  34122. /**
  34123. * @readOnly
  34124. */
  34125. type: axisName + 'Axis.' + axisType,
  34126. mergeDefaultAndTheme: function (option, ecModel) {
  34127. var layoutMode = this.layoutMode;
  34128. var inputPositionParams = layoutMode
  34129. ? getLayoutParams(option) : {};
  34130. var themeModel = ecModel.getTheme();
  34131. merge(option, themeModel.get(axisType + 'Axis'));
  34132. merge(option, this.getDefaultOption());
  34133. option.type = axisTypeDefaulter(axisName, option);
  34134. if (layoutMode) {
  34135. mergeLayoutParam(option, inputPositionParams, layoutMode);
  34136. }
  34137. },
  34138. /**
  34139. * @override
  34140. */
  34141. optionUpdated: function () {
  34142. var thisOption = this.option;
  34143. if (thisOption.type === 'category') {
  34144. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  34145. }
  34146. },
  34147. /**
  34148. * Should not be called before all of 'getInitailData' finished.
  34149. * Because categories are collected during initializing data.
  34150. */
  34151. getCategories: function (rawData) {
  34152. var option = this.option;
  34153. // FIXME
  34154. // warning if called before all of 'getInitailData' finished.
  34155. if (option.type === 'category') {
  34156. if (rawData) {
  34157. return option.data;
  34158. }
  34159. return this.__ordinalMeta.categories;
  34160. }
  34161. },
  34162. getOrdinalMeta: function () {
  34163. return this.__ordinalMeta;
  34164. },
  34165. defaultOption: mergeAll(
  34166. [
  34167. {},
  34168. axisDefault[axisType + 'Axis'],
  34169. extraDefaultOption
  34170. ],
  34171. true
  34172. )
  34173. });
  34174. });
  34175. ComponentModel.registerSubTypeDefaulter(
  34176. axisName + 'Axis',
  34177. curry(axisTypeDefaulter, axisName)
  34178. );
  34179. };
  34180. /*
  34181. * Licensed to the Apache Software Foundation (ASF) under one
  34182. * or more contributor license agreements. See the NOTICE file
  34183. * distributed with this work for additional information
  34184. * regarding copyright ownership. The ASF licenses this file
  34185. * to you under the Apache License, Version 2.0 (the
  34186. * "License"); you may not use this file except in compliance
  34187. * with the License. You may obtain a copy of the License at
  34188. *
  34189. * http://www.apache.org/licenses/LICENSE-2.0
  34190. *
  34191. * Unless required by applicable law or agreed to in writing,
  34192. * software distributed under the License is distributed on an
  34193. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34194. * KIND, either express or implied. See the License for the
  34195. * specific language governing permissions and limitations
  34196. * under the License.
  34197. */
  34198. // import * as axisHelper from './axisHelper';
  34199. var axisModelCommonMixin = {
  34200. /**
  34201. * @param {boolean} origin
  34202. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  34203. */
  34204. getMin: function (origin) {
  34205. var option = this.option;
  34206. var min = (!origin && option.rangeStart != null)
  34207. ? option.rangeStart : option.min;
  34208. if (this.axis
  34209. && min != null
  34210. && min !== 'dataMin'
  34211. && typeof min !== 'function'
  34212. && !eqNaN(min)
  34213. ) {
  34214. min = this.axis.scale.parse(min);
  34215. }
  34216. return min;
  34217. },
  34218. /**
  34219. * @param {boolean} origin
  34220. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  34221. */
  34222. getMax: function (origin) {
  34223. var option = this.option;
  34224. var max = (!origin && option.rangeEnd != null)
  34225. ? option.rangeEnd : option.max;
  34226. if (this.axis
  34227. && max != null
  34228. && max !== 'dataMax'
  34229. && typeof max !== 'function'
  34230. && !eqNaN(max)
  34231. ) {
  34232. max = this.axis.scale.parse(max);
  34233. }
  34234. return max;
  34235. },
  34236. /**
  34237. * @return {boolean}
  34238. */
  34239. getNeedCrossZero: function () {
  34240. var option = this.option;
  34241. return (option.rangeStart != null || option.rangeEnd != null)
  34242. ? false : !option.scale;
  34243. },
  34244. /**
  34245. * Should be implemented by each axis model if necessary.
  34246. * @return {module:echarts/model/Component} coordinate system model
  34247. */
  34248. getCoordSysModel: noop,
  34249. /**
  34250. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  34251. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  34252. */
  34253. setRange: function (rangeStart, rangeEnd) {
  34254. this.option.rangeStart = rangeStart;
  34255. this.option.rangeEnd = rangeEnd;
  34256. },
  34257. /**
  34258. * Reset range
  34259. */
  34260. resetRange: function () {
  34261. // rangeStart and rangeEnd is readonly.
  34262. this.option.rangeStart = this.option.rangeEnd = null;
  34263. }
  34264. };
  34265. /*
  34266. * Licensed to the Apache Software Foundation (ASF) under one
  34267. * or more contributor license agreements. See the NOTICE file
  34268. * distributed with this work for additional information
  34269. * regarding copyright ownership. The ASF licenses this file
  34270. * to you under the Apache License, Version 2.0 (the
  34271. * "License"); you may not use this file except in compliance
  34272. * with the License. You may obtain a copy of the License at
  34273. *
  34274. * http://www.apache.org/licenses/LICENSE-2.0
  34275. *
  34276. * Unless required by applicable law or agreed to in writing,
  34277. * software distributed under the License is distributed on an
  34278. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34279. * KIND, either express or implied. See the License for the
  34280. * specific language governing permissions and limitations
  34281. * under the License.
  34282. */
  34283. var AxisModel = ComponentModel.extend({
  34284. type: 'cartesian2dAxis',
  34285. /**
  34286. * @type {module:echarts/coord/cartesian/Axis2D}
  34287. */
  34288. axis: null,
  34289. /**
  34290. * @override
  34291. */
  34292. init: function () {
  34293. AxisModel.superApply(this, 'init', arguments);
  34294. this.resetRange();
  34295. },
  34296. /**
  34297. * @override
  34298. */
  34299. mergeOption: function () {
  34300. AxisModel.superApply(this, 'mergeOption', arguments);
  34301. this.resetRange();
  34302. },
  34303. /**
  34304. * @override
  34305. */
  34306. restoreData: function () {
  34307. AxisModel.superApply(this, 'restoreData', arguments);
  34308. this.resetRange();
  34309. },
  34310. /**
  34311. * @override
  34312. * @return {module:echarts/model/Component}
  34313. */
  34314. getCoordSysModel: function () {
  34315. return this.ecModel.queryComponents({
  34316. mainType: 'grid',
  34317. index: this.option.gridIndex,
  34318. id: this.option.gridId
  34319. })[0];
  34320. }
  34321. });
  34322. function getAxisType(axisDim, option) {
  34323. // Default axis with data is category axis
  34324. return option.type || (option.data ? 'category' : 'value');
  34325. }
  34326. merge(AxisModel.prototype, axisModelCommonMixin);
  34327. var extraOption = {
  34328. // gridIndex: 0,
  34329. // gridId: '',
  34330. // Offset is for multiple axis on the same position
  34331. offset: 0
  34332. };
  34333. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  34334. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  34335. /*
  34336. * Licensed to the Apache Software Foundation (ASF) under one
  34337. * or more contributor license agreements. See the NOTICE file
  34338. * distributed with this work for additional information
  34339. * regarding copyright ownership. The ASF licenses this file
  34340. * to you under the Apache License, Version 2.0 (the
  34341. * "License"); you may not use this file except in compliance
  34342. * with the License. You may obtain a copy of the License at
  34343. *
  34344. * http://www.apache.org/licenses/LICENSE-2.0
  34345. *
  34346. * Unless required by applicable law or agreed to in writing,
  34347. * software distributed under the License is distributed on an
  34348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34349. * KIND, either express or implied. See the License for the
  34350. * specific language governing permissions and limitations
  34351. * under the License.
  34352. */
  34353. // Grid 是在有直角坐标系的时候必须要存在的
  34354. // 所以这里也要被 Cartesian2D 依赖
  34355. ComponentModel.extend({
  34356. type: 'grid',
  34357. dependencies: ['xAxis', 'yAxis'],
  34358. layoutMode: 'box',
  34359. /**
  34360. * @type {module:echarts/coord/cartesian/Grid}
  34361. */
  34362. coordinateSystem: null,
  34363. defaultOption: {
  34364. show: false,
  34365. zlevel: 0,
  34366. z: 0,
  34367. left: '10%',
  34368. top: 60,
  34369. right: '10%',
  34370. bottom: 60,
  34371. // If grid size contain label
  34372. containLabel: false,
  34373. // width: {totalWidth} - left - right,
  34374. // height: {totalHeight} - top - bottom,
  34375. backgroundColor: 'rgba(0,0,0,0)',
  34376. borderWidth: 1,
  34377. borderColor: '#ccc'
  34378. }
  34379. });
  34380. /*
  34381. * Licensed to the Apache Software Foundation (ASF) under one
  34382. * or more contributor license agreements. See the NOTICE file
  34383. * distributed with this work for additional information
  34384. * regarding copyright ownership. The ASF licenses this file
  34385. * to you under the Apache License, Version 2.0 (the
  34386. * "License"); you may not use this file except in compliance
  34387. * with the License. You may obtain a copy of the License at
  34388. *
  34389. * http://www.apache.org/licenses/LICENSE-2.0
  34390. *
  34391. * Unless required by applicable law or agreed to in writing,
  34392. * software distributed under the License is distributed on an
  34393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34394. * KIND, either express or implied. See the License for the
  34395. * specific language governing permissions and limitations
  34396. * under the License.
  34397. */
  34398. /**
  34399. * Grid is a region which contains at most 4 cartesian systems
  34400. *
  34401. * TODO Default cartesian
  34402. */
  34403. // Depends on GridModel, AxisModel, which performs preprocess.
  34404. /**
  34405. * Check if the axis is used in the specified grid
  34406. * @inner
  34407. */
  34408. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  34409. return axisModel.getCoordSysModel() === gridModel;
  34410. }
  34411. function Grid(gridModel, ecModel, api) {
  34412. /**
  34413. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  34414. * @private
  34415. */
  34416. this._coordsMap = {};
  34417. /**
  34418. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  34419. * @private
  34420. */
  34421. this._coordsList = [];
  34422. /**
  34423. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  34424. * @private
  34425. */
  34426. this._axesMap = {};
  34427. /**
  34428. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  34429. * @private
  34430. */
  34431. this._axesList = [];
  34432. this._initCartesian(gridModel, ecModel, api);
  34433. this.model = gridModel;
  34434. }
  34435. var gridProto = Grid.prototype;
  34436. gridProto.type = 'grid';
  34437. gridProto.axisPointerEnabled = true;
  34438. gridProto.getRect = function () {
  34439. return this._rect;
  34440. };
  34441. gridProto.update = function (ecModel, api) {
  34442. var axesMap = this._axesMap;
  34443. this._updateScale(ecModel, this.model);
  34444. each$1(axesMap.x, function (xAxis) {
  34445. niceScaleExtent(xAxis.scale, xAxis.model);
  34446. });
  34447. each$1(axesMap.y, function (yAxis) {
  34448. niceScaleExtent(yAxis.scale, yAxis.model);
  34449. });
  34450. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  34451. var onZeroRecords = {};
  34452. each$1(axesMap.x, function (xAxis) {
  34453. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  34454. });
  34455. each$1(axesMap.y, function (yAxis) {
  34456. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  34457. });
  34458. // Resize again if containLabel is enabled
  34459. // FIXME It may cause getting wrong grid size in data processing stage
  34460. this.resize(this.model, api);
  34461. };
  34462. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  34463. axis.getAxesOnZeroOf = function () {
  34464. // TODO: onZero of multiple axes.
  34465. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  34466. };
  34467. // onZero can not be enabled in these two situations:
  34468. // 1. When any other axis is a category axis.
  34469. // 2. When no axis is cross 0 point.
  34470. var otherAxes = axesMap[otherAxisDim];
  34471. var otherAxisOnZeroOf;
  34472. var axisModel = axis.model;
  34473. var onZero = axisModel.get('axisLine.onZero');
  34474. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  34475. if (!onZero) {
  34476. return;
  34477. }
  34478. // If target axis is specified.
  34479. if (onZeroAxisIndex != null) {
  34480. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  34481. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  34482. }
  34483. }
  34484. else {
  34485. // Find the first available other axis.
  34486. for (var idx in otherAxes) {
  34487. if (otherAxes.hasOwnProperty(idx)
  34488. && canOnZeroToAxis(otherAxes[idx])
  34489. // Consider that two Y axes on one value axis,
  34490. // if both onZero, the two Y axes overlap.
  34491. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  34492. ) {
  34493. otherAxisOnZeroOf = otherAxes[idx];
  34494. break;
  34495. }
  34496. }
  34497. }
  34498. if (otherAxisOnZeroOf) {
  34499. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  34500. }
  34501. function getOnZeroRecordKey(axis) {
  34502. return axis.dim + '_' + axis.index;
  34503. }
  34504. }
  34505. function canOnZeroToAxis(axis) {
  34506. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  34507. }
  34508. /**
  34509. * Resize the grid
  34510. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34511. * @param {module:echarts/ExtensionAPI} api
  34512. */
  34513. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  34514. var gridRect = getLayoutRect(
  34515. gridModel.getBoxLayoutParams(), {
  34516. width: api.getWidth(),
  34517. height: api.getHeight()
  34518. });
  34519. this._rect = gridRect;
  34520. var axesList = this._axesList;
  34521. adjustAxes();
  34522. // Minus label size
  34523. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  34524. each$1(axesList, function (axis) {
  34525. if (!axis.model.get('axisLabel.inside')) {
  34526. var labelUnionRect = estimateLabelUnionRect(axis);
  34527. if (labelUnionRect) {
  34528. var dim = axis.isHorizontal() ? 'height' : 'width';
  34529. var margin = axis.model.get('axisLabel.margin');
  34530. gridRect[dim] -= labelUnionRect[dim] + margin;
  34531. if (axis.position === 'top') {
  34532. gridRect.y += labelUnionRect.height + margin;
  34533. }
  34534. else if (axis.position === 'left') {
  34535. gridRect.x += labelUnionRect.width + margin;
  34536. }
  34537. }
  34538. }
  34539. });
  34540. adjustAxes();
  34541. }
  34542. function adjustAxes() {
  34543. each$1(axesList, function (axis) {
  34544. var isHorizontal = axis.isHorizontal();
  34545. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  34546. var idx = axis.inverse ? 1 : 0;
  34547. axis.setExtent(extent[idx], extent[1 - idx]);
  34548. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34549. });
  34550. }
  34551. };
  34552. /**
  34553. * @param {string} axisType
  34554. * @param {number} [axisIndex]
  34555. */
  34556. gridProto.getAxis = function (axisType, axisIndex) {
  34557. var axesMapOnDim = this._axesMap[axisType];
  34558. if (axesMapOnDim != null) {
  34559. if (axisIndex == null) {
  34560. // Find first axis
  34561. for (var name in axesMapOnDim) {
  34562. if (axesMapOnDim.hasOwnProperty(name)) {
  34563. return axesMapOnDim[name];
  34564. }
  34565. }
  34566. }
  34567. return axesMapOnDim[axisIndex];
  34568. }
  34569. };
  34570. /**
  34571. * @return {Array.<module:echarts/coord/Axis>}
  34572. */
  34573. gridProto.getAxes = function () {
  34574. return this._axesList.slice();
  34575. };
  34576. /**
  34577. * Usage:
  34578. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34579. * grid.getCartesian(xAxisIndex);
  34580. * grid.getCartesian(null, yAxisIndex);
  34581. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34582. *
  34583. * @param {number|Object} [xAxisIndex]
  34584. * @param {number} [yAxisIndex]
  34585. */
  34586. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34587. if (xAxisIndex != null && yAxisIndex != null) {
  34588. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34589. return this._coordsMap[key];
  34590. }
  34591. if (isObject$1(xAxisIndex)) {
  34592. yAxisIndex = xAxisIndex.yAxisIndex;
  34593. xAxisIndex = xAxisIndex.xAxisIndex;
  34594. }
  34595. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34596. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34597. if (coordList[i].getAxis('x').index === xAxisIndex
  34598. || coordList[i].getAxis('y').index === yAxisIndex
  34599. ) {
  34600. return coordList[i];
  34601. }
  34602. }
  34603. };
  34604. gridProto.getCartesians = function () {
  34605. return this._coordsList.slice();
  34606. };
  34607. /**
  34608. * @implements
  34609. * see {module:echarts/CoodinateSystem}
  34610. */
  34611. gridProto.convertToPixel = function (ecModel, finder, value) {
  34612. var target = this._findConvertTarget(ecModel, finder);
  34613. return target.cartesian
  34614. ? target.cartesian.dataToPoint(value)
  34615. : target.axis
  34616. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34617. : null;
  34618. };
  34619. /**
  34620. * @implements
  34621. * see {module:echarts/CoodinateSystem}
  34622. */
  34623. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34624. var target = this._findConvertTarget(ecModel, finder);
  34625. return target.cartesian
  34626. ? target.cartesian.pointToData(value)
  34627. : target.axis
  34628. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34629. : null;
  34630. };
  34631. /**
  34632. * @inner
  34633. */
  34634. gridProto._findConvertTarget = function (ecModel, finder) {
  34635. var seriesModel = finder.seriesModel;
  34636. var xAxisModel = finder.xAxisModel
  34637. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34638. var yAxisModel = finder.yAxisModel
  34639. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34640. var gridModel = finder.gridModel;
  34641. var coordsList = this._coordsList;
  34642. var cartesian;
  34643. var axis;
  34644. if (seriesModel) {
  34645. cartesian = seriesModel.coordinateSystem;
  34646. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34647. }
  34648. else if (xAxisModel && yAxisModel) {
  34649. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34650. }
  34651. else if (xAxisModel) {
  34652. axis = this.getAxis('x', xAxisModel.componentIndex);
  34653. }
  34654. else if (yAxisModel) {
  34655. axis = this.getAxis('y', yAxisModel.componentIndex);
  34656. }
  34657. // Lowest priority.
  34658. else if (gridModel) {
  34659. var grid = gridModel.coordinateSystem;
  34660. if (grid === this) {
  34661. cartesian = this._coordsList[0];
  34662. }
  34663. }
  34664. return {cartesian: cartesian, axis: axis};
  34665. };
  34666. /**
  34667. * @implements
  34668. * see {module:echarts/CoodinateSystem}
  34669. */
  34670. gridProto.containPoint = function (point) {
  34671. var coord = this._coordsList[0];
  34672. if (coord) {
  34673. return coord.containPoint(point);
  34674. }
  34675. };
  34676. /**
  34677. * Initialize cartesian coordinate systems
  34678. * @private
  34679. */
  34680. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34681. var axisPositionUsed = {
  34682. left: false,
  34683. right: false,
  34684. top: false,
  34685. bottom: false
  34686. };
  34687. var axesMap = {
  34688. x: {},
  34689. y: {}
  34690. };
  34691. var axesCount = {
  34692. x: 0,
  34693. y: 0
  34694. };
  34695. /// Create axis
  34696. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34697. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34698. if (!axesCount.x || !axesCount.y) {
  34699. // Roll back when there no either x or y axis
  34700. this._axesMap = {};
  34701. this._axesList = [];
  34702. return;
  34703. }
  34704. this._axesMap = axesMap;
  34705. /// Create cartesian2d
  34706. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34707. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34708. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34709. var cartesian = new Cartesian2D(key);
  34710. cartesian.grid = this;
  34711. cartesian.model = gridModel;
  34712. this._coordsMap[key] = cartesian;
  34713. this._coordsList.push(cartesian);
  34714. cartesian.addAxis(xAxis);
  34715. cartesian.addAxis(yAxis);
  34716. }, this);
  34717. }, this);
  34718. function createAxisCreator(axisType) {
  34719. return function (axisModel, idx) {
  34720. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34721. return;
  34722. }
  34723. var axisPosition = axisModel.get('position');
  34724. if (axisType === 'x') {
  34725. // Fix position
  34726. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34727. // Default bottom of X
  34728. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  34729. }
  34730. }
  34731. else {
  34732. // Fix position
  34733. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34734. // Default left of Y
  34735. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  34736. }
  34737. }
  34738. axisPositionUsed[axisPosition] = true;
  34739. var axis = new Axis2D(
  34740. axisType, createScaleByModel(axisModel),
  34741. [0, 0],
  34742. axisModel.get('type'),
  34743. axisPosition
  34744. );
  34745. var isCategory = axis.type === 'category';
  34746. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34747. axis.inverse = axisModel.get('inverse');
  34748. // Inject axis into axisModel
  34749. axisModel.axis = axis;
  34750. // Inject axisModel into axis
  34751. axis.model = axisModel;
  34752. // Inject grid info axis
  34753. axis.grid = this;
  34754. // Index of axis, can be used as key
  34755. axis.index = idx;
  34756. this._axesList.push(axis);
  34757. axesMap[axisType][idx] = axis;
  34758. axesCount[axisType]++;
  34759. };
  34760. }
  34761. };
  34762. /**
  34763. * Update cartesian properties from series
  34764. * @param {module:echarts/model/Option} option
  34765. * @private
  34766. */
  34767. gridProto._updateScale = function (ecModel, gridModel) {
  34768. // Reset scale
  34769. each$1(this._axesList, function (axis) {
  34770. axis.scale.setExtent(Infinity, -Infinity);
  34771. });
  34772. ecModel.eachSeries(function (seriesModel) {
  34773. if (isCartesian2D(seriesModel)) {
  34774. var axesModels = findAxesModels(seriesModel, ecModel);
  34775. var xAxisModel = axesModels[0];
  34776. var yAxisModel = axesModels[1];
  34777. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34778. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34779. ) {
  34780. return;
  34781. }
  34782. var cartesian = this.getCartesian(
  34783. xAxisModel.componentIndex, yAxisModel.componentIndex
  34784. );
  34785. var data = seriesModel.getData();
  34786. var xAxis = cartesian.getAxis('x');
  34787. var yAxis = cartesian.getAxis('y');
  34788. if (data.type === 'list') {
  34789. unionExtent(data, xAxis, seriesModel);
  34790. unionExtent(data, yAxis, seriesModel);
  34791. }
  34792. }
  34793. }, this);
  34794. function unionExtent(data, axis, seriesModel) {
  34795. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34796. axis.scale.unionExtentFromData(
  34797. // For example, the extent of the orginal dimension
  34798. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34799. // is [7, 9], the final extent should not include [0.1, 0.5].
  34800. data, getStackedDimension(data, dim)
  34801. );
  34802. });
  34803. }
  34804. };
  34805. /**
  34806. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34807. * @return {Object} {baseAxes: [], otherAxes: []}
  34808. */
  34809. gridProto.getTooltipAxes = function (dim) {
  34810. var baseAxes = [];
  34811. var otherAxes = [];
  34812. each$1(this.getCartesians(), function (cartesian) {
  34813. var baseAxis = (dim != null && dim !== 'auto')
  34814. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34815. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34816. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34817. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34818. });
  34819. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34820. };
  34821. /**
  34822. * @inner
  34823. */
  34824. function updateAxisTransform(axis, coordBase) {
  34825. var axisExtent = axis.getExtent();
  34826. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34827. // Fast transform
  34828. axis.toGlobalCoord = axis.dim === 'x'
  34829. ? function (coord) {
  34830. return coord + coordBase;
  34831. }
  34832. : function (coord) {
  34833. return axisExtentSum - coord + coordBase;
  34834. };
  34835. axis.toLocalCoord = axis.dim === 'x'
  34836. ? function (coord) {
  34837. return coord - coordBase;
  34838. }
  34839. : function (coord) {
  34840. return axisExtentSum - coord + coordBase;
  34841. };
  34842. }
  34843. var axesTypes = ['xAxis', 'yAxis'];
  34844. /**
  34845. * @inner
  34846. */
  34847. function findAxesModels(seriesModel, ecModel) {
  34848. return map(axesTypes, function (axisType) {
  34849. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34850. if (__DEV__) {
  34851. if (!axisModel) {
  34852. throw new Error(axisType + ' "' + retrieve(
  34853. seriesModel.get(axisType + 'Index'),
  34854. seriesModel.get(axisType + 'Id'),
  34855. 0
  34856. ) + '" not found');
  34857. }
  34858. }
  34859. return axisModel;
  34860. });
  34861. }
  34862. /**
  34863. * @inner
  34864. */
  34865. function isCartesian2D(seriesModel) {
  34866. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34867. }
  34868. Grid.create = function (ecModel, api) {
  34869. var grids = [];
  34870. ecModel.eachComponent('grid', function (gridModel, idx) {
  34871. var grid = new Grid(gridModel, ecModel, api);
  34872. grid.name = 'grid_' + idx;
  34873. // dataSampling requires axis extent, so resize
  34874. // should be performed in create stage.
  34875. grid.resize(gridModel, api, true);
  34876. gridModel.coordinateSystem = grid;
  34877. grids.push(grid);
  34878. });
  34879. // Inject the coordinateSystems into seriesModel
  34880. ecModel.eachSeries(function (seriesModel) {
  34881. if (!isCartesian2D(seriesModel)) {
  34882. return;
  34883. }
  34884. var axesModels = findAxesModels(seriesModel, ecModel);
  34885. var xAxisModel = axesModels[0];
  34886. var yAxisModel = axesModels[1];
  34887. var gridModel = xAxisModel.getCoordSysModel();
  34888. if (__DEV__) {
  34889. if (!gridModel) {
  34890. throw new Error(
  34891. 'Grid "' + retrieve(
  34892. xAxisModel.get('gridIndex'),
  34893. xAxisModel.get('gridId'),
  34894. 0
  34895. ) + '" not found'
  34896. );
  34897. }
  34898. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34899. throw new Error('xAxis and yAxis must use the same grid');
  34900. }
  34901. }
  34902. var grid = gridModel.coordinateSystem;
  34903. seriesModel.coordinateSystem = grid.getCartesian(
  34904. xAxisModel.componentIndex, yAxisModel.componentIndex
  34905. );
  34906. });
  34907. return grids;
  34908. };
  34909. // For deciding which dimensions to use when creating list data
  34910. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34911. CoordinateSystemManager.register('cartesian2d', Grid);
  34912. /*
  34913. * Licensed to the Apache Software Foundation (ASF) under one
  34914. * or more contributor license agreements. See the NOTICE file
  34915. * distributed with this work for additional information
  34916. * regarding copyright ownership. The ASF licenses this file
  34917. * to you under the Apache License, Version 2.0 (the
  34918. * "License"); you may not use this file except in compliance
  34919. * with the License. You may obtain a copy of the License at
  34920. *
  34921. * http://www.apache.org/licenses/LICENSE-2.0
  34922. *
  34923. * Unless required by applicable law or agreed to in writing,
  34924. * software distributed under the License is distributed on an
  34925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34926. * KIND, either express or implied. See the License for the
  34927. * specific language governing permissions and limitations
  34928. * under the License.
  34929. */
  34930. var PI$2 = Math.PI;
  34931. /**
  34932. * A final axis is translated and rotated from a "standard axis".
  34933. * So opt.position and opt.rotation is required.
  34934. *
  34935. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34936. * for example: (0, 0) ------------> (0, 50)
  34937. *
  34938. * nameDirection or tickDirection or labelDirection is 1 means tick
  34939. * or label is below the standard axis, whereas is -1 means above
  34940. * the standard axis. labelOffset means offset between label and axis,
  34941. * which is useful when 'onZero', where axisLabel is in the grid and
  34942. * label in outside grid.
  34943. *
  34944. * Tips: like always,
  34945. * positive rotation represents anticlockwise, and negative rotation
  34946. * represents clockwise.
  34947. * The direction of position coordinate is the same as the direction
  34948. * of screen coordinate.
  34949. *
  34950. * Do not need to consider axis 'inverse', which is auto processed by
  34951. * axis extent.
  34952. *
  34953. * @param {module:zrender/container/Group} group
  34954. * @param {Object} axisModel
  34955. * @param {Object} opt Standard axis parameters.
  34956. * @param {Array.<number>} opt.position [x, y]
  34957. * @param {number} opt.rotation by radian
  34958. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34959. * @param {number} [opt.tickDirection=1] 1 or -1
  34960. * @param {number} [opt.labelDirection=1] 1 or -1
  34961. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34962. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34963. * @param {string} [opt.axisName] default get from axisModel.
  34964. * @param {number} [opt.axisNameAvailableWidth]
  34965. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34966. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34967. * @param {number} [opt.nameTruncateMaxWidth]
  34968. */
  34969. var AxisBuilder = function (axisModel, opt) {
  34970. /**
  34971. * @readOnly
  34972. */
  34973. this.opt = opt;
  34974. /**
  34975. * @readOnly
  34976. */
  34977. this.axisModel = axisModel;
  34978. // Default value
  34979. defaults(
  34980. opt,
  34981. {
  34982. labelOffset: 0,
  34983. nameDirection: 1,
  34984. tickDirection: 1,
  34985. labelDirection: 1,
  34986. silent: true
  34987. }
  34988. );
  34989. /**
  34990. * @readOnly
  34991. */
  34992. this.group = new Group();
  34993. // FIXME Not use a seperate text group?
  34994. var dumbGroup = new Group({
  34995. position: opt.position.slice(),
  34996. rotation: opt.rotation
  34997. });
  34998. // this.group.add(dumbGroup);
  34999. // this._dumbGroup = dumbGroup;
  35000. dumbGroup.updateTransform();
  35001. this._transform = dumbGroup.transform;
  35002. this._dumbGroup = dumbGroup;
  35003. };
  35004. AxisBuilder.prototype = {
  35005. constructor: AxisBuilder,
  35006. hasBuilder: function (name) {
  35007. return !!builders[name];
  35008. },
  35009. add: function (name) {
  35010. builders[name].call(this);
  35011. },
  35012. getGroup: function () {
  35013. return this.group;
  35014. }
  35015. };
  35016. var builders = {
  35017. /**
  35018. * @private
  35019. */
  35020. axisLine: function () {
  35021. var opt = this.opt;
  35022. var axisModel = this.axisModel;
  35023. if (!axisModel.get('axisLine.show')) {
  35024. return;
  35025. }
  35026. var extent = this.axisModel.axis.getExtent();
  35027. var matrix = this._transform;
  35028. var pt1 = [extent[0], 0];
  35029. var pt2 = [extent[1], 0];
  35030. if (matrix) {
  35031. applyTransform(pt1, pt1, matrix);
  35032. applyTransform(pt2, pt2, matrix);
  35033. }
  35034. var lineStyle = extend(
  35035. {
  35036. lineCap: 'round'
  35037. },
  35038. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  35039. );
  35040. this.group.add(new Line({
  35041. // Id for animation
  35042. anid: 'line',
  35043. subPixelOptimize: true,
  35044. shape: {
  35045. x1: pt1[0],
  35046. y1: pt1[1],
  35047. x2: pt2[0],
  35048. y2: pt2[1]
  35049. },
  35050. style: lineStyle,
  35051. strokeContainThreshold: opt.strokeContainThreshold || 5,
  35052. silent: true,
  35053. z2: 1
  35054. }));
  35055. var arrows = axisModel.get('axisLine.symbol');
  35056. var arrowSize = axisModel.get('axisLine.symbolSize');
  35057. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  35058. if (typeof arrowOffset === 'number') {
  35059. arrowOffset = [arrowOffset, arrowOffset];
  35060. }
  35061. if (arrows != null) {
  35062. if (typeof arrows === 'string') {
  35063. // Use the same arrow for start and end point
  35064. arrows = [arrows, arrows];
  35065. }
  35066. if (typeof arrowSize === 'string'
  35067. || typeof arrowSize === 'number'
  35068. ) {
  35069. // Use the same size for width and height
  35070. arrowSize = [arrowSize, arrowSize];
  35071. }
  35072. var symbolWidth = arrowSize[0];
  35073. var symbolHeight = arrowSize[1];
  35074. each$1([{
  35075. rotate: opt.rotation + Math.PI / 2,
  35076. offset: arrowOffset[0],
  35077. r: 0
  35078. }, {
  35079. rotate: opt.rotation - Math.PI / 2,
  35080. offset: arrowOffset[1],
  35081. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  35082. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  35083. }], function (point, index) {
  35084. if (arrows[index] !== 'none' && arrows[index] != null) {
  35085. var symbol = createSymbol(
  35086. arrows[index],
  35087. -symbolWidth / 2,
  35088. -symbolHeight / 2,
  35089. symbolWidth,
  35090. symbolHeight,
  35091. lineStyle.stroke,
  35092. true
  35093. );
  35094. // Calculate arrow position with offset
  35095. var r = point.r + point.offset;
  35096. var pos = [
  35097. pt1[0] + r * Math.cos(opt.rotation),
  35098. pt1[1] - r * Math.sin(opt.rotation)
  35099. ];
  35100. symbol.attr({
  35101. rotation: point.rotate,
  35102. position: pos,
  35103. silent: true,
  35104. z2: 11
  35105. });
  35106. this.group.add(symbol);
  35107. }
  35108. }, this);
  35109. }
  35110. },
  35111. /**
  35112. * @private
  35113. */
  35114. axisTickLabel: function () {
  35115. var axisModel = this.axisModel;
  35116. var opt = this.opt;
  35117. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  35118. var labelEls = buildAxisLabel(this, axisModel, opt);
  35119. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  35120. buildAxisMinorTicks(this, axisModel, opt);
  35121. },
  35122. /**
  35123. * @private
  35124. */
  35125. axisName: function () {
  35126. var opt = this.opt;
  35127. var axisModel = this.axisModel;
  35128. var name = retrieve(opt.axisName, axisModel.get('name'));
  35129. if (!name) {
  35130. return;
  35131. }
  35132. var nameLocation = axisModel.get('nameLocation');
  35133. var nameDirection = opt.nameDirection;
  35134. var textStyleModel = axisModel.getModel('nameTextStyle');
  35135. var gap = axisModel.get('nameGap') || 0;
  35136. var extent = this.axisModel.axis.getExtent();
  35137. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  35138. var pos = [
  35139. nameLocation === 'start'
  35140. ? extent[0] - gapSignal * gap
  35141. : nameLocation === 'end'
  35142. ? extent[1] + gapSignal * gap
  35143. : (extent[0] + extent[1]) / 2, // 'middle'
  35144. // Reuse labelOffset.
  35145. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  35146. ];
  35147. var labelLayout;
  35148. var nameRotation = axisModel.get('nameRotate');
  35149. if (nameRotation != null) {
  35150. nameRotation = nameRotation * PI$2 / 180; // To radian.
  35151. }
  35152. var axisNameAvailableWidth;
  35153. if (isNameLocationCenter(nameLocation)) {
  35154. labelLayout = innerTextLayout(
  35155. opt.rotation,
  35156. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  35157. nameDirection
  35158. );
  35159. }
  35160. else {
  35161. labelLayout = endTextLayout(
  35162. opt, nameLocation, nameRotation || 0, extent
  35163. );
  35164. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  35165. if (axisNameAvailableWidth != null) {
  35166. axisNameAvailableWidth = Math.abs(
  35167. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  35168. );
  35169. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  35170. }
  35171. }
  35172. var textFont = textStyleModel.getFont();
  35173. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  35174. var ellipsis = truncateOpt.ellipsis;
  35175. var maxWidth = retrieve(
  35176. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  35177. );
  35178. // FIXME
  35179. // truncate rich text? (consider performance)
  35180. var truncatedText = (ellipsis != null && maxWidth != null)
  35181. ? truncateText$1(
  35182. name, maxWidth, textFont, ellipsis,
  35183. {minChar: 2, placeholder: truncateOpt.placeholder}
  35184. )
  35185. : name;
  35186. var tooltipOpt = axisModel.get('tooltip', true);
  35187. var mainType = axisModel.mainType;
  35188. var formatterParams = {
  35189. componentType: mainType,
  35190. name: name,
  35191. $vars: ['name']
  35192. };
  35193. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  35194. var textEl = new Text({
  35195. // Id for animation
  35196. anid: 'name',
  35197. __fullText: name,
  35198. __truncatedText: truncatedText,
  35199. position: pos,
  35200. rotation: labelLayout.rotation,
  35201. silent: isLabelSilent(axisModel),
  35202. z2: 1,
  35203. tooltip: (tooltipOpt && tooltipOpt.show)
  35204. ? extend({
  35205. content: name,
  35206. formatter: function () {
  35207. return name;
  35208. },
  35209. formatterParams: formatterParams
  35210. }, tooltipOpt)
  35211. : null
  35212. });
  35213. setTextStyle(textEl.style, textStyleModel, {
  35214. text: truncatedText,
  35215. textFont: textFont,
  35216. textFill: textStyleModel.getTextColor()
  35217. || axisModel.get('axisLine.lineStyle.color'),
  35218. textAlign: textStyleModel.get('align')
  35219. || labelLayout.textAlign,
  35220. textVerticalAlign: textStyleModel.get('verticalAlign')
  35221. || labelLayout.textVerticalAlign
  35222. });
  35223. if (axisModel.get('triggerEvent')) {
  35224. textEl.eventData = makeAxisEventDataBase(axisModel);
  35225. textEl.eventData.targetType = 'axisName';
  35226. textEl.eventData.name = name;
  35227. }
  35228. // FIXME
  35229. this._dumbGroup.add(textEl);
  35230. textEl.updateTransform();
  35231. this.group.add(textEl);
  35232. textEl.decomposeTransform();
  35233. }
  35234. };
  35235. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  35236. var eventData = {
  35237. componentType: axisModel.mainType,
  35238. componentIndex: axisModel.componentIndex
  35239. };
  35240. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  35241. return eventData;
  35242. };
  35243. /**
  35244. * @public
  35245. * @static
  35246. * @param {Object} opt
  35247. * @param {number} axisRotation in radian
  35248. * @param {number} textRotation in radian
  35249. * @param {number} direction
  35250. * @return {Object} {
  35251. * rotation, // according to axis
  35252. * textAlign,
  35253. * textVerticalAlign
  35254. * }
  35255. */
  35256. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  35257. var rotationDiff = remRadian(textRotation - axisRotation);
  35258. var textAlign;
  35259. var textVerticalAlign;
  35260. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  35261. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  35262. textAlign = 'center';
  35263. }
  35264. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  35265. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  35266. textAlign = 'center';
  35267. }
  35268. else {
  35269. textVerticalAlign = 'middle';
  35270. if (rotationDiff > 0 && rotationDiff < PI$2) {
  35271. textAlign = direction > 0 ? 'right' : 'left';
  35272. }
  35273. else {
  35274. textAlign = direction > 0 ? 'left' : 'right';
  35275. }
  35276. }
  35277. return {
  35278. rotation: rotationDiff,
  35279. textAlign: textAlign,
  35280. textVerticalAlign: textVerticalAlign
  35281. };
  35282. };
  35283. function endTextLayout(opt, textPosition, textRotate, extent) {
  35284. var rotationDiff = remRadian(textRotate - opt.rotation);
  35285. var textAlign;
  35286. var textVerticalAlign;
  35287. var inverse = extent[0] > extent[1];
  35288. var onLeft = (textPosition === 'start' && !inverse)
  35289. || (textPosition !== 'start' && inverse);
  35290. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  35291. textVerticalAlign = onLeft ? 'bottom' : 'top';
  35292. textAlign = 'center';
  35293. }
  35294. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  35295. textVerticalAlign = onLeft ? 'top' : 'bottom';
  35296. textAlign = 'center';
  35297. }
  35298. else {
  35299. textVerticalAlign = 'middle';
  35300. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  35301. textAlign = onLeft ? 'left' : 'right';
  35302. }
  35303. else {
  35304. textAlign = onLeft ? 'right' : 'left';
  35305. }
  35306. }
  35307. return {
  35308. rotation: rotationDiff,
  35309. textAlign: textAlign,
  35310. textVerticalAlign: textVerticalAlign
  35311. };
  35312. }
  35313. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  35314. var tooltipOpt = axisModel.get('tooltip');
  35315. return axisModel.get('silent')
  35316. // Consider mouse cursor, add these restrictions.
  35317. || !(
  35318. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  35319. );
  35320. };
  35321. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  35322. if (shouldShowAllLabels(axisModel.axis)) {
  35323. return;
  35324. }
  35325. // If min or max are user set, we need to check
  35326. // If the tick on min(max) are overlap on their neighbour tick
  35327. // If they are overlapped, we need to hide the min(max) tick label
  35328. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  35329. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  35330. // FIXME
  35331. // Have not consider onBand yet, where tick els is more than label els.
  35332. labelEls = labelEls || [];
  35333. tickEls = tickEls || [];
  35334. var firstLabel = labelEls[0];
  35335. var nextLabel = labelEls[1];
  35336. var lastLabel = labelEls[labelEls.length - 1];
  35337. var prevLabel = labelEls[labelEls.length - 2];
  35338. var firstTick = tickEls[0];
  35339. var nextTick = tickEls[1];
  35340. var lastTick = tickEls[tickEls.length - 1];
  35341. var prevTick = tickEls[tickEls.length - 2];
  35342. if (showMinLabel === false) {
  35343. ignoreEl(firstLabel);
  35344. ignoreEl(firstTick);
  35345. }
  35346. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  35347. if (showMinLabel) {
  35348. ignoreEl(nextLabel);
  35349. ignoreEl(nextTick);
  35350. }
  35351. else {
  35352. ignoreEl(firstLabel);
  35353. ignoreEl(firstTick);
  35354. }
  35355. }
  35356. if (showMaxLabel === false) {
  35357. ignoreEl(lastLabel);
  35358. ignoreEl(lastTick);
  35359. }
  35360. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  35361. if (showMaxLabel) {
  35362. ignoreEl(prevLabel);
  35363. ignoreEl(prevTick);
  35364. }
  35365. else {
  35366. ignoreEl(lastLabel);
  35367. ignoreEl(lastTick);
  35368. }
  35369. }
  35370. }
  35371. function ignoreEl(el) {
  35372. el && (el.ignore = true);
  35373. }
  35374. function isTwoLabelOverlapped(current, next, labelLayout) {
  35375. // current and next has the same rotation.
  35376. var firstRect = current && current.getBoundingRect().clone();
  35377. var nextRect = next && next.getBoundingRect().clone();
  35378. if (!firstRect || !nextRect) {
  35379. return;
  35380. }
  35381. // When checking intersect of two rotated labels, we use mRotationBack
  35382. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  35383. var mRotationBack = identity([]);
  35384. rotate(mRotationBack, mRotationBack, -current.rotation);
  35385. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  35386. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  35387. return firstRect.intersect(nextRect);
  35388. }
  35389. function isNameLocationCenter(nameLocation) {
  35390. return nameLocation === 'middle' || nameLocation === 'center';
  35391. }
  35392. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  35393. var tickEls = [];
  35394. var pt1 = [];
  35395. var pt2 = [];
  35396. for (var i = 0; i < ticksCoords.length; i++) {
  35397. var tickCoord = ticksCoords[i].coord;
  35398. pt1[0] = tickCoord;
  35399. pt1[1] = 0;
  35400. pt2[0] = tickCoord;
  35401. pt2[1] = tickEndCoord;
  35402. if (tickTransform) {
  35403. applyTransform(pt1, pt1, tickTransform);
  35404. applyTransform(pt2, pt2, tickTransform);
  35405. }
  35406. // Tick line, Not use group transform to have better line draw
  35407. var tickEl = new Line({
  35408. // Id for animation
  35409. anid: aniid + '_' + ticksCoords[i].tickValue,
  35410. subPixelOptimize: true,
  35411. shape: {
  35412. x1: pt1[0],
  35413. y1: pt1[1],
  35414. x2: pt2[0],
  35415. y2: pt2[1]
  35416. },
  35417. style: tickLineStyle,
  35418. z2: 2,
  35419. silent: true
  35420. });
  35421. tickEls.push(tickEl);
  35422. }
  35423. return tickEls;
  35424. }
  35425. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  35426. var axis = axisModel.axis;
  35427. var tickModel = axisModel.getModel('axisTick');
  35428. if (!tickModel.get('show') || axis.scale.isBlank()) {
  35429. return;
  35430. }
  35431. var lineStyleModel = tickModel.getModel('lineStyle');
  35432. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  35433. var ticksCoords = axis.getTicksCoords();
  35434. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  35435. lineStyleModel.getLineStyle(),
  35436. {
  35437. stroke: axisModel.get('axisLine.lineStyle.color')
  35438. }
  35439. ), 'ticks');
  35440. for (var i = 0; i < ticksEls.length; i++) {
  35441. axisBuilder.group.add(ticksEls[i]);
  35442. }
  35443. return ticksEls;
  35444. }
  35445. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  35446. var axis = axisModel.axis;
  35447. var minorTickModel = axisModel.getModel('minorTick');
  35448. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  35449. return;
  35450. }
  35451. var minorTicksCoords = axis.getMinorTicksCoords();
  35452. if (!minorTicksCoords.length) {
  35453. return;
  35454. }
  35455. var lineStyleModel = minorTickModel.getModel('lineStyle');
  35456. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  35457. var minorTickLineStyle = defaults(
  35458. lineStyleModel.getLineStyle(),
  35459. defaults(
  35460. axisModel.getModel('axisTick').getLineStyle(),
  35461. {
  35462. stroke: axisModel.get('axisLine.lineStyle.color')
  35463. }
  35464. )
  35465. );
  35466. for (var i = 0; i < minorTicksCoords.length; i++) {
  35467. var minorTicksEls = createTicks(
  35468. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  35469. );
  35470. for (var k = 0; k < minorTicksEls.length; k++) {
  35471. axisBuilder.group.add(minorTicksEls[k]);
  35472. }
  35473. }
  35474. }
  35475. function buildAxisLabel(axisBuilder, axisModel, opt) {
  35476. var axis = axisModel.axis;
  35477. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  35478. if (!show || axis.scale.isBlank()) {
  35479. return;
  35480. }
  35481. var labelModel = axisModel.getModel('axisLabel');
  35482. var labelMargin = labelModel.get('margin');
  35483. var labels = axis.getViewLabels();
  35484. // Special label rotate.
  35485. var labelRotation = (
  35486. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  35487. ) * PI$2 / 180;
  35488. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  35489. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  35490. var labelEls = [];
  35491. var silent = isLabelSilent(axisModel);
  35492. var triggerEvent = axisModel.get('triggerEvent');
  35493. each$1(labels, function (labelItem, index) {
  35494. var tickValue = labelItem.tickValue;
  35495. var formattedLabel = labelItem.formattedLabel;
  35496. var rawLabel = labelItem.rawLabel;
  35497. var itemLabelModel = labelModel;
  35498. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  35499. itemLabelModel = new Model(
  35500. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  35501. );
  35502. }
  35503. var textColor = itemLabelModel.getTextColor()
  35504. || axisModel.get('axisLine.lineStyle.color');
  35505. var tickCoord = axis.dataToCoord(tickValue);
  35506. var pos = [
  35507. tickCoord,
  35508. opt.labelOffset + opt.labelDirection * labelMargin
  35509. ];
  35510. var textEl = new Text({
  35511. // Id for animation
  35512. anid: 'label_' + tickValue,
  35513. position: pos,
  35514. rotation: labelLayout.rotation,
  35515. silent: silent,
  35516. z2: 10
  35517. });
  35518. setTextStyle(textEl.style, itemLabelModel, {
  35519. text: formattedLabel,
  35520. textAlign: itemLabelModel.getShallow('align', true)
  35521. || labelLayout.textAlign,
  35522. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  35523. || itemLabelModel.getShallow('baseline', true)
  35524. || labelLayout.textVerticalAlign,
  35525. textFill: typeof textColor === 'function'
  35526. ? textColor(
  35527. // (1) In category axis with data zoom, tick is not the original
  35528. // index of axis.data. So tick should not be exposed to user
  35529. // in category axis.
  35530. // (2) Compatible with previous version, which always use formatted label as
  35531. // input. But in interval scale the formatted label is like '223,445', which
  35532. // maked user repalce ','. So we modify it to return original val but remain
  35533. // it as 'string' to avoid error in replacing.
  35534. axis.type === 'category'
  35535. ? rawLabel
  35536. : axis.type === 'value'
  35537. ? tickValue + ''
  35538. : tickValue,
  35539. index
  35540. )
  35541. : textColor
  35542. });
  35543. // Pack data for mouse event
  35544. if (triggerEvent) {
  35545. textEl.eventData = makeAxisEventDataBase(axisModel);
  35546. textEl.eventData.targetType = 'axisLabel';
  35547. textEl.eventData.value = rawLabel;
  35548. }
  35549. // FIXME
  35550. axisBuilder._dumbGroup.add(textEl);
  35551. textEl.updateTransform();
  35552. labelEls.push(textEl);
  35553. axisBuilder.group.add(textEl);
  35554. textEl.decomposeTransform();
  35555. });
  35556. return labelEls;
  35557. }
  35558. /*
  35559. * Licensed to the Apache Software Foundation (ASF) under one
  35560. * or more contributor license agreements. See the NOTICE file
  35561. * distributed with this work for additional information
  35562. * regarding copyright ownership. The ASF licenses this file
  35563. * to you under the Apache License, Version 2.0 (the
  35564. * "License"); you may not use this file except in compliance
  35565. * with the License. You may obtain a copy of the License at
  35566. *
  35567. * http://www.apache.org/licenses/LICENSE-2.0
  35568. *
  35569. * Unless required by applicable law or agreed to in writing,
  35570. * software distributed under the License is distributed on an
  35571. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35572. * KIND, either express or implied. See the License for the
  35573. * specific language governing permissions and limitations
  35574. * under the License.
  35575. */
  35576. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  35577. // allAxesInfo should be updated when setOption performed.
  35578. function fixValue(axisModel) {
  35579. var axisInfo = getAxisInfo(axisModel);
  35580. if (!axisInfo) {
  35581. return;
  35582. }
  35583. var axisPointerModel = axisInfo.axisPointerModel;
  35584. var scale = axisInfo.axis.scale;
  35585. var option = axisPointerModel.option;
  35586. var status = axisPointerModel.get('status');
  35587. var value = axisPointerModel.get('value');
  35588. // Parse init value for category and time axis.
  35589. if (value != null) {
  35590. value = scale.parse(value);
  35591. }
  35592. var useHandle = isHandleTrigger(axisPointerModel);
  35593. // If `handle` used, `axisPointer` will always be displayed, so value
  35594. // and status should be initialized.
  35595. if (status == null) {
  35596. option.status = useHandle ? 'show' : 'hide';
  35597. }
  35598. var extent = scale.getExtent().slice();
  35599. extent[0] > extent[1] && extent.reverse();
  35600. if (// Pick a value on axis when initializing.
  35601. value == null
  35602. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35603. // where we should re-pick a value to keep `handle` displaying normally.
  35604. || value > extent[1]
  35605. ) {
  35606. // Make handle displayed on the end of the axis when init, which looks better.
  35607. value = extent[1];
  35608. }
  35609. if (value < extent[0]) {
  35610. value = extent[0];
  35611. }
  35612. option.value = value;
  35613. if (useHandle) {
  35614. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35615. }
  35616. }
  35617. function getAxisInfo(axisModel) {
  35618. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35619. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35620. }
  35621. function getAxisPointerModel(axisModel) {
  35622. var axisInfo = getAxisInfo(axisModel);
  35623. return axisInfo && axisInfo.axisPointerModel;
  35624. }
  35625. function isHandleTrigger(axisPointerModel) {
  35626. return !!axisPointerModel.get('handle.show');
  35627. }
  35628. /**
  35629. * @param {module:echarts/model/Model} model
  35630. * @return {string} unique key
  35631. */
  35632. function makeKey(model) {
  35633. return model.type + '||' + model.id;
  35634. }
  35635. /*
  35636. * Licensed to the Apache Software Foundation (ASF) under one
  35637. * or more contributor license agreements. See the NOTICE file
  35638. * distributed with this work for additional information
  35639. * regarding copyright ownership. The ASF licenses this file
  35640. * to you under the Apache License, Version 2.0 (the
  35641. * "License"); you may not use this file except in compliance
  35642. * with the License. You may obtain a copy of the License at
  35643. *
  35644. * http://www.apache.org/licenses/LICENSE-2.0
  35645. *
  35646. * Unless required by applicable law or agreed to in writing,
  35647. * software distributed under the License is distributed on an
  35648. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35649. * KIND, either express or implied. See the License for the
  35650. * specific language governing permissions and limitations
  35651. * under the License.
  35652. */
  35653. /**
  35654. * Base class of AxisView.
  35655. */
  35656. var AxisView = extendComponentView({
  35657. type: 'axis',
  35658. /**
  35659. * @private
  35660. */
  35661. _axisPointer: null,
  35662. /**
  35663. * @protected
  35664. * @type {string}
  35665. */
  35666. axisPointerClass: null,
  35667. /**
  35668. * @override
  35669. */
  35670. render: function (axisModel, ecModel, api, payload) {
  35671. // FIXME
  35672. // This process should proformed after coordinate systems updated
  35673. // (axis scale updated), and should be performed each time update.
  35674. // So put it here temporarily, although it is not appropriate to
  35675. // put a model-writing procedure in `view`.
  35676. this.axisPointerClass && fixValue(axisModel);
  35677. AxisView.superApply(this, 'render', arguments);
  35678. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35679. },
  35680. /**
  35681. * Action handler.
  35682. * @public
  35683. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35684. * @param {module:echarts/model/Global} ecModel
  35685. * @param {module:echarts/ExtensionAPI} api
  35686. * @param {Object} payload
  35687. */
  35688. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35689. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35690. },
  35691. /**
  35692. * @override
  35693. */
  35694. remove: function (ecModel, api) {
  35695. var axisPointer = this._axisPointer;
  35696. axisPointer && axisPointer.remove(api);
  35697. AxisView.superApply(this, 'remove', arguments);
  35698. },
  35699. /**
  35700. * @override
  35701. */
  35702. dispose: function (ecModel, api) {
  35703. disposeAxisPointer(this, api);
  35704. AxisView.superApply(this, 'dispose', arguments);
  35705. }
  35706. });
  35707. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35708. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35709. if (!Clazz) {
  35710. return;
  35711. }
  35712. var axisPointerModel = getAxisPointerModel(axisModel);
  35713. axisPointerModel
  35714. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35715. .render(axisModel, axisPointerModel, api, forceRender)
  35716. : disposeAxisPointer(axisView, api);
  35717. }
  35718. function disposeAxisPointer(axisView, ecModel, api) {
  35719. var axisPointer = axisView._axisPointer;
  35720. axisPointer && axisPointer.dispose(ecModel, api);
  35721. axisView._axisPointer = null;
  35722. }
  35723. var axisPointerClazz = [];
  35724. AxisView.registerAxisPointerClass = function (type, clazz) {
  35725. if (__DEV__) {
  35726. if (axisPointerClazz[type]) {
  35727. throw new Error('axisPointer ' + type + ' exists');
  35728. }
  35729. }
  35730. axisPointerClazz[type] = clazz;
  35731. };
  35732. AxisView.getAxisPointerClass = function (type) {
  35733. return type && axisPointerClazz[type];
  35734. };
  35735. /*
  35736. * Licensed to the Apache Software Foundation (ASF) under one
  35737. * or more contributor license agreements. See the NOTICE file
  35738. * distributed with this work for additional information
  35739. * regarding copyright ownership. The ASF licenses this file
  35740. * to you under the Apache License, Version 2.0 (the
  35741. * "License"); you may not use this file except in compliance
  35742. * with the License. You may obtain a copy of the License at
  35743. *
  35744. * http://www.apache.org/licenses/LICENSE-2.0
  35745. *
  35746. * Unless required by applicable law or agreed to in writing,
  35747. * software distributed under the License is distributed on an
  35748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35749. * KIND, either express or implied. See the License for the
  35750. * specific language governing permissions and limitations
  35751. * under the License.
  35752. */
  35753. /**
  35754. * Can only be called after coordinate system creation stage.
  35755. * (Can be called before coordinate system update stage).
  35756. *
  35757. * @param {Object} opt {labelInside}
  35758. * @return {Object} {
  35759. * position, rotation, labelDirection, labelOffset,
  35760. * tickDirection, labelRotate, z2
  35761. * }
  35762. */
  35763. function layout$1(gridModel, axisModel, opt) {
  35764. opt = opt || {};
  35765. var grid = gridModel.coordinateSystem;
  35766. var axis = axisModel.axis;
  35767. var layout = {};
  35768. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35769. var rawAxisPosition = axis.position;
  35770. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35771. var axisDim = axis.dim;
  35772. var rect = grid.getRect();
  35773. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35774. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35775. var axisOffset = axisModel.get('offset') || 0;
  35776. var posBound = axisDim === 'x'
  35777. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35778. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35779. if (otherAxisOnZeroOf) {
  35780. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35781. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35782. }
  35783. // Axis position
  35784. layout.position = [
  35785. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35786. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35787. ];
  35788. // Axis rotation
  35789. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35790. // Tick and label direction, x y is axisDim
  35791. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35792. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35793. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35794. if (axisModel.get('axisTick.inside')) {
  35795. layout.tickDirection = -layout.tickDirection;
  35796. }
  35797. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35798. layout.labelDirection = -layout.labelDirection;
  35799. }
  35800. // Special label rotation
  35801. var labelRotate = axisModel.get('axisLabel.rotate');
  35802. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35803. // Over splitLine and splitArea
  35804. layout.z2 = 1;
  35805. return layout;
  35806. }
  35807. /*
  35808. * Licensed to the Apache Software Foundation (ASF) under one
  35809. * or more contributor license agreements. See the NOTICE file
  35810. * distributed with this work for additional information
  35811. * regarding copyright ownership. The ASF licenses this file
  35812. * to you under the Apache License, Version 2.0 (the
  35813. * "License"); you may not use this file except in compliance
  35814. * with the License. You may obtain a copy of the License at
  35815. *
  35816. * http://www.apache.org/licenses/LICENSE-2.0
  35817. *
  35818. * Unless required by applicable law or agreed to in writing,
  35819. * software distributed under the License is distributed on an
  35820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35821. * KIND, either express or implied. See the License for the
  35822. * specific language governing permissions and limitations
  35823. * under the License.
  35824. */
  35825. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  35826. var axis = axisModel.axis;
  35827. if (axis.scale.isBlank()) {
  35828. return;
  35829. }
  35830. var splitAreaModel = axisModel.getModel('splitArea');
  35831. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35832. var areaColors = areaStyleModel.get('color');
  35833. var gridRect = gridModel.coordinateSystem.getRect();
  35834. var ticksCoords = axis.getTicksCoords({
  35835. tickModel: splitAreaModel,
  35836. clamp: true
  35837. });
  35838. if (!ticksCoords.length) {
  35839. return;
  35840. }
  35841. // For Making appropriate splitArea animation, the color and anid
  35842. // should be corresponding to previous one if possible.
  35843. var areaColorsLen = areaColors.length;
  35844. var lastSplitAreaColors = axisView.__splitAreaColors;
  35845. var newSplitAreaColors = createHashMap();
  35846. var colorIndex = 0;
  35847. if (lastSplitAreaColors) {
  35848. for (var i = 0; i < ticksCoords.length; i++) {
  35849. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35850. if (cIndex != null) {
  35851. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35852. break;
  35853. }
  35854. }
  35855. }
  35856. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35857. var areaStyle = areaStyleModel.getAreaStyle();
  35858. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35859. for (var i = 1; i < ticksCoords.length; i++) {
  35860. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35861. var x;
  35862. var y;
  35863. var width;
  35864. var height;
  35865. if (axis.isHorizontal()) {
  35866. x = prev;
  35867. y = gridRect.y;
  35868. width = tickCoord - x;
  35869. height = gridRect.height;
  35870. prev = x + width;
  35871. }
  35872. else {
  35873. x = gridRect.x;
  35874. y = prev;
  35875. width = gridRect.width;
  35876. height = tickCoord - y;
  35877. prev = y + height;
  35878. }
  35879. var tickValue = ticksCoords[i - 1].tickValue;
  35880. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35881. axisGroup.add(new Rect({
  35882. anid: tickValue != null ? 'area_' + tickValue : null,
  35883. shape: {
  35884. x: x,
  35885. y: y,
  35886. width: width,
  35887. height: height
  35888. },
  35889. style: defaults({
  35890. fill: areaColors[colorIndex]
  35891. }, areaStyle),
  35892. silent: true
  35893. }));
  35894. colorIndex = (colorIndex + 1) % areaColorsLen;
  35895. }
  35896. axisView.__splitAreaColors = newSplitAreaColors;
  35897. }
  35898. function rectCoordAxisHandleRemove(axisView) {
  35899. axisView.__splitAreaColors = null;
  35900. }
  35901. /*
  35902. * Licensed to the Apache Software Foundation (ASF) under one
  35903. * or more contributor license agreements. See the NOTICE file
  35904. * distributed with this work for additional information
  35905. * regarding copyright ownership. The ASF licenses this file
  35906. * to you under the Apache License, Version 2.0 (the
  35907. * "License"); you may not use this file except in compliance
  35908. * with the License. You may obtain a copy of the License at
  35909. *
  35910. * http://www.apache.org/licenses/LICENSE-2.0
  35911. *
  35912. * Unless required by applicable law or agreed to in writing,
  35913. * software distributed under the License is distributed on an
  35914. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35915. * KIND, either express or implied. See the License for the
  35916. * specific language governing permissions and limitations
  35917. * under the License.
  35918. */
  35919. var axisBuilderAttrs = [
  35920. 'axisLine', 'axisTickLabel', 'axisName'
  35921. ];
  35922. var selfBuilderAttrs = [
  35923. 'splitArea', 'splitLine', 'minorSplitLine'
  35924. ];
  35925. var CartesianAxisView = AxisView.extend({
  35926. type: 'cartesianAxis',
  35927. axisPointerClass: 'CartesianAxisPointer',
  35928. /**
  35929. * @override
  35930. */
  35931. render: function (axisModel, ecModel, api, payload) {
  35932. this.group.removeAll();
  35933. var oldAxisGroup = this._axisGroup;
  35934. this._axisGroup = new Group();
  35935. this.group.add(this._axisGroup);
  35936. if (!axisModel.get('show')) {
  35937. return;
  35938. }
  35939. var gridModel = axisModel.getCoordSysModel();
  35940. var layout = layout$1(gridModel, axisModel);
  35941. var axisBuilder = new AxisBuilder(axisModel, layout);
  35942. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35943. this._axisGroup.add(axisBuilder.getGroup());
  35944. each$1(selfBuilderAttrs, function (name) {
  35945. if (axisModel.get(name + '.show')) {
  35946. this['_' + name](axisModel, gridModel);
  35947. }
  35948. }, this);
  35949. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35950. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35951. },
  35952. remove: function () {
  35953. rectCoordAxisHandleRemove(this);
  35954. },
  35955. /**
  35956. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35957. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35958. * @private
  35959. */
  35960. _splitLine: function (axisModel, gridModel) {
  35961. var axis = axisModel.axis;
  35962. if (axis.scale.isBlank()) {
  35963. return;
  35964. }
  35965. var splitLineModel = axisModel.getModel('splitLine');
  35966. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35967. var lineColors = lineStyleModel.get('color');
  35968. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35969. var gridRect = gridModel.coordinateSystem.getRect();
  35970. var isHorizontal = axis.isHorizontal();
  35971. var lineCount = 0;
  35972. var ticksCoords = axis.getTicksCoords({
  35973. tickModel: splitLineModel
  35974. });
  35975. var p1 = [];
  35976. var p2 = [];
  35977. var lineStyle = lineStyleModel.getLineStyle();
  35978. for (var i = 0; i < ticksCoords.length; i++) {
  35979. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35980. if (isHorizontal) {
  35981. p1[0] = tickCoord;
  35982. p1[1] = gridRect.y;
  35983. p2[0] = tickCoord;
  35984. p2[1] = gridRect.y + gridRect.height;
  35985. }
  35986. else {
  35987. p1[0] = gridRect.x;
  35988. p1[1] = tickCoord;
  35989. p2[0] = gridRect.x + gridRect.width;
  35990. p2[1] = tickCoord;
  35991. }
  35992. var colorIndex = (lineCount++) % lineColors.length;
  35993. var tickValue = ticksCoords[i].tickValue;
  35994. this._axisGroup.add(new Line({
  35995. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35996. subPixelOptimize: true,
  35997. shape: {
  35998. x1: p1[0],
  35999. y1: p1[1],
  36000. x2: p2[0],
  36001. y2: p2[1]
  36002. },
  36003. style: defaults({
  36004. stroke: lineColors[colorIndex]
  36005. }, lineStyle),
  36006. silent: true
  36007. }));
  36008. }
  36009. },
  36010. /**
  36011. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36012. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  36013. * @private
  36014. */
  36015. _minorSplitLine: function (axisModel, gridModel) {
  36016. var axis = axisModel.axis;
  36017. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  36018. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  36019. var gridRect = gridModel.coordinateSystem.getRect();
  36020. var isHorizontal = axis.isHorizontal();
  36021. var minorTicksCoords = axis.getMinorTicksCoords();
  36022. if (!minorTicksCoords.length) {
  36023. return;
  36024. }
  36025. var p1 = [];
  36026. var p2 = [];
  36027. var lineStyle = lineStyleModel.getLineStyle();
  36028. for (var i = 0; i < minorTicksCoords.length; i++) {
  36029. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  36030. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  36031. if (isHorizontal) {
  36032. p1[0] = tickCoord;
  36033. p1[1] = gridRect.y;
  36034. p2[0] = tickCoord;
  36035. p2[1] = gridRect.y + gridRect.height;
  36036. }
  36037. else {
  36038. p1[0] = gridRect.x;
  36039. p1[1] = tickCoord;
  36040. p2[0] = gridRect.x + gridRect.width;
  36041. p2[1] = tickCoord;
  36042. }
  36043. this._axisGroup.add(new Line({
  36044. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  36045. subPixelOptimize: true,
  36046. shape: {
  36047. x1: p1[0],
  36048. y1: p1[1],
  36049. x2: p2[0],
  36050. y2: p2[1]
  36051. },
  36052. style: lineStyle,
  36053. silent: true
  36054. }));
  36055. }
  36056. }
  36057. },
  36058. /**
  36059. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  36060. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  36061. * @private
  36062. */
  36063. _splitArea: function (axisModel, gridModel) {
  36064. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  36065. }
  36066. });
  36067. CartesianAxisView.extend({
  36068. type: 'xAxis'
  36069. });
  36070. CartesianAxisView.extend({
  36071. type: 'yAxis'
  36072. });
  36073. /*
  36074. * Licensed to the Apache Software Foundation (ASF) under one
  36075. * or more contributor license agreements. See the NOTICE file
  36076. * distributed with this work for additional information
  36077. * regarding copyright ownership. The ASF licenses this file
  36078. * to you under the Apache License, Version 2.0 (the
  36079. * "License"); you may not use this file except in compliance
  36080. * with the License. You may obtain a copy of the License at
  36081. *
  36082. * http://www.apache.org/licenses/LICENSE-2.0
  36083. *
  36084. * Unless required by applicable law or agreed to in writing,
  36085. * software distributed under the License is distributed on an
  36086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36087. * KIND, either express or implied. See the License for the
  36088. * specific language governing permissions and limitations
  36089. * under the License.
  36090. */
  36091. /*
  36092. * Licensed to the Apache Software Foundation (ASF) under one
  36093. * or more contributor license agreements. See the NOTICE file
  36094. * distributed with this work for additional information
  36095. * regarding copyright ownership. The ASF licenses this file
  36096. * to you under the Apache License, Version 2.0 (the
  36097. * "License"); you may not use this file except in compliance
  36098. * with the License. You may obtain a copy of the License at
  36099. *
  36100. * http://www.apache.org/licenses/LICENSE-2.0
  36101. *
  36102. * Unless required by applicable law or agreed to in writing,
  36103. * software distributed under the License is distributed on an
  36104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36105. * KIND, either express or implied. See the License for the
  36106. * specific language governing permissions and limitations
  36107. * under the License.
  36108. */
  36109. // Grid view
  36110. extendComponentView({
  36111. type: 'grid',
  36112. render: function (gridModel, ecModel) {
  36113. this.group.removeAll();
  36114. if (gridModel.get('show')) {
  36115. this.group.add(new Rect({
  36116. shape: gridModel.coordinateSystem.getRect(),
  36117. style: defaults({
  36118. fill: gridModel.get('backgroundColor')
  36119. }, gridModel.getItemStyle()),
  36120. silent: true,
  36121. z2: -1
  36122. }));
  36123. }
  36124. }
  36125. });
  36126. registerPreprocessor(function (option) {
  36127. // Only create grid when need
  36128. if (option.xAxis && option.yAxis && !option.grid) {
  36129. option.grid = {};
  36130. }
  36131. });
  36132. /*
  36133. * Licensed to the Apache Software Foundation (ASF) under one
  36134. * or more contributor license agreements. See the NOTICE file
  36135. * distributed with this work for additional information
  36136. * regarding copyright ownership. The ASF licenses this file
  36137. * to you under the Apache License, Version 2.0 (the
  36138. * "License"); you may not use this file except in compliance
  36139. * with the License. You may obtain a copy of the License at
  36140. *
  36141. * http://www.apache.org/licenses/LICENSE-2.0
  36142. *
  36143. * Unless required by applicable law or agreed to in writing,
  36144. * software distributed under the License is distributed on an
  36145. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36146. * KIND, either express or implied. See the License for the
  36147. * specific language governing permissions and limitations
  36148. * under the License.
  36149. */
  36150. // In case developer forget to include grid component
  36151. registerVisual(visualSymbol('line', 'circle', 'line'));
  36152. registerLayout(layoutPoints('line'));
  36153. // Down sample after filter
  36154. registerProcessor(
  36155. PRIORITY.PROCESSOR.STATISTIC,
  36156. dataSample('line')
  36157. );
  36158. /*
  36159. * Licensed to the Apache Software Foundation (ASF) under one
  36160. * or more contributor license agreements. See the NOTICE file
  36161. * distributed with this work for additional information
  36162. * regarding copyright ownership. The ASF licenses this file
  36163. * to you under the Apache License, Version 2.0 (the
  36164. * "License"); you may not use this file except in compliance
  36165. * with the License. You may obtain a copy of the License at
  36166. *
  36167. * http://www.apache.org/licenses/LICENSE-2.0
  36168. *
  36169. * Unless required by applicable law or agreed to in writing,
  36170. * software distributed under the License is distributed on an
  36171. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36172. * KIND, either express or implied. See the License for the
  36173. * specific language governing permissions and limitations
  36174. * under the License.
  36175. */
  36176. var BaseBarSeries = SeriesModel.extend({
  36177. type: 'series.__base_bar__',
  36178. getInitialData: function (option, ecModel) {
  36179. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  36180. },
  36181. getMarkerPosition: function (value) {
  36182. var coordSys = this.coordinateSystem;
  36183. if (coordSys) {
  36184. // PENDING if clamp ?
  36185. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  36186. var data = this.getData();
  36187. var offset = data.getLayout('offset');
  36188. var size = data.getLayout('size');
  36189. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36190. pt[offsetIndex] += offset + size / 2;
  36191. return pt;
  36192. }
  36193. return [NaN, NaN];
  36194. },
  36195. defaultOption: {
  36196. zlevel: 0, // 一级层叠
  36197. z: 2, // 二级层叠
  36198. coordinateSystem: 'cartesian2d',
  36199. legendHoverLink: true,
  36200. // stack: null
  36201. // Cartesian coordinate system
  36202. // xAxisIndex: 0,
  36203. // yAxisIndex: 0,
  36204. // 最小高度改为0
  36205. barMinHeight: 0,
  36206. // 最小角度为0,仅对极坐标系下的柱状图有效
  36207. barMinAngle: 0,
  36208. // cursor: null,
  36209. large: false,
  36210. largeThreshold: 400,
  36211. progressive: 3e3,
  36212. progressiveChunkMode: 'mod',
  36213. // barMaxWidth: null,
  36214. // In cartesian, the default value is 1. Otherwise null.
  36215. // barMinWidth: null,
  36216. // 默认自适应
  36217. // barWidth: null,
  36218. // 柱间距离,默认为柱形宽度的30%,可设固定值
  36219. // barGap: '30%',
  36220. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  36221. // barCategoryGap: '20%',
  36222. // label: {
  36223. // show: false
  36224. // },
  36225. itemStyle: {},
  36226. emphasis: {}
  36227. }
  36228. });
  36229. /*
  36230. * Licensed to the Apache Software Foundation (ASF) under one
  36231. * or more contributor license agreements. See the NOTICE file
  36232. * distributed with this work for additional information
  36233. * regarding copyright ownership. The ASF licenses this file
  36234. * to you under the Apache License, Version 2.0 (the
  36235. * "License"); you may not use this file except in compliance
  36236. * with the License. You may obtain a copy of the License at
  36237. *
  36238. * http://www.apache.org/licenses/LICENSE-2.0
  36239. *
  36240. * Unless required by applicable law or agreed to in writing,
  36241. * software distributed under the License is distributed on an
  36242. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36243. * KIND, either express or implied. See the License for the
  36244. * specific language governing permissions and limitations
  36245. * under the License.
  36246. */
  36247. BaseBarSeries.extend({
  36248. type: 'series.bar',
  36249. dependencies: ['grid', 'polar'],
  36250. brushSelector: 'rect',
  36251. /**
  36252. * @override
  36253. */
  36254. getProgressive: function () {
  36255. // Do not support progressive in normal mode.
  36256. return this.get('large')
  36257. ? this.get('progressive')
  36258. : false;
  36259. },
  36260. /**
  36261. * @override
  36262. */
  36263. getProgressiveThreshold: function () {
  36264. // Do not support progressive in normal mode.
  36265. var progressiveThreshold = this.get('progressiveThreshold');
  36266. var largeThreshold = this.get('largeThreshold');
  36267. if (largeThreshold > progressiveThreshold) {
  36268. progressiveThreshold = largeThreshold;
  36269. }
  36270. return progressiveThreshold;
  36271. },
  36272. defaultOption: {
  36273. // If clipped
  36274. // Only available on cartesian2d
  36275. clip: true,
  36276. // If use caps on two sides of bars
  36277. // Only available on tangential polar bar
  36278. roundCap: false,
  36279. showBackground: false,
  36280. backgroundStyle: {
  36281. color: 'rgba(180, 180, 180, 0.2)',
  36282. borderColor: null,
  36283. borderWidth: 0,
  36284. borderType: 'solid',
  36285. borderRadius: 0,
  36286. shadowBlur: 0,
  36287. shadowColor: null,
  36288. shadowOffsetX: 0,
  36289. shadowOffsetY: 0,
  36290. opacity: 1
  36291. }
  36292. }
  36293. });
  36294. /*
  36295. * Licensed to the Apache Software Foundation (ASF) under one
  36296. * or more contributor license agreements. See the NOTICE file
  36297. * distributed with this work for additional information
  36298. * regarding copyright ownership. The ASF licenses this file
  36299. * to you under the Apache License, Version 2.0 (the
  36300. * "License"); you may not use this file except in compliance
  36301. * with the License. You may obtain a copy of the License at
  36302. *
  36303. * http://www.apache.org/licenses/LICENSE-2.0
  36304. *
  36305. * Unless required by applicable law or agreed to in writing,
  36306. * software distributed under the License is distributed on an
  36307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36308. * KIND, either express or implied. See the License for the
  36309. * specific language governing permissions and limitations
  36310. * under the License.
  36311. */
  36312. function setLabel(
  36313. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  36314. ) {
  36315. var labelModel = itemModel.getModel('label');
  36316. var hoverLabelModel = itemModel.getModel('emphasis.label');
  36317. setLabelStyle(
  36318. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  36319. {
  36320. labelFetcher: seriesModel,
  36321. labelDataIndex: dataIndex,
  36322. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  36323. isRectText: true,
  36324. autoColor: color
  36325. }
  36326. );
  36327. fixPosition(normalStyle);
  36328. fixPosition(hoverStyle);
  36329. }
  36330. function fixPosition(style, labelPositionOutside) {
  36331. if (style.textPosition === 'outside') {
  36332. style.textPosition = labelPositionOutside;
  36333. }
  36334. }
  36335. /*
  36336. * Licensed to the Apache Software Foundation (ASF) under one
  36337. * or more contributor license agreements. See the NOTICE file
  36338. * distributed with this work for additional information
  36339. * regarding copyright ownership. The ASF licenses this file
  36340. * to you under the Apache License, Version 2.0 (the
  36341. * "License"); you may not use this file except in compliance
  36342. * with the License. You may obtain a copy of the License at
  36343. *
  36344. * http://www.apache.org/licenses/LICENSE-2.0
  36345. *
  36346. * Unless required by applicable law or agreed to in writing,
  36347. * software distributed under the License is distributed on an
  36348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36349. * KIND, either express or implied. See the License for the
  36350. * specific language governing permissions and limitations
  36351. * under the License.
  36352. */
  36353. var getBarItemStyle = makeStyleMapper(
  36354. [
  36355. ['fill', 'color'],
  36356. ['stroke', 'borderColor'],
  36357. ['lineWidth', 'borderWidth'],
  36358. // Compatitable with 2
  36359. ['stroke', 'barBorderColor'],
  36360. ['lineWidth', 'barBorderWidth'],
  36361. ['opacity'],
  36362. ['shadowBlur'],
  36363. ['shadowOffsetX'],
  36364. ['shadowOffsetY'],
  36365. ['shadowColor']
  36366. ]
  36367. );
  36368. var barItemStyle = {
  36369. getBarItemStyle: function (excludes) {
  36370. var style = getBarItemStyle(this, excludes);
  36371. if (this.getBorderLineDash) {
  36372. var lineDash = this.getBorderLineDash();
  36373. lineDash && (style.lineDash = lineDash);
  36374. }
  36375. return style;
  36376. }
  36377. };
  36378. /*
  36379. * Licensed to the Apache Software Foundation (ASF) under one
  36380. * or more contributor license agreements. See the NOTICE file
  36381. * distributed with this work for additional information
  36382. * regarding copyright ownership. The ASF licenses this file
  36383. * to you under the Apache License, Version 2.0 (the
  36384. * "License"); you may not use this file except in compliance
  36385. * with the License. You may obtain a copy of the License at
  36386. *
  36387. * http://www.apache.org/licenses/LICENSE-2.0
  36388. *
  36389. * Unless required by applicable law or agreed to in writing,
  36390. * software distributed under the License is distributed on an
  36391. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36392. * KIND, either express or implied. See the License for the
  36393. * specific language governing permissions and limitations
  36394. * under the License.
  36395. */
  36396. /**
  36397. * Sausage: similar to sector, but have half circle on both sides
  36398. * @public
  36399. */
  36400. var Sausage = extendShape({
  36401. type: 'sausage',
  36402. shape: {
  36403. cx: 0,
  36404. cy: 0,
  36405. r0: 0,
  36406. r: 0,
  36407. startAngle: 0,
  36408. endAngle: Math.PI * 2,
  36409. clockwise: true
  36410. },
  36411. buildPath: function (ctx, shape) {
  36412. var x = shape.cx;
  36413. var y = shape.cy;
  36414. var r0 = Math.max(shape.r0 || 0, 0);
  36415. var r = Math.max(shape.r, 0);
  36416. var dr = (r - r0) * 0.5;
  36417. var rCenter = r0 + dr;
  36418. var startAngle = shape.startAngle;
  36419. var endAngle = shape.endAngle;
  36420. var clockwise = shape.clockwise;
  36421. var unitStartX = Math.cos(startAngle);
  36422. var unitStartY = Math.sin(startAngle);
  36423. var unitEndX = Math.cos(endAngle);
  36424. var unitEndY = Math.sin(endAngle);
  36425. var lessThanCircle = clockwise
  36426. ? endAngle - startAngle < Math.PI * 2
  36427. : startAngle - endAngle < Math.PI * 2;
  36428. if (lessThanCircle) {
  36429. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  36430. ctx.arc(
  36431. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  36432. -Math.PI + startAngle, startAngle, !clockwise
  36433. );
  36434. }
  36435. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  36436. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  36437. ctx.arc(
  36438. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  36439. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  36440. );
  36441. if (r0 !== 0) {
  36442. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  36443. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  36444. }
  36445. ctx.closePath();
  36446. }
  36447. });
  36448. /*
  36449. * Licensed to the Apache Software Foundation (ASF) under one
  36450. * or more contributor license agreements. See the NOTICE file
  36451. * distributed with this work for additional information
  36452. * regarding copyright ownership. The ASF licenses this file
  36453. * to you under the Apache License, Version 2.0 (the
  36454. * "License"); you may not use this file except in compliance
  36455. * with the License. You may obtain a copy of the License at
  36456. *
  36457. * http://www.apache.org/licenses/LICENSE-2.0
  36458. *
  36459. * Unless required by applicable law or agreed to in writing,
  36460. * software distributed under the License is distributed on an
  36461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36462. * KIND, either express or implied. See the License for the
  36463. * specific language governing permissions and limitations
  36464. * under the License.
  36465. */
  36466. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  36467. var _eventPos = [0, 0];
  36468. // FIXME
  36469. // Just for compatible with ec2.
  36470. extend(Model.prototype, barItemStyle);
  36471. function getClipArea(coord, data) {
  36472. var coordSysClipArea = coord.getArea && coord.getArea();
  36473. if (coord.type === 'cartesian2d') {
  36474. var baseAxis = coord.getBaseAxis();
  36475. // When boundaryGap is false or using time axis. bar may exceed the grid.
  36476. // We should not clip this part.
  36477. // See test/bar2.html
  36478. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  36479. var expandWidth = data.getLayout('bandWidth');
  36480. if (baseAxis.isHorizontal()) {
  36481. coordSysClipArea.x -= expandWidth;
  36482. coordSysClipArea.width += expandWidth * 2;
  36483. }
  36484. else {
  36485. coordSysClipArea.y -= expandWidth;
  36486. coordSysClipArea.height += expandWidth * 2;
  36487. }
  36488. }
  36489. }
  36490. return coordSysClipArea;
  36491. }
  36492. extendChartView({
  36493. type: 'bar',
  36494. render: function (seriesModel, ecModel, api) {
  36495. this._updateDrawMode(seriesModel);
  36496. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36497. if (coordinateSystemType === 'cartesian2d'
  36498. || coordinateSystemType === 'polar'
  36499. ) {
  36500. this._isLargeDraw
  36501. ? this._renderLarge(seriesModel, ecModel, api)
  36502. : this._renderNormal(seriesModel, ecModel, api);
  36503. }
  36504. else if (__DEV__) {
  36505. console.warn('Only cartesian2d and polar supported for bar.');
  36506. }
  36507. return this.group;
  36508. },
  36509. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36510. this._clear();
  36511. this._updateDrawMode(seriesModel);
  36512. },
  36513. incrementalRender: function (params, seriesModel, ecModel, api) {
  36514. // Do not support progressive in normal mode.
  36515. this._incrementalRenderLarge(params, seriesModel);
  36516. },
  36517. _updateDrawMode: function (seriesModel) {
  36518. var isLargeDraw = seriesModel.pipelineContext.large;
  36519. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  36520. this._isLargeDraw = isLargeDraw;
  36521. this._clear();
  36522. }
  36523. },
  36524. _renderNormal: function (seriesModel, ecModel, api) {
  36525. var group = this.group;
  36526. var data = seriesModel.getData();
  36527. var oldData = this._data;
  36528. var coord = seriesModel.coordinateSystem;
  36529. var baseAxis = coord.getBaseAxis();
  36530. var isHorizontalOrRadial;
  36531. if (coord.type === 'cartesian2d') {
  36532. isHorizontalOrRadial = baseAxis.isHorizontal();
  36533. }
  36534. else if (coord.type === 'polar') {
  36535. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36536. }
  36537. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36538. var needsClip = seriesModel.get('clip', true);
  36539. var coordSysClipArea = getClipArea(coord, data);
  36540. // If there is clipPath created in large mode. Remove it.
  36541. group.removeClipPath();
  36542. // We don't use clipPath in normal mode because we needs a perfect animation
  36543. // And don't want the label are clipped.
  36544. var roundCap = seriesModel.get('roundCap', true);
  36545. var drawBackground = seriesModel.get('showBackground', true);
  36546. var backgroundModel = seriesModel.getModel('backgroundStyle');
  36547. var bgEls = [];
  36548. var oldBgEls = this._backgroundEls || [];
  36549. data.diff(oldData)
  36550. .add(function (dataIndex) {
  36551. var itemModel = data.getItemModel(dataIndex);
  36552. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36553. if (drawBackground) {
  36554. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, layout);
  36555. bgEl.useStyle(backgroundModel.getBarItemStyle());
  36556. bgEls[dataIndex] = bgEl;
  36557. }
  36558. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  36559. if (!data.hasValue(dataIndex)) {
  36560. return;
  36561. }
  36562. if (needsClip) {
  36563. // Clip will modify the layout params.
  36564. // And return a boolean to determine if the shape are fully clipped.
  36565. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36566. if (isClipped) {
  36567. group.remove(el);
  36568. return;
  36569. }
  36570. }
  36571. var el = elementCreator[coord.type](
  36572. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  36573. );
  36574. data.setItemGraphicEl(dataIndex, el);
  36575. group.add(el);
  36576. updateStyle(
  36577. el, data, dataIndex, itemModel, layout,
  36578. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36579. );
  36580. })
  36581. .update(function (newIndex, oldIndex) {
  36582. var itemModel = data.getItemModel(newIndex);
  36583. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36584. if (drawBackground) {
  36585. var bgEl = oldBgEls[oldIndex];
  36586. bgEl.useStyle(backgroundModel.getBarItemStyle());
  36587. bgEls[newIndex] = bgEl;
  36588. var shape = createBackgroundShape(isHorizontalOrRadial, layout, coord);
  36589. updateProps(bgEl, { shape: shape }, animationModel, newIndex);
  36590. }
  36591. var el = oldData.getItemGraphicEl(oldIndex);
  36592. if (!data.hasValue(newIndex)) {
  36593. group.remove(el);
  36594. return;
  36595. }
  36596. if (needsClip) {
  36597. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36598. if (isClipped) {
  36599. group.remove(el);
  36600. return;
  36601. }
  36602. }
  36603. if (el) {
  36604. updateProps(el, {shape: layout}, animationModel, newIndex);
  36605. }
  36606. else {
  36607. el = elementCreator[coord.type](
  36608. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  36609. );
  36610. }
  36611. data.setItemGraphicEl(newIndex, el);
  36612. // Add back
  36613. group.add(el);
  36614. updateStyle(
  36615. el, data, newIndex, itemModel, layout,
  36616. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36617. );
  36618. })
  36619. .remove(function (dataIndex) {
  36620. var el = oldData.getItemGraphicEl(dataIndex);
  36621. if (coord.type === 'cartesian2d') {
  36622. el && removeRect(dataIndex, animationModel, el);
  36623. }
  36624. else {
  36625. el && removeSector(dataIndex, animationModel, el);
  36626. }
  36627. })
  36628. .execute();
  36629. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  36630. bgGroup.removeAll();
  36631. for (var i = 0; i < bgEls.length; ++i) {
  36632. bgGroup.add(bgEls[i]);
  36633. }
  36634. group.add(bgGroup);
  36635. this._backgroundEls = bgEls;
  36636. this._data = data;
  36637. },
  36638. _renderLarge: function (seriesModel, ecModel, api) {
  36639. this._clear();
  36640. createLarge(seriesModel, this.group);
  36641. // Use clipPath in large mode.
  36642. var clipPath = seriesModel.get('clip', true)
  36643. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  36644. : null;
  36645. if (clipPath) {
  36646. this.group.setClipPath(clipPath);
  36647. }
  36648. else {
  36649. this.group.removeClipPath();
  36650. }
  36651. },
  36652. _incrementalRenderLarge: function (params, seriesModel) {
  36653. this._removeBackground();
  36654. createLarge(seriesModel, this.group, true);
  36655. },
  36656. dispose: noop,
  36657. remove: function (ecModel) {
  36658. this._clear(ecModel);
  36659. },
  36660. _clear: function (ecModel) {
  36661. var group = this.group;
  36662. var data = this._data;
  36663. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36664. this._removeBackground();
  36665. this._backgroundEls = [];
  36666. data.eachItemGraphicEl(function (el) {
  36667. if (el.type === 'sector') {
  36668. removeSector(el.dataIndex, ecModel, el);
  36669. }
  36670. else {
  36671. removeRect(el.dataIndex, ecModel, el);
  36672. }
  36673. });
  36674. }
  36675. else {
  36676. group.removeAll();
  36677. }
  36678. this._data = null;
  36679. },
  36680. _removeBackground: function () {
  36681. this.group.remove(this._backgroundGroup);
  36682. this._backgroundGroup = null;
  36683. }
  36684. });
  36685. var mathMax$4 = Math.max;
  36686. var mathMin$4 = Math.min;
  36687. var clip = {
  36688. cartesian2d: function (coordSysBoundingRect, layout) {
  36689. var signWidth = layout.width < 0 ? -1 : 1;
  36690. var signHeight = layout.height < 0 ? -1 : 1;
  36691. // Needs positive width and height
  36692. if (signWidth < 0) {
  36693. layout.x += layout.width;
  36694. layout.width = -layout.width;
  36695. }
  36696. if (signHeight < 0) {
  36697. layout.y += layout.height;
  36698. layout.height = -layout.height;
  36699. }
  36700. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  36701. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  36702. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  36703. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  36704. layout.x = x;
  36705. layout.y = y;
  36706. layout.width = x2 - x;
  36707. layout.height = y2 - y;
  36708. var clipped = layout.width < 0 || layout.height < 0;
  36709. // Reverse back
  36710. if (signWidth < 0) {
  36711. layout.x += layout.width;
  36712. layout.width = -layout.width;
  36713. }
  36714. if (signHeight < 0) {
  36715. layout.y += layout.height;
  36716. layout.height = -layout.height;
  36717. }
  36718. return clipped;
  36719. },
  36720. polar: function (coordSysClipArea) {
  36721. return false;
  36722. }
  36723. };
  36724. var elementCreator = {
  36725. cartesian2d: function (
  36726. dataIndex, layout, isHorizontal,
  36727. animationModel, isUpdate
  36728. ) {
  36729. var rect = new Rect({
  36730. shape: extend({}, layout),
  36731. z2: 1
  36732. });
  36733. rect.name = 'item';
  36734. // Animation
  36735. if (animationModel) {
  36736. var rectShape = rect.shape;
  36737. var animateProperty = isHorizontal ? 'height' : 'width';
  36738. var animateTarget = {};
  36739. rectShape[animateProperty] = 0;
  36740. animateTarget[animateProperty] = layout[animateProperty];
  36741. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36742. shape: animateTarget
  36743. }, animationModel, dataIndex);
  36744. }
  36745. return rect;
  36746. },
  36747. polar: function (
  36748. dataIndex, layout, isRadial,
  36749. animationModel, isUpdate, roundCap
  36750. ) {
  36751. // Keep the same logic with bar in catesion: use end value to control
  36752. // direction. Notice that if clockwise is true (by default), the sector
  36753. // will always draw clockwisely, no matter whether endAngle is greater
  36754. // or less than startAngle.
  36755. var clockwise = layout.startAngle < layout.endAngle;
  36756. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  36757. var sector = new ShapeClass({
  36758. shape: defaults({clockwise: clockwise}, layout),
  36759. z2: 1
  36760. });
  36761. sector.name = 'item';
  36762. // Animation
  36763. if (animationModel) {
  36764. var sectorShape = sector.shape;
  36765. var animateProperty = isRadial ? 'r' : 'endAngle';
  36766. var animateTarget = {};
  36767. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36768. animateTarget[animateProperty] = layout[animateProperty];
  36769. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36770. shape: animateTarget
  36771. }, animationModel, dataIndex);
  36772. }
  36773. return sector;
  36774. }
  36775. };
  36776. function removeRect(dataIndex, animationModel, el) {
  36777. // Not show text when animating
  36778. el.style.text = null;
  36779. updateProps(el, {
  36780. shape: {
  36781. width: 0
  36782. }
  36783. }, animationModel, dataIndex, function () {
  36784. el.parent && el.parent.remove(el);
  36785. });
  36786. }
  36787. function removeSector(dataIndex, animationModel, el) {
  36788. // Not show text when animating
  36789. el.style.text = null;
  36790. updateProps(el, {
  36791. shape: {
  36792. r: el.shape.r0
  36793. }
  36794. }, animationModel, dataIndex, function () {
  36795. el.parent && el.parent.remove(el);
  36796. });
  36797. }
  36798. var getLayout = {
  36799. cartesian2d: function (data, dataIndex, itemModel) {
  36800. var layout = data.getItemLayout(dataIndex);
  36801. var fixedLineWidth = getLineWidth(itemModel, layout);
  36802. // fix layout with lineWidth
  36803. var signX = layout.width > 0 ? 1 : -1;
  36804. var signY = layout.height > 0 ? 1 : -1;
  36805. return {
  36806. x: layout.x + signX * fixedLineWidth / 2,
  36807. y: layout.y + signY * fixedLineWidth / 2,
  36808. width: layout.width - signX * fixedLineWidth,
  36809. height: layout.height - signY * fixedLineWidth
  36810. };
  36811. },
  36812. polar: function (data, dataIndex, itemModel) {
  36813. var layout = data.getItemLayout(dataIndex);
  36814. return {
  36815. cx: layout.cx,
  36816. cy: layout.cy,
  36817. r0: layout.r0,
  36818. r: layout.r,
  36819. startAngle: layout.startAngle,
  36820. endAngle: layout.endAngle
  36821. };
  36822. }
  36823. };
  36824. function isZeroOnPolar(layout) {
  36825. return layout.startAngle != null
  36826. && layout.endAngle != null
  36827. && layout.startAngle === layout.endAngle;
  36828. }
  36829. function updateStyle(
  36830. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36831. ) {
  36832. var color = data.getItemVisual(dataIndex, 'color');
  36833. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36834. var stroke = data.getVisual('borderColor');
  36835. var itemStyleModel = itemModel.getModel('itemStyle');
  36836. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36837. if (!isPolar) {
  36838. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36839. }
  36840. el.useStyle(defaults(
  36841. {
  36842. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  36843. fill: isZeroOnPolar(layout) ? 'none' : color,
  36844. opacity: opacity
  36845. },
  36846. itemStyleModel.getBarItemStyle()
  36847. ));
  36848. var cursorStyle = itemModel.getShallow('cursor');
  36849. cursorStyle && el.attr('cursor', cursorStyle);
  36850. var labelPositionOutside = isHorizontal
  36851. ? (layout.height > 0 ? 'bottom' : 'top')
  36852. : (layout.width > 0 ? 'left' : 'right');
  36853. if (!isPolar) {
  36854. setLabel(
  36855. el.style, hoverStyle, itemModel, color,
  36856. seriesModel, dataIndex, labelPositionOutside
  36857. );
  36858. }
  36859. if (isZeroOnPolar(layout)) {
  36860. hoverStyle.fill = hoverStyle.stroke = 'none';
  36861. }
  36862. setHoverStyle(el, hoverStyle);
  36863. }
  36864. // In case width or height are too small.
  36865. function getLineWidth(itemModel, rawLayout) {
  36866. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36867. // width or height may be NaN for empty data
  36868. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  36869. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  36870. return Math.min(lineWidth, width, height);
  36871. }
  36872. var LargePath = Path.extend({
  36873. type: 'largeBar',
  36874. shape: {points: []},
  36875. buildPath: function (ctx, shape) {
  36876. // Drawing lines is more efficient than drawing
  36877. // a whole line or drawing rects.
  36878. var points = shape.points;
  36879. var startPoint = this.__startPoint;
  36880. var baseDimIdx = this.__baseDimIdx;
  36881. for (var i = 0; i < points.length; i += 2) {
  36882. startPoint[baseDimIdx] = points[i + baseDimIdx];
  36883. ctx.moveTo(startPoint[0], startPoint[1]);
  36884. ctx.lineTo(points[i], points[i + 1]);
  36885. }
  36886. }
  36887. });
  36888. function createLarge(seriesModel, group, incremental) {
  36889. // TODO support polar
  36890. var data = seriesModel.getData();
  36891. var startPoint = [];
  36892. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36893. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  36894. var largeDataIndices = data.getLayout('largeDataIndices');
  36895. var barWidth = data.getLayout('barWidth');
  36896. var backgroundModel = seriesModel.getModel('backgroundStyle');
  36897. var drawBackground = seriesModel.get('showBackground', true);
  36898. if (drawBackground) {
  36899. var points = data.getLayout('largeBackgroundPoints');
  36900. var backgroundStartPoint = [];
  36901. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  36902. var bgEl = new LargePath({
  36903. shape: {points: points},
  36904. incremental: !!incremental,
  36905. __startPoint: backgroundStartPoint,
  36906. __baseDimIdx: baseDimIdx,
  36907. __largeDataIndices: largeDataIndices,
  36908. __barWidth: barWidth,
  36909. silent: true,
  36910. z2: 0
  36911. });
  36912. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  36913. group.add(bgEl);
  36914. }
  36915. var el = new LargePath({
  36916. shape: {points: data.getLayout('largePoints')},
  36917. incremental: !!incremental,
  36918. __startPoint: startPoint,
  36919. __baseDimIdx: baseDimIdx,
  36920. __largeDataIndices: largeDataIndices,
  36921. __barWidth: barWidth
  36922. });
  36923. group.add(el);
  36924. setLargeStyle(el, seriesModel, data);
  36925. // Enable tooltip and user mouse/touch event handlers.
  36926. el.seriesIndex = seriesModel.seriesIndex;
  36927. if (!seriesModel.get('silent')) {
  36928. el.on('mousedown', largePathUpdateDataIndex);
  36929. el.on('mousemove', largePathUpdateDataIndex);
  36930. }
  36931. }
  36932. // Use throttle to avoid frequently traverse to find dataIndex.
  36933. var largePathUpdateDataIndex = throttle(function (event) {
  36934. var largePath = this;
  36935. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  36936. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  36937. }, 30, false);
  36938. function largePathFindDataIndex(largePath, x, y) {
  36939. var baseDimIdx = largePath.__baseDimIdx;
  36940. var valueDimIdx = 1 - baseDimIdx;
  36941. var points = largePath.shape.points;
  36942. var largeDataIndices = largePath.__largeDataIndices;
  36943. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  36944. var startValueVal = largePath.__startPoint[valueDimIdx];
  36945. _eventPos[0] = x;
  36946. _eventPos[1] = y;
  36947. var pointerBaseVal = _eventPos[baseDimIdx];
  36948. var pointerValueVal = _eventPos[1 - baseDimIdx];
  36949. var baseLowerBound = pointerBaseVal - barWidthHalf;
  36950. var baseUpperBound = pointerBaseVal + barWidthHalf;
  36951. for (var i = 0, len = points.length / 2; i < len; i++) {
  36952. var ii = i * 2;
  36953. var barBaseVal = points[ii + baseDimIdx];
  36954. var barValueVal = points[ii + valueDimIdx];
  36955. if (
  36956. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  36957. && (
  36958. startValueVal <= barValueVal
  36959. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  36960. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  36961. )
  36962. ) {
  36963. return largeDataIndices[i];
  36964. }
  36965. }
  36966. return -1;
  36967. }
  36968. function setLargeStyle(el, seriesModel, data) {
  36969. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36970. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36971. el.useStyle(itemStyle);
  36972. el.style.fill = null;
  36973. el.style.stroke = borderColor;
  36974. el.style.lineWidth = data.getLayout('barWidth');
  36975. }
  36976. function setLargeBackgroundStyle(el, backgroundModel, data) {
  36977. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  36978. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  36979. el.useStyle(itemStyle);
  36980. el.style.fill = null;
  36981. el.style.stroke = borderColor;
  36982. el.style.lineWidth = data.getLayout('barWidth');
  36983. }
  36984. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  36985. var coordLayout;
  36986. var isPolar = coord.type === 'polar';
  36987. if (isPolar) {
  36988. coordLayout = coord.getArea();
  36989. }
  36990. else {
  36991. coordLayout = coord.grid.getRect();
  36992. }
  36993. if (isPolar) {
  36994. return {
  36995. cx: coordLayout.cx,
  36996. cy: coordLayout.cy,
  36997. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  36998. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  36999. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  37000. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  37001. };
  37002. }
  37003. else {
  37004. return {
  37005. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  37006. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  37007. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  37008. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  37009. };
  37010. }
  37011. }
  37012. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  37013. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  37014. return new ElementClz({
  37015. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  37016. silent: true,
  37017. z2: 0
  37018. });
  37019. }
  37020. /*
  37021. * Licensed to the Apache Software Foundation (ASF) under one
  37022. * or more contributor license agreements. See the NOTICE file
  37023. * distributed with this work for additional information
  37024. * regarding copyright ownership. The ASF licenses this file
  37025. * to you under the Apache License, Version 2.0 (the
  37026. * "License"); you may not use this file except in compliance
  37027. * with the License. You may obtain a copy of the License at
  37028. *
  37029. * http://www.apache.org/licenses/LICENSE-2.0
  37030. *
  37031. * Unless required by applicable law or agreed to in writing,
  37032. * software distributed under the License is distributed on an
  37033. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37034. * KIND, either express or implied. See the License for the
  37035. * specific language governing permissions and limitations
  37036. * under the License.
  37037. */
  37038. // In case developer forget to include grid component
  37039. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  37040. // Use higher prority to avoid to be blocked by other overall layout, which do not
  37041. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  37042. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  37043. registerVisual({
  37044. seriesType: 'bar',
  37045. reset: function (seriesModel) {
  37046. // Visual coding for legend
  37047. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  37048. }
  37049. });
  37050. /*
  37051. * Licensed to the Apache Software Foundation (ASF) under one
  37052. * or more contributor license agreements. See the NOTICE file
  37053. * distributed with this work for additional information
  37054. * regarding copyright ownership. The ASF licenses this file
  37055. * to you under the Apache License, Version 2.0 (the
  37056. * "License"); you may not use this file except in compliance
  37057. * with the License. You may obtain a copy of the License at
  37058. *
  37059. * http://www.apache.org/licenses/LICENSE-2.0
  37060. *
  37061. * Unless required by applicable law or agreed to in writing,
  37062. * software distributed under the License is distributed on an
  37063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37064. * KIND, either express or implied. See the License for the
  37065. * specific language governing permissions and limitations
  37066. * under the License.
  37067. */
  37068. /**
  37069. * [Usage]:
  37070. * (1)
  37071. * createListSimply(seriesModel, ['value']);
  37072. * (2)
  37073. * createListSimply(seriesModel, {
  37074. * coordDimensions: ['value'],
  37075. * dimensionsCount: 5
  37076. * });
  37077. *
  37078. * @param {module:echarts/model/Series} seriesModel
  37079. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  37080. * The options in opt, see `echarts/data/helper/createDimensions`
  37081. * @param {Array.<string>} [nameList]
  37082. * @return {module:echarts/data/List}
  37083. */
  37084. var createListSimply = function (seriesModel, opt, nameList) {
  37085. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  37086. var source = seriesModel.getSource();
  37087. var dimensionsInfo = createDimensions(source, opt);
  37088. var list = new List(dimensionsInfo, seriesModel);
  37089. list.initData(source, nameList);
  37090. return list;
  37091. };
  37092. /*
  37093. * Licensed to the Apache Software Foundation (ASF) under one
  37094. * or more contributor license agreements. See the NOTICE file
  37095. * distributed with this work for additional information
  37096. * regarding copyright ownership. The ASF licenses this file
  37097. * to you under the Apache License, Version 2.0 (the
  37098. * "License"); you may not use this file except in compliance
  37099. * with the License. You may obtain a copy of the License at
  37100. *
  37101. * http://www.apache.org/licenses/LICENSE-2.0
  37102. *
  37103. * Unless required by applicable law or agreed to in writing,
  37104. * software distributed under the License is distributed on an
  37105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37106. * KIND, either express or implied. See the License for the
  37107. * specific language governing permissions and limitations
  37108. * under the License.
  37109. */
  37110. /**
  37111. * Data selectable mixin for chart series.
  37112. * To eanble data select, option of series must have `selectedMode`.
  37113. * And each data item will use `selected` to toggle itself selected status
  37114. */
  37115. var dataSelectableMixin = {
  37116. /**
  37117. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  37118. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  37119. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  37120. */
  37121. updateSelectedMap: function (targetList) {
  37122. this._targetList = isArray(targetList) ? targetList.slice() : [];
  37123. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  37124. targetMap.set(target.name, target);
  37125. return targetMap;
  37126. }, createHashMap());
  37127. },
  37128. /**
  37129. * Either name or id should be passed as input here.
  37130. * If both of them are defined, id is used.
  37131. *
  37132. * @param {string|undefined} name name of data
  37133. * @param {number|undefined} id dataIndex of data
  37134. */
  37135. // PENGING If selectedMode is null ?
  37136. select: function (name, id) {
  37137. var target = id != null
  37138. ? this._targetList[id]
  37139. : this._selectTargetMap.get(name);
  37140. var selectedMode = this.get('selectedMode');
  37141. if (selectedMode === 'single') {
  37142. this._selectTargetMap.each(function (target) {
  37143. target.selected = false;
  37144. });
  37145. }
  37146. target && (target.selected = true);
  37147. },
  37148. /**
  37149. * Either name or id should be passed as input here.
  37150. * If both of them are defined, id is used.
  37151. *
  37152. * @param {string|undefined} name name of data
  37153. * @param {number|undefined} id dataIndex of data
  37154. */
  37155. unSelect: function (name, id) {
  37156. var target = id != null
  37157. ? this._targetList[id]
  37158. : this._selectTargetMap.get(name);
  37159. // var selectedMode = this.get('selectedMode');
  37160. // selectedMode !== 'single' && target && (target.selected = false);
  37161. target && (target.selected = false);
  37162. },
  37163. /**
  37164. * Either name or id should be passed as input here.
  37165. * If both of them are defined, id is used.
  37166. *
  37167. * @param {string|undefined} name name of data
  37168. * @param {number|undefined} id dataIndex of data
  37169. */
  37170. toggleSelected: function (name, id) {
  37171. var target = id != null
  37172. ? this._targetList[id]
  37173. : this._selectTargetMap.get(name);
  37174. if (target != null) {
  37175. this[target.selected ? 'unSelect' : 'select'](name, id);
  37176. return target.selected;
  37177. }
  37178. },
  37179. /**
  37180. * Either name or id should be passed as input here.
  37181. * If both of them are defined, id is used.
  37182. *
  37183. * @param {string|undefined} name name of data
  37184. * @param {number|undefined} id dataIndex of data
  37185. */
  37186. isSelected: function (name, id) {
  37187. var target = id != null
  37188. ? this._targetList[id]
  37189. : this._selectTargetMap.get(name);
  37190. return target && target.selected;
  37191. }
  37192. };
  37193. /*
  37194. * Licensed to the Apache Software Foundation (ASF) under one
  37195. * or more contributor license agreements. See the NOTICE file
  37196. * distributed with this work for additional information
  37197. * regarding copyright ownership. The ASF licenses this file
  37198. * to you under the Apache License, Version 2.0 (the
  37199. * "License"); you may not use this file except in compliance
  37200. * with the License. You may obtain a copy of the License at
  37201. *
  37202. * http://www.apache.org/licenses/LICENSE-2.0
  37203. *
  37204. * Unless required by applicable law or agreed to in writing,
  37205. * software distributed under the License is distributed on an
  37206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37207. * KIND, either express or implied. See the License for the
  37208. * specific language governing permissions and limitations
  37209. * under the License.
  37210. */
  37211. /**
  37212. * LegendVisualProvider is an bridge that pick encoded color from data and
  37213. * provide to the legend component.
  37214. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  37215. * @param {Function} getRawData Function to get raw data before filtered.
  37216. */
  37217. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  37218. this.getAllNames = function () {
  37219. var rawData = getRawData();
  37220. // We find the name from the raw data. In case it's filtered by the legend component.
  37221. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  37222. return rawData.mapArray(rawData.getName);
  37223. };
  37224. this.containName = function (name) {
  37225. var rawData = getRawData();
  37226. return rawData.indexOfName(name) >= 0;
  37227. };
  37228. this.indexOfName = function (name) {
  37229. // Only get data when necessary.
  37230. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  37231. // Invoking Series#getData immediately will throw an error.
  37232. var dataWithEncodedVisual = getDataWithEncodedVisual();
  37233. return dataWithEncodedVisual.indexOfName(name);
  37234. };
  37235. this.getItemVisual = function (dataIndex, key) {
  37236. // Get encoded visual properties from final filtered data.
  37237. var dataWithEncodedVisual = getDataWithEncodedVisual();
  37238. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  37239. };
  37240. }
  37241. /*
  37242. * Licensed to the Apache Software Foundation (ASF) under one
  37243. * or more contributor license agreements. See the NOTICE file
  37244. * distributed with this work for additional information
  37245. * regarding copyright ownership. The ASF licenses this file
  37246. * to you under the Apache License, Version 2.0 (the
  37247. * "License"); you may not use this file except in compliance
  37248. * with the License. You may obtain a copy of the License at
  37249. *
  37250. * http://www.apache.org/licenses/LICENSE-2.0
  37251. *
  37252. * Unless required by applicable law or agreed to in writing,
  37253. * software distributed under the License is distributed on an
  37254. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37255. * KIND, either express or implied. See the License for the
  37256. * specific language governing permissions and limitations
  37257. * under the License.
  37258. */
  37259. var PieSeries = extendSeriesModel({
  37260. type: 'series.pie',
  37261. // Overwrite
  37262. init: function (option) {
  37263. PieSeries.superApply(this, 'init', arguments);
  37264. // Enable legend selection for each data item
  37265. // Use a function instead of direct access because data reference may changed
  37266. this.legendVisualProvider = new LegendVisualProvider(
  37267. bind(this.getData, this), bind(this.getRawData, this)
  37268. );
  37269. this.updateSelectedMap(this._createSelectableList());
  37270. this._defaultLabelLine(option);
  37271. },
  37272. // Overwrite
  37273. mergeOption: function (newOption) {
  37274. PieSeries.superCall(this, 'mergeOption', newOption);
  37275. this.updateSelectedMap(this._createSelectableList());
  37276. },
  37277. getInitialData: function (option, ecModel) {
  37278. return createListSimply(this, {
  37279. coordDimensions: ['value'],
  37280. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  37281. });
  37282. },
  37283. _createSelectableList: function () {
  37284. var data = this.getRawData();
  37285. var valueDim = data.mapDimension('value');
  37286. var targetList = [];
  37287. for (var i = 0, len = data.count(); i < len; i++) {
  37288. targetList.push({
  37289. name: data.getName(i),
  37290. value: data.get(valueDim, i),
  37291. selected: retrieveRawAttr(data, i, 'selected')
  37292. });
  37293. }
  37294. return targetList;
  37295. },
  37296. // Overwrite
  37297. getDataParams: function (dataIndex) {
  37298. var data = this.getData();
  37299. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  37300. // FIXME toFixed?
  37301. var valueList = [];
  37302. data.each(data.mapDimension('value'), function (value) {
  37303. valueList.push(value);
  37304. });
  37305. params.percent = getPercentWithPrecision(
  37306. valueList,
  37307. dataIndex,
  37308. data.hostModel.get('percentPrecision')
  37309. );
  37310. params.$vars.push('percent');
  37311. return params;
  37312. },
  37313. _defaultLabelLine: function (option) {
  37314. // Extend labelLine emphasis
  37315. defaultEmphasis(option, 'labelLine', ['show']);
  37316. var labelLineNormalOpt = option.labelLine;
  37317. var labelLineEmphasisOpt = option.emphasis.labelLine;
  37318. // Not show label line if `label.normal.show = false`
  37319. labelLineNormalOpt.show = labelLineNormalOpt.show
  37320. && option.label.show;
  37321. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  37322. && option.emphasis.label.show;
  37323. },
  37324. defaultOption: {
  37325. zlevel: 0,
  37326. z: 2,
  37327. legendHoverLink: true,
  37328. hoverAnimation: true,
  37329. // 默认全局居中
  37330. center: ['50%', '50%'],
  37331. radius: [0, '75%'],
  37332. // 默认顺时针
  37333. clockwise: true,
  37334. startAngle: 90,
  37335. // 最小角度改为0
  37336. minAngle: 0,
  37337. // If the angle of a sector less than `minShowLabelAngle`,
  37338. // the label will not be displayed.
  37339. minShowLabelAngle: 0,
  37340. // 选中时扇区偏移量
  37341. selectedOffset: 10,
  37342. // 高亮扇区偏移量
  37343. hoverOffset: 10,
  37344. // If use strategy to avoid label overlapping
  37345. avoidLabelOverlap: true,
  37346. // 选择模式,默认关闭,可选single,multiple
  37347. // selectedMode: false,
  37348. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  37349. // roseType: null,
  37350. percentPrecision: 2,
  37351. // If still show when all data zero.
  37352. stillShowZeroSum: true,
  37353. // cursor: null,
  37354. left: 0,
  37355. top: 0,
  37356. right: 0,
  37357. bottom: 0,
  37358. width: null,
  37359. height: null,
  37360. label: {
  37361. // If rotate around circle
  37362. rotate: false,
  37363. show: true,
  37364. // 'outer', 'inside', 'center'
  37365. position: 'outer',
  37366. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  37367. alignTo: 'none',
  37368. // Closest distance between label and chart edge.
  37369. // Works only position is 'outer' and alignTo is 'edge'.
  37370. margin: '25%',
  37371. // Works only position is 'outer' and alignTo is not 'edge'.
  37372. bleedMargin: 10,
  37373. // Distance between text and label line.
  37374. distanceToLabelLine: 5
  37375. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37376. // 默认使用全局文本样式,详见TEXTSTYLE
  37377. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  37378. },
  37379. // Enabled when label.normal.position is 'outer'
  37380. labelLine: {
  37381. show: true,
  37382. // 引导线两段中的第一段长度
  37383. length: 15,
  37384. // 引导线两段中的第二段长度
  37385. length2: 15,
  37386. smooth: false,
  37387. lineStyle: {
  37388. // color: 各异,
  37389. width: 1,
  37390. type: 'solid'
  37391. }
  37392. },
  37393. itemStyle: {
  37394. borderWidth: 1
  37395. },
  37396. // Animation type. Valid values: expansion, scale
  37397. animationType: 'expansion',
  37398. // Animation type when update. Valid values: transition, expansion
  37399. animationTypeUpdate: 'transition',
  37400. animationEasing: 'cubicOut'
  37401. }
  37402. });
  37403. mixin(PieSeries, dataSelectableMixin);
  37404. /*
  37405. * Licensed to the Apache Software Foundation (ASF) under one
  37406. * or more contributor license agreements. See the NOTICE file
  37407. * distributed with this work for additional information
  37408. * regarding copyright ownership. The ASF licenses this file
  37409. * to you under the Apache License, Version 2.0 (the
  37410. * "License"); you may not use this file except in compliance
  37411. * with the License. You may obtain a copy of the License at
  37412. *
  37413. * http://www.apache.org/licenses/LICENSE-2.0
  37414. *
  37415. * Unless required by applicable law or agreed to in writing,
  37416. * software distributed under the License is distributed on an
  37417. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37418. * KIND, either express or implied. See the License for the
  37419. * specific language governing permissions and limitations
  37420. * under the License.
  37421. */
  37422. /**
  37423. * @param {module:echarts/model/Series} seriesModel
  37424. * @param {boolean} hasAnimation
  37425. * @inner
  37426. */
  37427. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  37428. var data = seriesModel.getData();
  37429. var dataIndex = this.dataIndex;
  37430. var name = data.getName(dataIndex);
  37431. var selectedOffset = seriesModel.get('selectedOffset');
  37432. api.dispatchAction({
  37433. type: 'pieToggleSelect',
  37434. from: uid,
  37435. name: name,
  37436. seriesId: seriesModel.id
  37437. });
  37438. data.each(function (idx) {
  37439. toggleItemSelected(
  37440. data.getItemGraphicEl(idx),
  37441. data.getItemLayout(idx),
  37442. seriesModel.isSelected(data.getName(idx)),
  37443. selectedOffset,
  37444. hasAnimation
  37445. );
  37446. });
  37447. }
  37448. /**
  37449. * @param {module:zrender/graphic/Sector} el
  37450. * @param {Object} layout
  37451. * @param {boolean} isSelected
  37452. * @param {number} selectedOffset
  37453. * @param {boolean} hasAnimation
  37454. * @inner
  37455. */
  37456. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  37457. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37458. var dx = Math.cos(midAngle);
  37459. var dy = Math.sin(midAngle);
  37460. var offset = isSelected ? selectedOffset : 0;
  37461. var position = [dx * offset, dy * offset];
  37462. hasAnimation
  37463. // animateTo will stop revious animation like update transition
  37464. ? el.animate()
  37465. .when(200, {
  37466. position: position
  37467. })
  37468. .start('bounceOut')
  37469. : el.attr('position', position);
  37470. }
  37471. /**
  37472. * Piece of pie including Sector, Label, LabelLine
  37473. * @constructor
  37474. * @extends {module:zrender/graphic/Group}
  37475. */
  37476. function PiePiece(data, idx) {
  37477. Group.call(this);
  37478. var sector = new Sector({
  37479. z2: 2
  37480. });
  37481. var polyline = new Polyline();
  37482. var text = new Text();
  37483. this.add(sector);
  37484. this.add(polyline);
  37485. this.add(text);
  37486. this.updateData(data, idx, true);
  37487. }
  37488. var piePieceProto = PiePiece.prototype;
  37489. piePieceProto.updateData = function (data, idx, firstCreate) {
  37490. var sector = this.childAt(0);
  37491. var labelLine = this.childAt(1);
  37492. var labelText = this.childAt(2);
  37493. var seriesModel = data.hostModel;
  37494. var itemModel = data.getItemModel(idx);
  37495. var layout = data.getItemLayout(idx);
  37496. var sectorShape = extend({}, layout);
  37497. sectorShape.label = null;
  37498. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  37499. if (firstCreate) {
  37500. sector.setShape(sectorShape);
  37501. var animationType = seriesModel.getShallow('animationType');
  37502. if (animationType === 'scale') {
  37503. sector.shape.r = layout.r0;
  37504. initProps(sector, {
  37505. shape: {
  37506. r: layout.r
  37507. }
  37508. }, seriesModel, idx);
  37509. }
  37510. // Expansion
  37511. else {
  37512. sector.shape.endAngle = layout.startAngle;
  37513. updateProps(sector, {
  37514. shape: {
  37515. endAngle: layout.endAngle
  37516. }
  37517. }, seriesModel, idx);
  37518. }
  37519. }
  37520. else {
  37521. if (animationTypeUpdate === 'expansion') {
  37522. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  37523. sector.setShape(sectorShape);
  37524. }
  37525. else {
  37526. // Transition animation from the old shape
  37527. updateProps(sector, {
  37528. shape: sectorShape
  37529. }, seriesModel, idx);
  37530. }
  37531. }
  37532. // Update common style
  37533. var visualColor = data.getItemVisual(idx, 'color');
  37534. sector.useStyle(
  37535. defaults(
  37536. {
  37537. lineJoin: 'bevel',
  37538. fill: visualColor
  37539. },
  37540. itemModel.getModel('itemStyle').getItemStyle()
  37541. )
  37542. );
  37543. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  37544. var cursorStyle = itemModel.getShallow('cursor');
  37545. cursorStyle && sector.attr('cursor', cursorStyle);
  37546. // Toggle selected
  37547. toggleItemSelected(
  37548. this,
  37549. data.getItemLayout(idx),
  37550. seriesModel.isSelected(data.getName(idx)),
  37551. seriesModel.get('selectedOffset'),
  37552. seriesModel.get('animation')
  37553. );
  37554. // Label and text animation should be applied only for transition type animation when update
  37555. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  37556. this._updateLabel(data, idx, withAnimation);
  37557. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  37558. ? function (fromState, toState) {
  37559. if (toState === 'emphasis') {
  37560. labelLine.ignore = labelLine.hoverIgnore;
  37561. labelText.ignore = labelText.hoverIgnore;
  37562. // Sector may has animation of updating data. Force to move to the last frame
  37563. // Or it may stopped on the wrong shape
  37564. sector.stopAnimation(true);
  37565. sector.animateTo({
  37566. shape: {
  37567. r: layout.r + seriesModel.get('hoverOffset')
  37568. }
  37569. }, 300, 'elasticOut');
  37570. }
  37571. else {
  37572. labelLine.ignore = labelLine.normalIgnore;
  37573. labelText.ignore = labelText.normalIgnore;
  37574. sector.stopAnimation(true);
  37575. sector.animateTo({
  37576. shape: {
  37577. r: layout.r
  37578. }
  37579. }, 300, 'elasticOut');
  37580. }
  37581. }
  37582. : null;
  37583. setHoverStyle(this);
  37584. };
  37585. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  37586. var labelLine = this.childAt(1);
  37587. var labelText = this.childAt(2);
  37588. var seriesModel = data.hostModel;
  37589. var itemModel = data.getItemModel(idx);
  37590. var layout = data.getItemLayout(idx);
  37591. var labelLayout = layout.label;
  37592. var visualColor = data.getItemVisual(idx, 'color');
  37593. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  37594. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  37595. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  37596. return;
  37597. }
  37598. var targetLineShape = {
  37599. points: labelLayout.linePoints || [
  37600. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  37601. ]
  37602. };
  37603. var targetTextStyle = {
  37604. x: labelLayout.x,
  37605. y: labelLayout.y
  37606. };
  37607. if (withAnimation) {
  37608. updateProps(labelLine, {
  37609. shape: targetLineShape
  37610. }, seriesModel, idx);
  37611. updateProps(labelText, {
  37612. style: targetTextStyle
  37613. }, seriesModel, idx);
  37614. }
  37615. else {
  37616. labelLine.attr({
  37617. shape: targetLineShape
  37618. });
  37619. labelText.attr({
  37620. style: targetTextStyle
  37621. });
  37622. }
  37623. labelText.attr({
  37624. rotation: labelLayout.rotation,
  37625. origin: [labelLayout.x, labelLayout.y],
  37626. z2: 10
  37627. });
  37628. var labelModel = itemModel.getModel('label');
  37629. var labelHoverModel = itemModel.getModel('emphasis.label');
  37630. var labelLineModel = itemModel.getModel('labelLine');
  37631. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  37632. var visualColor = data.getItemVisual(idx, 'color');
  37633. setLabelStyle(
  37634. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  37635. {
  37636. labelFetcher: data.hostModel,
  37637. labelDataIndex: idx,
  37638. defaultText: labelLayout.text,
  37639. autoColor: visualColor,
  37640. useInsideStyle: !!labelLayout.inside
  37641. },
  37642. {
  37643. textAlign: labelLayout.textAlign,
  37644. textVerticalAlign: labelLayout.verticalAlign,
  37645. opacity: data.getItemVisual(idx, 'opacity')
  37646. }
  37647. );
  37648. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  37649. labelText.hoverIgnore = !labelHoverModel.get('show');
  37650. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  37651. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  37652. // Default use item visual color
  37653. labelLine.setStyle({
  37654. stroke: visualColor,
  37655. opacity: data.getItemVisual(idx, 'opacity')
  37656. });
  37657. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  37658. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  37659. var smooth = labelLineModel.get('smooth');
  37660. if (smooth && smooth === true) {
  37661. smooth = 0.4;
  37662. }
  37663. labelLine.setShape({
  37664. smooth: smooth
  37665. });
  37666. };
  37667. inherits(PiePiece, Group);
  37668. // Pie view
  37669. var PieView = Chart.extend({
  37670. type: 'pie',
  37671. init: function () {
  37672. var sectorGroup = new Group();
  37673. this._sectorGroup = sectorGroup;
  37674. },
  37675. render: function (seriesModel, ecModel, api, payload) {
  37676. if (payload && (payload.from === this.uid)) {
  37677. return;
  37678. }
  37679. var data = seriesModel.getData();
  37680. var oldData = this._data;
  37681. var group = this.group;
  37682. var hasAnimation = ecModel.get('animation');
  37683. var isFirstRender = !oldData;
  37684. var animationType = seriesModel.get('animationType');
  37685. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  37686. var onSectorClick = curry(
  37687. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  37688. );
  37689. var selectedMode = seriesModel.get('selectedMode');
  37690. data.diff(oldData)
  37691. .add(function (idx) {
  37692. var piePiece = new PiePiece(data, idx);
  37693. // Default expansion animation
  37694. if (isFirstRender && animationType !== 'scale') {
  37695. piePiece.eachChild(function (child) {
  37696. child.stopAnimation(true);
  37697. });
  37698. }
  37699. selectedMode && piePiece.on('click', onSectorClick);
  37700. data.setItemGraphicEl(idx, piePiece);
  37701. group.add(piePiece);
  37702. })
  37703. .update(function (newIdx, oldIdx) {
  37704. var piePiece = oldData.getItemGraphicEl(oldIdx);
  37705. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  37706. piePiece.eachChild(function (child) {
  37707. child.stopAnimation(true);
  37708. });
  37709. }
  37710. piePiece.updateData(data, newIdx);
  37711. piePiece.off('click');
  37712. selectedMode && piePiece.on('click', onSectorClick);
  37713. group.add(piePiece);
  37714. data.setItemGraphicEl(newIdx, piePiece);
  37715. })
  37716. .remove(function (idx) {
  37717. var piePiece = oldData.getItemGraphicEl(idx);
  37718. group.remove(piePiece);
  37719. })
  37720. .execute();
  37721. if (
  37722. hasAnimation && data.count() > 0
  37723. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  37724. ) {
  37725. var shape = data.getItemLayout(0);
  37726. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  37727. shape = data.getItemLayout(s);
  37728. }
  37729. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  37730. var removeClipPath = bind(group.removeClipPath, group);
  37731. group.setClipPath(this._createClipPath(
  37732. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  37733. ));
  37734. }
  37735. else {
  37736. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  37737. group.removeClipPath();
  37738. }
  37739. this._data = data;
  37740. },
  37741. dispose: function () {},
  37742. _createClipPath: function (
  37743. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  37744. ) {
  37745. var clipPath = new Sector({
  37746. shape: {
  37747. cx: cx,
  37748. cy: cy,
  37749. r0: 0,
  37750. r: r,
  37751. startAngle: startAngle,
  37752. endAngle: startAngle,
  37753. clockwise: clockwise
  37754. }
  37755. });
  37756. var initOrUpdate = isFirstRender ? initProps : updateProps;
  37757. initOrUpdate(clipPath, {
  37758. shape: {
  37759. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  37760. }
  37761. }, seriesModel, cb);
  37762. return clipPath;
  37763. },
  37764. /**
  37765. * @implement
  37766. */
  37767. containPoint: function (point, seriesModel) {
  37768. var data = seriesModel.getData();
  37769. var itemLayout = data.getItemLayout(0);
  37770. if (itemLayout) {
  37771. var dx = point[0] - itemLayout.cx;
  37772. var dy = point[1] - itemLayout.cy;
  37773. var radius = Math.sqrt(dx * dx + dy * dy);
  37774. return radius <= itemLayout.r && radius >= itemLayout.r0;
  37775. }
  37776. }
  37777. });
  37778. /*
  37779. * Licensed to the Apache Software Foundation (ASF) under one
  37780. * or more contributor license agreements. See the NOTICE file
  37781. * distributed with this work for additional information
  37782. * regarding copyright ownership. The ASF licenses this file
  37783. * to you under the Apache License, Version 2.0 (the
  37784. * "License"); you may not use this file except in compliance
  37785. * with the License. You may obtain a copy of the License at
  37786. *
  37787. * http://www.apache.org/licenses/LICENSE-2.0
  37788. *
  37789. * Unless required by applicable law or agreed to in writing,
  37790. * software distributed under the License is distributed on an
  37791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37792. * KIND, either express or implied. See the License for the
  37793. * specific language governing permissions and limitations
  37794. * under the License.
  37795. */
  37796. var createDataSelectAction = function (seriesType, actionInfos) {
  37797. each$1(actionInfos, function (actionInfo) {
  37798. actionInfo.update = 'updateView';
  37799. /**
  37800. * @payload
  37801. * @property {string} seriesName
  37802. * @property {string} name
  37803. */
  37804. registerAction(actionInfo, function (payload, ecModel) {
  37805. var selected = {};
  37806. ecModel.eachComponent(
  37807. {mainType: 'series', subType: seriesType, query: payload},
  37808. function (seriesModel) {
  37809. if (seriesModel[actionInfo.method]) {
  37810. seriesModel[actionInfo.method](
  37811. payload.name,
  37812. payload.dataIndex
  37813. );
  37814. }
  37815. var data = seriesModel.getData();
  37816. // Create selected map
  37817. data.each(function (idx) {
  37818. var name = data.getName(idx);
  37819. selected[name] = seriesModel.isSelected(name)
  37820. || false;
  37821. });
  37822. }
  37823. );
  37824. return {
  37825. name: payload.name,
  37826. selected: selected,
  37827. seriesId: payload.seriesId
  37828. };
  37829. });
  37830. });
  37831. };
  37832. /*
  37833. * Licensed to the Apache Software Foundation (ASF) under one
  37834. * or more contributor license agreements. See the NOTICE file
  37835. * distributed with this work for additional information
  37836. * regarding copyright ownership. The ASF licenses this file
  37837. * to you under the Apache License, Version 2.0 (the
  37838. * "License"); you may not use this file except in compliance
  37839. * with the License. You may obtain a copy of the License at
  37840. *
  37841. * http://www.apache.org/licenses/LICENSE-2.0
  37842. *
  37843. * Unless required by applicable law or agreed to in writing,
  37844. * software distributed under the License is distributed on an
  37845. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37846. * KIND, either express or implied. See the License for the
  37847. * specific language governing permissions and limitations
  37848. * under the License.
  37849. */
  37850. // Pick color from palette for each data item.
  37851. // Applicable for charts that require applying color palette
  37852. // in data level (like pie, funnel, chord).
  37853. var dataColor = function (seriesType) {
  37854. return {
  37855. getTargetSeries: function (ecModel) {
  37856. // Pie and funnel may use diferrent scope
  37857. var paletteScope = {};
  37858. var seiresModelMap = createHashMap();
  37859. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37860. seriesModel.__paletteScope = paletteScope;
  37861. seiresModelMap.set(seriesModel.uid, seriesModel);
  37862. });
  37863. return seiresModelMap;
  37864. },
  37865. reset: function (seriesModel, ecModel) {
  37866. var dataAll = seriesModel.getRawData();
  37867. var idxMap = {};
  37868. var data = seriesModel.getData();
  37869. data.each(function (idx) {
  37870. var rawIdx = data.getRawIndex(idx);
  37871. idxMap[rawIdx] = idx;
  37872. });
  37873. dataAll.each(function (rawIdx) {
  37874. var filteredIdx = idxMap[rawIdx];
  37875. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37876. var singleDataColor = filteredIdx != null
  37877. && data.getItemVisual(filteredIdx, 'color', true);
  37878. var singleDataBorderColor = filteredIdx != null
  37879. && data.getItemVisual(filteredIdx, 'borderColor', true);
  37880. var itemModel;
  37881. if (!singleDataColor || !singleDataBorderColor) {
  37882. // FIXME Performance
  37883. itemModel = dataAll.getItemModel(rawIdx);
  37884. }
  37885. if (!singleDataColor) {
  37886. var color = itemModel.get('itemStyle.color')
  37887. || seriesModel.getColorFromPalette(
  37888. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37889. dataAll.count()
  37890. );
  37891. // Data is not filtered
  37892. if (filteredIdx != null) {
  37893. data.setItemVisual(filteredIdx, 'color', color);
  37894. }
  37895. }
  37896. if (!singleDataBorderColor) {
  37897. var borderColor = itemModel.get('itemStyle.borderColor');
  37898. // Data is not filtered
  37899. if (filteredIdx != null) {
  37900. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  37901. }
  37902. }
  37903. });
  37904. }
  37905. };
  37906. };
  37907. /*
  37908. * Licensed to the Apache Software Foundation (ASF) under one
  37909. * or more contributor license agreements. See the NOTICE file
  37910. * distributed with this work for additional information
  37911. * regarding copyright ownership. The ASF licenses this file
  37912. * to you under the Apache License, Version 2.0 (the
  37913. * "License"); you may not use this file except in compliance
  37914. * with the License. You may obtain a copy of the License at
  37915. *
  37916. * http://www.apache.org/licenses/LICENSE-2.0
  37917. *
  37918. * Unless required by applicable law or agreed to in writing,
  37919. * software distributed under the License is distributed on an
  37920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37921. * KIND, either express or implied. See the License for the
  37922. * specific language governing permissions and limitations
  37923. * under the License.
  37924. */
  37925. // FIXME emphasis label position is not same with normal label position
  37926. var RADIAN$1 = Math.PI / 180;
  37927. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  37928. list.sort(function (a, b) {
  37929. return a.y - b.y;
  37930. });
  37931. function shiftDown(start, end, delta, dir) {
  37932. for (var j = start; j < end; j++) {
  37933. if (list[j].y + delta > viewTop + viewHeight) {
  37934. break;
  37935. }
  37936. list[j].y += delta;
  37937. if (j > start
  37938. && j + 1 < end
  37939. && list[j + 1].y > list[j].y + list[j].height
  37940. ) {
  37941. shiftUp(j, delta / 2);
  37942. return;
  37943. }
  37944. }
  37945. shiftUp(end - 1, delta / 2);
  37946. }
  37947. function shiftUp(end, delta) {
  37948. for (var j = end; j >= 0; j--) {
  37949. if (list[j].y - delta < viewTop) {
  37950. break;
  37951. }
  37952. list[j].y -= delta;
  37953. if (j > 0
  37954. && list[j].y > list[j - 1].y + list[j - 1].height
  37955. ) {
  37956. break;
  37957. }
  37958. }
  37959. }
  37960. function changeX(list, isDownList, cx, cy, r, dir) {
  37961. var lastDeltaX = dir > 0
  37962. ? isDownList // right-side
  37963. ? Number.MAX_VALUE // down
  37964. : 0 // up
  37965. : isDownList // left-side
  37966. ? Number.MAX_VALUE // down
  37967. : 0; // up
  37968. for (var i = 0, l = list.length; i < l; i++) {
  37969. if (list[i].labelAlignTo !== 'none') {
  37970. continue;
  37971. }
  37972. var deltaY = Math.abs(list[i].y - cy);
  37973. var length = list[i].len;
  37974. var length2 = list[i].len2;
  37975. var deltaX = (deltaY < r + length)
  37976. ? Math.sqrt(
  37977. (r + length + length2) * (r + length + length2)
  37978. - deltaY * deltaY
  37979. )
  37980. : Math.abs(list[i].x - cx);
  37981. if (isDownList && deltaX >= lastDeltaX) {
  37982. // right-down, left-down
  37983. deltaX = lastDeltaX - 10;
  37984. }
  37985. if (!isDownList && deltaX <= lastDeltaX) {
  37986. // right-up, left-up
  37987. deltaX = lastDeltaX + 10;
  37988. }
  37989. list[i].x = cx + deltaX * dir;
  37990. lastDeltaX = deltaX;
  37991. }
  37992. }
  37993. var lastY = 0;
  37994. var delta;
  37995. var len = list.length;
  37996. var upList = [];
  37997. var downList = [];
  37998. for (var i = 0; i < len; i++) {
  37999. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  38000. var dx = list[i].x - farthestX;
  38001. list[i].linePoints[1][0] += dx;
  38002. list[i].x = farthestX;
  38003. }
  38004. delta = list[i].y - lastY;
  38005. if (delta < 0) {
  38006. shiftDown(i, len, -delta, dir);
  38007. }
  38008. lastY = list[i].y + list[i].height;
  38009. }
  38010. if (viewHeight - lastY < 0) {
  38011. shiftUp(len - 1, lastY - viewHeight);
  38012. }
  38013. for (var i = 0; i < len; i++) {
  38014. if (list[i].y >= cy) {
  38015. downList.push(list[i]);
  38016. }
  38017. else {
  38018. upList.push(list[i]);
  38019. }
  38020. }
  38021. changeX(upList, false, cx, cy, r, dir);
  38022. changeX(downList, true, cx, cy, r, dir);
  38023. }
  38024. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  38025. var leftList = [];
  38026. var rightList = [];
  38027. var leftmostX = Number.MAX_VALUE;
  38028. var rightmostX = -Number.MAX_VALUE;
  38029. for (var i = 0; i < labelLayoutList.length; i++) {
  38030. if (isPositionCenter(labelLayoutList[i])) {
  38031. continue;
  38032. }
  38033. if (labelLayoutList[i].x < cx) {
  38034. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  38035. leftList.push(labelLayoutList[i]);
  38036. }
  38037. else {
  38038. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  38039. rightList.push(labelLayoutList[i]);
  38040. }
  38041. }
  38042. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  38043. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  38044. for (var i = 0; i < labelLayoutList.length; i++) {
  38045. var layout = labelLayoutList[i];
  38046. if (isPositionCenter(layout)) {
  38047. continue;
  38048. }
  38049. var linePoints = layout.linePoints;
  38050. if (linePoints) {
  38051. var isAlignToEdge = layout.labelAlignTo === 'edge';
  38052. var realTextWidth = layout.textRect.width;
  38053. var targetTextWidth;
  38054. if (isAlignToEdge) {
  38055. if (layout.x < cx) {
  38056. targetTextWidth = linePoints[2][0] - layout.labelDistance
  38057. - viewLeft - layout.labelMargin;
  38058. }
  38059. else {
  38060. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  38061. - linePoints[2][0] - layout.labelDistance;
  38062. }
  38063. }
  38064. else {
  38065. if (layout.x < cx) {
  38066. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  38067. }
  38068. else {
  38069. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  38070. }
  38071. }
  38072. if (targetTextWidth < layout.textRect.width) {
  38073. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  38074. if (layout.labelAlignTo === 'edge') {
  38075. realTextWidth = getWidth(layout.text, layout.font);
  38076. }
  38077. }
  38078. var dist = linePoints[1][0] - linePoints[2][0];
  38079. if (isAlignToEdge) {
  38080. if (layout.x < cx) {
  38081. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  38082. }
  38083. else {
  38084. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  38085. - realTextWidth - layout.labelDistance;
  38086. }
  38087. }
  38088. else {
  38089. if (layout.x < cx) {
  38090. linePoints[2][0] = layout.x + layout.labelDistance;
  38091. }
  38092. else {
  38093. linePoints[2][0] = layout.x - layout.labelDistance;
  38094. }
  38095. linePoints[1][0] = linePoints[2][0] + dist;
  38096. }
  38097. linePoints[1][1] = linePoints[2][1] = layout.y;
  38098. }
  38099. }
  38100. }
  38101. function isPositionCenter(layout) {
  38102. // Not change x for center label
  38103. return layout.position === 'center';
  38104. }
  38105. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  38106. var data = seriesModel.getData();
  38107. var labelLayoutList = [];
  38108. var cx;
  38109. var cy;
  38110. var hasLabelRotate = false;
  38111. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  38112. data.each(function (idx) {
  38113. var layout = data.getItemLayout(idx);
  38114. var itemModel = data.getItemModel(idx);
  38115. var labelModel = itemModel.getModel('label');
  38116. // Use position in normal or emphasis
  38117. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  38118. var labelDistance = labelModel.get('distanceToLabelLine');
  38119. var labelAlignTo = labelModel.get('alignTo');
  38120. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  38121. var bleedMargin = labelModel.get('bleedMargin');
  38122. var font = labelModel.getFont();
  38123. var labelLineModel = itemModel.getModel('labelLine');
  38124. var labelLineLen = labelLineModel.get('length');
  38125. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  38126. var labelLineLen2 = labelLineModel.get('length2');
  38127. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  38128. if (layout.angle < minShowLabelRadian) {
  38129. return;
  38130. }
  38131. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38132. var dx = Math.cos(midAngle);
  38133. var dy = Math.sin(midAngle);
  38134. var textX;
  38135. var textY;
  38136. var linePoints;
  38137. var textAlign;
  38138. cx = layout.cx;
  38139. cy = layout.cy;
  38140. var text = seriesModel.getFormattedLabel(idx, 'normal')
  38141. || data.getName(idx);
  38142. var textRect = getBoundingRect(
  38143. text, font, textAlign, 'top'
  38144. );
  38145. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  38146. if (labelPosition === 'center') {
  38147. textX = layout.cx;
  38148. textY = layout.cy;
  38149. textAlign = 'center';
  38150. }
  38151. else {
  38152. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  38153. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  38154. textX = x1 + dx * 3;
  38155. textY = y1 + dy * 3;
  38156. if (!isLabelInside) {
  38157. // For roseType
  38158. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  38159. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  38160. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  38161. var y3 = y2;
  38162. if (labelAlignTo === 'edge') {
  38163. // Adjust textX because text align of edge is opposite
  38164. textX = dx < 0
  38165. ? viewLeft + labelMargin
  38166. : viewLeft + viewWidth - labelMargin;
  38167. }
  38168. else {
  38169. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  38170. }
  38171. textY = y3;
  38172. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  38173. }
  38174. textAlign = isLabelInside
  38175. ? 'center'
  38176. : (labelAlignTo === 'edge'
  38177. ? (dx > 0 ? 'right' : 'left')
  38178. : (dx > 0 ? 'left' : 'right'));
  38179. }
  38180. var labelRotate;
  38181. var rotate = labelModel.get('rotate');
  38182. if (typeof rotate === 'number') {
  38183. labelRotate = rotate * (Math.PI / 180);
  38184. }
  38185. else {
  38186. labelRotate = rotate
  38187. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  38188. : 0;
  38189. }
  38190. hasLabelRotate = !!labelRotate;
  38191. layout.label = {
  38192. x: textX,
  38193. y: textY,
  38194. position: labelPosition,
  38195. height: textRect.height,
  38196. len: labelLineLen,
  38197. len2: labelLineLen2,
  38198. linePoints: linePoints,
  38199. textAlign: textAlign,
  38200. verticalAlign: 'middle',
  38201. rotation: labelRotate,
  38202. inside: isLabelInside,
  38203. labelDistance: labelDistance,
  38204. labelAlignTo: labelAlignTo,
  38205. labelMargin: labelMargin,
  38206. bleedMargin: bleedMargin,
  38207. textRect: textRect,
  38208. text: text,
  38209. font: font
  38210. };
  38211. // Not layout the inside label
  38212. if (!isLabelInside) {
  38213. labelLayoutList.push(layout.label);
  38214. }
  38215. });
  38216. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  38217. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  38218. }
  38219. };
  38220. /*
  38221. * Licensed to the Apache Software Foundation (ASF) under one
  38222. * or more contributor license agreements. See the NOTICE file
  38223. * distributed with this work for additional information
  38224. * regarding copyright ownership. The ASF licenses this file
  38225. * to you under the Apache License, Version 2.0 (the
  38226. * "License"); you may not use this file except in compliance
  38227. * with the License. You may obtain a copy of the License at
  38228. *
  38229. * http://www.apache.org/licenses/LICENSE-2.0
  38230. *
  38231. * Unless required by applicable law or agreed to in writing,
  38232. * software distributed under the License is distributed on an
  38233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38234. * KIND, either express or implied. See the License for the
  38235. * specific language governing permissions and limitations
  38236. * under the License.
  38237. */
  38238. var PI2$4 = Math.PI * 2;
  38239. var RADIAN = Math.PI / 180;
  38240. function getViewRect(seriesModel, api) {
  38241. return getLayoutRect(
  38242. seriesModel.getBoxLayoutParams(), {
  38243. width: api.getWidth(),
  38244. height: api.getHeight()
  38245. }
  38246. );
  38247. }
  38248. var pieLayout = function (seriesType, ecModel, api, payload) {
  38249. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  38250. var data = seriesModel.getData();
  38251. var valueDim = data.mapDimension('value');
  38252. var viewRect = getViewRect(seriesModel, api);
  38253. var center = seriesModel.get('center');
  38254. var radius = seriesModel.get('radius');
  38255. if (!isArray(radius)) {
  38256. radius = [0, radius];
  38257. }
  38258. if (!isArray(center)) {
  38259. center = [center, center];
  38260. }
  38261. var width = parsePercent$1(viewRect.width, api.getWidth());
  38262. var height = parsePercent$1(viewRect.height, api.getHeight());
  38263. var size = Math.min(width, height);
  38264. var cx = parsePercent$1(center[0], width) + viewRect.x;
  38265. var cy = parsePercent$1(center[1], height) + viewRect.y;
  38266. var r0 = parsePercent$1(radius[0], size / 2);
  38267. var r = parsePercent$1(radius[1], size / 2);
  38268. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  38269. var minAngle = seriesModel.get('minAngle') * RADIAN;
  38270. var validDataCount = 0;
  38271. data.each(valueDim, function (value) {
  38272. !isNaN(value) && validDataCount++;
  38273. });
  38274. var sum = data.getSum(valueDim);
  38275. // Sum may be 0
  38276. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  38277. var clockwise = seriesModel.get('clockwise');
  38278. var roseType = seriesModel.get('roseType');
  38279. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  38280. // [0...max]
  38281. var extent = data.getDataExtent(valueDim);
  38282. extent[0] = 0;
  38283. // In the case some sector angle is smaller than minAngle
  38284. var restAngle = PI2$4;
  38285. var valueSumLargerThanMinAngle = 0;
  38286. var currentAngle = startAngle;
  38287. var dir = clockwise ? 1 : -1;
  38288. data.each(valueDim, function (value, idx) {
  38289. var angle;
  38290. if (isNaN(value)) {
  38291. data.setItemLayout(idx, {
  38292. angle: NaN,
  38293. startAngle: NaN,
  38294. endAngle: NaN,
  38295. clockwise: clockwise,
  38296. cx: cx,
  38297. cy: cy,
  38298. r0: r0,
  38299. r: roseType
  38300. ? NaN
  38301. : r,
  38302. viewRect: viewRect
  38303. });
  38304. return;
  38305. }
  38306. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  38307. if (roseType !== 'area') {
  38308. angle = (sum === 0 && stillShowZeroSum)
  38309. ? unitRadian : (value * unitRadian);
  38310. }
  38311. else {
  38312. angle = PI2$4 / validDataCount;
  38313. }
  38314. if (angle < minAngle) {
  38315. angle = minAngle;
  38316. restAngle -= minAngle;
  38317. }
  38318. else {
  38319. valueSumLargerThanMinAngle += value;
  38320. }
  38321. var endAngle = currentAngle + dir * angle;
  38322. data.setItemLayout(idx, {
  38323. angle: angle,
  38324. startAngle: currentAngle,
  38325. endAngle: endAngle,
  38326. clockwise: clockwise,
  38327. cx: cx,
  38328. cy: cy,
  38329. r0: r0,
  38330. r: roseType
  38331. ? linearMap(value, extent, [r0, r])
  38332. : r,
  38333. viewRect: viewRect
  38334. });
  38335. currentAngle = endAngle;
  38336. });
  38337. // Some sector is constrained by minAngle
  38338. // Rest sectors needs recalculate angle
  38339. if (restAngle < PI2$4 && validDataCount) {
  38340. // Average the angle if rest angle is not enough after all angles is
  38341. // Constrained by minAngle
  38342. if (restAngle <= 1e-3) {
  38343. var angle = PI2$4 / validDataCount;
  38344. data.each(valueDim, function (value, idx) {
  38345. if (!isNaN(value)) {
  38346. var layout = data.getItemLayout(idx);
  38347. layout.angle = angle;
  38348. layout.startAngle = startAngle + dir * idx * angle;
  38349. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  38350. }
  38351. });
  38352. }
  38353. else {
  38354. unitRadian = restAngle / valueSumLargerThanMinAngle;
  38355. currentAngle = startAngle;
  38356. data.each(valueDim, function (value, idx) {
  38357. if (!isNaN(value)) {
  38358. var layout = data.getItemLayout(idx);
  38359. var angle = layout.angle === minAngle
  38360. ? minAngle : value * unitRadian;
  38361. layout.startAngle = currentAngle;
  38362. layout.endAngle = currentAngle + dir * angle;
  38363. currentAngle += dir * angle;
  38364. }
  38365. });
  38366. }
  38367. }
  38368. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  38369. });
  38370. };
  38371. /*
  38372. * Licensed to the Apache Software Foundation (ASF) under one
  38373. * or more contributor license agreements. See the NOTICE file
  38374. * distributed with this work for additional information
  38375. * regarding copyright ownership. The ASF licenses this file
  38376. * to you under the Apache License, Version 2.0 (the
  38377. * "License"); you may not use this file except in compliance
  38378. * with the License. You may obtain a copy of the License at
  38379. *
  38380. * http://www.apache.org/licenses/LICENSE-2.0
  38381. *
  38382. * Unless required by applicable law or agreed to in writing,
  38383. * software distributed under the License is distributed on an
  38384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38385. * KIND, either express or implied. See the License for the
  38386. * specific language governing permissions and limitations
  38387. * under the License.
  38388. */
  38389. var dataFilter = function (seriesType) {
  38390. return {
  38391. seriesType: seriesType,
  38392. reset: function (seriesModel, ecModel) {
  38393. var legendModels = ecModel.findComponents({
  38394. mainType: 'legend'
  38395. });
  38396. if (!legendModels || !legendModels.length) {
  38397. return;
  38398. }
  38399. var data = seriesModel.getData();
  38400. data.filterSelf(function (idx) {
  38401. var name = data.getName(idx);
  38402. // If in any legend component the status is not selected.
  38403. for (var i = 0; i < legendModels.length; i++) {
  38404. if (!legendModels[i].isSelected(name)) {
  38405. return false;
  38406. }
  38407. }
  38408. return true;
  38409. });
  38410. }
  38411. };
  38412. };
  38413. /*
  38414. * Licensed to the Apache Software Foundation (ASF) under one
  38415. * or more contributor license agreements. See the NOTICE file
  38416. * distributed with this work for additional information
  38417. * regarding copyright ownership. The ASF licenses this file
  38418. * to you under the Apache License, Version 2.0 (the
  38419. * "License"); you may not use this file except in compliance
  38420. * with the License. You may obtain a copy of the License at
  38421. *
  38422. * http://www.apache.org/licenses/LICENSE-2.0
  38423. *
  38424. * Unless required by applicable law or agreed to in writing,
  38425. * software distributed under the License is distributed on an
  38426. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38427. * KIND, either express or implied. See the License for the
  38428. * specific language governing permissions and limitations
  38429. * under the License.
  38430. */
  38431. createDataSelectAction('pie', [{
  38432. type: 'pieToggleSelect',
  38433. event: 'pieselectchanged',
  38434. method: 'toggleSelected'
  38435. }, {
  38436. type: 'pieSelect',
  38437. event: 'pieselected',
  38438. method: 'select'
  38439. }, {
  38440. type: 'pieUnSelect',
  38441. event: 'pieunselected',
  38442. method: 'unSelect'
  38443. }]);
  38444. registerVisual(dataColor('pie'));
  38445. registerLayout(curry(pieLayout, 'pie'));
  38446. registerProcessor(dataFilter('pie'));
  38447. /*
  38448. * Licensed to the Apache Software Foundation (ASF) under one
  38449. * or more contributor license agreements. See the NOTICE file
  38450. * distributed with this work for additional information
  38451. * regarding copyright ownership. The ASF licenses this file
  38452. * to you under the Apache License, Version 2.0 (the
  38453. * "License"); you may not use this file except in compliance
  38454. * with the License. You may obtain a copy of the License at
  38455. *
  38456. * http://www.apache.org/licenses/LICENSE-2.0
  38457. *
  38458. * Unless required by applicable law or agreed to in writing,
  38459. * software distributed under the License is distributed on an
  38460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38461. * KIND, either express or implied. See the License for the
  38462. * specific language governing permissions and limitations
  38463. * under the License.
  38464. */
  38465. exports.version = version;
  38466. exports.dependencies = dependencies;
  38467. exports.PRIORITY = PRIORITY;
  38468. exports.init = init;
  38469. exports.connect = connect;
  38470. exports.disConnect = disConnect;
  38471. exports.disconnect = disconnect;
  38472. exports.dispose = dispose;
  38473. exports.getInstanceByDom = getInstanceByDom;
  38474. exports.getInstanceById = getInstanceById;
  38475. exports.registerTheme = registerTheme;
  38476. exports.registerPreprocessor = registerPreprocessor;
  38477. exports.registerProcessor = registerProcessor;
  38478. exports.registerPostUpdate = registerPostUpdate;
  38479. exports.registerAction = registerAction;
  38480. exports.registerCoordinateSystem = registerCoordinateSystem;
  38481. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  38482. exports.registerLayout = registerLayout;
  38483. exports.registerVisual = registerVisual;
  38484. exports.registerLoading = registerLoading;
  38485. exports.extendComponentModel = extendComponentModel;
  38486. exports.extendComponentView = extendComponentView;
  38487. exports.extendSeriesModel = extendSeriesModel;
  38488. exports.extendChartView = extendChartView;
  38489. exports.setCanvasCreator = setCanvasCreator;
  38490. exports.registerMap = registerMap;
  38491. exports.getMap = getMap;
  38492. exports.dataTool = dataTool;
  38493. })));