echarts-en.simple.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.echarts = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /*
  7. * Licensed to the Apache Software Foundation (ASF) under one
  8. * or more contributor license agreements. See the NOTICE file
  9. * distributed with this work for additional information
  10. * regarding copyright ownership. The ASF licenses this file
  11. * to you under the Apache License, Version 2.0 (the
  12. * "License"); you may not use this file except in compliance
  13. * with the License. You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing,
  18. * software distributed under the License is distributed on an
  19. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20. * KIND, either express or implied. See the License for the
  21. * specific language governing permissions and limitations
  22. * under the License.
  23. */
  24. // (1) The code `if (__DEV__) ...` can be removed by build tool.
  25. // (2) If intend to use `__DEV__`, this module should be imported. Use a global
  26. // variable `__DEV__` may cause that miss the declaration (see #6535), or the
  27. // declaration is behind of the using position (for example in `Model.extent`,
  28. // And tools like rollup can not analysis the dependency if not import).
  29. var dev;
  30. // In browser
  31. if (typeof window !== 'undefined') {
  32. dev = window.__DEV__;
  33. }
  34. // In node
  35. else if (typeof global !== 'undefined') {
  36. dev = global.__DEV__;
  37. }
  38. if (typeof dev === 'undefined') {
  39. dev = true;
  40. }
  41. var __DEV__ = dev;
  42. /**
  43. * zrender: 生成唯一id
  44. *
  45. * @author errorrik (errorrik@gmail.com)
  46. */
  47. var idStart = 0x0907;
  48. var guid = function () {
  49. return idStart++;
  50. };
  51. /**
  52. * echarts设备环境识别
  53. *
  54. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  55. * @author firede[firede@firede.us]
  56. * @desc thanks zepto.
  57. */
  58. /* global wx */
  59. var env = {};
  60. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  61. // In Weixin Application
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. wxa: true, // Weixin Application
  67. canvasSupported: true,
  68. svgSupported: false,
  69. touchEventsSupported: true,
  70. domSupported: false
  71. };
  72. }
  73. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  74. // In worker
  75. env = {
  76. browser: {},
  77. os: {},
  78. node: false,
  79. worker: true,
  80. canvasSupported: true,
  81. domSupported: false
  82. };
  83. }
  84. else if (typeof navigator === 'undefined') {
  85. // In node
  86. env = {
  87. browser: {},
  88. os: {},
  89. node: true,
  90. worker: false,
  91. // Assume canvas is supported
  92. canvasSupported: true,
  93. svgSupported: true,
  94. domSupported: false
  95. };
  96. }
  97. else {
  98. env = detect(navigator.userAgent);
  99. }
  100. var env$1 = env;
  101. // Zepto.js
  102. // (c) 2010-2013 Thomas Fuchs
  103. // Zepto.js may be freely distributed under the MIT license.
  104. function detect(ua) {
  105. var os = {};
  106. var browser = {};
  107. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  108. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  109. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  110. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  111. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  112. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  113. // var touchpad = webos && ua.match(/TouchPad/);
  114. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  115. // var silk = ua.match(/Silk\/([\d._]+)/);
  116. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  117. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  118. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  119. // var playbook = ua.match(/PlayBook/);
  120. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  121. var firefox = ua.match(/Firefox\/([\d.]+)/);
  122. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  123. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  124. var ie = ua.match(/MSIE\s([\d.]+)/)
  125. // IE 11 Trident/7.0; rv:11.0
  126. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  127. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  128. var weChat = (/micromessenger/i).test(ua);
  129. // Todo: clean this up with a better OS/browser seperation:
  130. // - discern (more) between multiple browsers on android
  131. // - decide if kindle fire in silk mode is android or not
  132. // - Firefox on Android doesn't specify the Android version
  133. // - possibly devide in os, device and browser hashes
  134. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  135. // if (android) os.android = true, os.version = android[2];
  136. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  137. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  138. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  139. // if (webos) os.webos = true, os.version = webos[2];
  140. // if (touchpad) os.touchpad = true;
  141. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  142. // if (bb10) os.bb10 = true, os.version = bb10[2];
  143. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  144. // if (playbook) browser.playbook = true;
  145. // if (kindle) os.kindle = true, os.version = kindle[1];
  146. // if (silk) browser.silk = true, browser.version = silk[1];
  147. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  148. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  149. if (firefox) {
  150. browser.firefox = true;
  151. browser.version = firefox[1];
  152. }
  153. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  154. // if (webview) browser.webview = true;
  155. if (ie) {
  156. browser.ie = true;
  157. browser.version = ie[1];
  158. }
  159. if (edge) {
  160. browser.edge = true;
  161. browser.version = edge[1];
  162. }
  163. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  164. // not be set on win phone. So we do not consider Win Phone.
  165. if (weChat) {
  166. browser.weChat = true;
  167. }
  168. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  169. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  170. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  171. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  172. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  173. return {
  174. browser: browser,
  175. os: os,
  176. node: false,
  177. // 原生canvas支持,改极端点了
  178. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  179. canvasSupported: !!document.createElement('canvas').getContext,
  180. svgSupported: typeof SVGRect !== 'undefined',
  181. // works on most browsers
  182. // IE10/11 does not support touch event, and MS Edge supports them but not by
  183. // default, so we dont check navigator.maxTouchPoints for them here.
  184. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  185. // <http://caniuse.com/#search=pointer%20event>.
  186. pointerEventsSupported:
  187. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  188. // events currently. So we dont use that on other browsers unless tested sufficiently.
  189. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  190. // scroll, the `pointermove` event can not be fired any more. That will break some
  191. // features like "pan horizontally to move something and pan vertically to page scroll".
  192. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  193. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  194. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  195. 'onpointerdown' in window
  196. && (browser.edge || (browser.ie && browser.version >= 11)),
  197. // passiveSupported: detectPassiveSupport()
  198. domSupported: typeof document !== 'undefined'
  199. };
  200. }
  201. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  202. // function detectPassiveSupport() {
  203. // // Test via a getter in the options object to see if the passive property is accessed
  204. // var supportsPassive = false;
  205. // try {
  206. // var opts = Object.defineProperty({}, 'passive', {
  207. // get: function() {
  208. // supportsPassive = true;
  209. // }
  210. // });
  211. // window.addEventListener('testPassive', function() {}, opts);
  212. // } catch (e) {
  213. // }
  214. // return supportsPassive;
  215. // }
  216. /**
  217. * @module zrender/core/util
  218. */
  219. // 用于处理merge时无法遍历Date等对象的问题
  220. var BUILTIN_OBJECT = {
  221. '[object Function]': 1,
  222. '[object RegExp]': 1,
  223. '[object Date]': 1,
  224. '[object Error]': 1,
  225. '[object CanvasGradient]': 1,
  226. '[object CanvasPattern]': 1,
  227. // For node-canvas
  228. '[object Image]': 1,
  229. '[object Canvas]': 1
  230. };
  231. var TYPED_ARRAY = {
  232. '[object Int8Array]': 1,
  233. '[object Uint8Array]': 1,
  234. '[object Uint8ClampedArray]': 1,
  235. '[object Int16Array]': 1,
  236. '[object Uint16Array]': 1,
  237. '[object Int32Array]': 1,
  238. '[object Uint32Array]': 1,
  239. '[object Float32Array]': 1,
  240. '[object Float64Array]': 1
  241. };
  242. var objToString = Object.prototype.toString;
  243. var arrayProto = Array.prototype;
  244. var nativeForEach = arrayProto.forEach;
  245. var nativeFilter = arrayProto.filter;
  246. var nativeSlice = arrayProto.slice;
  247. var nativeMap = arrayProto.map;
  248. var nativeReduce = arrayProto.reduce;
  249. // Avoid assign to an exported variable, for transforming to cjs.
  250. var methods = {};
  251. function $override(name, fn) {
  252. // Clear ctx instance for different environment
  253. if (name === 'createCanvas') {
  254. _ctx = null;
  255. }
  256. methods[name] = fn;
  257. }
  258. /**
  259. * Those data types can be cloned:
  260. * Plain object, Array, TypedArray, number, string, null, undefined.
  261. * Those data types will be assgined using the orginal data:
  262. * BUILTIN_OBJECT
  263. * Instance of user defined class will be cloned to a plain object, without
  264. * properties in prototype.
  265. * Other data types is not supported (not sure what will happen).
  266. *
  267. * Caution: do not support clone Date, for performance consideration.
  268. * (There might be a large number of date in `series.data`).
  269. * So date should not be modified in and out of echarts.
  270. *
  271. * @param {*} source
  272. * @return {*} new
  273. */
  274. function clone(source) {
  275. if (source == null || typeof source !== 'object') {
  276. return source;
  277. }
  278. var result = source;
  279. var typeStr = objToString.call(source);
  280. if (typeStr === '[object Array]') {
  281. if (!isPrimitive(source)) {
  282. result = [];
  283. for (var i = 0, len = source.length; i < len; i++) {
  284. result[i] = clone(source[i]);
  285. }
  286. }
  287. }
  288. else if (TYPED_ARRAY[typeStr]) {
  289. if (!isPrimitive(source)) {
  290. var Ctor = source.constructor;
  291. if (source.constructor.from) {
  292. result = Ctor.from(source);
  293. }
  294. else {
  295. result = new Ctor(source.length);
  296. for (var i = 0, len = source.length; i < len; i++) {
  297. result[i] = clone(source[i]);
  298. }
  299. }
  300. }
  301. }
  302. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  303. result = {};
  304. for (var key in source) {
  305. if (source.hasOwnProperty(key)) {
  306. result[key] = clone(source[key]);
  307. }
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * @memberOf module:zrender/core/util
  314. * @param {*} target
  315. * @param {*} source
  316. * @param {boolean} [overwrite=false]
  317. */
  318. function merge(target, source, overwrite) {
  319. // We should escapse that source is string
  320. // and enter for ... in ...
  321. if (!isObject$1(source) || !isObject$1(target)) {
  322. return overwrite ? clone(source) : target;
  323. }
  324. for (var key in source) {
  325. if (source.hasOwnProperty(key)) {
  326. var targetProp = target[key];
  327. var sourceProp = source[key];
  328. if (isObject$1(sourceProp)
  329. && isObject$1(targetProp)
  330. && !isArray(sourceProp)
  331. && !isArray(targetProp)
  332. && !isDom(sourceProp)
  333. && !isDom(targetProp)
  334. && !isBuiltInObject(sourceProp)
  335. && !isBuiltInObject(targetProp)
  336. && !isPrimitive(sourceProp)
  337. && !isPrimitive(targetProp)
  338. ) {
  339. // 如果需要递归覆盖,就递归调用merge
  340. merge(targetProp, sourceProp, overwrite);
  341. }
  342. else if (overwrite || !(key in target)) {
  343. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  344. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  345. target[key] = clone(source[key], true);
  346. }
  347. }
  348. }
  349. return target;
  350. }
  351. /**
  352. * @param {Array} targetAndSources The first item is target, and the rests are source.
  353. * @param {boolean} [overwrite=false]
  354. * @return {*} target
  355. */
  356. function mergeAll(targetAndSources, overwrite) {
  357. var result = targetAndSources[0];
  358. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  359. result = merge(result, targetAndSources[i], overwrite);
  360. }
  361. return result;
  362. }
  363. /**
  364. * @param {*} target
  365. * @param {*} source
  366. * @memberOf module:zrender/core/util
  367. */
  368. function extend(target, source) {
  369. for (var key in source) {
  370. if (source.hasOwnProperty(key)) {
  371. target[key] = source[key];
  372. }
  373. }
  374. return target;
  375. }
  376. /**
  377. * @param {*} target
  378. * @param {*} source
  379. * @param {boolean} [overlay=false]
  380. * @memberOf module:zrender/core/util
  381. */
  382. function defaults(target, source, overlay) {
  383. for (var key in source) {
  384. if (source.hasOwnProperty(key)
  385. && (overlay ? source[key] != null : target[key] == null)
  386. ) {
  387. target[key] = source[key];
  388. }
  389. }
  390. return target;
  391. }
  392. var createCanvas = function () {
  393. return methods.createCanvas();
  394. };
  395. methods.createCanvas = function () {
  396. return document.createElement('canvas');
  397. };
  398. // FIXME
  399. var _ctx;
  400. function getContext() {
  401. if (!_ctx) {
  402. // Use util.createCanvas instead of createCanvas
  403. // because createCanvas may be overwritten in different environment
  404. _ctx = createCanvas().getContext('2d');
  405. }
  406. return _ctx;
  407. }
  408. /**
  409. * 查询数组中元素的index
  410. * @memberOf module:zrender/core/util
  411. */
  412. function indexOf(array, value) {
  413. if (array) {
  414. if (array.indexOf) {
  415. return array.indexOf(value);
  416. }
  417. for (var i = 0, len = array.length; i < len; i++) {
  418. if (array[i] === value) {
  419. return i;
  420. }
  421. }
  422. }
  423. return -1;
  424. }
  425. /**
  426. * 构造类继承关系
  427. *
  428. * @memberOf module:zrender/core/util
  429. * @param {Function} clazz 源类
  430. * @param {Function} baseClazz 基类
  431. */
  432. function inherits(clazz, baseClazz) {
  433. var clazzPrototype = clazz.prototype;
  434. function F() {}
  435. F.prototype = baseClazz.prototype;
  436. clazz.prototype = new F();
  437. for (var prop in clazzPrototype) {
  438. if (clazzPrototype.hasOwnProperty(prop)) {
  439. clazz.prototype[prop] = clazzPrototype[prop];
  440. }
  441. }
  442. clazz.prototype.constructor = clazz;
  443. clazz.superClass = baseClazz;
  444. }
  445. /**
  446. * @memberOf module:zrender/core/util
  447. * @param {Object|Function} target
  448. * @param {Object|Function} sorce
  449. * @param {boolean} overlay
  450. */
  451. function mixin(target, source, overlay) {
  452. target = 'prototype' in target ? target.prototype : target;
  453. source = 'prototype' in source ? source.prototype : source;
  454. defaults(target, source, overlay);
  455. }
  456. /**
  457. * Consider typed array.
  458. * @param {Array|TypedArray} data
  459. */
  460. function isArrayLike(data) {
  461. if (!data) {
  462. return;
  463. }
  464. if (typeof data === 'string') {
  465. return false;
  466. }
  467. return typeof data.length === 'number';
  468. }
  469. /**
  470. * 数组或对象遍历
  471. * @memberOf module:zrender/core/util
  472. * @param {Object|Array} obj
  473. * @param {Function} cb
  474. * @param {*} [context]
  475. */
  476. function each$1(obj, cb, context) {
  477. if (!(obj && cb)) {
  478. return;
  479. }
  480. if (obj.forEach && obj.forEach === nativeForEach) {
  481. obj.forEach(cb, context);
  482. }
  483. else if (obj.length === +obj.length) {
  484. for (var i = 0, len = obj.length; i < len; i++) {
  485. cb.call(context, obj[i], i, obj);
  486. }
  487. }
  488. else {
  489. for (var key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. cb.call(context, obj[key], key, obj);
  492. }
  493. }
  494. }
  495. }
  496. /**
  497. * 数组映射
  498. * @memberOf module:zrender/core/util
  499. * @param {Array} obj
  500. * @param {Function} cb
  501. * @param {*} [context]
  502. * @return {Array}
  503. */
  504. function map(obj, cb, context) {
  505. if (!(obj && cb)) {
  506. return;
  507. }
  508. if (obj.map && obj.map === nativeMap) {
  509. return obj.map(cb, context);
  510. }
  511. else {
  512. var result = [];
  513. for (var i = 0, len = obj.length; i < len; i++) {
  514. result.push(cb.call(context, obj[i], i, obj));
  515. }
  516. return result;
  517. }
  518. }
  519. /**
  520. * @memberOf module:zrender/core/util
  521. * @param {Array} obj
  522. * @param {Function} cb
  523. * @param {Object} [memo]
  524. * @param {*} [context]
  525. * @return {Array}
  526. */
  527. function reduce(obj, cb, memo, context) {
  528. if (!(obj && cb)) {
  529. return;
  530. }
  531. if (obj.reduce && obj.reduce === nativeReduce) {
  532. return obj.reduce(cb, memo, context);
  533. }
  534. else {
  535. for (var i = 0, len = obj.length; i < len; i++) {
  536. memo = cb.call(context, memo, obj[i], i, obj);
  537. }
  538. return memo;
  539. }
  540. }
  541. /**
  542. * 数组过滤
  543. * @memberOf module:zrender/core/util
  544. * @param {Array} obj
  545. * @param {Function} cb
  546. * @param {*} [context]
  547. * @return {Array}
  548. */
  549. function filter(obj, cb, context) {
  550. if (!(obj && cb)) {
  551. return;
  552. }
  553. if (obj.filter && obj.filter === nativeFilter) {
  554. return obj.filter(cb, context);
  555. }
  556. else {
  557. var result = [];
  558. for (var i = 0, len = obj.length; i < len; i++) {
  559. if (cb.call(context, obj[i], i, obj)) {
  560. result.push(obj[i]);
  561. }
  562. }
  563. return result;
  564. }
  565. }
  566. /**
  567. * 数组项查找
  568. * @memberOf module:zrender/core/util
  569. * @param {Array} obj
  570. * @param {Function} cb
  571. * @param {*} [context]
  572. * @return {*}
  573. */
  574. /**
  575. * @memberOf module:zrender/core/util
  576. * @param {Function} func
  577. * @param {*} context
  578. * @return {Function}
  579. */
  580. function bind(func, context) {
  581. var args = nativeSlice.call(arguments, 2);
  582. return function () {
  583. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  584. };
  585. }
  586. /**
  587. * @memberOf module:zrender/core/util
  588. * @param {Function} func
  589. * @return {Function}
  590. */
  591. function curry(func) {
  592. var args = nativeSlice.call(arguments, 1);
  593. return function () {
  594. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  595. };
  596. }
  597. /**
  598. * @memberOf module:zrender/core/util
  599. * @param {*} value
  600. * @return {boolean}
  601. */
  602. function isArray(value) {
  603. return objToString.call(value) === '[object Array]';
  604. }
  605. /**
  606. * @memberOf module:zrender/core/util
  607. * @param {*} value
  608. * @return {boolean}
  609. */
  610. function isFunction$1(value) {
  611. return typeof value === 'function';
  612. }
  613. /**
  614. * @memberOf module:zrender/core/util
  615. * @param {*} value
  616. * @return {boolean}
  617. */
  618. function isString(value) {
  619. return objToString.call(value) === '[object String]';
  620. }
  621. /**
  622. * @memberOf module:zrender/core/util
  623. * @param {*} value
  624. * @return {boolean}
  625. */
  626. function isObject$1(value) {
  627. // Avoid a V8 JIT bug in Chrome 19-20.
  628. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  629. var type = typeof value;
  630. return type === 'function' || (!!value && type === 'object');
  631. }
  632. /**
  633. * @memberOf module:zrender/core/util
  634. * @param {*} value
  635. * @return {boolean}
  636. */
  637. function isBuiltInObject(value) {
  638. return !!BUILTIN_OBJECT[objToString.call(value)];
  639. }
  640. /**
  641. * @memberOf module:zrender/core/util
  642. * @param {*} value
  643. * @return {boolean}
  644. */
  645. function isTypedArray(value) {
  646. return !!TYPED_ARRAY[objToString.call(value)];
  647. }
  648. /**
  649. * @memberOf module:zrender/core/util
  650. * @param {*} value
  651. * @return {boolean}
  652. */
  653. function isDom(value) {
  654. return typeof value === 'object'
  655. && typeof value.nodeType === 'number'
  656. && typeof value.ownerDocument === 'object';
  657. }
  658. /**
  659. * Whether is exactly NaN. Notice isNaN('a') returns true.
  660. * @param {*} value
  661. * @return {boolean}
  662. */
  663. function eqNaN(value) {
  664. /* eslint-disable-next-line no-self-compare */
  665. return value !== value;
  666. }
  667. /**
  668. * If value1 is not null, then return value1, otherwise judget rest of values.
  669. * Low performance.
  670. * @memberOf module:zrender/core/util
  671. * @return {*} Final value
  672. */
  673. function retrieve(values) {
  674. for (var i = 0, len = arguments.length; i < len; i++) {
  675. if (arguments[i] != null) {
  676. return arguments[i];
  677. }
  678. }
  679. }
  680. function retrieve2(value0, value1) {
  681. return value0 != null
  682. ? value0
  683. : value1;
  684. }
  685. function retrieve3(value0, value1, value2) {
  686. return value0 != null
  687. ? value0
  688. : value1 != null
  689. ? value1
  690. : value2;
  691. }
  692. /**
  693. * @memberOf module:zrender/core/util
  694. * @param {Array} arr
  695. * @param {number} startIndex
  696. * @param {number} endIndex
  697. * @return {Array}
  698. */
  699. function slice() {
  700. return Function.call.apply(nativeSlice, arguments);
  701. }
  702. /**
  703. * Normalize css liked array configuration
  704. * e.g.
  705. * 3 => [3, 3, 3, 3]
  706. * [4, 2] => [4, 2, 4, 2]
  707. * [4, 3, 2] => [4, 3, 2, 3]
  708. * @param {number|Array.<number>} val
  709. * @return {Array.<number>}
  710. */
  711. function normalizeCssArray(val) {
  712. if (typeof (val) === 'number') {
  713. return [val, val, val, val];
  714. }
  715. var len = val.length;
  716. if (len === 2) {
  717. // vertical | horizontal
  718. return [val[0], val[1], val[0], val[1]];
  719. }
  720. else if (len === 3) {
  721. // top | horizontal | bottom
  722. return [val[0], val[1], val[2], val[1]];
  723. }
  724. return val;
  725. }
  726. /**
  727. * @memberOf module:zrender/core/util
  728. * @param {boolean} condition
  729. * @param {string} message
  730. */
  731. function assert$1(condition, message) {
  732. if (!condition) {
  733. throw new Error(message);
  734. }
  735. }
  736. /**
  737. * @memberOf module:zrender/core/util
  738. * @param {string} str string to be trimed
  739. * @return {string} trimed string
  740. */
  741. function trim(str) {
  742. if (str == null) {
  743. return null;
  744. }
  745. else if (typeof str.trim === 'function') {
  746. return str.trim();
  747. }
  748. else {
  749. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  750. }
  751. }
  752. var primitiveKey = '__ec_primitive__';
  753. /**
  754. * Set an object as primitive to be ignored traversing children in clone or merge
  755. */
  756. function setAsPrimitive(obj) {
  757. obj[primitiveKey] = true;
  758. }
  759. function isPrimitive(obj) {
  760. return obj[primitiveKey];
  761. }
  762. /**
  763. * @constructor
  764. * @param {Object} obj Only apply `ownProperty`.
  765. */
  766. function HashMap(obj) {
  767. var isArr = isArray(obj);
  768. // Key should not be set on this, otherwise
  769. // methods get/set/... may be overrided.
  770. this.data = {};
  771. var thisMap = this;
  772. (obj instanceof HashMap)
  773. ? obj.each(visit)
  774. : (obj && each$1(obj, visit));
  775. function visit(value, key) {
  776. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  777. }
  778. }
  779. HashMap.prototype = {
  780. constructor: HashMap,
  781. // Do not provide `has` method to avoid defining what is `has`.
  782. // (We usually treat `null` and `undefined` as the same, different
  783. // from ES6 Map).
  784. get: function (key) {
  785. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  786. },
  787. set: function (key, value) {
  788. // Comparing with invocation chaining, `return value` is more commonly
  789. // used in this case: `var someVal = map.set('a', genVal());`
  790. return (this.data[key] = value);
  791. },
  792. // Although util.each can be performed on this hashMap directly, user
  793. // should not use the exposed keys, who are prefixed.
  794. each: function (cb, context) {
  795. context !== void 0 && (cb = bind(cb, context));
  796. /* eslint-disable guard-for-in */
  797. for (var key in this.data) {
  798. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  799. }
  800. /* eslint-enable guard-for-in */
  801. },
  802. // Do not use this method if performance sensitive.
  803. removeKey: function (key) {
  804. delete this.data[key];
  805. }
  806. };
  807. function createHashMap(obj) {
  808. return new HashMap(obj);
  809. }
  810. function noop() {}
  811. /* global Float32Array */
  812. var ArrayCtor = typeof Float32Array === 'undefined'
  813. ? Array
  814. : Float32Array;
  815. /**
  816. * 创建一个向量
  817. * @param {number} [x=0]
  818. * @param {number} [y=0]
  819. * @return {Vector2}
  820. */
  821. function create(x, y) {
  822. var out = new ArrayCtor(2);
  823. if (x == null) {
  824. x = 0;
  825. }
  826. if (y == null) {
  827. y = 0;
  828. }
  829. out[0] = x;
  830. out[1] = y;
  831. return out;
  832. }
  833. /**
  834. * 复制向量数据
  835. * @param {Vector2} out
  836. * @param {Vector2} v
  837. * @return {Vector2}
  838. */
  839. function copy(out, v) {
  840. out[0] = v[0];
  841. out[1] = v[1];
  842. return out;
  843. }
  844. /**
  845. * 克隆一个向量
  846. * @param {Vector2} v
  847. * @return {Vector2}
  848. */
  849. function clone$1(v) {
  850. var out = new ArrayCtor(2);
  851. out[0] = v[0];
  852. out[1] = v[1];
  853. return out;
  854. }
  855. /**
  856. * 设置向量的两个项
  857. * @param {Vector2} out
  858. * @param {number} a
  859. * @param {number} b
  860. * @return {Vector2} 结果
  861. */
  862. /**
  863. * 向量相加
  864. * @param {Vector2} out
  865. * @param {Vector2} v1
  866. * @param {Vector2} v2
  867. */
  868. function add(out, v1, v2) {
  869. out[0] = v1[0] + v2[0];
  870. out[1] = v1[1] + v2[1];
  871. return out;
  872. }
  873. /**
  874. * 向量缩放后相加
  875. * @param {Vector2} out
  876. * @param {Vector2} v1
  877. * @param {Vector2} v2
  878. * @param {number} a
  879. */
  880. function scaleAndAdd(out, v1, v2, a) {
  881. out[0] = v1[0] + v2[0] * a;
  882. out[1] = v1[1] + v2[1] * a;
  883. return out;
  884. }
  885. /**
  886. * 向量相减
  887. * @param {Vector2} out
  888. * @param {Vector2} v1
  889. * @param {Vector2} v2
  890. */
  891. function sub(out, v1, v2) {
  892. out[0] = v1[0] - v2[0];
  893. out[1] = v1[1] - v2[1];
  894. return out;
  895. }
  896. /**
  897. * 向量长度
  898. * @param {Vector2} v
  899. * @return {number}
  900. */
  901. function len(v) {
  902. return Math.sqrt(lenSquare(v));
  903. }
  904. // jshint ignore:line
  905. /**
  906. * 向量长度平方
  907. * @param {Vector2} v
  908. * @return {number}
  909. */
  910. function lenSquare(v) {
  911. return v[0] * v[0] + v[1] * v[1];
  912. }
  913. /**
  914. * 向量乘法
  915. * @param {Vector2} out
  916. * @param {Vector2} v1
  917. * @param {Vector2} v2
  918. */
  919. /**
  920. * 向量除法
  921. * @param {Vector2} out
  922. * @param {Vector2} v1
  923. * @param {Vector2} v2
  924. */
  925. /**
  926. * 向量点乘
  927. * @param {Vector2} v1
  928. * @param {Vector2} v2
  929. * @return {number}
  930. */
  931. /**
  932. * 向量缩放
  933. * @param {Vector2} out
  934. * @param {Vector2} v
  935. * @param {number} s
  936. */
  937. function scale(out, v, s) {
  938. out[0] = v[0] * s;
  939. out[1] = v[1] * s;
  940. return out;
  941. }
  942. /**
  943. * 向量归一化
  944. * @param {Vector2} out
  945. * @param {Vector2} v
  946. */
  947. function normalize(out, v) {
  948. var d = len(v);
  949. if (d === 0) {
  950. out[0] = 0;
  951. out[1] = 0;
  952. }
  953. else {
  954. out[0] = v[0] / d;
  955. out[1] = v[1] / d;
  956. }
  957. return out;
  958. }
  959. /**
  960. * 计算向量间距离
  961. * @param {Vector2} v1
  962. * @param {Vector2} v2
  963. * @return {number}
  964. */
  965. function distance(v1, v2) {
  966. return Math.sqrt(
  967. (v1[0] - v2[0]) * (v1[0] - v2[0])
  968. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  969. );
  970. }
  971. var dist = distance;
  972. /**
  973. * 向量距离平方
  974. * @param {Vector2} v1
  975. * @param {Vector2} v2
  976. * @return {number}
  977. */
  978. function distanceSquare(v1, v2) {
  979. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  980. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  981. }
  982. var distSquare = distanceSquare;
  983. /**
  984. * 求负向量
  985. * @param {Vector2} out
  986. * @param {Vector2} v
  987. */
  988. /**
  989. * 插值两个点
  990. * @param {Vector2} out
  991. * @param {Vector2} v1
  992. * @param {Vector2} v2
  993. * @param {number} t
  994. */
  995. /**
  996. * 矩阵左乘向量
  997. * @param {Vector2} out
  998. * @param {Vector2} v
  999. * @param {Vector2} m
  1000. */
  1001. function applyTransform(out, v, m) {
  1002. var x = v[0];
  1003. var y = v[1];
  1004. out[0] = m[0] * x + m[2] * y + m[4];
  1005. out[1] = m[1] * x + m[3] * y + m[5];
  1006. return out;
  1007. }
  1008. /**
  1009. * 求两个向量最小值
  1010. * @param {Vector2} out
  1011. * @param {Vector2} v1
  1012. * @param {Vector2} v2
  1013. */
  1014. function min(out, v1, v2) {
  1015. out[0] = Math.min(v1[0], v2[0]);
  1016. out[1] = Math.min(v1[1], v2[1]);
  1017. return out;
  1018. }
  1019. /**
  1020. * 求两个向量最大值
  1021. * @param {Vector2} out
  1022. * @param {Vector2} v1
  1023. * @param {Vector2} v2
  1024. */
  1025. function max(out, v1, v2) {
  1026. out[0] = Math.max(v1[0], v2[0]);
  1027. out[1] = Math.max(v1[1], v2[1]);
  1028. return out;
  1029. }
  1030. // TODO Draggable for group
  1031. // FIXME Draggable on element which has parent rotation or scale
  1032. function Draggable() {
  1033. this.on('mousedown', this._dragStart, this);
  1034. this.on('mousemove', this._drag, this);
  1035. this.on('mouseup', this._dragEnd, this);
  1036. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1037. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1038. // `_dragEnd` when globalout. That would brings better user experience.
  1039. // this.on('globalout', this._dragEnd, this);
  1040. // this._dropTarget = null;
  1041. // this._draggingTarget = null;
  1042. // this._x = 0;
  1043. // this._y = 0;
  1044. }
  1045. Draggable.prototype = {
  1046. constructor: Draggable,
  1047. _dragStart: function (e) {
  1048. var draggingTarget = e.target;
  1049. if (draggingTarget && draggingTarget.draggable) {
  1050. this._draggingTarget = draggingTarget;
  1051. draggingTarget.dragging = true;
  1052. this._x = e.offsetX;
  1053. this._y = e.offsetY;
  1054. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1055. }
  1056. },
  1057. _drag: function (e) {
  1058. var draggingTarget = this._draggingTarget;
  1059. if (draggingTarget) {
  1060. var x = e.offsetX;
  1061. var y = e.offsetY;
  1062. var dx = x - this._x;
  1063. var dy = y - this._y;
  1064. this._x = x;
  1065. this._y = y;
  1066. draggingTarget.drift(dx, dy, e);
  1067. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1068. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1069. var lastDropTarget = this._dropTarget;
  1070. this._dropTarget = dropTarget;
  1071. if (draggingTarget !== dropTarget) {
  1072. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1073. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1074. }
  1075. if (dropTarget && dropTarget !== lastDropTarget) {
  1076. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1077. }
  1078. }
  1079. }
  1080. },
  1081. _dragEnd: function (e) {
  1082. var draggingTarget = this._draggingTarget;
  1083. if (draggingTarget) {
  1084. draggingTarget.dragging = false;
  1085. }
  1086. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1087. if (this._dropTarget) {
  1088. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1089. }
  1090. this._draggingTarget = null;
  1091. this._dropTarget = null;
  1092. }
  1093. };
  1094. function param(target, e) {
  1095. return {target: target, topTarget: e && e.topTarget};
  1096. }
  1097. /**
  1098. * Event Mixin
  1099. * @module zrender/mixin/Eventful
  1100. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1101. * pissang (https://www.github.com/pissang)
  1102. */
  1103. var arrySlice = Array.prototype.slice;
  1104. /**
  1105. * Event dispatcher.
  1106. *
  1107. * @alias module:zrender/mixin/Eventful
  1108. * @constructor
  1109. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1110. * `eventProcessor.xxx` called.
  1111. * @param {Function} [eventProcessor.normalizeQuery]
  1112. * param: {string|Object} Raw query.
  1113. * return: {string|Object} Normalized query.
  1114. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1115. * if it returns `true`.
  1116. * param: {string} eventType
  1117. * param: {string|Object} query
  1118. * return: {boolean}
  1119. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1120. * param: {string} eventType
  1121. */
  1122. var Eventful = function (eventProcessor) {
  1123. this._$handlers = {};
  1124. this._$eventProcessor = eventProcessor;
  1125. };
  1126. Eventful.prototype = {
  1127. constructor: Eventful,
  1128. /**
  1129. * The handler can only be triggered once, then removed.
  1130. *
  1131. * @param {string} event The event name.
  1132. * @param {string|Object} [query] Condition used on event filter.
  1133. * @param {Function} handler The event handler.
  1134. * @param {Object} context
  1135. */
  1136. one: function (event, query, handler, context) {
  1137. return on(this, event, query, handler, context, true);
  1138. },
  1139. /**
  1140. * Bind a handler.
  1141. *
  1142. * @param {string} event The event name.
  1143. * @param {string|Object} [query] Condition used on event filter.
  1144. * @param {Function} handler The event handler.
  1145. * @param {Object} [context]
  1146. */
  1147. on: function (event, query, handler, context) {
  1148. return on(this, event, query, handler, context, false);
  1149. },
  1150. /**
  1151. * Whether any handler has bound.
  1152. *
  1153. * @param {string} event
  1154. * @return {boolean}
  1155. */
  1156. isSilent: function (event) {
  1157. var _h = this._$handlers;
  1158. return !_h[event] || !_h[event].length;
  1159. },
  1160. /**
  1161. * Unbind a event.
  1162. *
  1163. * @param {string} [event] The event name.
  1164. * If no `event` input, "off" all listeners.
  1165. * @param {Function} [handler] The event handler.
  1166. * If no `handler` input, "off" all listeners of the `event`.
  1167. */
  1168. off: function (event, handler) {
  1169. var _h = this._$handlers;
  1170. if (!event) {
  1171. this._$handlers = {};
  1172. return this;
  1173. }
  1174. if (handler) {
  1175. if (_h[event]) {
  1176. var newList = [];
  1177. for (var i = 0, l = _h[event].length; i < l; i++) {
  1178. if (_h[event][i].h !== handler) {
  1179. newList.push(_h[event][i]);
  1180. }
  1181. }
  1182. _h[event] = newList;
  1183. }
  1184. if (_h[event] && _h[event].length === 0) {
  1185. delete _h[event];
  1186. }
  1187. }
  1188. else {
  1189. delete _h[event];
  1190. }
  1191. return this;
  1192. },
  1193. /**
  1194. * Dispatch a event.
  1195. *
  1196. * @param {string} type The event name.
  1197. */
  1198. trigger: function (type) {
  1199. var _h = this._$handlers[type];
  1200. var eventProcessor = this._$eventProcessor;
  1201. if (_h) {
  1202. var args = arguments;
  1203. var argLen = args.length;
  1204. if (argLen > 3) {
  1205. args = arrySlice.call(args, 1);
  1206. }
  1207. var len = _h.length;
  1208. for (var i = 0; i < len;) {
  1209. var hItem = _h[i];
  1210. if (eventProcessor
  1211. && eventProcessor.filter
  1212. && hItem.query != null
  1213. && !eventProcessor.filter(type, hItem.query)
  1214. ) {
  1215. i++;
  1216. continue;
  1217. }
  1218. // Optimize advise from backbone
  1219. switch (argLen) {
  1220. case 1:
  1221. hItem.h.call(hItem.ctx);
  1222. break;
  1223. case 2:
  1224. hItem.h.call(hItem.ctx, args[1]);
  1225. break;
  1226. case 3:
  1227. hItem.h.call(hItem.ctx, args[1], args[2]);
  1228. break;
  1229. default:
  1230. // have more than 2 given arguments
  1231. hItem.h.apply(hItem.ctx, args);
  1232. break;
  1233. }
  1234. if (hItem.one) {
  1235. _h.splice(i, 1);
  1236. len--;
  1237. }
  1238. else {
  1239. i++;
  1240. }
  1241. }
  1242. }
  1243. eventProcessor && eventProcessor.afterTrigger
  1244. && eventProcessor.afterTrigger(type);
  1245. return this;
  1246. },
  1247. /**
  1248. * Dispatch a event with context, which is specified at the last parameter.
  1249. *
  1250. * @param {string} type The event name.
  1251. */
  1252. triggerWithContext: function (type) {
  1253. var _h = this._$handlers[type];
  1254. var eventProcessor = this._$eventProcessor;
  1255. if (_h) {
  1256. var args = arguments;
  1257. var argLen = args.length;
  1258. if (argLen > 4) {
  1259. args = arrySlice.call(args, 1, args.length - 1);
  1260. }
  1261. var ctx = args[args.length - 1];
  1262. var len = _h.length;
  1263. for (var i = 0; i < len;) {
  1264. var hItem = _h[i];
  1265. if (eventProcessor
  1266. && eventProcessor.filter
  1267. && hItem.query != null
  1268. && !eventProcessor.filter(type, hItem.query)
  1269. ) {
  1270. i++;
  1271. continue;
  1272. }
  1273. // Optimize advise from backbone
  1274. switch (argLen) {
  1275. case 1:
  1276. hItem.h.call(ctx);
  1277. break;
  1278. case 2:
  1279. hItem.h.call(ctx, args[1]);
  1280. break;
  1281. case 3:
  1282. hItem.h.call(ctx, args[1], args[2]);
  1283. break;
  1284. default:
  1285. // have more than 2 given arguments
  1286. hItem.h.apply(ctx, args);
  1287. break;
  1288. }
  1289. if (hItem.one) {
  1290. _h.splice(i, 1);
  1291. len--;
  1292. }
  1293. else {
  1294. i++;
  1295. }
  1296. }
  1297. }
  1298. eventProcessor && eventProcessor.afterTrigger
  1299. && eventProcessor.afterTrigger(type);
  1300. return this;
  1301. }
  1302. };
  1303. function normalizeQuery(host, query) {
  1304. var eventProcessor = host._$eventProcessor;
  1305. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1306. query = eventProcessor.normalizeQuery(query);
  1307. }
  1308. return query;
  1309. }
  1310. function on(eventful, event, query, handler, context, isOnce) {
  1311. var _h = eventful._$handlers;
  1312. if (typeof query === 'function') {
  1313. context = handler;
  1314. handler = query;
  1315. query = null;
  1316. }
  1317. if (!handler || !event) {
  1318. return eventful;
  1319. }
  1320. query = normalizeQuery(eventful, query);
  1321. if (!_h[event]) {
  1322. _h[event] = [];
  1323. }
  1324. for (var i = 0; i < _h[event].length; i++) {
  1325. if (_h[event][i].h === handler) {
  1326. return eventful;
  1327. }
  1328. }
  1329. var wrap = {
  1330. h: handler,
  1331. one: isOnce,
  1332. query: query,
  1333. ctx: context || eventful,
  1334. // FIXME
  1335. // Do not publish this feature util it is proved that it makes sense.
  1336. callAtLast: handler.zrEventfulCallAtLast
  1337. };
  1338. var lastIndex = _h[event].length - 1;
  1339. var lastWrap = _h[event][lastIndex];
  1340. (lastWrap && lastWrap.callAtLast)
  1341. ? _h[event].splice(lastIndex, 0, wrap)
  1342. : _h[event].push(wrap);
  1343. return eventful;
  1344. }
  1345. /**
  1346. * The algoritm is learnt from
  1347. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1348. * And we made some optimization for matrix inversion.
  1349. * Other similar approaches:
  1350. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1351. */
  1352. var LN2 = Math.log(2);
  1353. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1354. var cacheKey = rowMask + '-' + colMask;
  1355. var fullRank = rows.length;
  1356. if (detCache.hasOwnProperty(cacheKey)) {
  1357. return detCache[cacheKey];
  1358. }
  1359. if (rank === 1) {
  1360. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1361. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1362. return rows[rowStart][colStart];
  1363. }
  1364. var subRowMask = rowMask | (1 << rowStart);
  1365. var subRowStart = rowStart + 1;
  1366. while (rowMask & (1 << subRowStart)) {
  1367. subRowStart++;
  1368. }
  1369. var sum = 0;
  1370. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1371. var colTag = 1 << j;
  1372. if (!(colTag & colMask)) {
  1373. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1374. // det(subMatrix(0, j))
  1375. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1376. colLocalIdx++;
  1377. }
  1378. }
  1379. detCache[cacheKey] = sum;
  1380. return sum;
  1381. }
  1382. /**
  1383. * Usage:
  1384. * ```js
  1385. * var transformer = buildTransformer(
  1386. * [10, 44, 100, 44, 100, 300, 10, 300],
  1387. * [50, 54, 130, 14, 140, 330, 14, 220]
  1388. * );
  1389. * var out = [];
  1390. * transformer && transformer([11, 33], out);
  1391. * ```
  1392. *
  1393. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1394. *
  1395. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1396. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1397. * @return {Function} transformer If fail, return null/undefined.
  1398. */
  1399. function buildTransformer(src, dest) {
  1400. var mA = [
  1401. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1402. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1403. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1404. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1405. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1406. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1407. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1408. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1409. ];
  1410. var detCache = {};
  1411. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1412. if (det === 0) {
  1413. return;
  1414. }
  1415. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1416. var vh = [];
  1417. for (var i = 0; i < 8; i++) {
  1418. for (var j = 0; j < 8; j++) {
  1419. vh[j] == null && (vh[j] = 0);
  1420. vh[j] += ((i + j) % 2 ? -1 : 1)
  1421. // det(subMatrix(i, j))
  1422. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1423. / det * dest[i];
  1424. }
  1425. }
  1426. return function (out, srcPointX, srcPointY) {
  1427. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1428. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1429. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1430. };
  1431. }
  1432. /**
  1433. * Utilities for mouse or touch events.
  1434. */
  1435. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1436. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1437. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1438. var _calcOut = [];
  1439. /**
  1440. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1441. * the input `el`.
  1442. * CSS transform (2D & 3D) is supported.
  1443. *
  1444. * The strategy to fetch the coords:
  1445. * + If `calculate` is not set as `true`, users of this method should
  1446. * ensure that `el` is the same or the same size & location as `e.target`.
  1447. * Otherwise the result coords are probably not expected. Because we
  1448. * firstly try to get coords from e.offsetX/e.offsetY.
  1449. * + If `calculate` is set as `true`, the input `el` can be any element
  1450. * and we force to calculate the coords based on `el`.
  1451. * + The input `el` should be positionable (not position:static).
  1452. *
  1453. * The force `calculate` can be used in case like:
  1454. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1455. *
  1456. * @param {HTMLElement} el DOM element.
  1457. * @param {Event} e Mouse event or touch event.
  1458. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1459. * @param {boolean} [calculate=false] Whether to force calculate
  1460. * the coordinates but not use ones provided by browser.
  1461. */
  1462. function clientToLocal(el, e, out, calculate) {
  1463. out = out || {};
  1464. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1465. // to the padding edge of the target element. The only browser using this convention
  1466. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1467. // not support the properties.
  1468. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1469. // In zr painter.dom, padding edge equals to border edge.
  1470. if (calculate || !env$1.canvasSupported) {
  1471. calculateZrXY(el, e, out);
  1472. }
  1473. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1474. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1475. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1476. // zoom-factor, overflow / opacity layers, transforms ...)
  1477. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1478. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1479. // BTW3, In ff, offsetX/offsetY is always 0.
  1480. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1481. out.zrX = e.layerX;
  1482. out.zrY = e.layerY;
  1483. }
  1484. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1485. else if (e.offsetX != null) {
  1486. out.zrX = e.offsetX;
  1487. out.zrY = e.offsetY;
  1488. }
  1489. // For some other device, e.g., IOS safari.
  1490. else {
  1491. calculateZrXY(el, e, out);
  1492. }
  1493. return out;
  1494. }
  1495. function calculateZrXY(el, e, out) {
  1496. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1497. if (el.getBoundingClientRect && env$1.domSupported) {
  1498. var ex = e.clientX;
  1499. var ey = e.clientY;
  1500. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1501. // Original approach, which do not support CSS transform.
  1502. // marker can not be locationed in a canvas container
  1503. // (getBoundingClientRect is always 0). We do not support
  1504. // that input a pre-created canvas to zr while using css
  1505. // transform in iOS.
  1506. var box = el.getBoundingClientRect();
  1507. out.zrX = ex - box.left;
  1508. out.zrY = ey - box.top;
  1509. return;
  1510. }
  1511. else {
  1512. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1513. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1514. if (transformer) {
  1515. transformer(_calcOut, ex, ey);
  1516. out.zrX = _calcOut[0];
  1517. out.zrY = _calcOut[1];
  1518. return;
  1519. }
  1520. }
  1521. }
  1522. out.zrX = out.zrY = 0;
  1523. }
  1524. function prepareCoordMarkers(el, saved) {
  1525. var markers = saved.markers;
  1526. if (markers) {
  1527. return markers;
  1528. }
  1529. markers = saved.markers = [];
  1530. var propLR = ['left', 'right'];
  1531. var propTB = ['top', 'bottom'];
  1532. for (var i = 0; i < 4; i++) {
  1533. var marker = document.createElement('div');
  1534. var stl = marker.style;
  1535. var idxLR = i % 2;
  1536. var idxTB = (i >> 1) % 2;
  1537. stl.cssText = [
  1538. 'position:absolute',
  1539. 'visibility: hidden',
  1540. 'padding: 0',
  1541. 'margin: 0',
  1542. 'border-width: 0',
  1543. 'width:0',
  1544. 'height:0',
  1545. // 'width: 5px',
  1546. // 'height: 5px',
  1547. propLR[idxLR] + ':0',
  1548. propTB[idxTB] + ':0',
  1549. propLR[1 - idxLR] + ':auto',
  1550. propTB[1 - idxTB] + ':auto',
  1551. ''
  1552. ].join('!important;');
  1553. el.appendChild(marker);
  1554. markers.push(marker);
  1555. }
  1556. return markers;
  1557. }
  1558. function preparePointerTransformer(markers, saved) {
  1559. var transformer = saved.transformer;
  1560. var oldSrcCoords = saved.srcCoords;
  1561. var useOld = true;
  1562. var srcCoords = [];
  1563. var destCoords = [];
  1564. for (var i = 0; i < 4; i++) {
  1565. var rect = markers[i].getBoundingClientRect();
  1566. var ii = 2 * i;
  1567. var x = rect.left;
  1568. var y = rect.top;
  1569. srcCoords.push(x, y);
  1570. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1571. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1572. }
  1573. // Cache to avoid time consuming of `buildTransformer`.
  1574. return useOld
  1575. ? transformer
  1576. : (
  1577. saved.srcCoords = srcCoords,
  1578. saved.transformer = buildTransformer(srcCoords, destCoords)
  1579. );
  1580. }
  1581. /**
  1582. * Find native event compat for legency IE.
  1583. * Should be called at the begining of a native event listener.
  1584. *
  1585. * @param {Event} [e] Mouse event or touch event or pointer event.
  1586. * For lagency IE, we use `window.event` is used.
  1587. * @return {Event} The native event.
  1588. */
  1589. function getNativeEvent(e) {
  1590. return e || window.event;
  1591. }
  1592. /**
  1593. * Normalize the coordinates of the input event.
  1594. *
  1595. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1596. * the input `el`.
  1597. * Get `e.zrDelta` if using mouse wheel.
  1598. * Get `e.which`, see the comment inside this function.
  1599. *
  1600. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1601. *
  1602. * Notice: see comments in `clientToLocal`. check the relationship
  1603. * between the result coords and the parameters `el` and `calculate`.
  1604. *
  1605. * @param {HTMLElement} el DOM element.
  1606. * @param {Event} [e] See `getNativeEvent`.
  1607. * @param {boolean} [calculate=false] Whether to force calculate
  1608. * the coordinates but not use ones provided by browser.
  1609. * @return {UIEvent} The normalized native UIEvent.
  1610. */
  1611. function normalizeEvent(el, e, calculate) {
  1612. e = getNativeEvent(e);
  1613. if (e.zrX != null) {
  1614. return e;
  1615. }
  1616. var eventType = e.type;
  1617. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1618. if (!isTouch) {
  1619. clientToLocal(el, e, e, calculate);
  1620. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1621. }
  1622. else {
  1623. var touch = eventType !== 'touchend'
  1624. ? e.targetTouches[0]
  1625. : e.changedTouches[0];
  1626. touch && clientToLocal(el, touch, e, calculate);
  1627. }
  1628. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1629. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1630. // If e.which has been defined, it may be readonly,
  1631. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1632. var button = e.button;
  1633. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1634. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1635. }
  1636. // [Caution]: `e.which` from browser is not always reliable. For example,
  1637. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1638. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1639. // `mousedown (pointerdown)` is the same as Chrome does.
  1640. return e;
  1641. }
  1642. /**
  1643. * @param {HTMLElement} el
  1644. * @param {string} name
  1645. * @param {Function} handler
  1646. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1647. * @param {boolean} [opt.capture=false]
  1648. * @param {boolean} [opt.passive=false]
  1649. */
  1650. function addEventListener(el, name, handler, opt) {
  1651. if (isDomLevel2) {
  1652. // Reproduct the console warning:
  1653. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1654. // Consider marking event handler as 'passive' to make the page more responsive.
  1655. // Just set console log level: verbose in chrome dev tool.
  1656. // then the warning log will be printed when addEventListener called.
  1657. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1658. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1659. // listener delegate all of the upper events of element. Some of those events need
  1660. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1661. // Before passive can be adopted, these issues should be considered:
  1662. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1663. // passive or not.
  1664. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1665. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1666. // compatibility should be handled.
  1667. // var opts = (env.passiveSupported && name === 'mousewheel')
  1668. // ? {passive: true}
  1669. // // By default, the third param of el.addEventListener is `capture: false`.
  1670. // : void 0;
  1671. // el.addEventListener(name, handler /* , opts */);
  1672. el.addEventListener(name, handler, opt);
  1673. }
  1674. else {
  1675. // For simplicity, do not implement `setCapture` for IE9-.
  1676. el.attachEvent('on' + name, handler);
  1677. }
  1678. }
  1679. /**
  1680. * Parameter are the same as `addEventListener`.
  1681. *
  1682. * Notice that if a listener is registered twice, one with capture and one without,
  1683. * remove each one separately. Removal of a capturing listener does not affect a
  1684. * non-capturing version of the same listener, and vice versa.
  1685. */
  1686. function removeEventListener(el, name, handler, opt) {
  1687. if (isDomLevel2) {
  1688. el.removeEventListener(name, handler, opt);
  1689. }
  1690. else {
  1691. el.detachEvent('on' + name, handler);
  1692. }
  1693. }
  1694. /**
  1695. * preventDefault and stopPropagation.
  1696. * Notice: do not use this method in zrender. It can only be
  1697. * used by upper applications if necessary.
  1698. *
  1699. * @param {Event} e A mouse or touch event.
  1700. */
  1701. var stop = isDomLevel2
  1702. ? function (e) {
  1703. e.preventDefault();
  1704. e.stopPropagation();
  1705. e.cancelBubble = true;
  1706. }
  1707. : function (e) {
  1708. e.returnValue = false;
  1709. e.cancelBubble = true;
  1710. };
  1711. /**
  1712. * This method only works for mouseup and mousedown. The functionality is restricted
  1713. * for fault tolerance, See the `e.which` compatibility above.
  1714. *
  1715. * @param {MouseEvent} e
  1716. * @return {boolean}
  1717. */
  1718. /**
  1719. * To be removed.
  1720. * @deprecated
  1721. */
  1722. /**
  1723. * Only implements needed gestures for mobile.
  1724. */
  1725. var GestureMgr = function () {
  1726. /**
  1727. * @private
  1728. * @type {Array.<Object>}
  1729. */
  1730. this._track = [];
  1731. };
  1732. GestureMgr.prototype = {
  1733. constructor: GestureMgr,
  1734. recognize: function (event, target, root) {
  1735. this._doTrack(event, target, root);
  1736. return this._recognize(event);
  1737. },
  1738. clear: function () {
  1739. this._track.length = 0;
  1740. return this;
  1741. },
  1742. _doTrack: function (event, target, root) {
  1743. var touches = event.touches;
  1744. if (!touches) {
  1745. return;
  1746. }
  1747. var trackItem = {
  1748. points: [],
  1749. touches: [],
  1750. target: target,
  1751. event: event
  1752. };
  1753. for (var i = 0, len = touches.length; i < len; i++) {
  1754. var touch = touches[i];
  1755. var pos = clientToLocal(root, touch, {});
  1756. trackItem.points.push([pos.zrX, pos.zrY]);
  1757. trackItem.touches.push(touch);
  1758. }
  1759. this._track.push(trackItem);
  1760. },
  1761. _recognize: function (event) {
  1762. for (var eventName in recognizers) {
  1763. if (recognizers.hasOwnProperty(eventName)) {
  1764. var gestureInfo = recognizers[eventName](this._track, event);
  1765. if (gestureInfo) {
  1766. return gestureInfo;
  1767. }
  1768. }
  1769. }
  1770. }
  1771. };
  1772. function dist$1(pointPair) {
  1773. var dx = pointPair[1][0] - pointPair[0][0];
  1774. var dy = pointPair[1][1] - pointPair[0][1];
  1775. return Math.sqrt(dx * dx + dy * dy);
  1776. }
  1777. function center(pointPair) {
  1778. return [
  1779. (pointPair[0][0] + pointPair[1][0]) / 2,
  1780. (pointPair[0][1] + pointPair[1][1]) / 2
  1781. ];
  1782. }
  1783. var recognizers = {
  1784. pinch: function (track, event) {
  1785. var trackLen = track.length;
  1786. if (!trackLen) {
  1787. return;
  1788. }
  1789. var pinchEnd = (track[trackLen - 1] || {}).points;
  1790. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1791. if (pinchPre
  1792. && pinchPre.length > 1
  1793. && pinchEnd
  1794. && pinchEnd.length > 1
  1795. ) {
  1796. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1797. !isFinite(pinchScale) && (pinchScale = 1);
  1798. event.pinchScale = pinchScale;
  1799. var pinchCenter = center(pinchEnd);
  1800. event.pinchX = pinchCenter[0];
  1801. event.pinchY = pinchCenter[1];
  1802. return {
  1803. type: 'pinch',
  1804. target: track[0].target,
  1805. event: event
  1806. };
  1807. }
  1808. }
  1809. // Only pinch currently.
  1810. };
  1811. /**
  1812. * [The interface between `Handler` and `HandlerProxy`]:
  1813. *
  1814. * The default `HandlerProxy` only support the common standard web environment
  1815. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1816. * But `HandlerProxy` can be replaced to support more non-standard environment
  1817. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1818. * not provided (like echarts-gl did).
  1819. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1820. * make break changes util inevitable. The interface include the public methods
  1821. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1822. * drives `Handler`.
  1823. */
  1824. /**
  1825. * [Drag outside]:
  1826. *
  1827. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1828. * zrender area when dragging. That is important for the improvement of the user experience
  1829. * when dragging something near the boundary without being terminated unexpectedly.
  1830. *
  1831. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1832. * to resolve this issue. But some drawbacks of it is described in
  1833. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1834. *
  1835. * Instead, we referenced the specifications:
  1836. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1837. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1838. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1839. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1840. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1841. *
  1842. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1843. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1844. * to fire until release the pointer. That is implemented by listen to those event on
  1845. * `document`.
  1846. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1847. * The touch event support this feature by default.
  1848. *
  1849. * Note:
  1850. * There might be some cases that the mouse event can not be
  1851. * received on `document`. For example,
  1852. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1853. * of zr dom throw Error .
  1854. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1855. * zr dom call `stopPropagation`.
  1856. * In these cases, the `mousemove` event might be keep triggered event
  1857. * if the mouse is released. We try to reduce the side-effect in those cases.
  1858. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1859. *
  1860. * Note:
  1861. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1862. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1863. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1864. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1865. * But they are needed to work when the pointer inside the zrender dom.
  1866. */
  1867. var SILENT = 'silent';
  1868. function makeEventPacket(eveType, targetInfo, event) {
  1869. return {
  1870. type: eveType,
  1871. event: event,
  1872. // target can only be an element that is not silent.
  1873. target: targetInfo.target,
  1874. // topTarget can be a silent element.
  1875. topTarget: targetInfo.topTarget,
  1876. cancelBubble: false,
  1877. offsetX: event.zrX,
  1878. offsetY: event.zrY,
  1879. gestureEvent: event.gestureEvent,
  1880. pinchX: event.pinchX,
  1881. pinchY: event.pinchY,
  1882. pinchScale: event.pinchScale,
  1883. wheelDelta: event.zrDelta,
  1884. zrByTouch: event.zrByTouch,
  1885. which: event.which,
  1886. stop: stopEvent
  1887. };
  1888. }
  1889. function stopEvent() {
  1890. stop(this.event);
  1891. }
  1892. function EmptyProxy() {}
  1893. EmptyProxy.prototype.dispose = function () {};
  1894. var handlerNames = [
  1895. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1896. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1897. ];
  1898. /**
  1899. * @alias module:zrender/Handler
  1900. * @constructor
  1901. * @extends module:zrender/mixin/Eventful
  1902. * @param {module:zrender/Storage} storage Storage instance.
  1903. * @param {module:zrender/Painter} painter Painter instance.
  1904. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1905. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1906. */
  1907. var Handler = function (storage, painter, proxy, painterRoot) {
  1908. Eventful.call(this);
  1909. this.storage = storage;
  1910. this.painter = painter;
  1911. this.painterRoot = painterRoot;
  1912. proxy = proxy || new EmptyProxy();
  1913. /**
  1914. * Proxy of event. can be Dom, WebGLSurface, etc.
  1915. */
  1916. this.proxy = null;
  1917. /**
  1918. * {target, topTarget, x, y}
  1919. * @private
  1920. * @type {Object}
  1921. */
  1922. this._hovered = {};
  1923. /**
  1924. * @private
  1925. * @type {Date}
  1926. */
  1927. this._lastTouchMoment;
  1928. /**
  1929. * @private
  1930. * @type {number}
  1931. */
  1932. this._lastX;
  1933. /**
  1934. * @private
  1935. * @type {number}
  1936. */
  1937. this._lastY;
  1938. /**
  1939. * @private
  1940. * @type {module:zrender/core/GestureMgr}
  1941. */
  1942. this._gestureMgr;
  1943. Draggable.call(this);
  1944. this.setHandlerProxy(proxy);
  1945. };
  1946. Handler.prototype = {
  1947. constructor: Handler,
  1948. setHandlerProxy: function (proxy) {
  1949. if (this.proxy) {
  1950. this.proxy.dispose();
  1951. }
  1952. if (proxy) {
  1953. each$1(handlerNames, function (name) {
  1954. proxy.on && proxy.on(name, this[name], this);
  1955. }, this);
  1956. // Attach handler
  1957. proxy.handler = this;
  1958. }
  1959. this.proxy = proxy;
  1960. },
  1961. mousemove: function (event) {
  1962. var x = event.zrX;
  1963. var y = event.zrY;
  1964. var isOutside = isOutsideBoundary(this, x, y);
  1965. var lastHovered = this._hovered;
  1966. var lastHoveredTarget = lastHovered.target;
  1967. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1968. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1969. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1970. // See #6198.
  1971. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1972. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1973. lastHoveredTarget = lastHovered.target;
  1974. }
  1975. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  1976. var hoveredTarget = hovered.target;
  1977. var proxy = this.proxy;
  1978. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1979. // Mouse out on previous hovered element
  1980. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1981. this.dispatchToElement(lastHovered, 'mouseout', event);
  1982. }
  1983. // Mouse moving on one element
  1984. this.dispatchToElement(hovered, 'mousemove', event);
  1985. // Mouse over on a new element
  1986. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1987. this.dispatchToElement(hovered, 'mouseover', event);
  1988. }
  1989. },
  1990. mouseout: function (event) {
  1991. var eventControl = event.zrEventControl;
  1992. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  1993. if (eventControl !== 'only_globalout') {
  1994. this.dispatchToElement(this._hovered, 'mouseout', event);
  1995. }
  1996. if (eventControl !== 'no_globalout') {
  1997. // FIXME: if the pointer moving from the extra doms to realy "outside",
  1998. // the `globalout` should have been triggered. But currently not.
  1999. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2000. }
  2001. },
  2002. /**
  2003. * Resize
  2004. */
  2005. resize: function (event) {
  2006. this._hovered = {};
  2007. },
  2008. /**
  2009. * Dispatch event
  2010. * @param {string} eventName
  2011. * @param {event=} eventArgs
  2012. */
  2013. dispatch: function (eventName, eventArgs) {
  2014. var handler = this[eventName];
  2015. handler && handler.call(this, eventArgs);
  2016. },
  2017. /**
  2018. * Dispose
  2019. */
  2020. dispose: function () {
  2021. this.proxy.dispose();
  2022. this.storage =
  2023. this.proxy =
  2024. this.painter = null;
  2025. },
  2026. /**
  2027. * 设置默认的cursor style
  2028. * @param {string} [cursorStyle='default'] 例如 crosshair
  2029. */
  2030. setCursorStyle: function (cursorStyle) {
  2031. var proxy = this.proxy;
  2032. proxy.setCursor && proxy.setCursor(cursorStyle);
  2033. },
  2034. /**
  2035. * 事件分发代理
  2036. *
  2037. * @private
  2038. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2039. * @param {string} eventName 事件名称
  2040. * @param {Object} event 事件对象
  2041. */
  2042. dispatchToElement: function (targetInfo, eventName, event) {
  2043. targetInfo = targetInfo || {};
  2044. var el = targetInfo.target;
  2045. if (el && el.silent) {
  2046. return;
  2047. }
  2048. var eventHandler = 'on' + eventName;
  2049. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2050. while (el) {
  2051. el[eventHandler]
  2052. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2053. el.trigger(eventName, eventPacket);
  2054. el = el.parent;
  2055. if (eventPacket.cancelBubble) {
  2056. break;
  2057. }
  2058. }
  2059. if (!eventPacket.cancelBubble) {
  2060. // 冒泡到顶级 zrender 对象
  2061. this.trigger(eventName, eventPacket);
  2062. // 分发事件到用户自定义层
  2063. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2064. this.painter && this.painter.eachOtherLayer(function (layer) {
  2065. if (typeof (layer[eventHandler]) === 'function') {
  2066. layer[eventHandler].call(layer, eventPacket);
  2067. }
  2068. if (layer.trigger) {
  2069. layer.trigger(eventName, eventPacket);
  2070. }
  2071. });
  2072. }
  2073. },
  2074. /**
  2075. * @private
  2076. * @param {number} x
  2077. * @param {number} y
  2078. * @param {module:zrender/graphic/Displayable} exclude
  2079. * @return {model:zrender/Element}
  2080. * @method
  2081. */
  2082. findHover: function (x, y, exclude) {
  2083. var list = this.storage.getDisplayList();
  2084. var out = {x: x, y: y};
  2085. for (var i = list.length - 1; i >= 0; i--) {
  2086. var hoverCheckResult;
  2087. if (list[i] !== exclude
  2088. // getDisplayList may include ignored item in VML mode
  2089. && !list[i].ignore
  2090. && (hoverCheckResult = isHover(list[i], x, y))
  2091. ) {
  2092. !out.topTarget && (out.topTarget = list[i]);
  2093. if (hoverCheckResult !== SILENT) {
  2094. out.target = list[i];
  2095. break;
  2096. }
  2097. }
  2098. }
  2099. return out;
  2100. },
  2101. processGesture: function (event, stage) {
  2102. if (!this._gestureMgr) {
  2103. this._gestureMgr = new GestureMgr();
  2104. }
  2105. var gestureMgr = this._gestureMgr;
  2106. stage === 'start' && gestureMgr.clear();
  2107. var gestureInfo = gestureMgr.recognize(
  2108. event,
  2109. this.findHover(event.zrX, event.zrY, null).target,
  2110. this.proxy.dom
  2111. );
  2112. stage === 'end' && gestureMgr.clear();
  2113. // Do not do any preventDefault here. Upper application do that if necessary.
  2114. if (gestureInfo) {
  2115. var type = gestureInfo.type;
  2116. event.gestureEvent = type;
  2117. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2118. }
  2119. }
  2120. };
  2121. // Common handlers
  2122. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2123. Handler.prototype[name] = function (event) {
  2124. var x = event.zrX;
  2125. var y = event.zrY;
  2126. var isOutside = isOutsideBoundary(this, x, y);
  2127. var hovered;
  2128. var hoveredTarget;
  2129. if (name !== 'mouseup' || !isOutside) {
  2130. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2131. hovered = this.findHover(x, y);
  2132. hoveredTarget = hovered.target;
  2133. }
  2134. if (name === 'mousedown') {
  2135. this._downEl = hoveredTarget;
  2136. this._downPoint = [event.zrX, event.zrY];
  2137. // In case click triggered before mouseup
  2138. this._upEl = hoveredTarget;
  2139. }
  2140. else if (name === 'mouseup') {
  2141. this._upEl = hoveredTarget;
  2142. }
  2143. else if (name === 'click') {
  2144. if (this._downEl !== this._upEl
  2145. // Original click event is triggered on the whole canvas element,
  2146. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2147. // which should be filtered, otherwise it will bring trouble to
  2148. // pan and zoom.
  2149. || !this._downPoint
  2150. // Arbitrary value
  2151. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2152. ) {
  2153. return;
  2154. }
  2155. this._downPoint = null;
  2156. }
  2157. this.dispatchToElement(hovered, name, event);
  2158. };
  2159. });
  2160. function isHover(displayable, x, y) {
  2161. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2162. var el = displayable;
  2163. var isSilent;
  2164. while (el) {
  2165. // If clipped by ancestor.
  2166. // FIXME: If clipPath has neither stroke nor fill,
  2167. // el.clipPath.contain(x, y) will always return false.
  2168. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2169. return false;
  2170. }
  2171. if (el.silent) {
  2172. isSilent = true;
  2173. }
  2174. el = el.parent;
  2175. }
  2176. return isSilent ? SILENT : true;
  2177. }
  2178. return false;
  2179. }
  2180. /**
  2181. * See [Drag outside].
  2182. */
  2183. function isOutsideBoundary(handlerInstance, x, y) {
  2184. var painter = handlerInstance.painter;
  2185. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2186. }
  2187. mixin(Handler, Eventful);
  2188. mixin(Handler, Draggable);
  2189. /**
  2190. * 3x2矩阵操作类
  2191. * @exports zrender/tool/matrix
  2192. */
  2193. /* global Float32Array */
  2194. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2195. ? Array
  2196. : Float32Array;
  2197. /**
  2198. * Create a identity matrix.
  2199. * @return {Float32Array|Array.<number>}
  2200. */
  2201. function create$1() {
  2202. var out = new ArrayCtor$1(6);
  2203. identity(out);
  2204. return out;
  2205. }
  2206. /**
  2207. * 设置矩阵为单位矩阵
  2208. * @param {Float32Array|Array.<number>} out
  2209. */
  2210. function identity(out) {
  2211. out[0] = 1;
  2212. out[1] = 0;
  2213. out[2] = 0;
  2214. out[3] = 1;
  2215. out[4] = 0;
  2216. out[5] = 0;
  2217. return out;
  2218. }
  2219. /**
  2220. * 复制矩阵
  2221. * @param {Float32Array|Array.<number>} out
  2222. * @param {Float32Array|Array.<number>} m
  2223. */
  2224. function copy$1(out, m) {
  2225. out[0] = m[0];
  2226. out[1] = m[1];
  2227. out[2] = m[2];
  2228. out[3] = m[3];
  2229. out[4] = m[4];
  2230. out[5] = m[5];
  2231. return out;
  2232. }
  2233. /**
  2234. * 矩阵相乘
  2235. * @param {Float32Array|Array.<number>} out
  2236. * @param {Float32Array|Array.<number>} m1
  2237. * @param {Float32Array|Array.<number>} m2
  2238. */
  2239. function mul$1(out, m1, m2) {
  2240. // Consider matrix.mul(m, m2, m);
  2241. // where out is the same as m2.
  2242. // So use temp variable to escape error.
  2243. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2244. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2245. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2246. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2247. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2248. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2249. out[0] = out0;
  2250. out[1] = out1;
  2251. out[2] = out2;
  2252. out[3] = out3;
  2253. out[4] = out4;
  2254. out[5] = out5;
  2255. return out;
  2256. }
  2257. /**
  2258. * 平移变换
  2259. * @param {Float32Array|Array.<number>} out
  2260. * @param {Float32Array|Array.<number>} a
  2261. * @param {Float32Array|Array.<number>} v
  2262. */
  2263. function translate(out, a, v) {
  2264. out[0] = a[0];
  2265. out[1] = a[1];
  2266. out[2] = a[2];
  2267. out[3] = a[3];
  2268. out[4] = a[4] + v[0];
  2269. out[5] = a[5] + v[1];
  2270. return out;
  2271. }
  2272. /**
  2273. * 旋转变换
  2274. * @param {Float32Array|Array.<number>} out
  2275. * @param {Float32Array|Array.<number>} a
  2276. * @param {number} rad
  2277. */
  2278. function rotate(out, a, rad) {
  2279. var aa = a[0];
  2280. var ac = a[2];
  2281. var atx = a[4];
  2282. var ab = a[1];
  2283. var ad = a[3];
  2284. var aty = a[5];
  2285. var st = Math.sin(rad);
  2286. var ct = Math.cos(rad);
  2287. out[0] = aa * ct + ab * st;
  2288. out[1] = -aa * st + ab * ct;
  2289. out[2] = ac * ct + ad * st;
  2290. out[3] = -ac * st + ct * ad;
  2291. out[4] = ct * atx + st * aty;
  2292. out[5] = ct * aty - st * atx;
  2293. return out;
  2294. }
  2295. /**
  2296. * 缩放变换
  2297. * @param {Float32Array|Array.<number>} out
  2298. * @param {Float32Array|Array.<number>} a
  2299. * @param {Float32Array|Array.<number>} v
  2300. */
  2301. function scale$1(out, a, v) {
  2302. var vx = v[0];
  2303. var vy = v[1];
  2304. out[0] = a[0] * vx;
  2305. out[1] = a[1] * vy;
  2306. out[2] = a[2] * vx;
  2307. out[3] = a[3] * vy;
  2308. out[4] = a[4] * vx;
  2309. out[5] = a[5] * vy;
  2310. return out;
  2311. }
  2312. /**
  2313. * 求逆矩阵
  2314. * @param {Float32Array|Array.<number>} out
  2315. * @param {Float32Array|Array.<number>} a
  2316. */
  2317. function invert(out, a) {
  2318. var aa = a[0];
  2319. var ac = a[2];
  2320. var atx = a[4];
  2321. var ab = a[1];
  2322. var ad = a[3];
  2323. var aty = a[5];
  2324. var det = aa * ad - ab * ac;
  2325. if (!det) {
  2326. return null;
  2327. }
  2328. det = 1.0 / det;
  2329. out[0] = ad * det;
  2330. out[1] = -ab * det;
  2331. out[2] = -ac * det;
  2332. out[3] = aa * det;
  2333. out[4] = (ac * aty - ad * atx) * det;
  2334. out[5] = (ab * atx - aa * aty) * det;
  2335. return out;
  2336. }
  2337. /**
  2338. * Clone a new matrix.
  2339. * @param {Float32Array|Array.<number>} a
  2340. */
  2341. /**
  2342. * 提供变换扩展
  2343. * @module zrender/mixin/Transformable
  2344. * @author pissang (https://www.github.com/pissang)
  2345. */
  2346. var mIdentity = identity;
  2347. var EPSILON = 5e-5;
  2348. function isNotAroundZero(val) {
  2349. return val > EPSILON || val < -EPSILON;
  2350. }
  2351. /**
  2352. * @alias module:zrender/mixin/Transformable
  2353. * @constructor
  2354. */
  2355. var Transformable = function (opts) {
  2356. opts = opts || {};
  2357. // If there are no given position, rotation, scale
  2358. if (!opts.position) {
  2359. /**
  2360. * 平移
  2361. * @type {Array.<number>}
  2362. * @default [0, 0]
  2363. */
  2364. this.position = [0, 0];
  2365. }
  2366. if (opts.rotation == null) {
  2367. /**
  2368. * 旋转
  2369. * @type {Array.<number>}
  2370. * @default 0
  2371. */
  2372. this.rotation = 0;
  2373. }
  2374. if (!opts.scale) {
  2375. /**
  2376. * 缩放
  2377. * @type {Array.<number>}
  2378. * @default [1, 1]
  2379. */
  2380. this.scale = [1, 1];
  2381. }
  2382. /**
  2383. * 旋转和缩放的原点
  2384. * @type {Array.<number>}
  2385. * @default null
  2386. */
  2387. this.origin = this.origin || null;
  2388. };
  2389. var transformableProto = Transformable.prototype;
  2390. transformableProto.transform = null;
  2391. /**
  2392. * 判断是否需要有坐标变换
  2393. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2394. */
  2395. transformableProto.needLocalTransform = function () {
  2396. return isNotAroundZero(this.rotation)
  2397. || isNotAroundZero(this.position[0])
  2398. || isNotAroundZero(this.position[1])
  2399. || isNotAroundZero(this.scale[0] - 1)
  2400. || isNotAroundZero(this.scale[1] - 1);
  2401. };
  2402. var scaleTmp = [];
  2403. transformableProto.updateTransform = function () {
  2404. var parent = this.parent;
  2405. var parentHasTransform = parent && parent.transform;
  2406. var needLocalTransform = this.needLocalTransform();
  2407. var m = this.transform;
  2408. if (!(needLocalTransform || parentHasTransform)) {
  2409. m && mIdentity(m);
  2410. return;
  2411. }
  2412. m = m || create$1();
  2413. if (needLocalTransform) {
  2414. this.getLocalTransform(m);
  2415. }
  2416. else {
  2417. mIdentity(m);
  2418. }
  2419. // 应用父节点变换
  2420. if (parentHasTransform) {
  2421. if (needLocalTransform) {
  2422. mul$1(m, parent.transform, m);
  2423. }
  2424. else {
  2425. copy$1(m, parent.transform);
  2426. }
  2427. }
  2428. // 保存这个变换矩阵
  2429. this.transform = m;
  2430. var globalScaleRatio = this.globalScaleRatio;
  2431. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2432. this.getGlobalScale(scaleTmp);
  2433. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2434. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2435. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2436. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2437. m[0] *= sx;
  2438. m[1] *= sx;
  2439. m[2] *= sy;
  2440. m[3] *= sy;
  2441. }
  2442. this.invTransform = this.invTransform || create$1();
  2443. invert(this.invTransform, m);
  2444. };
  2445. transformableProto.getLocalTransform = function (m) {
  2446. return Transformable.getLocalTransform(this, m);
  2447. };
  2448. /**
  2449. * 将自己的transform应用到context上
  2450. * @param {CanvasRenderingContext2D} ctx
  2451. */
  2452. transformableProto.setTransform = function (ctx) {
  2453. var m = this.transform;
  2454. var dpr = ctx.dpr || 1;
  2455. if (m) {
  2456. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2457. }
  2458. else {
  2459. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2460. }
  2461. };
  2462. transformableProto.restoreTransform = function (ctx) {
  2463. var dpr = ctx.dpr || 1;
  2464. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2465. };
  2466. var tmpTransform = [];
  2467. var originTransform = create$1();
  2468. transformableProto.setLocalTransform = function (m) {
  2469. if (!m) {
  2470. // TODO return or set identity?
  2471. return;
  2472. }
  2473. var sx = m[0] * m[0] + m[1] * m[1];
  2474. var sy = m[2] * m[2] + m[3] * m[3];
  2475. var position = this.position;
  2476. var scale$$1 = this.scale;
  2477. if (isNotAroundZero(sx - 1)) {
  2478. sx = Math.sqrt(sx);
  2479. }
  2480. if (isNotAroundZero(sy - 1)) {
  2481. sy = Math.sqrt(sy);
  2482. }
  2483. if (m[0] < 0) {
  2484. sx = -sx;
  2485. }
  2486. if (m[3] < 0) {
  2487. sy = -sy;
  2488. }
  2489. position[0] = m[4];
  2490. position[1] = m[5];
  2491. scale$$1[0] = sx;
  2492. scale$$1[1] = sy;
  2493. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2494. };
  2495. /**
  2496. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2497. */
  2498. transformableProto.decomposeTransform = function () {
  2499. if (!this.transform) {
  2500. return;
  2501. }
  2502. var parent = this.parent;
  2503. var m = this.transform;
  2504. if (parent && parent.transform) {
  2505. // Get local transform and decompose them to position, scale, rotation
  2506. mul$1(tmpTransform, parent.invTransform, m);
  2507. m = tmpTransform;
  2508. }
  2509. var origin = this.origin;
  2510. if (origin && (origin[0] || origin[1])) {
  2511. originTransform[4] = origin[0];
  2512. originTransform[5] = origin[1];
  2513. mul$1(tmpTransform, m, originTransform);
  2514. tmpTransform[4] -= origin[0];
  2515. tmpTransform[5] -= origin[1];
  2516. m = tmpTransform;
  2517. }
  2518. this.setLocalTransform(m);
  2519. };
  2520. /**
  2521. * Get global scale
  2522. * @return {Array.<number>}
  2523. */
  2524. transformableProto.getGlobalScale = function (out) {
  2525. var m = this.transform;
  2526. out = out || [];
  2527. if (!m) {
  2528. out[0] = 1;
  2529. out[1] = 1;
  2530. return out;
  2531. }
  2532. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2533. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2534. if (m[0] < 0) {
  2535. out[0] = -out[0];
  2536. }
  2537. if (m[3] < 0) {
  2538. out[1] = -out[1];
  2539. }
  2540. return out;
  2541. };
  2542. /**
  2543. * 变换坐标位置到 shape 的局部坐标空间
  2544. * @method
  2545. * @param {number} x
  2546. * @param {number} y
  2547. * @return {Array.<number>}
  2548. */
  2549. transformableProto.transformCoordToLocal = function (x, y) {
  2550. var v2 = [x, y];
  2551. var invTransform = this.invTransform;
  2552. if (invTransform) {
  2553. applyTransform(v2, v2, invTransform);
  2554. }
  2555. return v2;
  2556. };
  2557. /**
  2558. * 变换局部坐标位置到全局坐标空间
  2559. * @method
  2560. * @param {number} x
  2561. * @param {number} y
  2562. * @return {Array.<number>}
  2563. */
  2564. transformableProto.transformCoordToGlobal = function (x, y) {
  2565. var v2 = [x, y];
  2566. var transform = this.transform;
  2567. if (transform) {
  2568. applyTransform(v2, v2, transform);
  2569. }
  2570. return v2;
  2571. };
  2572. /**
  2573. * @static
  2574. * @param {Object} target
  2575. * @param {Array.<number>} target.origin
  2576. * @param {number} target.rotation
  2577. * @param {Array.<number>} target.position
  2578. * @param {Array.<number>} [m]
  2579. */
  2580. Transformable.getLocalTransform = function (target, m) {
  2581. m = m || [];
  2582. mIdentity(m);
  2583. var origin = target.origin;
  2584. var scale$$1 = target.scale || [1, 1];
  2585. var rotation = target.rotation || 0;
  2586. var position = target.position || [0, 0];
  2587. if (origin) {
  2588. // Translate to origin
  2589. m[4] -= origin[0];
  2590. m[5] -= origin[1];
  2591. }
  2592. scale$1(m, m, scale$$1);
  2593. if (rotation) {
  2594. rotate(m, m, rotation);
  2595. }
  2596. if (origin) {
  2597. // Translate back from origin
  2598. m[4] += origin[0];
  2599. m[5] += origin[1];
  2600. }
  2601. m[4] += position[0];
  2602. m[5] += position[1];
  2603. return m;
  2604. };
  2605. /**
  2606. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2607. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2608. * @exports zrender/animation/easing
  2609. */
  2610. var easing = {
  2611. /**
  2612. * @param {number} k
  2613. * @return {number}
  2614. */
  2615. linear: function (k) {
  2616. return k;
  2617. },
  2618. /**
  2619. * @param {number} k
  2620. * @return {number}
  2621. */
  2622. quadraticIn: function (k) {
  2623. return k * k;
  2624. },
  2625. /**
  2626. * @param {number} k
  2627. * @return {number}
  2628. */
  2629. quadraticOut: function (k) {
  2630. return k * (2 - k);
  2631. },
  2632. /**
  2633. * @param {number} k
  2634. * @return {number}
  2635. */
  2636. quadraticInOut: function (k) {
  2637. if ((k *= 2) < 1) {
  2638. return 0.5 * k * k;
  2639. }
  2640. return -0.5 * (--k * (k - 2) - 1);
  2641. },
  2642. // 三次方的缓动(t^3)
  2643. /**
  2644. * @param {number} k
  2645. * @return {number}
  2646. */
  2647. cubicIn: function (k) {
  2648. return k * k * k;
  2649. },
  2650. /**
  2651. * @param {number} k
  2652. * @return {number}
  2653. */
  2654. cubicOut: function (k) {
  2655. return --k * k * k + 1;
  2656. },
  2657. /**
  2658. * @param {number} k
  2659. * @return {number}
  2660. */
  2661. cubicInOut: function (k) {
  2662. if ((k *= 2) < 1) {
  2663. return 0.5 * k * k * k;
  2664. }
  2665. return 0.5 * ((k -= 2) * k * k + 2);
  2666. },
  2667. // 四次方的缓动(t^4)
  2668. /**
  2669. * @param {number} k
  2670. * @return {number}
  2671. */
  2672. quarticIn: function (k) {
  2673. return k * k * k * k;
  2674. },
  2675. /**
  2676. * @param {number} k
  2677. * @return {number}
  2678. */
  2679. quarticOut: function (k) {
  2680. return 1 - (--k * k * k * k);
  2681. },
  2682. /**
  2683. * @param {number} k
  2684. * @return {number}
  2685. */
  2686. quarticInOut: function (k) {
  2687. if ((k *= 2) < 1) {
  2688. return 0.5 * k * k * k * k;
  2689. }
  2690. return -0.5 * ((k -= 2) * k * k * k - 2);
  2691. },
  2692. // 五次方的缓动(t^5)
  2693. /**
  2694. * @param {number} k
  2695. * @return {number}
  2696. */
  2697. quinticIn: function (k) {
  2698. return k * k * k * k * k;
  2699. },
  2700. /**
  2701. * @param {number} k
  2702. * @return {number}
  2703. */
  2704. quinticOut: function (k) {
  2705. return --k * k * k * k * k + 1;
  2706. },
  2707. /**
  2708. * @param {number} k
  2709. * @return {number}
  2710. */
  2711. quinticInOut: function (k) {
  2712. if ((k *= 2) < 1) {
  2713. return 0.5 * k * k * k * k * k;
  2714. }
  2715. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2716. },
  2717. // 正弦曲线的缓动(sin(t))
  2718. /**
  2719. * @param {number} k
  2720. * @return {number}
  2721. */
  2722. sinusoidalIn: function (k) {
  2723. return 1 - Math.cos(k * Math.PI / 2);
  2724. },
  2725. /**
  2726. * @param {number} k
  2727. * @return {number}
  2728. */
  2729. sinusoidalOut: function (k) {
  2730. return Math.sin(k * Math.PI / 2);
  2731. },
  2732. /**
  2733. * @param {number} k
  2734. * @return {number}
  2735. */
  2736. sinusoidalInOut: function (k) {
  2737. return 0.5 * (1 - Math.cos(Math.PI * k));
  2738. },
  2739. // 指数曲线的缓动(2^t)
  2740. /**
  2741. * @param {number} k
  2742. * @return {number}
  2743. */
  2744. exponentialIn: function (k) {
  2745. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2746. },
  2747. /**
  2748. * @param {number} k
  2749. * @return {number}
  2750. */
  2751. exponentialOut: function (k) {
  2752. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2753. },
  2754. /**
  2755. * @param {number} k
  2756. * @return {number}
  2757. */
  2758. exponentialInOut: function (k) {
  2759. if (k === 0) {
  2760. return 0;
  2761. }
  2762. if (k === 1) {
  2763. return 1;
  2764. }
  2765. if ((k *= 2) < 1) {
  2766. return 0.5 * Math.pow(1024, k - 1);
  2767. }
  2768. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2769. },
  2770. // 圆形曲线的缓动(sqrt(1-t^2))
  2771. /**
  2772. * @param {number} k
  2773. * @return {number}
  2774. */
  2775. circularIn: function (k) {
  2776. return 1 - Math.sqrt(1 - k * k);
  2777. },
  2778. /**
  2779. * @param {number} k
  2780. * @return {number}
  2781. */
  2782. circularOut: function (k) {
  2783. return Math.sqrt(1 - (--k * k));
  2784. },
  2785. /**
  2786. * @param {number} k
  2787. * @return {number}
  2788. */
  2789. circularInOut: function (k) {
  2790. if ((k *= 2) < 1) {
  2791. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2792. }
  2793. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2794. },
  2795. // 创建类似于弹簧在停止前来回振荡的动画
  2796. /**
  2797. * @param {number} k
  2798. * @return {number}
  2799. */
  2800. elasticIn: function (k) {
  2801. var s;
  2802. var a = 0.1;
  2803. var p = 0.4;
  2804. if (k === 0) {
  2805. return 0;
  2806. }
  2807. if (k === 1) {
  2808. return 1;
  2809. }
  2810. if (!a || a < 1) {
  2811. a = 1;
  2812. s = p / 4;
  2813. }
  2814. else {
  2815. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2816. }
  2817. return -(a * Math.pow(2, 10 * (k -= 1))
  2818. * Math.sin((k - s) * (2 * Math.PI) / p));
  2819. },
  2820. /**
  2821. * @param {number} k
  2822. * @return {number}
  2823. */
  2824. elasticOut: function (k) {
  2825. var s;
  2826. var a = 0.1;
  2827. var p = 0.4;
  2828. if (k === 0) {
  2829. return 0;
  2830. }
  2831. if (k === 1) {
  2832. return 1;
  2833. }
  2834. if (!a || a < 1) {
  2835. a = 1;
  2836. s = p / 4;
  2837. }
  2838. else {
  2839. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2840. }
  2841. return (a * Math.pow(2, -10 * k)
  2842. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2843. },
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. elasticInOut: function (k) {
  2849. var s;
  2850. var a = 0.1;
  2851. var p = 0.4;
  2852. if (k === 0) {
  2853. return 0;
  2854. }
  2855. if (k === 1) {
  2856. return 1;
  2857. }
  2858. if (!a || a < 1) {
  2859. a = 1;
  2860. s = p / 4;
  2861. }
  2862. else {
  2863. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2864. }
  2865. if ((k *= 2) < 1) {
  2866. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2867. * Math.sin((k - s) * (2 * Math.PI) / p));
  2868. }
  2869. return a * Math.pow(2, -10 * (k -= 1))
  2870. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2871. },
  2872. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2873. /**
  2874. * @param {number} k
  2875. * @return {number}
  2876. */
  2877. backIn: function (k) {
  2878. var s = 1.70158;
  2879. return k * k * ((s + 1) * k - s);
  2880. },
  2881. /**
  2882. * @param {number} k
  2883. * @return {number}
  2884. */
  2885. backOut: function (k) {
  2886. var s = 1.70158;
  2887. return --k * k * ((s + 1) * k + s) + 1;
  2888. },
  2889. /**
  2890. * @param {number} k
  2891. * @return {number}
  2892. */
  2893. backInOut: function (k) {
  2894. var s = 1.70158 * 1.525;
  2895. if ((k *= 2) < 1) {
  2896. return 0.5 * (k * k * ((s + 1) * k - s));
  2897. }
  2898. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2899. },
  2900. // 创建弹跳效果
  2901. /**
  2902. * @param {number} k
  2903. * @return {number}
  2904. */
  2905. bounceIn: function (k) {
  2906. return 1 - easing.bounceOut(1 - k);
  2907. },
  2908. /**
  2909. * @param {number} k
  2910. * @return {number}
  2911. */
  2912. bounceOut: function (k) {
  2913. if (k < (1 / 2.75)) {
  2914. return 7.5625 * k * k;
  2915. }
  2916. else if (k < (2 / 2.75)) {
  2917. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2918. }
  2919. else if (k < (2.5 / 2.75)) {
  2920. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2921. }
  2922. else {
  2923. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2924. }
  2925. },
  2926. /**
  2927. * @param {number} k
  2928. * @return {number}
  2929. */
  2930. bounceInOut: function (k) {
  2931. if (k < 0.5) {
  2932. return easing.bounceIn(k * 2) * 0.5;
  2933. }
  2934. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2935. }
  2936. };
  2937. /**
  2938. * 动画主控制器
  2939. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2940. * @config life(1000) 动画时长
  2941. * @config delay(0) 动画延迟时间
  2942. * @config loop(true)
  2943. * @config gap(0) 循环的间隔时间
  2944. * @config onframe
  2945. * @config easing(optional)
  2946. * @config ondestroy(optional)
  2947. * @config onrestart(optional)
  2948. *
  2949. * TODO pause
  2950. */
  2951. function Clip(options) {
  2952. this._target = options.target;
  2953. // 生命周期
  2954. this._life = options.life || 1000;
  2955. // 延时
  2956. this._delay = options.delay || 0;
  2957. // 开始时间
  2958. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2959. this._initialized = false;
  2960. // 是否循环
  2961. this.loop = options.loop == null ? false : options.loop;
  2962. this.gap = options.gap || 0;
  2963. this.easing = options.easing || 'Linear';
  2964. this.onframe = options.onframe;
  2965. this.ondestroy = options.ondestroy;
  2966. this.onrestart = options.onrestart;
  2967. this._pausedTime = 0;
  2968. this._paused = false;
  2969. }
  2970. Clip.prototype = {
  2971. constructor: Clip,
  2972. step: function (globalTime, deltaTime) {
  2973. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2974. // PENDING
  2975. if (!this._initialized) {
  2976. this._startTime = globalTime + this._delay;
  2977. this._initialized = true;
  2978. }
  2979. if (this._paused) {
  2980. this._pausedTime += deltaTime;
  2981. return;
  2982. }
  2983. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2984. // 还没开始
  2985. if (percent < 0) {
  2986. return;
  2987. }
  2988. percent = Math.min(percent, 1);
  2989. var easing$$1 = this.easing;
  2990. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  2991. var schedule = typeof easingFunc === 'function'
  2992. ? easingFunc(percent)
  2993. : percent;
  2994. this.fire('frame', schedule);
  2995. // 结束
  2996. if (percent === 1) {
  2997. if (this.loop) {
  2998. this.restart(globalTime);
  2999. // 重新开始周期
  3000. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3001. return 'restart';
  3002. }
  3003. // 动画完成将这个控制器标识为待删除
  3004. // 在Animation.update中进行批量删除
  3005. this._needsRemove = true;
  3006. return 'destroy';
  3007. }
  3008. return null;
  3009. },
  3010. restart: function (globalTime) {
  3011. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3012. this._startTime = globalTime - remainder + this.gap;
  3013. this._pausedTime = 0;
  3014. this._needsRemove = false;
  3015. },
  3016. fire: function (eventType, arg) {
  3017. eventType = 'on' + eventType;
  3018. if (this[eventType]) {
  3019. this[eventType](this._target, arg);
  3020. }
  3021. },
  3022. pause: function () {
  3023. this._paused = true;
  3024. },
  3025. resume: function () {
  3026. this._paused = false;
  3027. }
  3028. };
  3029. // Simple LRU cache use doubly linked list
  3030. // @module zrender/core/LRU
  3031. /**
  3032. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3033. * @constructor
  3034. */
  3035. var LinkedList = function () {
  3036. /**
  3037. * @type {module:zrender/core/LRU~Entry}
  3038. */
  3039. this.head = null;
  3040. /**
  3041. * @type {module:zrender/core/LRU~Entry}
  3042. */
  3043. this.tail = null;
  3044. this._len = 0;
  3045. };
  3046. var linkedListProto = LinkedList.prototype;
  3047. /**
  3048. * Insert a new value at the tail
  3049. * @param {} val
  3050. * @return {module:zrender/core/LRU~Entry}
  3051. */
  3052. linkedListProto.insert = function (val) {
  3053. var entry = new Entry(val);
  3054. this.insertEntry(entry);
  3055. return entry;
  3056. };
  3057. /**
  3058. * Insert an entry at the tail
  3059. * @param {module:zrender/core/LRU~Entry} entry
  3060. */
  3061. linkedListProto.insertEntry = function (entry) {
  3062. if (!this.head) {
  3063. this.head = this.tail = entry;
  3064. }
  3065. else {
  3066. this.tail.next = entry;
  3067. entry.prev = this.tail;
  3068. entry.next = null;
  3069. this.tail = entry;
  3070. }
  3071. this._len++;
  3072. };
  3073. /**
  3074. * Remove entry.
  3075. * @param {module:zrender/core/LRU~Entry} entry
  3076. */
  3077. linkedListProto.remove = function (entry) {
  3078. var prev = entry.prev;
  3079. var next = entry.next;
  3080. if (prev) {
  3081. prev.next = next;
  3082. }
  3083. else {
  3084. // Is head
  3085. this.head = next;
  3086. }
  3087. if (next) {
  3088. next.prev = prev;
  3089. }
  3090. else {
  3091. // Is tail
  3092. this.tail = prev;
  3093. }
  3094. entry.next = entry.prev = null;
  3095. this._len--;
  3096. };
  3097. /**
  3098. * @return {number}
  3099. */
  3100. linkedListProto.len = function () {
  3101. return this._len;
  3102. };
  3103. /**
  3104. * Clear list
  3105. */
  3106. linkedListProto.clear = function () {
  3107. this.head = this.tail = null;
  3108. this._len = 0;
  3109. };
  3110. /**
  3111. * @constructor
  3112. * @param {} val
  3113. */
  3114. var Entry = function (val) {
  3115. /**
  3116. * @type {}
  3117. */
  3118. this.value = val;
  3119. /**
  3120. * @type {module:zrender/core/LRU~Entry}
  3121. */
  3122. this.next;
  3123. /**
  3124. * @type {module:zrender/core/LRU~Entry}
  3125. */
  3126. this.prev;
  3127. };
  3128. /**
  3129. * LRU Cache
  3130. * @constructor
  3131. * @alias module:zrender/core/LRU
  3132. */
  3133. var LRU = function (maxSize) {
  3134. this._list = new LinkedList();
  3135. this._map = {};
  3136. this._maxSize = maxSize || 10;
  3137. this._lastRemovedEntry = null;
  3138. };
  3139. var LRUProto = LRU.prototype;
  3140. /**
  3141. * @param {string} key
  3142. * @param {} value
  3143. * @return {} Removed value
  3144. */
  3145. LRUProto.put = function (key, value) {
  3146. var list = this._list;
  3147. var map = this._map;
  3148. var removed = null;
  3149. if (map[key] == null) {
  3150. var len = list.len();
  3151. // Reuse last removed entry
  3152. var entry = this._lastRemovedEntry;
  3153. if (len >= this._maxSize && len > 0) {
  3154. // Remove the least recently used
  3155. var leastUsedEntry = list.head;
  3156. list.remove(leastUsedEntry);
  3157. delete map[leastUsedEntry.key];
  3158. removed = leastUsedEntry.value;
  3159. this._lastRemovedEntry = leastUsedEntry;
  3160. }
  3161. if (entry) {
  3162. entry.value = value;
  3163. }
  3164. else {
  3165. entry = new Entry(value);
  3166. }
  3167. entry.key = key;
  3168. list.insertEntry(entry);
  3169. map[key] = entry;
  3170. }
  3171. return removed;
  3172. };
  3173. /**
  3174. * @param {string} key
  3175. * @return {}
  3176. */
  3177. LRUProto.get = function (key) {
  3178. var entry = this._map[key];
  3179. var list = this._list;
  3180. if (entry != null) {
  3181. // Put the latest used entry in the tail
  3182. if (entry !== list.tail) {
  3183. list.remove(entry);
  3184. list.insertEntry(entry);
  3185. }
  3186. return entry.value;
  3187. }
  3188. };
  3189. /**
  3190. * Clear the cache
  3191. */
  3192. LRUProto.clear = function () {
  3193. this._list.clear();
  3194. this._map = {};
  3195. };
  3196. var kCSSColorTable = {
  3197. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3198. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3199. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3200. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3201. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3202. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3203. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3204. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3205. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3206. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3207. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3208. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3209. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3210. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3211. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3212. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3213. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3214. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3215. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3216. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3217. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3218. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3219. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3220. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3221. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3222. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3223. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3224. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3225. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3226. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3227. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3228. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3229. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3230. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3231. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3232. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3233. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3234. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3235. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3236. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3237. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3238. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3239. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3240. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3241. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3242. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3243. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3244. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3245. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3246. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3247. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3248. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3249. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3250. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3251. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3252. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3253. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3254. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3255. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3256. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3257. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3258. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3259. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3260. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3261. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3262. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3263. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3264. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3265. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3266. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3267. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3268. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3269. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3270. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3271. };
  3272. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3273. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3274. return i < 0 ? 0 : i > 255 ? 255 : i;
  3275. }
  3276. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3277. return f < 0 ? 0 : f > 1 ? 1 : f;
  3278. }
  3279. function parseCssInt(str) { // int or percentage.
  3280. if (str.length && str.charAt(str.length - 1) === '%') {
  3281. return clampCssByte(parseFloat(str) / 100 * 255);
  3282. }
  3283. return clampCssByte(parseInt(str, 10));
  3284. }
  3285. function parseCssFloat(str) { // float or percentage.
  3286. if (str.length && str.charAt(str.length - 1) === '%') {
  3287. return clampCssFloat(parseFloat(str) / 100);
  3288. }
  3289. return clampCssFloat(parseFloat(str));
  3290. }
  3291. function cssHueToRgb(m1, m2, h) {
  3292. if (h < 0) {
  3293. h += 1;
  3294. }
  3295. else if (h > 1) {
  3296. h -= 1;
  3297. }
  3298. if (h * 6 < 1) {
  3299. return m1 + (m2 - m1) * h * 6;
  3300. }
  3301. if (h * 2 < 1) {
  3302. return m2;
  3303. }
  3304. if (h * 3 < 2) {
  3305. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3306. }
  3307. return m1;
  3308. }
  3309. function setRgba(out, r, g, b, a) {
  3310. out[0] = r;
  3311. out[1] = g;
  3312. out[2] = b;
  3313. out[3] = a;
  3314. return out;
  3315. }
  3316. function copyRgba(out, a) {
  3317. out[0] = a[0];
  3318. out[1] = a[1];
  3319. out[2] = a[2];
  3320. out[3] = a[3];
  3321. return out;
  3322. }
  3323. var colorCache = new LRU(20);
  3324. var lastRemovedArr = null;
  3325. function putToCache(colorStr, rgbaArr) {
  3326. // Reuse removed array
  3327. if (lastRemovedArr) {
  3328. copyRgba(lastRemovedArr, rgbaArr);
  3329. }
  3330. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3331. }
  3332. /**
  3333. * @param {string} colorStr
  3334. * @param {Array.<number>} out
  3335. * @return {Array.<number>}
  3336. * @memberOf module:zrender/util/color
  3337. */
  3338. function parse(colorStr, rgbaArr) {
  3339. if (!colorStr) {
  3340. return;
  3341. }
  3342. rgbaArr = rgbaArr || [];
  3343. var cached = colorCache.get(colorStr);
  3344. if (cached) {
  3345. return copyRgba(rgbaArr, cached);
  3346. }
  3347. // colorStr may be not string
  3348. colorStr = colorStr + '';
  3349. // Remove all whitespace, not compliant, but should just be more accepting.
  3350. var str = colorStr.replace(/ /g, '').toLowerCase();
  3351. // Color keywords (and transparent) lookup.
  3352. if (str in kCSSColorTable) {
  3353. copyRgba(rgbaArr, kCSSColorTable[str]);
  3354. putToCache(colorStr, rgbaArr);
  3355. return rgbaArr;
  3356. }
  3357. // #abc and #abc123 syntax.
  3358. if (str.charAt(0) === '#') {
  3359. if (str.length === 4) {
  3360. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3361. if (!(iv >= 0 && iv <= 0xfff)) {
  3362. setRgba(rgbaArr, 0, 0, 0, 1);
  3363. return; // Covers NaN.
  3364. }
  3365. setRgba(rgbaArr,
  3366. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3367. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3368. (iv & 0xf) | ((iv & 0xf) << 4),
  3369. 1
  3370. );
  3371. putToCache(colorStr, rgbaArr);
  3372. return rgbaArr;
  3373. }
  3374. else if (str.length === 7) {
  3375. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3376. if (!(iv >= 0 && iv <= 0xffffff)) {
  3377. setRgba(rgbaArr, 0, 0, 0, 1);
  3378. return; // Covers NaN.
  3379. }
  3380. setRgba(rgbaArr,
  3381. (iv & 0xff0000) >> 16,
  3382. (iv & 0xff00) >> 8,
  3383. iv & 0xff,
  3384. 1
  3385. );
  3386. putToCache(colorStr, rgbaArr);
  3387. return rgbaArr;
  3388. }
  3389. return;
  3390. }
  3391. var op = str.indexOf('(');
  3392. var ep = str.indexOf(')');
  3393. if (op !== -1 && ep + 1 === str.length) {
  3394. var fname = str.substr(0, op);
  3395. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3396. var alpha = 1; // To allow case fallthrough.
  3397. switch (fname) {
  3398. case 'rgba':
  3399. if (params.length !== 4) {
  3400. setRgba(rgbaArr, 0, 0, 0, 1);
  3401. return;
  3402. }
  3403. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3404. // Fall through.
  3405. case 'rgb':
  3406. if (params.length !== 3) {
  3407. setRgba(rgbaArr, 0, 0, 0, 1);
  3408. return;
  3409. }
  3410. setRgba(rgbaArr,
  3411. parseCssInt(params[0]),
  3412. parseCssInt(params[1]),
  3413. parseCssInt(params[2]),
  3414. alpha
  3415. );
  3416. putToCache(colorStr, rgbaArr);
  3417. return rgbaArr;
  3418. case 'hsla':
  3419. if (params.length !== 4) {
  3420. setRgba(rgbaArr, 0, 0, 0, 1);
  3421. return;
  3422. }
  3423. params[3] = parseCssFloat(params[3]);
  3424. hsla2rgba(params, rgbaArr);
  3425. putToCache(colorStr, rgbaArr);
  3426. return rgbaArr;
  3427. case 'hsl':
  3428. if (params.length !== 3) {
  3429. setRgba(rgbaArr, 0, 0, 0, 1);
  3430. return;
  3431. }
  3432. hsla2rgba(params, rgbaArr);
  3433. putToCache(colorStr, rgbaArr);
  3434. return rgbaArr;
  3435. default:
  3436. return;
  3437. }
  3438. }
  3439. setRgba(rgbaArr, 0, 0, 0, 1);
  3440. return;
  3441. }
  3442. /**
  3443. * @param {Array.<number>} hsla
  3444. * @param {Array.<number>} rgba
  3445. * @return {Array.<number>} rgba
  3446. */
  3447. function hsla2rgba(hsla, rgba) {
  3448. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3449. // NOTE(deanm): According to the CSS spec s/l should only be
  3450. // percentages, but we don't bother and let float or percentage.
  3451. var s = parseCssFloat(hsla[1]);
  3452. var l = parseCssFloat(hsla[2]);
  3453. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3454. var m1 = l * 2 - m2;
  3455. rgba = rgba || [];
  3456. setRgba(rgba,
  3457. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3458. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3459. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3460. 1
  3461. );
  3462. if (hsla.length === 4) {
  3463. rgba[3] = hsla[3];
  3464. }
  3465. return rgba;
  3466. }
  3467. /**
  3468. * @param {string} color
  3469. * @param {number} level
  3470. * @return {string}
  3471. * @memberOf module:zrender/util/color
  3472. */
  3473. function lift(color, level) {
  3474. var colorArr = parse(color);
  3475. if (colorArr) {
  3476. for (var i = 0; i < 3; i++) {
  3477. if (level < 0) {
  3478. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3479. }
  3480. else {
  3481. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3482. }
  3483. if (colorArr[i] > 255) {
  3484. colorArr[i] = 255;
  3485. }
  3486. else if (color[i] < 0) {
  3487. colorArr[i] = 0;
  3488. }
  3489. }
  3490. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3491. }
  3492. }
  3493. /**
  3494. * @param {string} color
  3495. * @return {string}
  3496. * @memberOf module:zrender/util/color
  3497. */
  3498. /**
  3499. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3500. * @param {number} normalizedValue A float between 0 and 1.
  3501. * @param {Array.<Array.<number>>} colors List of rgba color array
  3502. * @param {Array.<number>} [out] Mapped gba color array
  3503. * @return {Array.<number>} will be null/undefined if input illegal.
  3504. */
  3505. /**
  3506. * @deprecated
  3507. */
  3508. /**
  3509. * @param {number} normalizedValue A float between 0 and 1.
  3510. * @param {Array.<string>} colors Color list.
  3511. * @param {boolean=} fullOutput Default false.
  3512. * @return {(string|Object)} Result color. If fullOutput,
  3513. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3514. * @memberOf module:zrender/util/color
  3515. */
  3516. /**
  3517. * @deprecated
  3518. */
  3519. /**
  3520. * @param {string} color
  3521. * @param {number=} h 0 ~ 360, ignore when null.
  3522. * @param {number=} s 0 ~ 1, ignore when null.
  3523. * @param {number=} l 0 ~ 1, ignore when null.
  3524. * @return {string} Color string in rgba format.
  3525. * @memberOf module:zrender/util/color
  3526. */
  3527. /**
  3528. * @param {string} color
  3529. * @param {number=} alpha 0 ~ 1
  3530. * @return {string} Color string in rgba format.
  3531. * @memberOf module:zrender/util/color
  3532. */
  3533. /**
  3534. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3535. * @param {string} type 'rgba', 'hsva', ...
  3536. * @return {string} Result color. (If input illegal, return undefined).
  3537. */
  3538. function stringify(arrColor, type) {
  3539. if (!arrColor || !arrColor.length) {
  3540. return;
  3541. }
  3542. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3543. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3544. colorStr += ',' + arrColor[3];
  3545. }
  3546. return type + '(' + colorStr + ')';
  3547. }
  3548. /**
  3549. * @module echarts/animation/Animator
  3550. */
  3551. var arraySlice = Array.prototype.slice;
  3552. function defaultGetter(target, key) {
  3553. return target[key];
  3554. }
  3555. function defaultSetter(target, key, value) {
  3556. target[key] = value;
  3557. }
  3558. /**
  3559. * @param {number} p0
  3560. * @param {number} p1
  3561. * @param {number} percent
  3562. * @return {number}
  3563. */
  3564. function interpolateNumber(p0, p1, percent) {
  3565. return (p1 - p0) * percent + p0;
  3566. }
  3567. /**
  3568. * @param {string} p0
  3569. * @param {string} p1
  3570. * @param {number} percent
  3571. * @return {string}
  3572. */
  3573. function interpolateString(p0, p1, percent) {
  3574. return percent > 0.5 ? p1 : p0;
  3575. }
  3576. /**
  3577. * @param {Array} p0
  3578. * @param {Array} p1
  3579. * @param {number} percent
  3580. * @param {Array} out
  3581. * @param {number} arrDim
  3582. */
  3583. function interpolateArray(p0, p1, percent, out, arrDim) {
  3584. var len = p0.length;
  3585. if (arrDim === 1) {
  3586. for (var i = 0; i < len; i++) {
  3587. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3588. }
  3589. }
  3590. else {
  3591. var len2 = len && p0[0].length;
  3592. for (var i = 0; i < len; i++) {
  3593. for (var j = 0; j < len2; j++) {
  3594. out[i][j] = interpolateNumber(
  3595. p0[i][j], p1[i][j], percent
  3596. );
  3597. }
  3598. }
  3599. }
  3600. }
  3601. // arr0 is source array, arr1 is target array.
  3602. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3603. function fillArr(arr0, arr1, arrDim) {
  3604. var arr0Len = arr0.length;
  3605. var arr1Len = arr1.length;
  3606. if (arr0Len !== arr1Len) {
  3607. // FIXME Not work for TypedArray
  3608. var isPreviousLarger = arr0Len > arr1Len;
  3609. if (isPreviousLarger) {
  3610. // Cut the previous
  3611. arr0.length = arr1Len;
  3612. }
  3613. else {
  3614. // Fill the previous
  3615. for (var i = arr0Len; i < arr1Len; i++) {
  3616. arr0.push(
  3617. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3618. );
  3619. }
  3620. }
  3621. }
  3622. // Handling NaN value
  3623. var len2 = arr0[0] && arr0[0].length;
  3624. for (var i = 0; i < arr0.length; i++) {
  3625. if (arrDim === 1) {
  3626. if (isNaN(arr0[i])) {
  3627. arr0[i] = arr1[i];
  3628. }
  3629. }
  3630. else {
  3631. for (var j = 0; j < len2; j++) {
  3632. if (isNaN(arr0[i][j])) {
  3633. arr0[i][j] = arr1[i][j];
  3634. }
  3635. }
  3636. }
  3637. }
  3638. }
  3639. /**
  3640. * @param {Array} arr0
  3641. * @param {Array} arr1
  3642. * @param {number} arrDim
  3643. * @return {boolean}
  3644. */
  3645. function isArraySame(arr0, arr1, arrDim) {
  3646. if (arr0 === arr1) {
  3647. return true;
  3648. }
  3649. var len = arr0.length;
  3650. if (len !== arr1.length) {
  3651. return false;
  3652. }
  3653. if (arrDim === 1) {
  3654. for (var i = 0; i < len; i++) {
  3655. if (arr0[i] !== arr1[i]) {
  3656. return false;
  3657. }
  3658. }
  3659. }
  3660. else {
  3661. var len2 = arr0[0].length;
  3662. for (var i = 0; i < len; i++) {
  3663. for (var j = 0; j < len2; j++) {
  3664. if (arr0[i][j] !== arr1[i][j]) {
  3665. return false;
  3666. }
  3667. }
  3668. }
  3669. }
  3670. return true;
  3671. }
  3672. /**
  3673. * Catmull Rom interpolate array
  3674. * @param {Array} p0
  3675. * @param {Array} p1
  3676. * @param {Array} p2
  3677. * @param {Array} p3
  3678. * @param {number} t
  3679. * @param {number} t2
  3680. * @param {number} t3
  3681. * @param {Array} out
  3682. * @param {number} arrDim
  3683. */
  3684. function catmullRomInterpolateArray(
  3685. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3686. ) {
  3687. var len = p0.length;
  3688. if (arrDim === 1) {
  3689. for (var i = 0; i < len; i++) {
  3690. out[i] = catmullRomInterpolate(
  3691. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3692. );
  3693. }
  3694. }
  3695. else {
  3696. var len2 = p0[0].length;
  3697. for (var i = 0; i < len; i++) {
  3698. for (var j = 0; j < len2; j++) {
  3699. out[i][j] = catmullRomInterpolate(
  3700. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3701. t, t2, t3
  3702. );
  3703. }
  3704. }
  3705. }
  3706. }
  3707. /**
  3708. * Catmull Rom interpolate number
  3709. * @param {number} p0
  3710. * @param {number} p1
  3711. * @param {number} p2
  3712. * @param {number} p3
  3713. * @param {number} t
  3714. * @param {number} t2
  3715. * @param {number} t3
  3716. * @return {number}
  3717. */
  3718. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3719. var v0 = (p2 - p0) * 0.5;
  3720. var v1 = (p3 - p1) * 0.5;
  3721. return (2 * (p1 - p2) + v0 + v1) * t3
  3722. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3723. + v0 * t + p1;
  3724. }
  3725. function cloneValue(value) {
  3726. if (isArrayLike(value)) {
  3727. var len = value.length;
  3728. if (isArrayLike(value[0])) {
  3729. var ret = [];
  3730. for (var i = 0; i < len; i++) {
  3731. ret.push(arraySlice.call(value[i]));
  3732. }
  3733. return ret;
  3734. }
  3735. return arraySlice.call(value);
  3736. }
  3737. return value;
  3738. }
  3739. function rgba2String(rgba) {
  3740. rgba[0] = Math.floor(rgba[0]);
  3741. rgba[1] = Math.floor(rgba[1]);
  3742. rgba[2] = Math.floor(rgba[2]);
  3743. return 'rgba(' + rgba.join(',') + ')';
  3744. }
  3745. function getArrayDim(keyframes) {
  3746. var lastValue = keyframes[keyframes.length - 1].value;
  3747. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3748. }
  3749. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3750. var getter = animator._getter;
  3751. var setter = animator._setter;
  3752. var useSpline = easing === 'spline';
  3753. var trackLen = keyframes.length;
  3754. if (!trackLen) {
  3755. return;
  3756. }
  3757. // Guess data type
  3758. var firstVal = keyframes[0].value;
  3759. var isValueArray = isArrayLike(firstVal);
  3760. var isValueColor = false;
  3761. var isValueString = false;
  3762. // For vertices morphing
  3763. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3764. var trackMaxTime;
  3765. // Sort keyframe as ascending
  3766. keyframes.sort(function (a, b) {
  3767. return a.time - b.time;
  3768. });
  3769. trackMaxTime = keyframes[trackLen - 1].time;
  3770. // Percents of each keyframe
  3771. var kfPercents = [];
  3772. // Value of each keyframe
  3773. var kfValues = [];
  3774. var prevValue = keyframes[0].value;
  3775. var isAllValueEqual = true;
  3776. for (var i = 0; i < trackLen; i++) {
  3777. kfPercents.push(keyframes[i].time / trackMaxTime);
  3778. // Assume value is a color when it is a string
  3779. var value = keyframes[i].value;
  3780. // Check if value is equal, deep check if value is array
  3781. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3782. || (!isValueArray && value === prevValue))) {
  3783. isAllValueEqual = false;
  3784. }
  3785. prevValue = value;
  3786. // Try converting a string to a color array
  3787. if (typeof value === 'string') {
  3788. var colorArray = parse(value);
  3789. if (colorArray) {
  3790. value = colorArray;
  3791. isValueColor = true;
  3792. }
  3793. else {
  3794. isValueString = true;
  3795. }
  3796. }
  3797. kfValues.push(value);
  3798. }
  3799. if (!forceAnimate && isAllValueEqual) {
  3800. return;
  3801. }
  3802. var lastValue = kfValues[trackLen - 1];
  3803. // Polyfill array and NaN value
  3804. for (var i = 0; i < trackLen - 1; i++) {
  3805. if (isValueArray) {
  3806. fillArr(kfValues[i], lastValue, arrDim);
  3807. }
  3808. else {
  3809. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3810. kfValues[i] = lastValue;
  3811. }
  3812. }
  3813. }
  3814. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3815. // Cache the key of last frame to speed up when
  3816. // animation playback is sequency
  3817. var lastFrame = 0;
  3818. var lastFramePercent = 0;
  3819. var start;
  3820. var w;
  3821. var p0;
  3822. var p1;
  3823. var p2;
  3824. var p3;
  3825. if (isValueColor) {
  3826. var rgba = [0, 0, 0, 0];
  3827. }
  3828. var onframe = function (target, percent) {
  3829. // Find the range keyframes
  3830. // kf1-----kf2---------current--------kf3
  3831. // find kf2 and kf3 and do interpolation
  3832. var frame;
  3833. // In the easing function like elasticOut, percent may less than 0
  3834. if (percent < 0) {
  3835. frame = 0;
  3836. }
  3837. else if (percent < lastFramePercent) {
  3838. // Start from next key
  3839. // PENDING start from lastFrame ?
  3840. start = Math.min(lastFrame + 1, trackLen - 1);
  3841. for (frame = start; frame >= 0; frame--) {
  3842. if (kfPercents[frame] <= percent) {
  3843. break;
  3844. }
  3845. }
  3846. // PENDING really need to do this ?
  3847. frame = Math.min(frame, trackLen - 2);
  3848. }
  3849. else {
  3850. for (frame = lastFrame; frame < trackLen; frame++) {
  3851. if (kfPercents[frame] > percent) {
  3852. break;
  3853. }
  3854. }
  3855. frame = Math.min(frame - 1, trackLen - 2);
  3856. }
  3857. lastFrame = frame;
  3858. lastFramePercent = percent;
  3859. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3860. if (range === 0) {
  3861. return;
  3862. }
  3863. else {
  3864. w = (percent - kfPercents[frame]) / range;
  3865. }
  3866. if (useSpline) {
  3867. p1 = kfValues[frame];
  3868. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3869. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3870. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3871. if (isValueArray) {
  3872. catmullRomInterpolateArray(
  3873. p0, p1, p2, p3, w, w * w, w * w * w,
  3874. getter(target, propName),
  3875. arrDim
  3876. );
  3877. }
  3878. else {
  3879. var value;
  3880. if (isValueColor) {
  3881. value = catmullRomInterpolateArray(
  3882. p0, p1, p2, p3, w, w * w, w * w * w,
  3883. rgba, 1
  3884. );
  3885. value = rgba2String(rgba);
  3886. }
  3887. else if (isValueString) {
  3888. // String is step(0.5)
  3889. return interpolateString(p1, p2, w);
  3890. }
  3891. else {
  3892. value = catmullRomInterpolate(
  3893. p0, p1, p2, p3, w, w * w, w * w * w
  3894. );
  3895. }
  3896. setter(
  3897. target,
  3898. propName,
  3899. value
  3900. );
  3901. }
  3902. }
  3903. else {
  3904. if (isValueArray) {
  3905. interpolateArray(
  3906. kfValues[frame], kfValues[frame + 1], w,
  3907. getter(target, propName),
  3908. arrDim
  3909. );
  3910. }
  3911. else {
  3912. var value;
  3913. if (isValueColor) {
  3914. interpolateArray(
  3915. kfValues[frame], kfValues[frame + 1], w,
  3916. rgba, 1
  3917. );
  3918. value = rgba2String(rgba);
  3919. }
  3920. else if (isValueString) {
  3921. // String is step(0.5)
  3922. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3923. }
  3924. else {
  3925. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3926. }
  3927. setter(
  3928. target,
  3929. propName,
  3930. value
  3931. );
  3932. }
  3933. }
  3934. };
  3935. var clip = new Clip({
  3936. target: animator._target,
  3937. life: trackMaxTime,
  3938. loop: animator._loop,
  3939. delay: animator._delay,
  3940. onframe: onframe,
  3941. ondestroy: oneTrackDone
  3942. });
  3943. if (easing && easing !== 'spline') {
  3944. clip.easing = easing;
  3945. }
  3946. return clip;
  3947. }
  3948. /**
  3949. * @alias module:zrender/animation/Animator
  3950. * @constructor
  3951. * @param {Object} target
  3952. * @param {boolean} loop
  3953. * @param {Function} getter
  3954. * @param {Function} setter
  3955. */
  3956. var Animator = function (target, loop, getter, setter) {
  3957. this._tracks = {};
  3958. this._target = target;
  3959. this._loop = loop || false;
  3960. this._getter = getter || defaultGetter;
  3961. this._setter = setter || defaultSetter;
  3962. this._clipCount = 0;
  3963. this._delay = 0;
  3964. this._doneList = [];
  3965. this._onframeList = [];
  3966. this._clipList = [];
  3967. };
  3968. Animator.prototype = {
  3969. /**
  3970. * 设置动画关键帧
  3971. * @param {number} time 关键帧时间,单位是ms
  3972. * @param {Object} props 关键帧的属性值,key-value表示
  3973. * @return {module:zrender/animation/Animator}
  3974. */
  3975. when: function (time /* ms */, props) {
  3976. var tracks = this._tracks;
  3977. for (var propName in props) {
  3978. if (!props.hasOwnProperty(propName)) {
  3979. continue;
  3980. }
  3981. if (!tracks[propName]) {
  3982. tracks[propName] = [];
  3983. // Invalid value
  3984. var value = this._getter(this._target, propName);
  3985. if (value == null) {
  3986. // zrLog('Invalid property ' + propName);
  3987. continue;
  3988. }
  3989. // If time is 0
  3990. // Then props is given initialize value
  3991. // Else
  3992. // Initialize value from current prop value
  3993. if (time !== 0) {
  3994. tracks[propName].push({
  3995. time: 0,
  3996. value: cloneValue(value)
  3997. });
  3998. }
  3999. }
  4000. tracks[propName].push({
  4001. time: time,
  4002. value: props[propName]
  4003. });
  4004. }
  4005. return this;
  4006. },
  4007. /**
  4008. * 添加动画每一帧的回调函数
  4009. * @param {Function} callback
  4010. * @return {module:zrender/animation/Animator}
  4011. */
  4012. during: function (callback) {
  4013. this._onframeList.push(callback);
  4014. return this;
  4015. },
  4016. pause: function () {
  4017. for (var i = 0; i < this._clipList.length; i++) {
  4018. this._clipList[i].pause();
  4019. }
  4020. this._paused = true;
  4021. },
  4022. resume: function () {
  4023. for (var i = 0; i < this._clipList.length; i++) {
  4024. this._clipList[i].resume();
  4025. }
  4026. this._paused = false;
  4027. },
  4028. isPaused: function () {
  4029. return !!this._paused;
  4030. },
  4031. _doneCallback: function () {
  4032. // Clear all tracks
  4033. this._tracks = {};
  4034. // Clear all clips
  4035. this._clipList.length = 0;
  4036. var doneList = this._doneList;
  4037. var len = doneList.length;
  4038. for (var i = 0; i < len; i++) {
  4039. doneList[i].call(this);
  4040. }
  4041. },
  4042. /**
  4043. * 开始执行动画
  4044. * @param {string|Function} [easing]
  4045. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4046. * @param {boolean} forceAnimate
  4047. * @return {module:zrender/animation/Animator}
  4048. */
  4049. start: function (easing, forceAnimate) {
  4050. var self = this;
  4051. var clipCount = 0;
  4052. var oneTrackDone = function () {
  4053. clipCount--;
  4054. if (!clipCount) {
  4055. self._doneCallback();
  4056. }
  4057. };
  4058. var lastClip;
  4059. for (var propName in this._tracks) {
  4060. if (!this._tracks.hasOwnProperty(propName)) {
  4061. continue;
  4062. }
  4063. var clip = createTrackClip(
  4064. this, easing, oneTrackDone,
  4065. this._tracks[propName], propName, forceAnimate
  4066. );
  4067. if (clip) {
  4068. this._clipList.push(clip);
  4069. clipCount++;
  4070. // If start after added to animation
  4071. if (this.animation) {
  4072. this.animation.addClip(clip);
  4073. }
  4074. lastClip = clip;
  4075. }
  4076. }
  4077. // Add during callback on the last clip
  4078. if (lastClip) {
  4079. var oldOnFrame = lastClip.onframe;
  4080. lastClip.onframe = function (target, percent) {
  4081. oldOnFrame(target, percent);
  4082. for (var i = 0; i < self._onframeList.length; i++) {
  4083. self._onframeList[i](target, percent);
  4084. }
  4085. };
  4086. }
  4087. // This optimization will help the case that in the upper application
  4088. // the view may be refreshed frequently, where animation will be
  4089. // called repeatly but nothing changed.
  4090. if (!clipCount) {
  4091. this._doneCallback();
  4092. }
  4093. return this;
  4094. },
  4095. /**
  4096. * 停止动画
  4097. * @param {boolean} forwardToLast If move to last frame before stop
  4098. */
  4099. stop: function (forwardToLast) {
  4100. var clipList = this._clipList;
  4101. var animation = this.animation;
  4102. for (var i = 0; i < clipList.length; i++) {
  4103. var clip = clipList[i];
  4104. if (forwardToLast) {
  4105. // Move to last frame before stop
  4106. clip.onframe(this._target, 1);
  4107. }
  4108. animation && animation.removeClip(clip);
  4109. }
  4110. clipList.length = 0;
  4111. },
  4112. /**
  4113. * 设置动画延迟开始的时间
  4114. * @param {number} time 单位ms
  4115. * @return {module:zrender/animation/Animator}
  4116. */
  4117. delay: function (time) {
  4118. this._delay = time;
  4119. return this;
  4120. },
  4121. /**
  4122. * 添加动画结束的回调
  4123. * @param {Function} cb
  4124. * @return {module:zrender/animation/Animator}
  4125. */
  4126. done: function (cb) {
  4127. if (cb) {
  4128. this._doneList.push(cb);
  4129. }
  4130. return this;
  4131. },
  4132. /**
  4133. * @return {Array.<module:zrender/animation/Clip>}
  4134. */
  4135. getClips: function () {
  4136. return this._clipList;
  4137. }
  4138. };
  4139. var dpr = 1;
  4140. // If in browser environment
  4141. if (typeof window !== 'undefined') {
  4142. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4143. }
  4144. /**
  4145. * config默认配置项
  4146. * @exports zrender/config
  4147. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4148. */
  4149. /**
  4150. * Debug log mode:
  4151. * 0: Do nothing, for release.
  4152. * 1: console.error, for debug.
  4153. */
  4154. var debugMode = 0;
  4155. // retina 屏幕优化
  4156. var devicePixelRatio = dpr;
  4157. var logError = function () {
  4158. };
  4159. if (debugMode === 1) {
  4160. logError = console.error;
  4161. }
  4162. var logError$1 = logError;
  4163. /**
  4164. * @alias modue:zrender/mixin/Animatable
  4165. * @constructor
  4166. */
  4167. var Animatable = function () {
  4168. /**
  4169. * @type {Array.<module:zrender/animation/Animator>}
  4170. * @readOnly
  4171. */
  4172. this.animators = [];
  4173. };
  4174. Animatable.prototype = {
  4175. constructor: Animatable,
  4176. /**
  4177. * 动画
  4178. *
  4179. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4180. * @param {boolean} [loop] Whether to loop animation.
  4181. * @return {module:zrender/animation/Animator}
  4182. * @example:
  4183. * el.animate('style', false)
  4184. * .when(1000, {x: 10} )
  4185. * .done(function(){ // Animation done })
  4186. * .start()
  4187. */
  4188. animate: function (path, loop) {
  4189. var target;
  4190. var animatingShape = false;
  4191. var el = this;
  4192. var zr = this.__zr;
  4193. if (path) {
  4194. var pathSplitted = path.split('.');
  4195. var prop = el;
  4196. // If animating shape
  4197. animatingShape = pathSplitted[0] === 'shape';
  4198. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4199. if (!prop) {
  4200. continue;
  4201. }
  4202. prop = prop[pathSplitted[i]];
  4203. }
  4204. if (prop) {
  4205. target = prop;
  4206. }
  4207. }
  4208. else {
  4209. target = el;
  4210. }
  4211. if (!target) {
  4212. logError$1(
  4213. 'Property "'
  4214. + path
  4215. + '" is not existed in element '
  4216. + el.id
  4217. );
  4218. return;
  4219. }
  4220. var animators = el.animators;
  4221. var animator = new Animator(target, loop);
  4222. animator.during(function (target) {
  4223. el.dirty(animatingShape);
  4224. })
  4225. .done(function () {
  4226. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4227. animators.splice(indexOf(animators, animator), 1);
  4228. });
  4229. animators.push(animator);
  4230. // If animate after added to the zrender
  4231. if (zr) {
  4232. zr.animation.addAnimator(animator);
  4233. }
  4234. return animator;
  4235. },
  4236. /**
  4237. * 停止动画
  4238. * @param {boolean} forwardToLast If move to last frame before stop
  4239. */
  4240. stopAnimation: function (forwardToLast) {
  4241. var animators = this.animators;
  4242. var len = animators.length;
  4243. for (var i = 0; i < len; i++) {
  4244. animators[i].stop(forwardToLast);
  4245. }
  4246. animators.length = 0;
  4247. return this;
  4248. },
  4249. /**
  4250. * Caution: this method will stop previous animation.
  4251. * So do not use this method to one element twice before
  4252. * animation starts, unless you know what you are doing.
  4253. * @param {Object} target
  4254. * @param {number} [time=500] Time in ms
  4255. * @param {string} [easing='linear']
  4256. * @param {number} [delay=0]
  4257. * @param {Function} [callback]
  4258. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4259. * immediently when target values are the same as current values.
  4260. *
  4261. * @example
  4262. * // Animate position
  4263. * el.animateTo({
  4264. * position: [10, 10]
  4265. * }, function () { // done })
  4266. *
  4267. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4268. * el.animateTo({
  4269. * shape: {
  4270. * width: 500
  4271. * },
  4272. * style: {
  4273. * fill: 'red'
  4274. * }
  4275. * position: [10, 10]
  4276. * }, 100, 100, 'cubicOut', function () { // done })
  4277. */
  4278. // TODO Return animation key
  4279. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4280. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4281. },
  4282. /**
  4283. * Animate from the target state to current state.
  4284. * The params and the return value are the same as `this.animateTo`.
  4285. */
  4286. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4287. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4288. }
  4289. };
  4290. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4291. // animateTo(target, time, easing, callback);
  4292. if (isString(delay)) {
  4293. callback = easing;
  4294. easing = delay;
  4295. delay = 0;
  4296. }
  4297. // animateTo(target, time, delay, callback);
  4298. else if (isFunction$1(easing)) {
  4299. callback = easing;
  4300. easing = 'linear';
  4301. delay = 0;
  4302. }
  4303. // animateTo(target, time, callback);
  4304. else if (isFunction$1(delay)) {
  4305. callback = delay;
  4306. delay = 0;
  4307. }
  4308. // animateTo(target, callback)
  4309. else if (isFunction$1(time)) {
  4310. callback = time;
  4311. time = 500;
  4312. }
  4313. // animateTo(target)
  4314. else if (!time) {
  4315. time = 500;
  4316. }
  4317. // Stop all previous animations
  4318. animatable.stopAnimation();
  4319. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4320. // Animators may be removed immediately after start
  4321. // if there is nothing to animate
  4322. var animators = animatable.animators.slice();
  4323. var count = animators.length;
  4324. function done() {
  4325. count--;
  4326. if (!count) {
  4327. callback && callback();
  4328. }
  4329. }
  4330. // No animators. This should be checked before animators[i].start(),
  4331. // because 'done' may be executed immediately if no need to animate.
  4332. if (!count) {
  4333. callback && callback();
  4334. }
  4335. // Start after all animators created
  4336. // Incase any animator is done immediately when all animation properties are not changed
  4337. for (var i = 0; i < animators.length; i++) {
  4338. animators[i]
  4339. .done(done)
  4340. .start(easing, forceAnimate);
  4341. }
  4342. }
  4343. /**
  4344. * @param {string} path=''
  4345. * @param {Object} source=animatable
  4346. * @param {Object} target
  4347. * @param {number} [time=500]
  4348. * @param {number} [delay=0]
  4349. * @param {boolean} [reverse] If `true`, animate
  4350. * from the `target` to current state.
  4351. *
  4352. * @example
  4353. * // Animate position
  4354. * el._animateToShallow({
  4355. * position: [10, 10]
  4356. * })
  4357. *
  4358. * // Animate shape, style and position in 100ms, delayed 100ms
  4359. * el._animateToShallow({
  4360. * shape: {
  4361. * width: 500
  4362. * },
  4363. * style: {
  4364. * fill: 'red'
  4365. * }
  4366. * position: [10, 10]
  4367. * }, 100, 100)
  4368. */
  4369. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4370. var objShallow = {};
  4371. var propertyCount = 0;
  4372. for (var name in target) {
  4373. if (!target.hasOwnProperty(name)) {
  4374. continue;
  4375. }
  4376. if (source[name] != null) {
  4377. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4378. animateToShallow(
  4379. animatable,
  4380. path ? path + '.' + name : name,
  4381. source[name],
  4382. target[name],
  4383. time,
  4384. delay,
  4385. reverse
  4386. );
  4387. }
  4388. else {
  4389. if (reverse) {
  4390. objShallow[name] = source[name];
  4391. setAttrByPath(animatable, path, name, target[name]);
  4392. }
  4393. else {
  4394. objShallow[name] = target[name];
  4395. }
  4396. propertyCount++;
  4397. }
  4398. }
  4399. else if (target[name] != null && !reverse) {
  4400. setAttrByPath(animatable, path, name, target[name]);
  4401. }
  4402. }
  4403. if (propertyCount > 0) {
  4404. animatable.animate(path, false)
  4405. .when(time == null ? 500 : time, objShallow)
  4406. .delay(delay || 0);
  4407. }
  4408. }
  4409. function setAttrByPath(el, path, name, value) {
  4410. // Attr directly if not has property
  4411. // FIXME, if some property not needed for element ?
  4412. if (!path) {
  4413. el.attr(name, value);
  4414. }
  4415. else {
  4416. // Only support set shape or style
  4417. var props = {};
  4418. props[path] = {};
  4419. props[path][name] = value;
  4420. el.attr(props);
  4421. }
  4422. }
  4423. /**
  4424. * @alias module:zrender/Element
  4425. * @constructor
  4426. * @extends {module:zrender/mixin/Animatable}
  4427. * @extends {module:zrender/mixin/Transformable}
  4428. * @extends {module:zrender/mixin/Eventful}
  4429. */
  4430. var Element = function (opts) { // jshint ignore:line
  4431. Transformable.call(this, opts);
  4432. Eventful.call(this, opts);
  4433. Animatable.call(this, opts);
  4434. /**
  4435. * 画布元素ID
  4436. * @type {string}
  4437. */
  4438. this.id = opts.id || guid();
  4439. };
  4440. Element.prototype = {
  4441. /**
  4442. * 元素类型
  4443. * Element type
  4444. * @type {string}
  4445. */
  4446. type: 'element',
  4447. /**
  4448. * 元素名字
  4449. * Element name
  4450. * @type {string}
  4451. */
  4452. name: '',
  4453. /**
  4454. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4455. * ZRender instance will be assigned when element is associated with zrender
  4456. * @name module:/zrender/Element#__zr
  4457. * @type {module:zrender/ZRender}
  4458. */
  4459. __zr: null,
  4460. /**
  4461. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4462. * If ignore drawing and events of the element object
  4463. * @name module:/zrender/Element#ignore
  4464. * @type {boolean}
  4465. * @default false
  4466. */
  4467. ignore: false,
  4468. /**
  4469. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4470. * 该路径会继承被裁减对象的变换
  4471. * @type {module:zrender/graphic/Path}
  4472. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4473. * @readOnly
  4474. */
  4475. clipPath: null,
  4476. /**
  4477. * 是否是 Group
  4478. * @type {boolean}
  4479. */
  4480. isGroup: false,
  4481. /**
  4482. * Drift element
  4483. * @param {number} dx dx on the global space
  4484. * @param {number} dy dy on the global space
  4485. */
  4486. drift: function (dx, dy) {
  4487. switch (this.draggable) {
  4488. case 'horizontal':
  4489. dy = 0;
  4490. break;
  4491. case 'vertical':
  4492. dx = 0;
  4493. break;
  4494. }
  4495. var m = this.transform;
  4496. if (!m) {
  4497. m = this.transform = [1, 0, 0, 1, 0, 0];
  4498. }
  4499. m[4] += dx;
  4500. m[5] += dy;
  4501. this.decomposeTransform();
  4502. this.dirty(false);
  4503. },
  4504. /**
  4505. * Hook before update
  4506. */
  4507. beforeUpdate: function () {},
  4508. /**
  4509. * Hook after update
  4510. */
  4511. afterUpdate: function () {},
  4512. /**
  4513. * Update each frame
  4514. */
  4515. update: function () {
  4516. this.updateTransform();
  4517. },
  4518. /**
  4519. * @param {Function} cb
  4520. * @param {} context
  4521. */
  4522. traverse: function (cb, context) {},
  4523. /**
  4524. * @protected
  4525. */
  4526. attrKV: function (key, value) {
  4527. if (key === 'position' || key === 'scale' || key === 'origin') {
  4528. // Copy the array
  4529. if (value) {
  4530. var target = this[key];
  4531. if (!target) {
  4532. target = this[key] = [];
  4533. }
  4534. target[0] = value[0];
  4535. target[1] = value[1];
  4536. }
  4537. }
  4538. else {
  4539. this[key] = value;
  4540. }
  4541. },
  4542. /**
  4543. * Hide the element
  4544. */
  4545. hide: function () {
  4546. this.ignore = true;
  4547. this.__zr && this.__zr.refresh();
  4548. },
  4549. /**
  4550. * Show the element
  4551. */
  4552. show: function () {
  4553. this.ignore = false;
  4554. this.__zr && this.__zr.refresh();
  4555. },
  4556. /**
  4557. * @param {string|Object} key
  4558. * @param {*} value
  4559. */
  4560. attr: function (key, value) {
  4561. if (typeof key === 'string') {
  4562. this.attrKV(key, value);
  4563. }
  4564. else if (isObject$1(key)) {
  4565. for (var name in key) {
  4566. if (key.hasOwnProperty(name)) {
  4567. this.attrKV(name, key[name]);
  4568. }
  4569. }
  4570. }
  4571. this.dirty(false);
  4572. return this;
  4573. },
  4574. /**
  4575. * @param {module:zrender/graphic/Path} clipPath
  4576. */
  4577. setClipPath: function (clipPath) {
  4578. var zr = this.__zr;
  4579. if (zr) {
  4580. clipPath.addSelfToZr(zr);
  4581. }
  4582. // Remove previous clip path
  4583. if (this.clipPath && this.clipPath !== clipPath) {
  4584. this.removeClipPath();
  4585. }
  4586. this.clipPath = clipPath;
  4587. clipPath.__zr = zr;
  4588. clipPath.__clipTarget = this;
  4589. this.dirty(false);
  4590. },
  4591. /**
  4592. */
  4593. removeClipPath: function () {
  4594. var clipPath = this.clipPath;
  4595. if (clipPath) {
  4596. if (clipPath.__zr) {
  4597. clipPath.removeSelfFromZr(clipPath.__zr);
  4598. }
  4599. clipPath.__zr = null;
  4600. clipPath.__clipTarget = null;
  4601. this.clipPath = null;
  4602. this.dirty(false);
  4603. }
  4604. },
  4605. /**
  4606. * Add self from zrender instance.
  4607. * Not recursively because it will be invoked when element added to storage.
  4608. * @param {module:zrender/ZRender} zr
  4609. */
  4610. addSelfToZr: function (zr) {
  4611. this.__zr = zr;
  4612. // 添加动画
  4613. var animators = this.animators;
  4614. if (animators) {
  4615. for (var i = 0; i < animators.length; i++) {
  4616. zr.animation.addAnimator(animators[i]);
  4617. }
  4618. }
  4619. if (this.clipPath) {
  4620. this.clipPath.addSelfToZr(zr);
  4621. }
  4622. },
  4623. /**
  4624. * Remove self from zrender instance.
  4625. * Not recursively because it will be invoked when element added to storage.
  4626. * @param {module:zrender/ZRender} zr
  4627. */
  4628. removeSelfFromZr: function (zr) {
  4629. this.__zr = null;
  4630. // 移除动画
  4631. var animators = this.animators;
  4632. if (animators) {
  4633. for (var i = 0; i < animators.length; i++) {
  4634. zr.animation.removeAnimator(animators[i]);
  4635. }
  4636. }
  4637. if (this.clipPath) {
  4638. this.clipPath.removeSelfFromZr(zr);
  4639. }
  4640. }
  4641. };
  4642. mixin(Element, Animatable);
  4643. mixin(Element, Transformable);
  4644. mixin(Element, Eventful);
  4645. /**
  4646. * @module echarts/core/BoundingRect
  4647. */
  4648. var v2ApplyTransform = applyTransform;
  4649. var mathMin = Math.min;
  4650. var mathMax = Math.max;
  4651. /**
  4652. * @alias module:echarts/core/BoundingRect
  4653. */
  4654. function BoundingRect(x, y, width, height) {
  4655. if (width < 0) {
  4656. x = x + width;
  4657. width = -width;
  4658. }
  4659. if (height < 0) {
  4660. y = y + height;
  4661. height = -height;
  4662. }
  4663. /**
  4664. * @type {number}
  4665. */
  4666. this.x = x;
  4667. /**
  4668. * @type {number}
  4669. */
  4670. this.y = y;
  4671. /**
  4672. * @type {number}
  4673. */
  4674. this.width = width;
  4675. /**
  4676. * @type {number}
  4677. */
  4678. this.height = height;
  4679. }
  4680. BoundingRect.prototype = {
  4681. constructor: BoundingRect,
  4682. /**
  4683. * @param {module:echarts/core/BoundingRect} other
  4684. */
  4685. union: function (other) {
  4686. var x = mathMin(other.x, this.x);
  4687. var y = mathMin(other.y, this.y);
  4688. this.width = mathMax(
  4689. other.x + other.width,
  4690. this.x + this.width
  4691. ) - x;
  4692. this.height = mathMax(
  4693. other.y + other.height,
  4694. this.y + this.height
  4695. ) - y;
  4696. this.x = x;
  4697. this.y = y;
  4698. },
  4699. /**
  4700. * @param {Array.<number>} m
  4701. * @methods
  4702. */
  4703. applyTransform: (function () {
  4704. var lt = [];
  4705. var rb = [];
  4706. var lb = [];
  4707. var rt = [];
  4708. return function (m) {
  4709. // In case usage like this
  4710. // el.getBoundingRect().applyTransform(el.transform)
  4711. // And element has no transform
  4712. if (!m) {
  4713. return;
  4714. }
  4715. lt[0] = lb[0] = this.x;
  4716. lt[1] = rt[1] = this.y;
  4717. rb[0] = rt[0] = this.x + this.width;
  4718. rb[1] = lb[1] = this.y + this.height;
  4719. v2ApplyTransform(lt, lt, m);
  4720. v2ApplyTransform(rb, rb, m);
  4721. v2ApplyTransform(lb, lb, m);
  4722. v2ApplyTransform(rt, rt, m);
  4723. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4724. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4725. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4726. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4727. this.width = maxX - this.x;
  4728. this.height = maxY - this.y;
  4729. };
  4730. })(),
  4731. /**
  4732. * Calculate matrix of transforming from self to target rect
  4733. * @param {module:zrender/core/BoundingRect} b
  4734. * @return {Array.<number>}
  4735. */
  4736. calculateTransform: function (b) {
  4737. var a = this;
  4738. var sx = b.width / a.width;
  4739. var sy = b.height / a.height;
  4740. var m = create$1();
  4741. // 矩阵右乘
  4742. translate(m, m, [-a.x, -a.y]);
  4743. scale$1(m, m, [sx, sy]);
  4744. translate(m, m, [b.x, b.y]);
  4745. return m;
  4746. },
  4747. /**
  4748. * @param {(module:echarts/core/BoundingRect|Object)} b
  4749. * @return {boolean}
  4750. */
  4751. intersect: function (b) {
  4752. if (!b) {
  4753. return false;
  4754. }
  4755. if (!(b instanceof BoundingRect)) {
  4756. // Normalize negative width/height.
  4757. b = BoundingRect.create(b);
  4758. }
  4759. var a = this;
  4760. var ax0 = a.x;
  4761. var ax1 = a.x + a.width;
  4762. var ay0 = a.y;
  4763. var ay1 = a.y + a.height;
  4764. var bx0 = b.x;
  4765. var bx1 = b.x + b.width;
  4766. var by0 = b.y;
  4767. var by1 = b.y + b.height;
  4768. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4769. },
  4770. contain: function (x, y) {
  4771. var rect = this;
  4772. return x >= rect.x
  4773. && x <= (rect.x + rect.width)
  4774. && y >= rect.y
  4775. && y <= (rect.y + rect.height);
  4776. },
  4777. /**
  4778. * @return {module:echarts/core/BoundingRect}
  4779. */
  4780. clone: function () {
  4781. return new BoundingRect(this.x, this.y, this.width, this.height);
  4782. },
  4783. /**
  4784. * Copy from another rect
  4785. */
  4786. copy: function (other) {
  4787. this.x = other.x;
  4788. this.y = other.y;
  4789. this.width = other.width;
  4790. this.height = other.height;
  4791. },
  4792. plain: function () {
  4793. return {
  4794. x: this.x,
  4795. y: this.y,
  4796. width: this.width,
  4797. height: this.height
  4798. };
  4799. }
  4800. };
  4801. /**
  4802. * @param {Object|module:zrender/core/BoundingRect} rect
  4803. * @param {number} rect.x
  4804. * @param {number} rect.y
  4805. * @param {number} rect.width
  4806. * @param {number} rect.height
  4807. * @return {module:zrender/core/BoundingRect}
  4808. */
  4809. BoundingRect.create = function (rect) {
  4810. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4811. };
  4812. /**
  4813. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4814. * @module zrender/graphic/Group
  4815. * @example
  4816. * var Group = require('zrender/container/Group');
  4817. * var Circle = require('zrender/graphic/shape/Circle');
  4818. * var g = new Group();
  4819. * g.position[0] = 100;
  4820. * g.position[1] = 100;
  4821. * g.add(new Circle({
  4822. * style: {
  4823. * x: 100,
  4824. * y: 100,
  4825. * r: 20,
  4826. * }
  4827. * }));
  4828. * zr.add(g);
  4829. */
  4830. /**
  4831. * @alias module:zrender/graphic/Group
  4832. * @constructor
  4833. * @extends module:zrender/mixin/Transformable
  4834. * @extends module:zrender/mixin/Eventful
  4835. */
  4836. var Group = function (opts) {
  4837. opts = opts || {};
  4838. Element.call(this, opts);
  4839. for (var key in opts) {
  4840. if (opts.hasOwnProperty(key)) {
  4841. this[key] = opts[key];
  4842. }
  4843. }
  4844. this._children = [];
  4845. this.__storage = null;
  4846. this.__dirty = true;
  4847. };
  4848. Group.prototype = {
  4849. constructor: Group,
  4850. isGroup: true,
  4851. /**
  4852. * @type {string}
  4853. */
  4854. type: 'group',
  4855. /**
  4856. * 所有子孙元素是否响应鼠标事件
  4857. * @name module:/zrender/container/Group#silent
  4858. * @type {boolean}
  4859. * @default false
  4860. */
  4861. silent: false,
  4862. /**
  4863. * @return {Array.<module:zrender/Element>}
  4864. */
  4865. children: function () {
  4866. return this._children.slice();
  4867. },
  4868. /**
  4869. * 获取指定 index 的儿子节点
  4870. * @param {number} idx
  4871. * @return {module:zrender/Element}
  4872. */
  4873. childAt: function (idx) {
  4874. return this._children[idx];
  4875. },
  4876. /**
  4877. * 获取指定名字的儿子节点
  4878. * @param {string} name
  4879. * @return {module:zrender/Element}
  4880. */
  4881. childOfName: function (name) {
  4882. var children = this._children;
  4883. for (var i = 0; i < children.length; i++) {
  4884. if (children[i].name === name) {
  4885. return children[i];
  4886. }
  4887. }
  4888. },
  4889. /**
  4890. * @return {number}
  4891. */
  4892. childCount: function () {
  4893. return this._children.length;
  4894. },
  4895. /**
  4896. * 添加子节点到最后
  4897. * @param {module:zrender/Element} child
  4898. */
  4899. add: function (child) {
  4900. if (child && child !== this && child.parent !== this) {
  4901. this._children.push(child);
  4902. this._doAdd(child);
  4903. }
  4904. return this;
  4905. },
  4906. /**
  4907. * 添加子节点在 nextSibling 之前
  4908. * @param {module:zrender/Element} child
  4909. * @param {module:zrender/Element} nextSibling
  4910. */
  4911. addBefore: function (child, nextSibling) {
  4912. if (child && child !== this && child.parent !== this
  4913. && nextSibling && nextSibling.parent === this) {
  4914. var children = this._children;
  4915. var idx = children.indexOf(nextSibling);
  4916. if (idx >= 0) {
  4917. children.splice(idx, 0, child);
  4918. this._doAdd(child);
  4919. }
  4920. }
  4921. return this;
  4922. },
  4923. _doAdd: function (child) {
  4924. if (child.parent) {
  4925. child.parent.remove(child);
  4926. }
  4927. child.parent = this;
  4928. var storage = this.__storage;
  4929. var zr = this.__zr;
  4930. if (storage && storage !== child.__storage) {
  4931. storage.addToStorage(child);
  4932. if (child instanceof Group) {
  4933. child.addChildrenToStorage(storage);
  4934. }
  4935. }
  4936. zr && zr.refresh();
  4937. },
  4938. /**
  4939. * 移除子节点
  4940. * @param {module:zrender/Element} child
  4941. */
  4942. remove: function (child) {
  4943. var zr = this.__zr;
  4944. var storage = this.__storage;
  4945. var children = this._children;
  4946. var idx = indexOf(children, child);
  4947. if (idx < 0) {
  4948. return this;
  4949. }
  4950. children.splice(idx, 1);
  4951. child.parent = null;
  4952. if (storage) {
  4953. storage.delFromStorage(child);
  4954. if (child instanceof Group) {
  4955. child.delChildrenFromStorage(storage);
  4956. }
  4957. }
  4958. zr && zr.refresh();
  4959. return this;
  4960. },
  4961. /**
  4962. * 移除所有子节点
  4963. */
  4964. removeAll: function () {
  4965. var children = this._children;
  4966. var storage = this.__storage;
  4967. var child;
  4968. var i;
  4969. for (i = 0; i < children.length; i++) {
  4970. child = children[i];
  4971. if (storage) {
  4972. storage.delFromStorage(child);
  4973. if (child instanceof Group) {
  4974. child.delChildrenFromStorage(storage);
  4975. }
  4976. }
  4977. child.parent = null;
  4978. }
  4979. children.length = 0;
  4980. return this;
  4981. },
  4982. /**
  4983. * 遍历所有子节点
  4984. * @param {Function} cb
  4985. * @param {} context
  4986. */
  4987. eachChild: function (cb, context) {
  4988. var children = this._children;
  4989. for (var i = 0; i < children.length; i++) {
  4990. var child = children[i];
  4991. cb.call(context, child, i);
  4992. }
  4993. return this;
  4994. },
  4995. /**
  4996. * 深度优先遍历所有子孙节点
  4997. * @param {Function} cb
  4998. * @param {} context
  4999. */
  5000. traverse: function (cb, context) {
  5001. for (var i = 0; i < this._children.length; i++) {
  5002. var child = this._children[i];
  5003. cb.call(context, child);
  5004. if (child.type === 'group') {
  5005. child.traverse(cb, context);
  5006. }
  5007. }
  5008. return this;
  5009. },
  5010. addChildrenToStorage: function (storage) {
  5011. for (var i = 0; i < this._children.length; i++) {
  5012. var child = this._children[i];
  5013. storage.addToStorage(child);
  5014. if (child instanceof Group) {
  5015. child.addChildrenToStorage(storage);
  5016. }
  5017. }
  5018. },
  5019. delChildrenFromStorage: function (storage) {
  5020. for (var i = 0; i < this._children.length; i++) {
  5021. var child = this._children[i];
  5022. storage.delFromStorage(child);
  5023. if (child instanceof Group) {
  5024. child.delChildrenFromStorage(storage);
  5025. }
  5026. }
  5027. },
  5028. dirty: function () {
  5029. this.__dirty = true;
  5030. this.__zr && this.__zr.refresh();
  5031. return this;
  5032. },
  5033. /**
  5034. * @return {module:zrender/core/BoundingRect}
  5035. */
  5036. getBoundingRect: function (includeChildren) {
  5037. // TODO Caching
  5038. var rect = null;
  5039. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5040. var children = includeChildren || this._children;
  5041. var tmpMat = [];
  5042. for (var i = 0; i < children.length; i++) {
  5043. var child = children[i];
  5044. if (child.ignore || child.invisible) {
  5045. continue;
  5046. }
  5047. var childRect = child.getBoundingRect();
  5048. var transform = child.getLocalTransform(tmpMat);
  5049. // TODO
  5050. // The boundingRect cacluated by transforming original
  5051. // rect may be bigger than the actual bundingRect when rotation
  5052. // is used. (Consider a circle rotated aginst its center, where
  5053. // the actual boundingRect should be the same as that not be
  5054. // rotated.) But we can not find better approach to calculate
  5055. // actual boundingRect yet, considering performance.
  5056. if (transform) {
  5057. tmpRect.copy(childRect);
  5058. tmpRect.applyTransform(transform);
  5059. rect = rect || tmpRect.clone();
  5060. rect.union(tmpRect);
  5061. }
  5062. else {
  5063. rect = rect || childRect.clone();
  5064. rect.union(childRect);
  5065. }
  5066. }
  5067. return rect || tmpRect;
  5068. }
  5069. };
  5070. inherits(Group, Element);
  5071. // https://github.com/mziccard/node-timsort
  5072. var DEFAULT_MIN_MERGE = 32;
  5073. var DEFAULT_MIN_GALLOPING = 7;
  5074. function minRunLength(n) {
  5075. var r = 0;
  5076. while (n >= DEFAULT_MIN_MERGE) {
  5077. r |= n & 1;
  5078. n >>= 1;
  5079. }
  5080. return n + r;
  5081. }
  5082. function makeAscendingRun(array, lo, hi, compare) {
  5083. var runHi = lo + 1;
  5084. if (runHi === hi) {
  5085. return 1;
  5086. }
  5087. if (compare(array[runHi++], array[lo]) < 0) {
  5088. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5089. runHi++;
  5090. }
  5091. reverseRun(array, lo, runHi);
  5092. }
  5093. else {
  5094. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5095. runHi++;
  5096. }
  5097. }
  5098. return runHi - lo;
  5099. }
  5100. function reverseRun(array, lo, hi) {
  5101. hi--;
  5102. while (lo < hi) {
  5103. var t = array[lo];
  5104. array[lo++] = array[hi];
  5105. array[hi--] = t;
  5106. }
  5107. }
  5108. function binaryInsertionSort(array, lo, hi, start, compare) {
  5109. if (start === lo) {
  5110. start++;
  5111. }
  5112. for (; start < hi; start++) {
  5113. var pivot = array[start];
  5114. var left = lo;
  5115. var right = start;
  5116. var mid;
  5117. while (left < right) {
  5118. mid = left + right >>> 1;
  5119. if (compare(pivot, array[mid]) < 0) {
  5120. right = mid;
  5121. }
  5122. else {
  5123. left = mid + 1;
  5124. }
  5125. }
  5126. var n = start - left;
  5127. switch (n) {
  5128. case 3:
  5129. array[left + 3] = array[left + 2];
  5130. case 2:
  5131. array[left + 2] = array[left + 1];
  5132. case 1:
  5133. array[left + 1] = array[left];
  5134. break;
  5135. default:
  5136. while (n > 0) {
  5137. array[left + n] = array[left + n - 1];
  5138. n--;
  5139. }
  5140. }
  5141. array[left] = pivot;
  5142. }
  5143. }
  5144. function gallopLeft(value, array, start, length, hint, compare) {
  5145. var lastOffset = 0;
  5146. var maxOffset = 0;
  5147. var offset = 1;
  5148. if (compare(value, array[start + hint]) > 0) {
  5149. maxOffset = length - hint;
  5150. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5151. lastOffset = offset;
  5152. offset = (offset << 1) + 1;
  5153. if (offset <= 0) {
  5154. offset = maxOffset;
  5155. }
  5156. }
  5157. if (offset > maxOffset) {
  5158. offset = maxOffset;
  5159. }
  5160. lastOffset += hint;
  5161. offset += hint;
  5162. }
  5163. else {
  5164. maxOffset = hint + 1;
  5165. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5166. lastOffset = offset;
  5167. offset = (offset << 1) + 1;
  5168. if (offset <= 0) {
  5169. offset = maxOffset;
  5170. }
  5171. }
  5172. if (offset > maxOffset) {
  5173. offset = maxOffset;
  5174. }
  5175. var tmp = lastOffset;
  5176. lastOffset = hint - offset;
  5177. offset = hint - tmp;
  5178. }
  5179. lastOffset++;
  5180. while (lastOffset < offset) {
  5181. var m = lastOffset + (offset - lastOffset >>> 1);
  5182. if (compare(value, array[start + m]) > 0) {
  5183. lastOffset = m + 1;
  5184. }
  5185. else {
  5186. offset = m;
  5187. }
  5188. }
  5189. return offset;
  5190. }
  5191. function gallopRight(value, array, start, length, hint, compare) {
  5192. var lastOffset = 0;
  5193. var maxOffset = 0;
  5194. var offset = 1;
  5195. if (compare(value, array[start + hint]) < 0) {
  5196. maxOffset = hint + 1;
  5197. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5198. lastOffset = offset;
  5199. offset = (offset << 1) + 1;
  5200. if (offset <= 0) {
  5201. offset = maxOffset;
  5202. }
  5203. }
  5204. if (offset > maxOffset) {
  5205. offset = maxOffset;
  5206. }
  5207. var tmp = lastOffset;
  5208. lastOffset = hint - offset;
  5209. offset = hint - tmp;
  5210. }
  5211. else {
  5212. maxOffset = length - hint;
  5213. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5214. lastOffset = offset;
  5215. offset = (offset << 1) + 1;
  5216. if (offset <= 0) {
  5217. offset = maxOffset;
  5218. }
  5219. }
  5220. if (offset > maxOffset) {
  5221. offset = maxOffset;
  5222. }
  5223. lastOffset += hint;
  5224. offset += hint;
  5225. }
  5226. lastOffset++;
  5227. while (lastOffset < offset) {
  5228. var m = lastOffset + (offset - lastOffset >>> 1);
  5229. if (compare(value, array[start + m]) < 0) {
  5230. offset = m;
  5231. }
  5232. else {
  5233. lastOffset = m + 1;
  5234. }
  5235. }
  5236. return offset;
  5237. }
  5238. function TimSort(array, compare) {
  5239. var minGallop = DEFAULT_MIN_GALLOPING;
  5240. var runStart;
  5241. var runLength;
  5242. var stackSize = 0;
  5243. var tmp = [];
  5244. runStart = [];
  5245. runLength = [];
  5246. function pushRun(_runStart, _runLength) {
  5247. runStart[stackSize] = _runStart;
  5248. runLength[stackSize] = _runLength;
  5249. stackSize += 1;
  5250. }
  5251. function mergeRuns() {
  5252. while (stackSize > 1) {
  5253. var n = stackSize - 2;
  5254. if (
  5255. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5256. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5257. ) {
  5258. if (runLength[n - 1] < runLength[n + 1]) {
  5259. n--;
  5260. }
  5261. }
  5262. else if (runLength[n] > runLength[n + 1]) {
  5263. break;
  5264. }
  5265. mergeAt(n);
  5266. }
  5267. }
  5268. function forceMergeRuns() {
  5269. while (stackSize > 1) {
  5270. var n = stackSize - 2;
  5271. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5272. n--;
  5273. }
  5274. mergeAt(n);
  5275. }
  5276. }
  5277. function mergeAt(i) {
  5278. var start1 = runStart[i];
  5279. var length1 = runLength[i];
  5280. var start2 = runStart[i + 1];
  5281. var length2 = runLength[i + 1];
  5282. runLength[i] = length1 + length2;
  5283. if (i === stackSize - 3) {
  5284. runStart[i + 1] = runStart[i + 2];
  5285. runLength[i + 1] = runLength[i + 2];
  5286. }
  5287. stackSize--;
  5288. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5289. start1 += k;
  5290. length1 -= k;
  5291. if (length1 === 0) {
  5292. return;
  5293. }
  5294. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5295. if (length2 === 0) {
  5296. return;
  5297. }
  5298. if (length1 <= length2) {
  5299. mergeLow(start1, length1, start2, length2);
  5300. }
  5301. else {
  5302. mergeHigh(start1, length1, start2, length2);
  5303. }
  5304. }
  5305. function mergeLow(start1, length1, start2, length2) {
  5306. var i = 0;
  5307. for (i = 0; i < length1; i++) {
  5308. tmp[i] = array[start1 + i];
  5309. }
  5310. var cursor1 = 0;
  5311. var cursor2 = start2;
  5312. var dest = start1;
  5313. array[dest++] = array[cursor2++];
  5314. if (--length2 === 0) {
  5315. for (i = 0; i < length1; i++) {
  5316. array[dest + i] = tmp[cursor1 + i];
  5317. }
  5318. return;
  5319. }
  5320. if (length1 === 1) {
  5321. for (i = 0; i < length2; i++) {
  5322. array[dest + i] = array[cursor2 + i];
  5323. }
  5324. array[dest + length2] = tmp[cursor1];
  5325. return;
  5326. }
  5327. var _minGallop = minGallop;
  5328. var count1;
  5329. var count2;
  5330. var exit;
  5331. while (1) {
  5332. count1 = 0;
  5333. count2 = 0;
  5334. exit = false;
  5335. do {
  5336. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5337. array[dest++] = array[cursor2++];
  5338. count2++;
  5339. count1 = 0;
  5340. if (--length2 === 0) {
  5341. exit = true;
  5342. break;
  5343. }
  5344. }
  5345. else {
  5346. array[dest++] = tmp[cursor1++];
  5347. count1++;
  5348. count2 = 0;
  5349. if (--length1 === 1) {
  5350. exit = true;
  5351. break;
  5352. }
  5353. }
  5354. } while ((count1 | count2) < _minGallop);
  5355. if (exit) {
  5356. break;
  5357. }
  5358. do {
  5359. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5360. if (count1 !== 0) {
  5361. for (i = 0; i < count1; i++) {
  5362. array[dest + i] = tmp[cursor1 + i];
  5363. }
  5364. dest += count1;
  5365. cursor1 += count1;
  5366. length1 -= count1;
  5367. if (length1 <= 1) {
  5368. exit = true;
  5369. break;
  5370. }
  5371. }
  5372. array[dest++] = array[cursor2++];
  5373. if (--length2 === 0) {
  5374. exit = true;
  5375. break;
  5376. }
  5377. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5378. if (count2 !== 0) {
  5379. for (i = 0; i < count2; i++) {
  5380. array[dest + i] = array[cursor2 + i];
  5381. }
  5382. dest += count2;
  5383. cursor2 += count2;
  5384. length2 -= count2;
  5385. if (length2 === 0) {
  5386. exit = true;
  5387. break;
  5388. }
  5389. }
  5390. array[dest++] = tmp[cursor1++];
  5391. if (--length1 === 1) {
  5392. exit = true;
  5393. break;
  5394. }
  5395. _minGallop--;
  5396. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5397. if (exit) {
  5398. break;
  5399. }
  5400. if (_minGallop < 0) {
  5401. _minGallop = 0;
  5402. }
  5403. _minGallop += 2;
  5404. }
  5405. minGallop = _minGallop;
  5406. minGallop < 1 && (minGallop = 1);
  5407. if (length1 === 1) {
  5408. for (i = 0; i < length2; i++) {
  5409. array[dest + i] = array[cursor2 + i];
  5410. }
  5411. array[dest + length2] = tmp[cursor1];
  5412. }
  5413. else if (length1 === 0) {
  5414. throw new Error();
  5415. // throw new Error('mergeLow preconditions were not respected');
  5416. }
  5417. else {
  5418. for (i = 0; i < length1; i++) {
  5419. array[dest + i] = tmp[cursor1 + i];
  5420. }
  5421. }
  5422. }
  5423. function mergeHigh(start1, length1, start2, length2) {
  5424. var i = 0;
  5425. for (i = 0; i < length2; i++) {
  5426. tmp[i] = array[start2 + i];
  5427. }
  5428. var cursor1 = start1 + length1 - 1;
  5429. var cursor2 = length2 - 1;
  5430. var dest = start2 + length2 - 1;
  5431. var customCursor = 0;
  5432. var customDest = 0;
  5433. array[dest--] = array[cursor1--];
  5434. if (--length1 === 0) {
  5435. customCursor = dest - (length2 - 1);
  5436. for (i = 0; i < length2; i++) {
  5437. array[customCursor + i] = tmp[i];
  5438. }
  5439. return;
  5440. }
  5441. if (length2 === 1) {
  5442. dest -= length1;
  5443. cursor1 -= length1;
  5444. customDest = dest + 1;
  5445. customCursor = cursor1 + 1;
  5446. for (i = length1 - 1; i >= 0; i--) {
  5447. array[customDest + i] = array[customCursor + i];
  5448. }
  5449. array[dest] = tmp[cursor2];
  5450. return;
  5451. }
  5452. var _minGallop = minGallop;
  5453. while (true) {
  5454. var count1 = 0;
  5455. var count2 = 0;
  5456. var exit = false;
  5457. do {
  5458. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5459. array[dest--] = array[cursor1--];
  5460. count1++;
  5461. count2 = 0;
  5462. if (--length1 === 0) {
  5463. exit = true;
  5464. break;
  5465. }
  5466. }
  5467. else {
  5468. array[dest--] = tmp[cursor2--];
  5469. count2++;
  5470. count1 = 0;
  5471. if (--length2 === 1) {
  5472. exit = true;
  5473. break;
  5474. }
  5475. }
  5476. } while ((count1 | count2) < _minGallop);
  5477. if (exit) {
  5478. break;
  5479. }
  5480. do {
  5481. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5482. if (count1 !== 0) {
  5483. dest -= count1;
  5484. cursor1 -= count1;
  5485. length1 -= count1;
  5486. customDest = dest + 1;
  5487. customCursor = cursor1 + 1;
  5488. for (i = count1 - 1; i >= 0; i--) {
  5489. array[customDest + i] = array[customCursor + i];
  5490. }
  5491. if (length1 === 0) {
  5492. exit = true;
  5493. break;
  5494. }
  5495. }
  5496. array[dest--] = tmp[cursor2--];
  5497. if (--length2 === 1) {
  5498. exit = true;
  5499. break;
  5500. }
  5501. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5502. if (count2 !== 0) {
  5503. dest -= count2;
  5504. cursor2 -= count2;
  5505. length2 -= count2;
  5506. customDest = dest + 1;
  5507. customCursor = cursor2 + 1;
  5508. for (i = 0; i < count2; i++) {
  5509. array[customDest + i] = tmp[customCursor + i];
  5510. }
  5511. if (length2 <= 1) {
  5512. exit = true;
  5513. break;
  5514. }
  5515. }
  5516. array[dest--] = array[cursor1--];
  5517. if (--length1 === 0) {
  5518. exit = true;
  5519. break;
  5520. }
  5521. _minGallop--;
  5522. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5523. if (exit) {
  5524. break;
  5525. }
  5526. if (_minGallop < 0) {
  5527. _minGallop = 0;
  5528. }
  5529. _minGallop += 2;
  5530. }
  5531. minGallop = _minGallop;
  5532. if (minGallop < 1) {
  5533. minGallop = 1;
  5534. }
  5535. if (length2 === 1) {
  5536. dest -= length1;
  5537. cursor1 -= length1;
  5538. customDest = dest + 1;
  5539. customCursor = cursor1 + 1;
  5540. for (i = length1 - 1; i >= 0; i--) {
  5541. array[customDest + i] = array[customCursor + i];
  5542. }
  5543. array[dest] = tmp[cursor2];
  5544. }
  5545. else if (length2 === 0) {
  5546. throw new Error();
  5547. // throw new Error('mergeHigh preconditions were not respected');
  5548. }
  5549. else {
  5550. customCursor = dest - (length2 - 1);
  5551. for (i = 0; i < length2; i++) {
  5552. array[customCursor + i] = tmp[i];
  5553. }
  5554. }
  5555. }
  5556. this.mergeRuns = mergeRuns;
  5557. this.forceMergeRuns = forceMergeRuns;
  5558. this.pushRun = pushRun;
  5559. }
  5560. function sort(array, compare, lo, hi) {
  5561. if (!lo) {
  5562. lo = 0;
  5563. }
  5564. if (!hi) {
  5565. hi = array.length;
  5566. }
  5567. var remaining = hi - lo;
  5568. if (remaining < 2) {
  5569. return;
  5570. }
  5571. var runLength = 0;
  5572. if (remaining < DEFAULT_MIN_MERGE) {
  5573. runLength = makeAscendingRun(array, lo, hi, compare);
  5574. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5575. return;
  5576. }
  5577. var ts = new TimSort(array, compare);
  5578. var minRun = minRunLength(remaining);
  5579. do {
  5580. runLength = makeAscendingRun(array, lo, hi, compare);
  5581. if (runLength < minRun) {
  5582. var force = remaining;
  5583. if (force > minRun) {
  5584. force = minRun;
  5585. }
  5586. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5587. runLength = force;
  5588. }
  5589. ts.pushRun(lo, runLength);
  5590. ts.mergeRuns();
  5591. remaining -= runLength;
  5592. lo += runLength;
  5593. } while (remaining !== 0);
  5594. ts.forceMergeRuns();
  5595. }
  5596. // Use timsort because in most case elements are partially sorted
  5597. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5598. function shapeCompareFunc(a, b) {
  5599. if (a.zlevel === b.zlevel) {
  5600. if (a.z === b.z) {
  5601. // if (a.z2 === b.z2) {
  5602. // // FIXME Slow has renderidx compare
  5603. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5604. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5605. // return a.__renderidx - b.__renderidx;
  5606. // }
  5607. return a.z2 - b.z2;
  5608. }
  5609. return a.z - b.z;
  5610. }
  5611. return a.zlevel - b.zlevel;
  5612. }
  5613. /**
  5614. * 内容仓库 (M)
  5615. * @alias module:zrender/Storage
  5616. * @constructor
  5617. */
  5618. var Storage = function () { // jshint ignore:line
  5619. this._roots = [];
  5620. this._displayList = [];
  5621. this._displayListLen = 0;
  5622. };
  5623. Storage.prototype = {
  5624. constructor: Storage,
  5625. /**
  5626. * @param {Function} cb
  5627. *
  5628. */
  5629. traverse: function (cb, context) {
  5630. for (var i = 0; i < this._roots.length; i++) {
  5631. this._roots[i].traverse(cb, context);
  5632. }
  5633. },
  5634. /**
  5635. * 返回所有图形的绘制队列
  5636. * @param {boolean} [update=false] 是否在返回前更新该数组
  5637. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5638. *
  5639. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5640. * @return {Array.<module:zrender/graphic/Displayable>}
  5641. */
  5642. getDisplayList: function (update, includeIgnore) {
  5643. includeIgnore = includeIgnore || false;
  5644. if (update) {
  5645. this.updateDisplayList(includeIgnore);
  5646. }
  5647. return this._displayList;
  5648. },
  5649. /**
  5650. * 更新图形的绘制队列。
  5651. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5652. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5653. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5654. */
  5655. updateDisplayList: function (includeIgnore) {
  5656. this._displayListLen = 0;
  5657. var roots = this._roots;
  5658. var displayList = this._displayList;
  5659. for (var i = 0, len = roots.length; i < len; i++) {
  5660. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5661. }
  5662. displayList.length = this._displayListLen;
  5663. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5664. },
  5665. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5666. if (el.ignore && !includeIgnore) {
  5667. return;
  5668. }
  5669. el.beforeUpdate();
  5670. if (el.__dirty) {
  5671. el.update();
  5672. }
  5673. el.afterUpdate();
  5674. var userSetClipPath = el.clipPath;
  5675. if (userSetClipPath) {
  5676. // FIXME 效率影响
  5677. if (clipPaths) {
  5678. clipPaths = clipPaths.slice();
  5679. }
  5680. else {
  5681. clipPaths = [];
  5682. }
  5683. var currentClipPath = userSetClipPath;
  5684. var parentClipPath = el;
  5685. // Recursively add clip path
  5686. while (currentClipPath) {
  5687. // clipPath 的变换是基于使用这个 clipPath 的元素
  5688. currentClipPath.parent = parentClipPath;
  5689. currentClipPath.updateTransform();
  5690. clipPaths.push(currentClipPath);
  5691. parentClipPath = currentClipPath;
  5692. currentClipPath = currentClipPath.clipPath;
  5693. }
  5694. }
  5695. if (el.isGroup) {
  5696. var children = el._children;
  5697. for (var i = 0; i < children.length; i++) {
  5698. var child = children[i];
  5699. // Force to mark as dirty if group is dirty
  5700. // FIXME __dirtyPath ?
  5701. if (el.__dirty) {
  5702. child.__dirty = true;
  5703. }
  5704. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5705. }
  5706. // Mark group clean here
  5707. el.__dirty = false;
  5708. }
  5709. else {
  5710. el.__clipPaths = clipPaths;
  5711. this._displayList[this._displayListLen++] = el;
  5712. }
  5713. },
  5714. /**
  5715. * 添加图形(Shape)或者组(Group)到根节点
  5716. * @param {module:zrender/Element} el
  5717. */
  5718. addRoot: function (el) {
  5719. if (el.__storage === this) {
  5720. return;
  5721. }
  5722. if (el instanceof Group) {
  5723. el.addChildrenToStorage(this);
  5724. }
  5725. this.addToStorage(el);
  5726. this._roots.push(el);
  5727. },
  5728. /**
  5729. * 删除指定的图形(Shape)或者组(Group)
  5730. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5731. */
  5732. delRoot: function (el) {
  5733. if (el == null) {
  5734. // 不指定el清空
  5735. for (var i = 0; i < this._roots.length; i++) {
  5736. var root = this._roots[i];
  5737. if (root instanceof Group) {
  5738. root.delChildrenFromStorage(this);
  5739. }
  5740. }
  5741. this._roots = [];
  5742. this._displayList = [];
  5743. this._displayListLen = 0;
  5744. return;
  5745. }
  5746. if (el instanceof Array) {
  5747. for (var i = 0, l = el.length; i < l; i++) {
  5748. this.delRoot(el[i]);
  5749. }
  5750. return;
  5751. }
  5752. var idx = indexOf(this._roots, el);
  5753. if (idx >= 0) {
  5754. this.delFromStorage(el);
  5755. this._roots.splice(idx, 1);
  5756. if (el instanceof Group) {
  5757. el.delChildrenFromStorage(this);
  5758. }
  5759. }
  5760. },
  5761. addToStorage: function (el) {
  5762. if (el) {
  5763. el.__storage = this;
  5764. el.dirty(false);
  5765. }
  5766. return this;
  5767. },
  5768. delFromStorage: function (el) {
  5769. if (el) {
  5770. el.__storage = null;
  5771. }
  5772. return this;
  5773. },
  5774. /**
  5775. * 清空并且释放Storage
  5776. */
  5777. dispose: function () {
  5778. this._renderList =
  5779. this._roots = null;
  5780. },
  5781. displayableSortFunc: shapeCompareFunc
  5782. };
  5783. var SHADOW_PROPS = {
  5784. 'shadowBlur': 1,
  5785. 'shadowOffsetX': 1,
  5786. 'shadowOffsetY': 1,
  5787. 'textShadowBlur': 1,
  5788. 'textShadowOffsetX': 1,
  5789. 'textShadowOffsetY': 1,
  5790. 'textBoxShadowBlur': 1,
  5791. 'textBoxShadowOffsetX': 1,
  5792. 'textBoxShadowOffsetY': 1
  5793. };
  5794. var fixShadow = function (ctx, propName, value) {
  5795. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5796. return value *= ctx.dpr;
  5797. }
  5798. return value;
  5799. };
  5800. var ContextCachedBy = {
  5801. NONE: 0,
  5802. STYLE_BIND: 1,
  5803. PLAIN_TEXT: 2
  5804. };
  5805. // Avoid confused with 0/false.
  5806. var WILL_BE_RESTORED = 9;
  5807. var STYLE_COMMON_PROPS = [
  5808. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5809. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5810. ];
  5811. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5812. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5813. var Style = function (opts) {
  5814. this.extendFrom(opts, false);
  5815. };
  5816. function createLinearGradient(ctx, obj, rect) {
  5817. var x = obj.x == null ? 0 : obj.x;
  5818. var x2 = obj.x2 == null ? 1 : obj.x2;
  5819. var y = obj.y == null ? 0 : obj.y;
  5820. var y2 = obj.y2 == null ? 0 : obj.y2;
  5821. if (!obj.global) {
  5822. x = x * rect.width + rect.x;
  5823. x2 = x2 * rect.width + rect.x;
  5824. y = y * rect.height + rect.y;
  5825. y2 = y2 * rect.height + rect.y;
  5826. }
  5827. // Fix NaN when rect is Infinity
  5828. x = isNaN(x) ? 0 : x;
  5829. x2 = isNaN(x2) ? 1 : x2;
  5830. y = isNaN(y) ? 0 : y;
  5831. y2 = isNaN(y2) ? 0 : y2;
  5832. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5833. return canvasGradient;
  5834. }
  5835. function createRadialGradient(ctx, obj, rect) {
  5836. var width = rect.width;
  5837. var height = rect.height;
  5838. var min = Math.min(width, height);
  5839. var x = obj.x == null ? 0.5 : obj.x;
  5840. var y = obj.y == null ? 0.5 : obj.y;
  5841. var r = obj.r == null ? 0.5 : obj.r;
  5842. if (!obj.global) {
  5843. x = x * width + rect.x;
  5844. y = y * height + rect.y;
  5845. r = r * min;
  5846. }
  5847. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5848. return canvasGradient;
  5849. }
  5850. Style.prototype = {
  5851. constructor: Style,
  5852. /**
  5853. * @type {string}
  5854. */
  5855. fill: '#000',
  5856. /**
  5857. * @type {string}
  5858. */
  5859. stroke: null,
  5860. /**
  5861. * @type {number}
  5862. */
  5863. opacity: 1,
  5864. /**
  5865. * @type {number}
  5866. */
  5867. fillOpacity: null,
  5868. /**
  5869. * @type {number}
  5870. */
  5871. strokeOpacity: null,
  5872. /**
  5873. * `true` is not supported.
  5874. * `false`/`null`/`undefined` are the same.
  5875. * `false` is used to remove lineDash in some
  5876. * case that `null`/`undefined` can not be set.
  5877. * (e.g., emphasis.lineStyle in echarts)
  5878. * @type {Array.<number>|boolean}
  5879. */
  5880. lineDash: null,
  5881. /**
  5882. * @type {number}
  5883. */
  5884. lineDashOffset: 0,
  5885. /**
  5886. * @type {number}
  5887. */
  5888. shadowBlur: 0,
  5889. /**
  5890. * @type {number}
  5891. */
  5892. shadowOffsetX: 0,
  5893. /**
  5894. * @type {number}
  5895. */
  5896. shadowOffsetY: 0,
  5897. /**
  5898. * @type {number}
  5899. */
  5900. lineWidth: 1,
  5901. /**
  5902. * If stroke ignore scale
  5903. * @type {Boolean}
  5904. */
  5905. strokeNoScale: false,
  5906. // Bounding rect text configuration
  5907. // Not affected by element transform
  5908. /**
  5909. * @type {string}
  5910. */
  5911. text: null,
  5912. /**
  5913. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5914. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5915. * So do not visit it directly in upper application (like echarts),
  5916. * but use `contain/text#makeFont` instead.
  5917. * @type {string}
  5918. */
  5919. font: null,
  5920. /**
  5921. * The same as font. Use font please.
  5922. * @deprecated
  5923. * @type {string}
  5924. */
  5925. textFont: null,
  5926. /**
  5927. * It helps merging respectively, rather than parsing an entire font string.
  5928. * @type {string}
  5929. */
  5930. fontStyle: null,
  5931. /**
  5932. * It helps merging respectively, rather than parsing an entire font string.
  5933. * @type {string}
  5934. */
  5935. fontWeight: null,
  5936. /**
  5937. * It helps merging respectively, rather than parsing an entire font string.
  5938. * Should be 12 but not '12px'.
  5939. * @type {number}
  5940. */
  5941. fontSize: null,
  5942. /**
  5943. * It helps merging respectively, rather than parsing an entire font string.
  5944. * @type {string}
  5945. */
  5946. fontFamily: null,
  5947. /**
  5948. * Reserved for special functinality, like 'hr'.
  5949. * @type {string}
  5950. */
  5951. textTag: null,
  5952. /**
  5953. * @type {string}
  5954. */
  5955. textFill: '#000',
  5956. /**
  5957. * @type {string}
  5958. */
  5959. textStroke: null,
  5960. /**
  5961. * @type {number}
  5962. */
  5963. textWidth: null,
  5964. /**
  5965. * Only for textBackground.
  5966. * @type {number}
  5967. */
  5968. textHeight: null,
  5969. /**
  5970. * textStroke may be set as some color as a default
  5971. * value in upper applicaion, where the default value
  5972. * of textStrokeWidth should be 0 to make sure that
  5973. * user can choose to do not use text stroke.
  5974. * @type {number}
  5975. */
  5976. textStrokeWidth: 0,
  5977. /**
  5978. * @type {number}
  5979. */
  5980. textLineHeight: null,
  5981. /**
  5982. * 'inside', 'left', 'right', 'top', 'bottom'
  5983. * [x, y]
  5984. * Based on x, y of rect.
  5985. * @type {string|Array.<number>}
  5986. * @default 'inside'
  5987. */
  5988. textPosition: 'inside',
  5989. /**
  5990. * If not specified, use the boundingRect of a `displayable`.
  5991. * @type {Object}
  5992. */
  5993. textRect: null,
  5994. /**
  5995. * [x, y]
  5996. * @type {Array.<number>}
  5997. */
  5998. textOffset: null,
  5999. /**
  6000. * @type {string}
  6001. */
  6002. textAlign: null,
  6003. /**
  6004. * @type {string}
  6005. */
  6006. textVerticalAlign: null,
  6007. /**
  6008. * @type {number}
  6009. */
  6010. textDistance: 5,
  6011. /**
  6012. * @type {string}
  6013. */
  6014. textShadowColor: 'transparent',
  6015. /**
  6016. * @type {number}
  6017. */
  6018. textShadowBlur: 0,
  6019. /**
  6020. * @type {number}
  6021. */
  6022. textShadowOffsetX: 0,
  6023. /**
  6024. * @type {number}
  6025. */
  6026. textShadowOffsetY: 0,
  6027. /**
  6028. * @type {string}
  6029. */
  6030. textBoxShadowColor: 'transparent',
  6031. /**
  6032. * @type {number}
  6033. */
  6034. textBoxShadowBlur: 0,
  6035. /**
  6036. * @type {number}
  6037. */
  6038. textBoxShadowOffsetX: 0,
  6039. /**
  6040. * @type {number}
  6041. */
  6042. textBoxShadowOffsetY: 0,
  6043. /**
  6044. * Whether transform text.
  6045. * Only available in Path and Image element,
  6046. * where the text is called as `RectText`.
  6047. * @type {boolean}
  6048. */
  6049. transformText: false,
  6050. /**
  6051. * Text rotate around position of Path or Image.
  6052. * The origin of the rotation can be specified by `textOrigin`.
  6053. * Only available in Path and Image element,
  6054. * where the text is called as `RectText`.
  6055. */
  6056. textRotation: 0,
  6057. /**
  6058. * Text origin of text rotation.
  6059. * Useful in the case like label rotation of circular symbol.
  6060. * Only available in Path and Image element, where the text is called
  6061. * as `RectText` and the element is called as "host element".
  6062. * The value can be:
  6063. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6064. * base on the left-top corner of the rect of its host element.
  6065. * + If specified as a string `center`, it is the center of the rect of
  6066. * its host element.
  6067. * + By default, this origin is the `textPosition`.
  6068. * @type {string|Array.<number>}
  6069. */
  6070. textOrigin: null,
  6071. /**
  6072. * @type {string}
  6073. */
  6074. textBackgroundColor: null,
  6075. /**
  6076. * @type {string}
  6077. */
  6078. textBorderColor: null,
  6079. /**
  6080. * @type {number}
  6081. */
  6082. textBorderWidth: 0,
  6083. /**
  6084. * @type {number}
  6085. */
  6086. textBorderRadius: 0,
  6087. /**
  6088. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6089. * @type {number|Array.<number>}
  6090. */
  6091. textPadding: null,
  6092. /**
  6093. * Text styles for rich text.
  6094. * @type {Object}
  6095. */
  6096. rich: null,
  6097. /**
  6098. * {outerWidth, outerHeight, ellipsis, placeholder}
  6099. * @type {Object}
  6100. */
  6101. truncate: null,
  6102. /**
  6103. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6104. * @type {string}
  6105. */
  6106. blend: null,
  6107. /**
  6108. * @param {CanvasRenderingContext2D} ctx
  6109. */
  6110. bind: function (ctx, el, prevEl) {
  6111. var style = this;
  6112. var prevStyle = prevEl && prevEl.style;
  6113. // If no prevStyle, it means first draw.
  6114. // Only apply cache if the last time cachced by this function.
  6115. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6116. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6117. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6118. var prop = STYLE_COMMON_PROPS[i];
  6119. var styleName = prop[0];
  6120. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6121. // FIXME Invalid property value will cause style leak from previous element.
  6122. ctx[styleName] =
  6123. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6124. }
  6125. }
  6126. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6127. ctx.fillStyle = style.fill;
  6128. }
  6129. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6130. ctx.strokeStyle = style.stroke;
  6131. }
  6132. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6133. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6134. }
  6135. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6136. ctx.globalCompositeOperation = style.blend || 'source-over';
  6137. }
  6138. if (this.hasStroke()) {
  6139. var lineWidth = style.lineWidth;
  6140. ctx.lineWidth = lineWidth / (
  6141. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6142. );
  6143. }
  6144. },
  6145. hasFill: function () {
  6146. var fill = this.fill;
  6147. return fill != null && fill !== 'none';
  6148. },
  6149. hasStroke: function () {
  6150. var stroke = this.stroke;
  6151. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6152. },
  6153. /**
  6154. * Extend from other style
  6155. * @param {zrender/graphic/Style} otherStyle
  6156. * @param {boolean} overwrite true: overwrirte any way.
  6157. * false: overwrite only when !target.hasOwnProperty
  6158. * others: overwrite when property is not null/undefined.
  6159. */
  6160. extendFrom: function (otherStyle, overwrite) {
  6161. if (otherStyle) {
  6162. for (var name in otherStyle) {
  6163. if (otherStyle.hasOwnProperty(name)
  6164. && (overwrite === true
  6165. || (
  6166. overwrite === false
  6167. ? !this.hasOwnProperty(name)
  6168. : otherStyle[name] != null
  6169. )
  6170. )
  6171. ) {
  6172. this[name] = otherStyle[name];
  6173. }
  6174. }
  6175. }
  6176. },
  6177. /**
  6178. * Batch setting style with a given object
  6179. * @param {Object|string} obj
  6180. * @param {*} [obj]
  6181. */
  6182. set: function (obj, value) {
  6183. if (typeof obj === 'string') {
  6184. this[obj] = value;
  6185. }
  6186. else {
  6187. this.extendFrom(obj, true);
  6188. }
  6189. },
  6190. /**
  6191. * Clone
  6192. * @return {zrender/graphic/Style} [description]
  6193. */
  6194. clone: function () {
  6195. var newStyle = new this.constructor();
  6196. newStyle.extendFrom(this, true);
  6197. return newStyle;
  6198. },
  6199. getGradient: function (ctx, obj, rect) {
  6200. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6201. var canvasGradient = method(ctx, obj, rect);
  6202. var colorStops = obj.colorStops;
  6203. for (var i = 0; i < colorStops.length; i++) {
  6204. canvasGradient.addColorStop(
  6205. colorStops[i].offset, colorStops[i].color
  6206. );
  6207. }
  6208. return canvasGradient;
  6209. }
  6210. };
  6211. var styleProto = Style.prototype;
  6212. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6213. var prop = STYLE_COMMON_PROPS[i];
  6214. if (!(prop[0] in styleProto)) {
  6215. styleProto[prop[0]] = prop[1];
  6216. }
  6217. }
  6218. // Provide for others
  6219. Style.getGradient = styleProto.getGradient;
  6220. var Pattern = function (image, repeat) {
  6221. // Should do nothing more in this constructor. Because gradient can be
  6222. // declard by `color: {image: ...}`, where this constructor will not be called.
  6223. this.image = image;
  6224. this.repeat = repeat;
  6225. // Can be cloned
  6226. this.type = 'pattern';
  6227. };
  6228. Pattern.prototype.getCanvasPattern = function (ctx) {
  6229. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6230. };
  6231. /**
  6232. * @module zrender/Layer
  6233. * @author pissang(https://www.github.com/pissang)
  6234. */
  6235. function returnFalse() {
  6236. return false;
  6237. }
  6238. /**
  6239. * 创建dom
  6240. *
  6241. * @inner
  6242. * @param {string} id dom id 待用
  6243. * @param {Painter} painter painter instance
  6244. * @param {number} number
  6245. */
  6246. function createDom(id, painter, dpr) {
  6247. var newDom = createCanvas();
  6248. var width = painter.getWidth();
  6249. var height = painter.getHeight();
  6250. var newDomStyle = newDom.style;
  6251. if (newDomStyle) { // In node or some other non-browser environment
  6252. newDomStyle.position = 'absolute';
  6253. newDomStyle.left = 0;
  6254. newDomStyle.top = 0;
  6255. newDomStyle.width = width + 'px';
  6256. newDomStyle.height = height + 'px';
  6257. newDom.setAttribute('data-zr-dom-id', id);
  6258. }
  6259. newDom.width = width * dpr;
  6260. newDom.height = height * dpr;
  6261. return newDom;
  6262. }
  6263. /**
  6264. * @alias module:zrender/Layer
  6265. * @constructor
  6266. * @extends module:zrender/mixin/Transformable
  6267. * @param {string} id
  6268. * @param {module:zrender/Painter} painter
  6269. * @param {number} [dpr]
  6270. */
  6271. var Layer = function (id, painter, dpr) {
  6272. var dom;
  6273. dpr = dpr || devicePixelRatio;
  6274. if (typeof id === 'string') {
  6275. dom = createDom(id, painter, dpr);
  6276. }
  6277. // Not using isDom because in node it will return false
  6278. else if (isObject$1(id)) {
  6279. dom = id;
  6280. id = dom.id;
  6281. }
  6282. this.id = id;
  6283. this.dom = dom;
  6284. var domStyle = dom.style;
  6285. if (domStyle) { // Not in node
  6286. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6287. domStyle['-webkit-user-select'] = 'none';
  6288. domStyle['user-select'] = 'none';
  6289. domStyle['-webkit-touch-callout'] = 'none';
  6290. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6291. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6292. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6293. domStyle['border-width'] = 0;
  6294. }
  6295. this.domBack = null;
  6296. this.ctxBack = null;
  6297. this.painter = painter;
  6298. this.config = null;
  6299. // Configs
  6300. /**
  6301. * 每次清空画布的颜色
  6302. * @type {string}
  6303. * @default 0
  6304. */
  6305. this.clearColor = 0;
  6306. /**
  6307. * 是否开启动态模糊
  6308. * @type {boolean}
  6309. * @default false
  6310. */
  6311. this.motionBlur = false;
  6312. /**
  6313. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6314. * @type {number}
  6315. * @default 0.7
  6316. */
  6317. this.lastFrameAlpha = 0.7;
  6318. /**
  6319. * Layer dpr
  6320. * @type {number}
  6321. */
  6322. this.dpr = dpr;
  6323. };
  6324. Layer.prototype = {
  6325. constructor: Layer,
  6326. __dirty: true,
  6327. __used: false,
  6328. __drawIndex: 0,
  6329. __startIndex: 0,
  6330. __endIndex: 0,
  6331. incremental: false,
  6332. getElementCount: function () {
  6333. return this.__endIndex - this.__startIndex;
  6334. },
  6335. initContext: function () {
  6336. this.ctx = this.dom.getContext('2d');
  6337. this.ctx.dpr = this.dpr;
  6338. },
  6339. createBackBuffer: function () {
  6340. var dpr = this.dpr;
  6341. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6342. this.ctxBack = this.domBack.getContext('2d');
  6343. if (dpr !== 1) {
  6344. this.ctxBack.scale(dpr, dpr);
  6345. }
  6346. },
  6347. /**
  6348. * @param {number} width
  6349. * @param {number} height
  6350. */
  6351. resize: function (width, height) {
  6352. var dpr = this.dpr;
  6353. var dom = this.dom;
  6354. var domStyle = dom.style;
  6355. var domBack = this.domBack;
  6356. if (domStyle) {
  6357. domStyle.width = width + 'px';
  6358. domStyle.height = height + 'px';
  6359. }
  6360. dom.width = width * dpr;
  6361. dom.height = height * dpr;
  6362. if (domBack) {
  6363. domBack.width = width * dpr;
  6364. domBack.height = height * dpr;
  6365. if (dpr !== 1) {
  6366. this.ctxBack.scale(dpr, dpr);
  6367. }
  6368. }
  6369. },
  6370. /**
  6371. * 清空该层画布
  6372. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6373. * @param {Color} [clearColor]
  6374. */
  6375. clear: function (clearAll, clearColor) {
  6376. var dom = this.dom;
  6377. var ctx = this.ctx;
  6378. var width = dom.width;
  6379. var height = dom.height;
  6380. var clearColor = clearColor || this.clearColor;
  6381. var haveMotionBLur = this.motionBlur && !clearAll;
  6382. var lastFrameAlpha = this.lastFrameAlpha;
  6383. var dpr = this.dpr;
  6384. if (haveMotionBLur) {
  6385. if (!this.domBack) {
  6386. this.createBackBuffer();
  6387. }
  6388. this.ctxBack.globalCompositeOperation = 'copy';
  6389. this.ctxBack.drawImage(
  6390. dom, 0, 0,
  6391. width / dpr,
  6392. height / dpr
  6393. );
  6394. }
  6395. ctx.clearRect(0, 0, width, height);
  6396. if (clearColor && clearColor !== 'transparent') {
  6397. var clearColorGradientOrPattern;
  6398. // Gradient
  6399. if (clearColor.colorStops) {
  6400. // Cache canvas gradient
  6401. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6402. x: 0,
  6403. y: 0,
  6404. width: width,
  6405. height: height
  6406. });
  6407. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6408. }
  6409. // Pattern
  6410. else if (clearColor.image) {
  6411. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6412. }
  6413. ctx.save();
  6414. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6415. ctx.fillRect(0, 0, width, height);
  6416. ctx.restore();
  6417. }
  6418. if (haveMotionBLur) {
  6419. var domBack = this.domBack;
  6420. ctx.save();
  6421. ctx.globalAlpha = lastFrameAlpha;
  6422. ctx.drawImage(domBack, 0, 0, width, height);
  6423. ctx.restore();
  6424. }
  6425. }
  6426. };
  6427. var requestAnimationFrame = (
  6428. typeof window !== 'undefined'
  6429. && (
  6430. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6431. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6432. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6433. || window.mozRequestAnimationFrame
  6434. || window.webkitRequestAnimationFrame
  6435. )
  6436. ) || function (func) {
  6437. setTimeout(func, 16);
  6438. };
  6439. var globalImageCache = new LRU(50);
  6440. /**
  6441. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6442. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6443. */
  6444. function findExistImage(newImageOrSrc) {
  6445. if (typeof newImageOrSrc === 'string') {
  6446. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6447. return cachedImgObj && cachedImgObj.image;
  6448. }
  6449. else {
  6450. return newImageOrSrc;
  6451. }
  6452. }
  6453. /**
  6454. * Caution: User should cache loaded images, but not just count on LRU.
  6455. * Consider if required images more than LRU size, will dead loop occur?
  6456. *
  6457. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6458. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6459. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6460. * @param {Function} [cb] params: (image, cbPayload)
  6461. * @param {Object} [cbPayload] Payload on cb calling.
  6462. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6463. */
  6464. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6465. if (!newImageOrSrc) {
  6466. return image;
  6467. }
  6468. else if (typeof newImageOrSrc === 'string') {
  6469. // Image should not be loaded repeatly.
  6470. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6471. return image;
  6472. }
  6473. // Only when there is no existent image or existent image src
  6474. // is different, this method is responsible for load.
  6475. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6476. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6477. if (cachedImgObj) {
  6478. image = cachedImgObj.image;
  6479. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6480. }
  6481. else {
  6482. image = new Image();
  6483. image.onload = image.onerror = imageOnLoad;
  6484. globalImageCache.put(
  6485. newImageOrSrc,
  6486. image.__cachedImgObj = {
  6487. image: image,
  6488. pending: [pendingWrap]
  6489. }
  6490. );
  6491. image.src = image.__zrImageSrc = newImageOrSrc;
  6492. }
  6493. return image;
  6494. }
  6495. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6496. else {
  6497. return newImageOrSrc;
  6498. }
  6499. }
  6500. function imageOnLoad() {
  6501. var cachedImgObj = this.__cachedImgObj;
  6502. this.onload = this.onerror = this.__cachedImgObj = null;
  6503. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6504. var pendingWrap = cachedImgObj.pending[i];
  6505. var cb = pendingWrap.cb;
  6506. cb && cb(this, pendingWrap.cbPayload);
  6507. pendingWrap.hostEl.dirty();
  6508. }
  6509. cachedImgObj.pending.length = 0;
  6510. }
  6511. function isImageReady(image) {
  6512. return image && image.width && image.height;
  6513. }
  6514. var textWidthCache = {};
  6515. var textWidthCacheCounter = 0;
  6516. var TEXT_CACHE_MAX = 5000;
  6517. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6518. var DEFAULT_FONT$1 = '12px sans-serif';
  6519. // Avoid assign to an exported variable, for transforming to cjs.
  6520. var methods$1 = {};
  6521. /**
  6522. * @public
  6523. * @param {string} text
  6524. * @param {string} font
  6525. * @return {number} width
  6526. */
  6527. function getWidth(text, font) {
  6528. font = font || DEFAULT_FONT$1;
  6529. var key = text + ':' + font;
  6530. if (textWidthCache[key]) {
  6531. return textWidthCache[key];
  6532. }
  6533. var textLines = (text + '').split('\n');
  6534. var width = 0;
  6535. for (var i = 0, l = textLines.length; i < l; i++) {
  6536. // textContain.measureText may be overrided in SVG or VML
  6537. width = Math.max(measureText(textLines[i], font).width, width);
  6538. }
  6539. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6540. textWidthCacheCounter = 0;
  6541. textWidthCache = {};
  6542. }
  6543. textWidthCacheCounter++;
  6544. textWidthCache[key] = width;
  6545. return width;
  6546. }
  6547. /**
  6548. * @public
  6549. * @param {string} text
  6550. * @param {string} font
  6551. * @param {string} [textAlign='left']
  6552. * @param {string} [textVerticalAlign='top']
  6553. * @param {Array.<number>} [textPadding]
  6554. * @param {Object} [rich]
  6555. * @param {Object} [truncate]
  6556. * @return {Object} {x, y, width, height, lineHeight}
  6557. */
  6558. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6559. return rich
  6560. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6561. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6562. }
  6563. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6564. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6565. var outerWidth = getWidth(text, font);
  6566. if (textPadding) {
  6567. outerWidth += textPadding[1] + textPadding[3];
  6568. }
  6569. var outerHeight = contentBlock.outerHeight;
  6570. var x = adjustTextX(0, outerWidth, textAlign);
  6571. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6572. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6573. rect.lineHeight = contentBlock.lineHeight;
  6574. return rect;
  6575. }
  6576. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6577. var contentBlock = parseRichText(text, {
  6578. rich: rich,
  6579. truncate: truncate,
  6580. font: font,
  6581. textAlign: textAlign,
  6582. textPadding: textPadding,
  6583. textLineHeight: textLineHeight
  6584. });
  6585. var outerWidth = contentBlock.outerWidth;
  6586. var outerHeight = contentBlock.outerHeight;
  6587. var x = adjustTextX(0, outerWidth, textAlign);
  6588. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6589. return new BoundingRect(x, y, outerWidth, outerHeight);
  6590. }
  6591. /**
  6592. * @public
  6593. * @param {number} x
  6594. * @param {number} width
  6595. * @param {string} [textAlign='left']
  6596. * @return {number} Adjusted x.
  6597. */
  6598. function adjustTextX(x, width, textAlign) {
  6599. // FIXME Right to left language
  6600. if (textAlign === 'right') {
  6601. x -= width;
  6602. }
  6603. else if (textAlign === 'center') {
  6604. x -= width / 2;
  6605. }
  6606. return x;
  6607. }
  6608. /**
  6609. * @public
  6610. * @param {number} y
  6611. * @param {number} height
  6612. * @param {string} [textVerticalAlign='top']
  6613. * @return {number} Adjusted y.
  6614. */
  6615. function adjustTextY(y, height, textVerticalAlign) {
  6616. if (textVerticalAlign === 'middle') {
  6617. y -= height / 2;
  6618. }
  6619. else if (textVerticalAlign === 'bottom') {
  6620. y -= height;
  6621. }
  6622. return y;
  6623. }
  6624. /**
  6625. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6626. * @public
  6627. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6628. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6629. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6630. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6631. */
  6632. function calculateTextPosition(out, style, rect) {
  6633. var textPosition = style.textPosition;
  6634. var distance = style.textDistance;
  6635. var x = rect.x;
  6636. var y = rect.y;
  6637. distance = distance || 0;
  6638. var height = rect.height;
  6639. var width = rect.width;
  6640. var halfHeight = height / 2;
  6641. var textAlign = 'left';
  6642. var textVerticalAlign = 'top';
  6643. switch (textPosition) {
  6644. case 'left':
  6645. x -= distance;
  6646. y += halfHeight;
  6647. textAlign = 'right';
  6648. textVerticalAlign = 'middle';
  6649. break;
  6650. case 'right':
  6651. x += distance + width;
  6652. y += halfHeight;
  6653. textVerticalAlign = 'middle';
  6654. break;
  6655. case 'top':
  6656. x += width / 2;
  6657. y -= distance;
  6658. textAlign = 'center';
  6659. textVerticalAlign = 'bottom';
  6660. break;
  6661. case 'bottom':
  6662. x += width / 2;
  6663. y += height + distance;
  6664. textAlign = 'center';
  6665. break;
  6666. case 'inside':
  6667. x += width / 2;
  6668. y += halfHeight;
  6669. textAlign = 'center';
  6670. textVerticalAlign = 'middle';
  6671. break;
  6672. case 'insideLeft':
  6673. x += distance;
  6674. y += halfHeight;
  6675. textVerticalAlign = 'middle';
  6676. break;
  6677. case 'insideRight':
  6678. x += width - distance;
  6679. y += halfHeight;
  6680. textAlign = 'right';
  6681. textVerticalAlign = 'middle';
  6682. break;
  6683. case 'insideTop':
  6684. x += width / 2;
  6685. y += distance;
  6686. textAlign = 'center';
  6687. break;
  6688. case 'insideBottom':
  6689. x += width / 2;
  6690. y += height - distance;
  6691. textAlign = 'center';
  6692. textVerticalAlign = 'bottom';
  6693. break;
  6694. case 'insideTopLeft':
  6695. x += distance;
  6696. y += distance;
  6697. break;
  6698. case 'insideTopRight':
  6699. x += width - distance;
  6700. y += distance;
  6701. textAlign = 'right';
  6702. break;
  6703. case 'insideBottomLeft':
  6704. x += distance;
  6705. y += height - distance;
  6706. textVerticalAlign = 'bottom';
  6707. break;
  6708. case 'insideBottomRight':
  6709. x += width - distance;
  6710. y += height - distance;
  6711. textAlign = 'right';
  6712. textVerticalAlign = 'bottom';
  6713. break;
  6714. }
  6715. out = out || {};
  6716. out.x = x;
  6717. out.y = y;
  6718. out.textAlign = textAlign;
  6719. out.textVerticalAlign = textVerticalAlign;
  6720. return out;
  6721. }
  6722. /**
  6723. * To be removed. But still do not remove in case that some one has imported it.
  6724. * @deprecated
  6725. * @public
  6726. * @param {stirng} textPosition
  6727. * @param {Object} rect {x, y, width, height}
  6728. * @param {number} distance
  6729. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6730. */
  6731. /**
  6732. * Show ellipsis if overflow.
  6733. *
  6734. * @public
  6735. * @param {string} text
  6736. * @param {string} containerWidth
  6737. * @param {string} font
  6738. * @param {number} [ellipsis='...']
  6739. * @param {Object} [options]
  6740. * @param {number} [options.maxIterations=3]
  6741. * @param {number} [options.minChar=0] If truncate result are less
  6742. * then minChar, ellipsis will not show, which is
  6743. * better for user hint in some cases.
  6744. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6745. * @return {string}
  6746. */
  6747. function truncateText(text, containerWidth, font, ellipsis, options) {
  6748. if (!containerWidth) {
  6749. return '';
  6750. }
  6751. var textLines = (text + '').split('\n');
  6752. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6753. // FIXME
  6754. // It is not appropriate that every line has '...' when truncate multiple lines.
  6755. for (var i = 0, len = textLines.length; i < len; i++) {
  6756. textLines[i] = truncateSingleLine(textLines[i], options);
  6757. }
  6758. return textLines.join('\n');
  6759. }
  6760. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6761. options = extend({}, options);
  6762. options.font = font;
  6763. var ellipsis = retrieve2(ellipsis, '...');
  6764. options.maxIterations = retrieve2(options.maxIterations, 2);
  6765. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6766. // FIXME
  6767. // Other languages?
  6768. options.cnCharWidth = getWidth('国', font);
  6769. // FIXME
  6770. // Consider proportional font?
  6771. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6772. options.placeholder = retrieve2(options.placeholder, '');
  6773. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6774. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6775. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6776. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6777. contentWidth -= ascCharWidth;
  6778. }
  6779. var ellipsisWidth = getWidth(ellipsis, font);
  6780. if (ellipsisWidth > contentWidth) {
  6781. ellipsis = '';
  6782. ellipsisWidth = 0;
  6783. }
  6784. contentWidth = containerWidth - ellipsisWidth;
  6785. options.ellipsis = ellipsis;
  6786. options.ellipsisWidth = ellipsisWidth;
  6787. options.contentWidth = contentWidth;
  6788. options.containerWidth = containerWidth;
  6789. return options;
  6790. }
  6791. function truncateSingleLine(textLine, options) {
  6792. var containerWidth = options.containerWidth;
  6793. var font = options.font;
  6794. var contentWidth = options.contentWidth;
  6795. if (!containerWidth) {
  6796. return '';
  6797. }
  6798. var lineWidth = getWidth(textLine, font);
  6799. if (lineWidth <= containerWidth) {
  6800. return textLine;
  6801. }
  6802. for (var j = 0; ; j++) {
  6803. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6804. textLine += options.ellipsis;
  6805. break;
  6806. }
  6807. var subLength = j === 0
  6808. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6809. : lineWidth > 0
  6810. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6811. : 0;
  6812. textLine = textLine.substr(0, subLength);
  6813. lineWidth = getWidth(textLine, font);
  6814. }
  6815. if (textLine === '') {
  6816. textLine = options.placeholder;
  6817. }
  6818. return textLine;
  6819. }
  6820. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6821. var width = 0;
  6822. var i = 0;
  6823. for (var len = text.length; i < len && width < contentWidth; i++) {
  6824. var charCode = text.charCodeAt(i);
  6825. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6826. }
  6827. return i;
  6828. }
  6829. /**
  6830. * @public
  6831. * @param {string} font
  6832. * @return {number} line height
  6833. */
  6834. function getLineHeight(font) {
  6835. // FIXME A rough approach.
  6836. return getWidth('国', font);
  6837. }
  6838. /**
  6839. * @public
  6840. * @param {string} text
  6841. * @param {string} font
  6842. * @return {Object} width
  6843. */
  6844. function measureText(text, font) {
  6845. return methods$1.measureText(text, font);
  6846. }
  6847. // Avoid assign to an exported variable, for transforming to cjs.
  6848. methods$1.measureText = function (text, font) {
  6849. var ctx = getContext();
  6850. ctx.font = font || DEFAULT_FONT$1;
  6851. return ctx.measureText(text);
  6852. };
  6853. /**
  6854. * @public
  6855. * @param {string} text
  6856. * @param {string} font
  6857. * @param {Object} [truncate]
  6858. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  6859. * Notice: for performance, do not calculate outerWidth util needed.
  6860. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  6861. * Thus we can simply comparing the `input` text to determin whether the result changed,
  6862. * without travel the result `lines`.
  6863. */
  6864. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6865. text != null && (text += '');
  6866. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6867. var lines = text ? text.split('\n') : [];
  6868. var height = lines.length * lineHeight;
  6869. var outerHeight = height;
  6870. var canCacheByTextString = true;
  6871. if (padding) {
  6872. outerHeight += padding[0] + padding[2];
  6873. }
  6874. if (text && truncate) {
  6875. canCacheByTextString = false;
  6876. var truncOuterHeight = truncate.outerHeight;
  6877. var truncOuterWidth = truncate.outerWidth;
  6878. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6879. text = '';
  6880. lines = [];
  6881. }
  6882. else if (truncOuterWidth != null) {
  6883. var options = prepareTruncateOptions(
  6884. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6885. font,
  6886. truncate.ellipsis,
  6887. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6888. );
  6889. // FIXME
  6890. // It is not appropriate that every line has '...' when truncate multiple lines.
  6891. for (var i = 0, len = lines.length; i < len; i++) {
  6892. lines[i] = truncateSingleLine(lines[i], options);
  6893. }
  6894. }
  6895. }
  6896. return {
  6897. lines: lines,
  6898. height: height,
  6899. outerHeight: outerHeight,
  6900. lineHeight: lineHeight,
  6901. canCacheByTextString: canCacheByTextString
  6902. };
  6903. }
  6904. /**
  6905. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6906. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6907. *
  6908. * @public
  6909. * @param {string} text
  6910. * @param {Object} style
  6911. * @return {Object} block
  6912. * {
  6913. * width,
  6914. * height,
  6915. * lines: [{
  6916. * lineHeight,
  6917. * width,
  6918. * tokens: [[{
  6919. * styleName,
  6920. * text,
  6921. * width, // include textPadding
  6922. * height, // include textPadding
  6923. * textWidth, // pure text width
  6924. * textHeight, // pure text height
  6925. * lineHeihgt,
  6926. * font,
  6927. * textAlign,
  6928. * textVerticalAlign
  6929. * }], [...], ...]
  6930. * }, ...]
  6931. * }
  6932. * If styleName is undefined, it is plain text.
  6933. */
  6934. function parseRichText(text, style) {
  6935. var contentBlock = {lines: [], width: 0, height: 0};
  6936. text != null && (text += '');
  6937. if (!text) {
  6938. return contentBlock;
  6939. }
  6940. var lastIndex = STYLE_REG.lastIndex = 0;
  6941. var result;
  6942. while ((result = STYLE_REG.exec(text)) != null) {
  6943. var matchedIndex = result.index;
  6944. if (matchedIndex > lastIndex) {
  6945. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6946. }
  6947. pushTokens(contentBlock, result[2], result[1]);
  6948. lastIndex = STYLE_REG.lastIndex;
  6949. }
  6950. if (lastIndex < text.length) {
  6951. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6952. }
  6953. var lines = contentBlock.lines;
  6954. var contentHeight = 0;
  6955. var contentWidth = 0;
  6956. // For `textWidth: 100%`
  6957. var pendingList = [];
  6958. var stlPadding = style.textPadding;
  6959. var truncate = style.truncate;
  6960. var truncateWidth = truncate && truncate.outerWidth;
  6961. var truncateHeight = truncate && truncate.outerHeight;
  6962. if (stlPadding) {
  6963. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6964. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6965. }
  6966. // Calculate layout info of tokens.
  6967. for (var i = 0; i < lines.length; i++) {
  6968. var line = lines[i];
  6969. var lineHeight = 0;
  6970. var lineWidth = 0;
  6971. for (var j = 0; j < line.tokens.length; j++) {
  6972. var token = line.tokens[j];
  6973. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6974. // textPadding should not inherit from style.
  6975. var textPadding = token.textPadding = tokenStyle.textPadding;
  6976. // textFont has been asigned to font by `normalizeStyle`.
  6977. var font = token.font = tokenStyle.font || style.font;
  6978. // textHeight can be used when textVerticalAlign is specified in token.
  6979. var tokenHeight = token.textHeight = retrieve2(
  6980. // textHeight should not be inherited, consider it can be specified
  6981. // as box height of the block.
  6982. tokenStyle.textHeight, getLineHeight(font)
  6983. );
  6984. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6985. token.height = tokenHeight;
  6986. token.lineHeight = retrieve3(
  6987. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6988. );
  6989. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6990. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6991. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6992. return {lines: [], width: 0, height: 0};
  6993. }
  6994. token.textWidth = getWidth(token.text, font);
  6995. var tokenWidth = tokenStyle.textWidth;
  6996. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6997. // Percent width, can be `100%`, can be used in drawing separate
  6998. // line when box width is needed to be auto.
  6999. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7000. token.percentWidth = tokenWidth;
  7001. pendingList.push(token);
  7002. tokenWidth = 0;
  7003. // Do not truncate in this case, because there is no user case
  7004. // and it is too complicated.
  7005. }
  7006. else {
  7007. if (tokenWidthNotSpecified) {
  7008. tokenWidth = token.textWidth;
  7009. // FIXME: If image is not loaded and textWidth is not specified, calling
  7010. // `getBoundingRect()` will not get correct result.
  7011. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7012. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7013. // Use cases:
  7014. // (1) If image is not loaded, it will be loaded at render phase and call
  7015. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7016. // image, and then the right size will be calculated here at the next tick.
  7017. // See `graphic/helper/text.js`.
  7018. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7019. // use `imageHelper.findExistImage` to find cached image.
  7020. // `imageHelper.findExistImage` will always be called here before
  7021. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7022. // which ensures that image will not be rendered before correct size calcualted.
  7023. if (bgImg) {
  7024. bgImg = findExistImage(bgImg);
  7025. if (isImageReady(bgImg)) {
  7026. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7027. }
  7028. }
  7029. }
  7030. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7031. tokenWidth += paddingW;
  7032. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7033. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7034. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7035. token.text = '';
  7036. token.textWidth = tokenWidth = 0;
  7037. }
  7038. else {
  7039. token.text = truncateText(
  7040. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7041. {minChar: truncate.minChar}
  7042. );
  7043. token.textWidth = getWidth(token.text, font);
  7044. tokenWidth = token.textWidth + paddingW;
  7045. }
  7046. }
  7047. }
  7048. lineWidth += (token.width = tokenWidth);
  7049. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7050. }
  7051. line.width = lineWidth;
  7052. line.lineHeight = lineHeight;
  7053. contentHeight += lineHeight;
  7054. contentWidth = Math.max(contentWidth, lineWidth);
  7055. }
  7056. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7057. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7058. if (stlPadding) {
  7059. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7060. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7061. }
  7062. for (var i = 0; i < pendingList.length; i++) {
  7063. var token = pendingList[i];
  7064. var percentWidth = token.percentWidth;
  7065. // Should not base on outerWidth, because token can not be placed out of padding.
  7066. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7067. }
  7068. return contentBlock;
  7069. }
  7070. function pushTokens(block, str, styleName) {
  7071. var isEmptyStr = str === '';
  7072. var strs = str.split('\n');
  7073. var lines = block.lines;
  7074. for (var i = 0; i < strs.length; i++) {
  7075. var text = strs[i];
  7076. var token = {
  7077. styleName: styleName,
  7078. text: text,
  7079. isLineHolder: !text && !isEmptyStr
  7080. };
  7081. // The first token should be appended to the last line.
  7082. if (!i) {
  7083. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7084. // Consider cases:
  7085. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7086. // (which is a placeholder) should be replaced by new token.
  7087. // (2) A image backage, where token likes {a|}.
  7088. // (3) A redundant '' will affect textAlign in line.
  7089. // (4) tokens with the same tplName should not be merged, because
  7090. // they should be displayed in different box (with border and padding).
  7091. var tokensLen = tokens.length;
  7092. (tokensLen === 1 && tokens[0].isLineHolder)
  7093. ? (tokens[0] = token)
  7094. // Consider text is '', only insert when it is the "lineHolder" or
  7095. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7096. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7097. }
  7098. // Other tokens always start a new line.
  7099. else {
  7100. // If there is '', insert it as a placeholder.
  7101. lines.push({tokens: [token]});
  7102. }
  7103. }
  7104. }
  7105. function makeFont(style) {
  7106. // FIXME in node-canvas fontWeight is before fontStyle
  7107. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7108. var font = (style.fontSize || style.fontFamily) && [
  7109. style.fontStyle,
  7110. style.fontWeight,
  7111. (style.fontSize || 12) + 'px',
  7112. // If font properties are defined, `fontFamily` should not be ignored.
  7113. style.fontFamily || 'sans-serif'
  7114. ].join(' ');
  7115. return font && trim(font) || style.textFont || style.font;
  7116. }
  7117. /**
  7118. * @param {Object} ctx
  7119. * @param {Object} shape
  7120. * @param {number} shape.x
  7121. * @param {number} shape.y
  7122. * @param {number} shape.width
  7123. * @param {number} shape.height
  7124. * @param {number} shape.r
  7125. */
  7126. function buildPath(ctx, shape) {
  7127. var x = shape.x;
  7128. var y = shape.y;
  7129. var width = shape.width;
  7130. var height = shape.height;
  7131. var r = shape.r;
  7132. var r1;
  7133. var r2;
  7134. var r3;
  7135. var r4;
  7136. // Convert width and height to positive for better borderRadius
  7137. if (width < 0) {
  7138. x = x + width;
  7139. width = -width;
  7140. }
  7141. if (height < 0) {
  7142. y = y + height;
  7143. height = -height;
  7144. }
  7145. if (typeof r === 'number') {
  7146. r1 = r2 = r3 = r4 = r;
  7147. }
  7148. else if (r instanceof Array) {
  7149. if (r.length === 1) {
  7150. r1 = r2 = r3 = r4 = r[0];
  7151. }
  7152. else if (r.length === 2) {
  7153. r1 = r3 = r[0];
  7154. r2 = r4 = r[1];
  7155. }
  7156. else if (r.length === 3) {
  7157. r1 = r[0];
  7158. r2 = r4 = r[1];
  7159. r3 = r[2];
  7160. }
  7161. else {
  7162. r1 = r[0];
  7163. r2 = r[1];
  7164. r3 = r[2];
  7165. r4 = r[3];
  7166. }
  7167. }
  7168. else {
  7169. r1 = r2 = r3 = r4 = 0;
  7170. }
  7171. var total;
  7172. if (r1 + r2 > width) {
  7173. total = r1 + r2;
  7174. r1 *= width / total;
  7175. r2 *= width / total;
  7176. }
  7177. if (r3 + r4 > width) {
  7178. total = r3 + r4;
  7179. r3 *= width / total;
  7180. r4 *= width / total;
  7181. }
  7182. if (r2 + r3 > height) {
  7183. total = r2 + r3;
  7184. r2 *= height / total;
  7185. r3 *= height / total;
  7186. }
  7187. if (r1 + r4 > height) {
  7188. total = r1 + r4;
  7189. r1 *= height / total;
  7190. r4 *= height / total;
  7191. }
  7192. ctx.moveTo(x + r1, y);
  7193. ctx.lineTo(x + width - r2, y);
  7194. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7195. ctx.lineTo(x + width, y + height - r3);
  7196. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7197. ctx.lineTo(x + r4, y + height);
  7198. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7199. ctx.lineTo(x, y + r1);
  7200. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7201. }
  7202. var DEFAULT_FONT = DEFAULT_FONT$1;
  7203. // TODO: Have not support 'start', 'end' yet.
  7204. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7205. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7206. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7207. // the default value of shadowColor is `'transparent'`.
  7208. var SHADOW_STYLE_COMMON_PROPS = [
  7209. ['textShadowBlur', 'shadowBlur', 0],
  7210. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7211. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7212. ['textShadowColor', 'shadowColor', 'transparent']
  7213. ];
  7214. var _tmpTextPositionResult = {};
  7215. var _tmpBoxPositionResult = {};
  7216. /**
  7217. * @param {module:zrender/graphic/Style} style
  7218. * @return {module:zrender/graphic/Style} The input style.
  7219. */
  7220. function normalizeTextStyle(style) {
  7221. normalizeStyle(style);
  7222. each$1(style.rich, normalizeStyle);
  7223. return style;
  7224. }
  7225. function normalizeStyle(style) {
  7226. if (style) {
  7227. style.font = makeFont(style);
  7228. var textAlign = style.textAlign;
  7229. textAlign === 'middle' && (textAlign = 'center');
  7230. style.textAlign = (
  7231. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7232. ) ? textAlign : 'left';
  7233. // Compatible with textBaseline.
  7234. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7235. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7236. style.textVerticalAlign = (
  7237. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7238. ) ? textVerticalAlign : 'top';
  7239. var textPadding = style.textPadding;
  7240. if (textPadding) {
  7241. style.textPadding = normalizeCssArray(style.textPadding);
  7242. }
  7243. }
  7244. }
  7245. /**
  7246. * @param {CanvasRenderingContext2D} ctx
  7247. * @param {string} text
  7248. * @param {module:zrender/graphic/Style} style
  7249. * @param {Object|boolean} [rect] {x, y, width, height}
  7250. * If set false, rect text is not used.
  7251. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7252. */
  7253. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7254. style.rich
  7255. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7256. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7257. }
  7258. // Avoid setting to ctx according to prevEl if possible for
  7259. // performance in scenarios of large amount text.
  7260. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7261. 'use strict';
  7262. var needDrawBg = needDrawBackground(style);
  7263. var prevStyle;
  7264. var checkCache = false;
  7265. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7266. // Only take and check cache for `Text` el, but not RectText.
  7267. if (prevEl !== WILL_BE_RESTORED) {
  7268. if (prevEl) {
  7269. prevStyle = prevEl.style;
  7270. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7271. }
  7272. // Prevent from using cache in `Style::bind`, because of the case:
  7273. // ctx property is modified by other properties than `Style::bind`
  7274. // used, and Style::bind is called next.
  7275. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7276. }
  7277. // Since this will be restored, prevent from using these props to check cache in the next
  7278. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7279. else if (cachedByMe) {
  7280. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7281. }
  7282. var styleFont = style.font || DEFAULT_FONT;
  7283. // PENDING
  7284. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7285. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7286. // But layer save/restore needed to be considered.
  7287. // if (styleFont !== ctx.__fontCache) {
  7288. // ctx.font = styleFont;
  7289. // if (prevEl !== WILL_BE_RESTORED) {
  7290. // ctx.__fontCache = styleFont;
  7291. // }
  7292. // }
  7293. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7294. ctx.font = styleFont;
  7295. }
  7296. // Use the final font from context-2d, because the final
  7297. // font might not be the style.font when it is illegal.
  7298. // But get `ctx.font` might be time consuming.
  7299. var computedFont = hostEl.__computedFont;
  7300. if (hostEl.__styleFont !== styleFont) {
  7301. hostEl.__styleFont = styleFont;
  7302. computedFont = hostEl.__computedFont = ctx.font;
  7303. }
  7304. var textPadding = style.textPadding;
  7305. var textLineHeight = style.textLineHeight;
  7306. var contentBlock = hostEl.__textCotentBlock;
  7307. if (!contentBlock || hostEl.__dirtyText) {
  7308. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7309. text, computedFont, textPadding, textLineHeight, style.truncate
  7310. );
  7311. }
  7312. var outerHeight = contentBlock.outerHeight;
  7313. var textLines = contentBlock.lines;
  7314. var lineHeight = contentBlock.lineHeight;
  7315. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7316. var baseX = boxPos.baseX;
  7317. var baseY = boxPos.baseY;
  7318. var textAlign = boxPos.textAlign || 'left';
  7319. var textVerticalAlign = boxPos.textVerticalAlign;
  7320. // Origin of textRotation should be the base point of text drawing.
  7321. applyTextRotation(ctx, style, rect, baseX, baseY);
  7322. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7323. var textX = baseX;
  7324. var textY = boxY;
  7325. if (needDrawBg || textPadding) {
  7326. // Consider performance, do not call getTextWidth util necessary.
  7327. var textWidth = getWidth(text, computedFont);
  7328. var outerWidth = textWidth;
  7329. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7330. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7331. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7332. if (textPadding) {
  7333. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7334. textY += textPadding[0];
  7335. }
  7336. }
  7337. // Always set textAlign and textBase line, because it is difficute to calculate
  7338. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7339. // font set happened.
  7340. ctx.textAlign = textAlign;
  7341. // Force baseline to be "middle". Otherwise, if using "top", the
  7342. // text will offset downward a little bit in font "Microsoft YaHei".
  7343. ctx.textBaseline = 'middle';
  7344. // Set text opacity
  7345. ctx.globalAlpha = style.opacity || 1;
  7346. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7347. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7348. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7349. var styleProp = propItem[0];
  7350. var ctxProp = propItem[1];
  7351. var val = style[styleProp];
  7352. if (!checkCache || val !== prevStyle[styleProp]) {
  7353. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7354. }
  7355. }
  7356. // `textBaseline` is set as 'middle'.
  7357. textY += lineHeight / 2;
  7358. var textStrokeWidth = style.textStrokeWidth;
  7359. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7360. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7361. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7362. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7363. var textFill = getFill(style.textFill);
  7364. if (textStroke) {
  7365. if (strokeWidthChanged) {
  7366. ctx.lineWidth = textStrokeWidth;
  7367. }
  7368. if (strokeChanged) {
  7369. ctx.strokeStyle = textStroke;
  7370. }
  7371. }
  7372. if (textFill) {
  7373. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7374. ctx.fillStyle = textFill;
  7375. }
  7376. }
  7377. // Optimize simply, in most cases only one line exists.
  7378. if (textLines.length === 1) {
  7379. // Fill after stroke so the outline will not cover the main part.
  7380. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7381. textFill && ctx.fillText(textLines[0], textX, textY);
  7382. }
  7383. else {
  7384. for (var i = 0; i < textLines.length; i++) {
  7385. // Fill after stroke so the outline will not cover the main part.
  7386. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7387. textFill && ctx.fillText(textLines[i], textX, textY);
  7388. textY += lineHeight;
  7389. }
  7390. }
  7391. }
  7392. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7393. // Do not do cache for rich text because of the complexity.
  7394. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7395. if (prevEl !== WILL_BE_RESTORED) {
  7396. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7397. }
  7398. var contentBlock = hostEl.__textCotentBlock;
  7399. if (!contentBlock || hostEl.__dirtyText) {
  7400. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7401. }
  7402. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7403. }
  7404. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7405. var contentWidth = contentBlock.width;
  7406. var outerWidth = contentBlock.outerWidth;
  7407. var outerHeight = contentBlock.outerHeight;
  7408. var textPadding = style.textPadding;
  7409. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7410. var baseX = boxPos.baseX;
  7411. var baseY = boxPos.baseY;
  7412. var textAlign = boxPos.textAlign;
  7413. var textVerticalAlign = boxPos.textVerticalAlign;
  7414. // Origin of textRotation should be the base point of text drawing.
  7415. applyTextRotation(ctx, style, rect, baseX, baseY);
  7416. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7417. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7418. var xLeft = boxX;
  7419. var lineTop = boxY;
  7420. if (textPadding) {
  7421. xLeft += textPadding[3];
  7422. lineTop += textPadding[0];
  7423. }
  7424. var xRight = xLeft + contentWidth;
  7425. needDrawBackground(style) && drawBackground(
  7426. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7427. );
  7428. for (var i = 0; i < contentBlock.lines.length; i++) {
  7429. var line = contentBlock.lines[i];
  7430. var tokens = line.tokens;
  7431. var tokenCount = tokens.length;
  7432. var lineHeight = line.lineHeight;
  7433. var usedWidth = line.width;
  7434. var leftIndex = 0;
  7435. var lineXLeft = xLeft;
  7436. var lineXRight = xRight;
  7437. var rightIndex = tokenCount - 1;
  7438. var token;
  7439. while (
  7440. leftIndex < tokenCount
  7441. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7442. ) {
  7443. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7444. usedWidth -= token.width;
  7445. lineXLeft += token.width;
  7446. leftIndex++;
  7447. }
  7448. while (
  7449. rightIndex >= 0
  7450. && (token = tokens[rightIndex], token.textAlign === 'right')
  7451. ) {
  7452. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7453. usedWidth -= token.width;
  7454. lineXRight -= token.width;
  7455. rightIndex--;
  7456. }
  7457. // The other tokens are placed as textAlign 'center' if there is enough space.
  7458. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7459. while (leftIndex <= rightIndex) {
  7460. token = tokens[leftIndex];
  7461. // Consider width specified by user, use 'center' rather than 'left'.
  7462. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7463. lineXLeft += token.width;
  7464. leftIndex++;
  7465. }
  7466. lineTop += lineHeight;
  7467. }
  7468. }
  7469. function applyTextRotation(ctx, style, rect, x, y) {
  7470. // textRotation only apply in RectText.
  7471. if (rect && style.textRotation) {
  7472. var origin = style.textOrigin;
  7473. if (origin === 'center') {
  7474. x = rect.width / 2 + rect.x;
  7475. y = rect.height / 2 + rect.y;
  7476. }
  7477. else if (origin) {
  7478. x = origin[0] + rect.x;
  7479. y = origin[1] + rect.y;
  7480. }
  7481. ctx.translate(x, y);
  7482. // Positive: anticlockwise
  7483. ctx.rotate(-style.textRotation);
  7484. ctx.translate(-x, -y);
  7485. }
  7486. }
  7487. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7488. var tokenStyle = style.rich[token.styleName] || {};
  7489. tokenStyle.text = token.text;
  7490. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7491. // the bias of "Microsoft YaHei".
  7492. var textVerticalAlign = token.textVerticalAlign;
  7493. var y = lineTop + lineHeight / 2;
  7494. if (textVerticalAlign === 'top') {
  7495. y = lineTop + token.height / 2;
  7496. }
  7497. else if (textVerticalAlign === 'bottom') {
  7498. y = lineTop + lineHeight - token.height / 2;
  7499. }
  7500. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7501. hostEl,
  7502. ctx,
  7503. tokenStyle,
  7504. textAlign === 'right'
  7505. ? x - token.width
  7506. : textAlign === 'center'
  7507. ? x - token.width / 2
  7508. : x,
  7509. y - token.height / 2,
  7510. token.width,
  7511. token.height
  7512. );
  7513. var textPadding = token.textPadding;
  7514. if (textPadding) {
  7515. x = getTextXForPadding(x, textAlign, textPadding);
  7516. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7517. }
  7518. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7519. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7520. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7521. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7522. setCtx(ctx, 'textAlign', textAlign);
  7523. // Force baseline to be "middle". Otherwise, if using "top", the
  7524. // text will offset downward a little bit in font "Microsoft YaHei".
  7525. setCtx(ctx, 'textBaseline', 'middle');
  7526. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7527. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7528. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7529. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7530. // Fill after stroke so the outline will not cover the main part.
  7531. if (textStroke) {
  7532. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7533. setCtx(ctx, 'strokeStyle', textStroke);
  7534. ctx.strokeText(token.text, x, y);
  7535. }
  7536. if (textFill) {
  7537. setCtx(ctx, 'fillStyle', textFill);
  7538. ctx.fillText(token.text, x, y);
  7539. }
  7540. }
  7541. function needDrawBackground(style) {
  7542. return !!(
  7543. style.textBackgroundColor
  7544. || (style.textBorderWidth && style.textBorderColor)
  7545. );
  7546. }
  7547. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7548. // shape: {x, y, width, height}
  7549. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7550. var textBackgroundColor = style.textBackgroundColor;
  7551. var textBorderWidth = style.textBorderWidth;
  7552. var textBorderColor = style.textBorderColor;
  7553. var isPlainBg = isString(textBackgroundColor);
  7554. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7555. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7556. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7557. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7558. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7559. ctx.beginPath();
  7560. var textBorderRadius = style.textBorderRadius;
  7561. if (!textBorderRadius) {
  7562. ctx.rect(x, y, width, height);
  7563. }
  7564. else {
  7565. buildPath(ctx, {
  7566. x: x, y: y, width: width, height: height, r: textBorderRadius
  7567. });
  7568. }
  7569. ctx.closePath();
  7570. }
  7571. if (isPlainBg) {
  7572. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7573. if (style.fillOpacity != null) {
  7574. var originalGlobalAlpha = ctx.globalAlpha;
  7575. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7576. ctx.fill();
  7577. ctx.globalAlpha = originalGlobalAlpha;
  7578. }
  7579. else {
  7580. ctx.fill();
  7581. }
  7582. }
  7583. else if (isObject$1(textBackgroundColor)) {
  7584. var image = textBackgroundColor.image;
  7585. image = createOrUpdateImage(
  7586. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7587. );
  7588. if (image && isImageReady(image)) {
  7589. ctx.drawImage(image, x, y, width, height);
  7590. }
  7591. }
  7592. if (textBorderWidth && textBorderColor) {
  7593. setCtx(ctx, 'lineWidth', textBorderWidth);
  7594. setCtx(ctx, 'strokeStyle', textBorderColor);
  7595. if (style.strokeOpacity != null) {
  7596. var originalGlobalAlpha = ctx.globalAlpha;
  7597. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7598. ctx.stroke();
  7599. ctx.globalAlpha = originalGlobalAlpha;
  7600. }
  7601. else {
  7602. ctx.stroke();
  7603. }
  7604. }
  7605. }
  7606. function onBgImageLoaded(image, textBackgroundColor) {
  7607. // Replace image, so that `contain/text.js#parseRichText`
  7608. // will get correct result in next tick.
  7609. textBackgroundColor.image = image;
  7610. }
  7611. function getBoxPosition(out, hostEl, style, rect) {
  7612. var baseX = style.x || 0;
  7613. var baseY = style.y || 0;
  7614. var textAlign = style.textAlign;
  7615. var textVerticalAlign = style.textVerticalAlign;
  7616. // Text position represented by coord
  7617. if (rect) {
  7618. var textPosition = style.textPosition;
  7619. if (textPosition instanceof Array) {
  7620. // Percent
  7621. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7622. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7623. }
  7624. else {
  7625. var res = (hostEl && hostEl.calculateTextPosition)
  7626. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7627. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7628. baseX = res.x;
  7629. baseY = res.y;
  7630. // Default align and baseline when has textPosition
  7631. textAlign = textAlign || res.textAlign;
  7632. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7633. }
  7634. // textOffset is only support in RectText, otherwise
  7635. // we have to adjust boundingRect for textOffset.
  7636. var textOffset = style.textOffset;
  7637. if (textOffset) {
  7638. baseX += textOffset[0];
  7639. baseY += textOffset[1];
  7640. }
  7641. }
  7642. out = out || {};
  7643. out.baseX = baseX;
  7644. out.baseY = baseY;
  7645. out.textAlign = textAlign;
  7646. out.textVerticalAlign = textVerticalAlign;
  7647. return out;
  7648. }
  7649. function setCtx(ctx, prop, value) {
  7650. ctx[prop] = fixShadow(ctx, prop, value);
  7651. return ctx[prop];
  7652. }
  7653. /**
  7654. * @param {string} [stroke] If specified, do not check style.textStroke.
  7655. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7656. * @param {number} style
  7657. */
  7658. function getStroke(stroke, lineWidth) {
  7659. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7660. ? null
  7661. // TODO pattern and gradient?
  7662. : (stroke.image || stroke.colorStops)
  7663. ? '#000'
  7664. : stroke;
  7665. }
  7666. function getFill(fill) {
  7667. return (fill == null || fill === 'none')
  7668. ? null
  7669. // TODO pattern and gradient?
  7670. : (fill.image || fill.colorStops)
  7671. ? '#000'
  7672. : fill;
  7673. }
  7674. function parsePercent(value, maxValue) {
  7675. if (typeof value === 'string') {
  7676. if (value.lastIndexOf('%') >= 0) {
  7677. return parseFloat(value) / 100 * maxValue;
  7678. }
  7679. return parseFloat(value);
  7680. }
  7681. return value;
  7682. }
  7683. function getTextXForPadding(x, textAlign, textPadding) {
  7684. return textAlign === 'right'
  7685. ? (x - textPadding[1])
  7686. : textAlign === 'center'
  7687. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7688. : (x + textPadding[3]);
  7689. }
  7690. /**
  7691. * @param {string} text
  7692. * @param {module:zrender/Style} style
  7693. * @return {boolean}
  7694. */
  7695. function needDrawText(text, style) {
  7696. return text != null
  7697. && (text
  7698. || style.textBackgroundColor
  7699. || (style.textBorderWidth && style.textBorderColor)
  7700. || style.textPadding
  7701. );
  7702. }
  7703. /**
  7704. * Mixin for drawing text in a element bounding rect
  7705. * @module zrender/mixin/RectText
  7706. */
  7707. var tmpRect$1 = new BoundingRect();
  7708. var RectText = function () {};
  7709. RectText.prototype = {
  7710. constructor: RectText,
  7711. /**
  7712. * Draw text in a rect with specified position.
  7713. * @param {CanvasRenderingContext2D} ctx
  7714. * @param {Object} rect Displayable rect
  7715. */
  7716. drawRectText: function (ctx, rect) {
  7717. var style = this.style;
  7718. rect = style.textRect || rect;
  7719. // Optimize, avoid normalize every time.
  7720. this.__dirty && normalizeTextStyle(style, true);
  7721. var text = style.text;
  7722. // Convert to string
  7723. text != null && (text += '');
  7724. if (!needDrawText(text, style)) {
  7725. return;
  7726. }
  7727. // FIXME
  7728. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7729. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7730. // text propably break the cache for its host elements.
  7731. ctx.save();
  7732. // Transform rect to view space
  7733. var transform = this.transform;
  7734. if (!style.transformText) {
  7735. if (transform) {
  7736. tmpRect$1.copy(rect);
  7737. tmpRect$1.applyTransform(transform);
  7738. rect = tmpRect$1;
  7739. }
  7740. }
  7741. else {
  7742. this.setTransform(ctx);
  7743. }
  7744. // transformText and textRotation can not be used at the same time.
  7745. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7746. ctx.restore();
  7747. }
  7748. };
  7749. /**
  7750. * Base class of all displayable graphic objects
  7751. * @module zrender/graphic/Displayable
  7752. */
  7753. /**
  7754. * @alias module:zrender/graphic/Displayable
  7755. * @extends module:zrender/Element
  7756. * @extends module:zrender/graphic/mixin/RectText
  7757. */
  7758. function Displayable(opts) {
  7759. opts = opts || {};
  7760. Element.call(this, opts);
  7761. // Extend properties
  7762. for (var name in opts) {
  7763. if (
  7764. opts.hasOwnProperty(name)
  7765. && name !== 'style'
  7766. ) {
  7767. this[name] = opts[name];
  7768. }
  7769. }
  7770. /**
  7771. * @type {module:zrender/graphic/Style}
  7772. */
  7773. this.style = new Style(opts.style, this);
  7774. this._rect = null;
  7775. // Shapes for cascade clipping.
  7776. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  7777. // because it is easy to only using null to check whether clipPaths changed.
  7778. this.__clipPaths = null;
  7779. // FIXME Stateful must be mixined after style is setted
  7780. // Stateful.call(this, opts);
  7781. }
  7782. Displayable.prototype = {
  7783. constructor: Displayable,
  7784. type: 'displayable',
  7785. /**
  7786. * Dirty flag. From which painter will determine if this displayable object needs brush.
  7787. * @name module:zrender/graphic/Displayable#__dirty
  7788. * @type {boolean}
  7789. */
  7790. __dirty: true,
  7791. /**
  7792. * Whether the displayable object is visible. when it is true, the displayable object
  7793. * is not drawn, but the mouse event can still trigger the object.
  7794. * @name module:/zrender/graphic/Displayable#invisible
  7795. * @type {boolean}
  7796. * @default false
  7797. */
  7798. invisible: false,
  7799. /**
  7800. * @name module:/zrender/graphic/Displayable#z
  7801. * @type {number}
  7802. * @default 0
  7803. */
  7804. z: 0,
  7805. /**
  7806. * @name module:/zrender/graphic/Displayable#z
  7807. * @type {number}
  7808. * @default 0
  7809. */
  7810. z2: 0,
  7811. /**
  7812. * The z level determines the displayable object can be drawn in which layer canvas.
  7813. * @name module:/zrender/graphic/Displayable#zlevel
  7814. * @type {number}
  7815. * @default 0
  7816. */
  7817. zlevel: 0,
  7818. /**
  7819. * Whether it can be dragged.
  7820. * @name module:/zrender/graphic/Displayable#draggable
  7821. * @type {boolean}
  7822. * @default false
  7823. */
  7824. draggable: false,
  7825. /**
  7826. * Whether is it dragging.
  7827. * @name module:/zrender/graphic/Displayable#draggable
  7828. * @type {boolean}
  7829. * @default false
  7830. */
  7831. dragging: false,
  7832. /**
  7833. * Whether to respond to mouse events.
  7834. * @name module:/zrender/graphic/Displayable#silent
  7835. * @type {boolean}
  7836. * @default false
  7837. */
  7838. silent: false,
  7839. /**
  7840. * If enable culling
  7841. * @type {boolean}
  7842. * @default false
  7843. */
  7844. culling: false,
  7845. /**
  7846. * Mouse cursor when hovered
  7847. * @name module:/zrender/graphic/Displayable#cursor
  7848. * @type {string}
  7849. */
  7850. cursor: 'pointer',
  7851. /**
  7852. * If hover area is bounding rect
  7853. * @name module:/zrender/graphic/Displayable#rectHover
  7854. * @type {string}
  7855. */
  7856. rectHover: false,
  7857. /**
  7858. * Render the element progressively when the value >= 0,
  7859. * usefull for large data.
  7860. * @type {boolean}
  7861. */
  7862. progressive: false,
  7863. /**
  7864. * @type {boolean}
  7865. */
  7866. incremental: false,
  7867. /**
  7868. * Scale ratio for global scale.
  7869. * @type {boolean}
  7870. */
  7871. globalScaleRatio: 1,
  7872. beforeBrush: function (ctx) {},
  7873. afterBrush: function (ctx) {},
  7874. /**
  7875. * Graphic drawing method.
  7876. * @param {CanvasRenderingContext2D} ctx
  7877. */
  7878. // Interface
  7879. brush: function (ctx, prevEl) {},
  7880. /**
  7881. * Get the minimum bounding box.
  7882. * @return {module:zrender/core/BoundingRect}
  7883. */
  7884. // Interface
  7885. getBoundingRect: function () {},
  7886. /**
  7887. * If displayable element contain coord x, y
  7888. * @param {number} x
  7889. * @param {number} y
  7890. * @return {boolean}
  7891. */
  7892. contain: function (x, y) {
  7893. return this.rectContain(x, y);
  7894. },
  7895. /**
  7896. * @param {Function} cb
  7897. * @param {} context
  7898. */
  7899. traverse: function (cb, context) {
  7900. cb.call(context, this);
  7901. },
  7902. /**
  7903. * If bounding rect of element contain coord x, y
  7904. * @param {number} x
  7905. * @param {number} y
  7906. * @return {boolean}
  7907. */
  7908. rectContain: function (x, y) {
  7909. var coord = this.transformCoordToLocal(x, y);
  7910. var rect = this.getBoundingRect();
  7911. return rect.contain(coord[0], coord[1]);
  7912. },
  7913. /**
  7914. * Mark displayable element dirty and refresh next frame
  7915. */
  7916. dirty: function () {
  7917. this.__dirty = this.__dirtyText = true;
  7918. this._rect = null;
  7919. this.__zr && this.__zr.refresh();
  7920. },
  7921. /**
  7922. * If displayable object binded any event
  7923. * @return {boolean}
  7924. */
  7925. // TODO, events bound by bind
  7926. // isSilent: function () {
  7927. // return !(
  7928. // this.hoverable || this.draggable
  7929. // || this.onmousemove || this.onmouseover || this.onmouseout
  7930. // || this.onmousedown || this.onmouseup || this.onclick
  7931. // || this.ondragenter || this.ondragover || this.ondragleave
  7932. // || this.ondrop
  7933. // );
  7934. // },
  7935. /**
  7936. * Alias for animate('style')
  7937. * @param {boolean} loop
  7938. */
  7939. animateStyle: function (loop) {
  7940. return this.animate('style', loop);
  7941. },
  7942. attrKV: function (key, value) {
  7943. if (key !== 'style') {
  7944. Element.prototype.attrKV.call(this, key, value);
  7945. }
  7946. else {
  7947. this.style.set(value);
  7948. }
  7949. },
  7950. /**
  7951. * @param {Object|string} key
  7952. * @param {*} value
  7953. */
  7954. setStyle: function (key, value) {
  7955. this.style.set(key, value);
  7956. this.dirty(false);
  7957. return this;
  7958. },
  7959. /**
  7960. * Use given style object
  7961. * @param {Object} obj
  7962. */
  7963. useStyle: function (obj) {
  7964. this.style = new Style(obj, this);
  7965. this.dirty(false);
  7966. return this;
  7967. },
  7968. /**
  7969. * The string value of `textPosition` needs to be calculated to a real postion.
  7970. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  7971. * by default. See `contain/text.js#calculateTextPosition` for more details.
  7972. * But some coutom shapes like "pin", "flag" have center that is not exactly
  7973. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  7974. * for those shapes. It will be called if the `style.textPosition` is a string.
  7975. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  7976. * be responsible for creating one.
  7977. * @param {module:zrender/graphic/Style} style
  7978. * @param {Object} rect {x, y, width, height}
  7979. * @return {Obejct} out The same as the input out.
  7980. * {
  7981. * x: number. mandatory.
  7982. * y: number. mandatory.
  7983. * textAlign: string. optional. use style.textAlign by default.
  7984. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  7985. * }
  7986. */
  7987. calculateTextPosition: null
  7988. };
  7989. inherits(Displayable, Element);
  7990. mixin(Displayable, RectText);
  7991. /**
  7992. * @alias zrender/graphic/Image
  7993. * @extends module:zrender/graphic/Displayable
  7994. * @constructor
  7995. * @param {Object} opts
  7996. */
  7997. function ZImage(opts) {
  7998. Displayable.call(this, opts);
  7999. }
  8000. ZImage.prototype = {
  8001. constructor: ZImage,
  8002. type: 'image',
  8003. brush: function (ctx, prevEl) {
  8004. var style = this.style;
  8005. var src = style.image;
  8006. // Must bind each time
  8007. style.bind(ctx, this, prevEl);
  8008. var image = this._image = createOrUpdateImage(
  8009. src,
  8010. this._image,
  8011. this,
  8012. this.onload
  8013. );
  8014. if (!image || !isImageReady(image)) {
  8015. return;
  8016. }
  8017. // 图片已经加载完成
  8018. // if (image.nodeName.toUpperCase() == 'IMG') {
  8019. // if (!image.complete) {
  8020. // return;
  8021. // }
  8022. // }
  8023. // Else is canvas
  8024. var x = style.x || 0;
  8025. var y = style.y || 0;
  8026. var width = style.width;
  8027. var height = style.height;
  8028. var aspect = image.width / image.height;
  8029. if (width == null && height != null) {
  8030. // Keep image/height ratio
  8031. width = height * aspect;
  8032. }
  8033. else if (height == null && width != null) {
  8034. height = width / aspect;
  8035. }
  8036. else if (width == null && height == null) {
  8037. width = image.width;
  8038. height = image.height;
  8039. }
  8040. // 设置transform
  8041. this.setTransform(ctx);
  8042. if (style.sWidth && style.sHeight) {
  8043. var sx = style.sx || 0;
  8044. var sy = style.sy || 0;
  8045. ctx.drawImage(
  8046. image,
  8047. sx, sy, style.sWidth, style.sHeight,
  8048. x, y, width, height
  8049. );
  8050. }
  8051. else if (style.sx && style.sy) {
  8052. var sx = style.sx;
  8053. var sy = style.sy;
  8054. var sWidth = width - sx;
  8055. var sHeight = height - sy;
  8056. ctx.drawImage(
  8057. image,
  8058. sx, sy, sWidth, sHeight,
  8059. x, y, width, height
  8060. );
  8061. }
  8062. else {
  8063. ctx.drawImage(image, x, y, width, height);
  8064. }
  8065. // Draw rect text
  8066. if (style.text != null) {
  8067. // Only restore transform when needs draw text.
  8068. this.restoreTransform(ctx);
  8069. this.drawRectText(ctx, this.getBoundingRect());
  8070. }
  8071. },
  8072. getBoundingRect: function () {
  8073. var style = this.style;
  8074. if (!this._rect) {
  8075. this._rect = new BoundingRect(
  8076. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8077. );
  8078. }
  8079. return this._rect;
  8080. }
  8081. };
  8082. inherits(ZImage, Displayable);
  8083. var HOVER_LAYER_ZLEVEL = 1e5;
  8084. var CANVAS_ZLEVEL = 314159;
  8085. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8086. var INCREMENTAL_INC = 0.001;
  8087. function parseInt10(val) {
  8088. return parseInt(val, 10);
  8089. }
  8090. function isLayerValid(layer) {
  8091. if (!layer) {
  8092. return false;
  8093. }
  8094. if (layer.__builtin__) {
  8095. return true;
  8096. }
  8097. if (typeof (layer.resize) !== 'function'
  8098. || typeof (layer.refresh) !== 'function'
  8099. ) {
  8100. return false;
  8101. }
  8102. return true;
  8103. }
  8104. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8105. var viewRect = new BoundingRect(0, 0, 0, 0);
  8106. function isDisplayableCulled(el, width, height) {
  8107. tmpRect.copy(el.getBoundingRect());
  8108. if (el.transform) {
  8109. tmpRect.applyTransform(el.transform);
  8110. }
  8111. viewRect.width = width;
  8112. viewRect.height = height;
  8113. return !tmpRect.intersect(viewRect);
  8114. }
  8115. function isClipPathChanged(clipPaths, prevClipPaths) {
  8116. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8117. if (clipPaths === prevClipPaths) {
  8118. return false;
  8119. }
  8120. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8121. return true;
  8122. }
  8123. for (var i = 0; i < clipPaths.length; i++) {
  8124. if (clipPaths[i] !== prevClipPaths[i]) {
  8125. return true;
  8126. }
  8127. }
  8128. return false;
  8129. }
  8130. function doClip(clipPaths, ctx) {
  8131. for (var i = 0; i < clipPaths.length; i++) {
  8132. var clipPath = clipPaths[i];
  8133. clipPath.setTransform(ctx);
  8134. ctx.beginPath();
  8135. clipPath.buildPath(ctx, clipPath.shape);
  8136. ctx.clip();
  8137. // Transform back
  8138. clipPath.restoreTransform(ctx);
  8139. }
  8140. }
  8141. function createRoot(width, height) {
  8142. var domRoot = document.createElement('div');
  8143. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8144. domRoot.style.cssText = [
  8145. 'position:relative',
  8146. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8147. // dom does not act as expected) when some of the parent dom has
  8148. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8149. // the canvas is not at the top part of the page.
  8150. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8151. // this `overflow:hidden` to avoid the bug.
  8152. // 'overflow:hidden',
  8153. 'width:' + width + 'px',
  8154. 'height:' + height + 'px',
  8155. 'padding:0',
  8156. 'margin:0',
  8157. 'border-width:0'
  8158. ].join(';') + ';';
  8159. return domRoot;
  8160. }
  8161. /**
  8162. * @alias module:zrender/Painter
  8163. * @constructor
  8164. * @param {HTMLElement} root 绘图容器
  8165. * @param {module:zrender/Storage} storage
  8166. * @param {Object} opts
  8167. */
  8168. var Painter = function (root, storage, opts) {
  8169. this.type = 'canvas';
  8170. // In node environment using node-canvas
  8171. var singleCanvas = !root.nodeName // In node ?
  8172. || root.nodeName.toUpperCase() === 'CANVAS';
  8173. this._opts = opts = extend({}, opts || {});
  8174. /**
  8175. * @type {number}
  8176. */
  8177. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8178. /**
  8179. * @type {boolean}
  8180. * @private
  8181. */
  8182. this._singleCanvas = singleCanvas;
  8183. /**
  8184. * 绘图容器
  8185. * @type {HTMLElement}
  8186. */
  8187. this.root = root;
  8188. var rootStyle = root.style;
  8189. if (rootStyle) {
  8190. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8191. rootStyle['-webkit-user-select'] =
  8192. rootStyle['user-select'] =
  8193. rootStyle['-webkit-touch-callout'] = 'none';
  8194. root.innerHTML = '';
  8195. }
  8196. /**
  8197. * @type {module:zrender/Storage}
  8198. */
  8199. this.storage = storage;
  8200. /**
  8201. * @type {Array.<number>}
  8202. * @private
  8203. */
  8204. var zlevelList = this._zlevelList = [];
  8205. /**
  8206. * @type {Object.<string, module:zrender/Layer>}
  8207. * @private
  8208. */
  8209. var layers = this._layers = {};
  8210. /**
  8211. * @type {Object.<string, Object>}
  8212. * @private
  8213. */
  8214. this._layerConfig = {};
  8215. /**
  8216. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8217. */
  8218. this._needsManuallyCompositing = false;
  8219. if (!singleCanvas) {
  8220. this._width = this._getSize(0);
  8221. this._height = this._getSize(1);
  8222. var domRoot = this._domRoot = createRoot(
  8223. this._width, this._height
  8224. );
  8225. root.appendChild(domRoot);
  8226. }
  8227. else {
  8228. var width = root.width;
  8229. var height = root.height;
  8230. if (opts.width != null) {
  8231. width = opts.width;
  8232. }
  8233. if (opts.height != null) {
  8234. height = opts.height;
  8235. }
  8236. this.dpr = opts.devicePixelRatio || 1;
  8237. // Use canvas width and height directly
  8238. root.width = width * this.dpr;
  8239. root.height = height * this.dpr;
  8240. this._width = width;
  8241. this._height = height;
  8242. // Create layer if only one given canvas
  8243. // Device can be specified to create a high dpi image.
  8244. var mainLayer = new Layer(root, this, this.dpr);
  8245. mainLayer.__builtin__ = true;
  8246. mainLayer.initContext();
  8247. // FIXME Use canvas width and height
  8248. // mainLayer.resize(width, height);
  8249. layers[CANVAS_ZLEVEL] = mainLayer;
  8250. mainLayer.zlevel = CANVAS_ZLEVEL;
  8251. // Not use common zlevel.
  8252. zlevelList.push(CANVAS_ZLEVEL);
  8253. this._domRoot = root;
  8254. }
  8255. /**
  8256. * @type {module:zrender/Layer}
  8257. * @private
  8258. */
  8259. this._hoverlayer = null;
  8260. this._hoverElements = [];
  8261. };
  8262. Painter.prototype = {
  8263. constructor: Painter,
  8264. getType: function () {
  8265. return 'canvas';
  8266. },
  8267. /**
  8268. * If painter use a single canvas
  8269. * @return {boolean}
  8270. */
  8271. isSingleCanvas: function () {
  8272. return this._singleCanvas;
  8273. },
  8274. /**
  8275. * @return {HTMLDivElement}
  8276. */
  8277. getViewportRoot: function () {
  8278. return this._domRoot;
  8279. },
  8280. getViewportRootOffset: function () {
  8281. var viewportRoot = this.getViewportRoot();
  8282. if (viewportRoot) {
  8283. return {
  8284. offsetLeft: viewportRoot.offsetLeft || 0,
  8285. offsetTop: viewportRoot.offsetTop || 0
  8286. };
  8287. }
  8288. },
  8289. /**
  8290. * 刷新
  8291. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8292. */
  8293. refresh: function (paintAll) {
  8294. var list = this.storage.getDisplayList(true);
  8295. var zlevelList = this._zlevelList;
  8296. this._redrawId = Math.random();
  8297. this._paintList(list, paintAll, this._redrawId);
  8298. // Paint custum layers
  8299. for (var i = 0; i < zlevelList.length; i++) {
  8300. var z = zlevelList[i];
  8301. var layer = this._layers[z];
  8302. if (!layer.__builtin__ && layer.refresh) {
  8303. var clearColor = i === 0 ? this._backgroundColor : null;
  8304. layer.refresh(clearColor);
  8305. }
  8306. }
  8307. this.refreshHover();
  8308. return this;
  8309. },
  8310. addHover: function (el, hoverStyle) {
  8311. if (el.__hoverMir) {
  8312. return;
  8313. }
  8314. var elMirror = new el.constructor({
  8315. style: el.style,
  8316. shape: el.shape,
  8317. z: el.z,
  8318. z2: el.z2,
  8319. silent: el.silent
  8320. });
  8321. elMirror.__from = el;
  8322. el.__hoverMir = elMirror;
  8323. hoverStyle && elMirror.setStyle(hoverStyle);
  8324. this._hoverElements.push(elMirror);
  8325. return elMirror;
  8326. },
  8327. removeHover: function (el) {
  8328. var elMirror = el.__hoverMir;
  8329. var hoverElements = this._hoverElements;
  8330. var idx = indexOf(hoverElements, elMirror);
  8331. if (idx >= 0) {
  8332. hoverElements.splice(idx, 1);
  8333. }
  8334. el.__hoverMir = null;
  8335. },
  8336. clearHover: function (el) {
  8337. var hoverElements = this._hoverElements;
  8338. for (var i = 0; i < hoverElements.length; i++) {
  8339. var from = hoverElements[i].__from;
  8340. if (from) {
  8341. from.__hoverMir = null;
  8342. }
  8343. }
  8344. hoverElements.length = 0;
  8345. },
  8346. refreshHover: function () {
  8347. var hoverElements = this._hoverElements;
  8348. var len = hoverElements.length;
  8349. var hoverLayer = this._hoverlayer;
  8350. hoverLayer && hoverLayer.clear();
  8351. if (!len) {
  8352. return;
  8353. }
  8354. sort(hoverElements, this.storage.displayableSortFunc);
  8355. // Use a extream large zlevel
  8356. // FIXME?
  8357. if (!hoverLayer) {
  8358. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8359. }
  8360. var scope = {};
  8361. hoverLayer.ctx.save();
  8362. for (var i = 0; i < len;) {
  8363. var el = hoverElements[i];
  8364. var originalEl = el.__from;
  8365. // Original el is removed
  8366. // PENDING
  8367. if (!(originalEl && originalEl.__zr)) {
  8368. hoverElements.splice(i, 1);
  8369. originalEl.__hoverMir = null;
  8370. len--;
  8371. continue;
  8372. }
  8373. i++;
  8374. // Use transform
  8375. // FIXME style and shape ?
  8376. if (!originalEl.invisible) {
  8377. el.transform = originalEl.transform;
  8378. el.invTransform = originalEl.invTransform;
  8379. el.__clipPaths = originalEl.__clipPaths;
  8380. // el.
  8381. this._doPaintEl(el, hoverLayer, true, scope);
  8382. }
  8383. }
  8384. hoverLayer.ctx.restore();
  8385. },
  8386. getHoverLayer: function () {
  8387. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8388. },
  8389. _paintList: function (list, paintAll, redrawId) {
  8390. if (this._redrawId !== redrawId) {
  8391. return;
  8392. }
  8393. paintAll = paintAll || false;
  8394. this._updateLayerStatus(list);
  8395. var finished = this._doPaintList(list, paintAll);
  8396. if (this._needsManuallyCompositing) {
  8397. this._compositeManually();
  8398. }
  8399. if (!finished) {
  8400. var self = this;
  8401. requestAnimationFrame(function () {
  8402. self._paintList(list, paintAll, redrawId);
  8403. });
  8404. }
  8405. },
  8406. _compositeManually: function () {
  8407. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8408. var width = this._domRoot.width;
  8409. var height = this._domRoot.height;
  8410. ctx.clearRect(0, 0, width, height);
  8411. // PENDING, If only builtin layer?
  8412. this.eachBuiltinLayer(function (layer) {
  8413. if (layer.virtual) {
  8414. ctx.drawImage(layer.dom, 0, 0, width, height);
  8415. }
  8416. });
  8417. },
  8418. _doPaintList: function (list, paintAll) {
  8419. var layerList = [];
  8420. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8421. var zlevel = this._zlevelList[zi];
  8422. var layer = this._layers[zlevel];
  8423. if (layer.__builtin__
  8424. && layer !== this._hoverlayer
  8425. && (layer.__dirty || paintAll)
  8426. ) {
  8427. layerList.push(layer);
  8428. }
  8429. }
  8430. var finished = true;
  8431. for (var k = 0; k < layerList.length; k++) {
  8432. var layer = layerList[k];
  8433. var ctx = layer.ctx;
  8434. var scope = {};
  8435. ctx.save();
  8436. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8437. var useTimer = !paintAll && layer.incremental && Date.now;
  8438. var startTime = useTimer && Date.now();
  8439. var clearColor = layer.zlevel === this._zlevelList[0]
  8440. ? this._backgroundColor : null;
  8441. // All elements in this layer are cleared.
  8442. if (layer.__startIndex === layer.__endIndex) {
  8443. layer.clear(false, clearColor);
  8444. }
  8445. else if (start === layer.__startIndex) {
  8446. var firstEl = list[start];
  8447. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8448. layer.clear(false, clearColor);
  8449. }
  8450. }
  8451. if (start === -1) {
  8452. console.error('For some unknown reason. drawIndex is -1');
  8453. start = layer.__startIndex;
  8454. }
  8455. for (var i = start; i < layer.__endIndex; i++) {
  8456. var el = list[i];
  8457. this._doPaintEl(el, layer, paintAll, scope);
  8458. el.__dirty = el.__dirtyText = false;
  8459. if (useTimer) {
  8460. // Date.now can be executed in 13,025,305 ops/second.
  8461. var dTime = Date.now() - startTime;
  8462. // Give 15 millisecond to draw.
  8463. // The rest elements will be drawn in the next frame.
  8464. if (dTime > 15) {
  8465. break;
  8466. }
  8467. }
  8468. }
  8469. layer.__drawIndex = i;
  8470. if (layer.__drawIndex < layer.__endIndex) {
  8471. finished = false;
  8472. }
  8473. if (scope.prevElClipPaths) {
  8474. // Needs restore the state. If last drawn element is in the clipping area.
  8475. ctx.restore();
  8476. }
  8477. ctx.restore();
  8478. }
  8479. if (env$1.wxa) {
  8480. // Flush for weixin application
  8481. each$1(this._layers, function (layer) {
  8482. if (layer && layer.ctx && layer.ctx.draw) {
  8483. layer.ctx.draw();
  8484. }
  8485. });
  8486. }
  8487. return finished;
  8488. },
  8489. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8490. var ctx = currentLayer.ctx;
  8491. var m = el.transform;
  8492. if (
  8493. (currentLayer.__dirty || forcePaint)
  8494. // Ignore invisible element
  8495. && !el.invisible
  8496. // Ignore transparent element
  8497. && el.style.opacity !== 0
  8498. // Ignore scale 0 element, in some environment like node-canvas
  8499. // Draw a scale 0 element can cause all following draw wrong
  8500. // And setTransform with scale 0 will cause set back transform failed.
  8501. && !(m && !m[0] && !m[3])
  8502. // Ignore culled element
  8503. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8504. ) {
  8505. var clipPaths = el.__clipPaths;
  8506. var prevElClipPaths = scope.prevElClipPaths;
  8507. // Optimize when clipping on group with several elements
  8508. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8509. // If has previous clipping state, restore from it
  8510. if (prevElClipPaths) {
  8511. ctx.restore();
  8512. scope.prevElClipPaths = null;
  8513. // Reset prevEl since context has been restored
  8514. scope.prevEl = null;
  8515. }
  8516. // New clipping state
  8517. if (clipPaths) {
  8518. ctx.save();
  8519. doClip(clipPaths, ctx);
  8520. scope.prevElClipPaths = clipPaths;
  8521. }
  8522. }
  8523. el.beforeBrush && el.beforeBrush(ctx);
  8524. el.brush(ctx, scope.prevEl || null);
  8525. scope.prevEl = el;
  8526. el.afterBrush && el.afterBrush(ctx);
  8527. }
  8528. },
  8529. /**
  8530. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8531. * @param {number} zlevel
  8532. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8533. * @return {module:zrender/Layer}
  8534. */
  8535. getLayer: function (zlevel, virtual) {
  8536. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8537. zlevel = CANVAS_ZLEVEL;
  8538. }
  8539. var layer = this._layers[zlevel];
  8540. if (!layer) {
  8541. // Create a new layer
  8542. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8543. layer.zlevel = zlevel;
  8544. layer.__builtin__ = true;
  8545. if (this._layerConfig[zlevel]) {
  8546. merge(layer, this._layerConfig[zlevel], true);
  8547. }
  8548. if (virtual) {
  8549. layer.virtual = virtual;
  8550. }
  8551. this.insertLayer(zlevel, layer);
  8552. // Context is created after dom inserted to document
  8553. // Or excanvas will get 0px clientWidth and clientHeight
  8554. layer.initContext();
  8555. }
  8556. return layer;
  8557. },
  8558. insertLayer: function (zlevel, layer) {
  8559. var layersMap = this._layers;
  8560. var zlevelList = this._zlevelList;
  8561. var len = zlevelList.length;
  8562. var prevLayer = null;
  8563. var i = -1;
  8564. var domRoot = this._domRoot;
  8565. if (layersMap[zlevel]) {
  8566. logError$1('ZLevel ' + zlevel + ' has been used already');
  8567. return;
  8568. }
  8569. // Check if is a valid layer
  8570. if (!isLayerValid(layer)) {
  8571. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8572. return;
  8573. }
  8574. if (len > 0 && zlevel > zlevelList[0]) {
  8575. for (i = 0; i < len - 1; i++) {
  8576. if (
  8577. zlevelList[i] < zlevel
  8578. && zlevelList[i + 1] > zlevel
  8579. ) {
  8580. break;
  8581. }
  8582. }
  8583. prevLayer = layersMap[zlevelList[i]];
  8584. }
  8585. zlevelList.splice(i + 1, 0, zlevel);
  8586. layersMap[zlevel] = layer;
  8587. // Vitual layer will not directly show on the screen.
  8588. // (It can be a WebGL layer and assigned to a ZImage element)
  8589. // But it still under management of zrender.
  8590. if (!layer.virtual) {
  8591. if (prevLayer) {
  8592. var prevDom = prevLayer.dom;
  8593. if (prevDom.nextSibling) {
  8594. domRoot.insertBefore(
  8595. layer.dom,
  8596. prevDom.nextSibling
  8597. );
  8598. }
  8599. else {
  8600. domRoot.appendChild(layer.dom);
  8601. }
  8602. }
  8603. else {
  8604. if (domRoot.firstChild) {
  8605. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8606. }
  8607. else {
  8608. domRoot.appendChild(layer.dom);
  8609. }
  8610. }
  8611. }
  8612. },
  8613. // Iterate each layer
  8614. eachLayer: function (cb, context) {
  8615. var zlevelList = this._zlevelList;
  8616. var z;
  8617. var i;
  8618. for (i = 0; i < zlevelList.length; i++) {
  8619. z = zlevelList[i];
  8620. cb.call(context, this._layers[z], z);
  8621. }
  8622. },
  8623. // Iterate each buildin layer
  8624. eachBuiltinLayer: function (cb, context) {
  8625. var zlevelList = this._zlevelList;
  8626. var layer;
  8627. var z;
  8628. var i;
  8629. for (i = 0; i < zlevelList.length; i++) {
  8630. z = zlevelList[i];
  8631. layer = this._layers[z];
  8632. if (layer.__builtin__) {
  8633. cb.call(context, layer, z);
  8634. }
  8635. }
  8636. },
  8637. // Iterate each other layer except buildin layer
  8638. eachOtherLayer: function (cb, context) {
  8639. var zlevelList = this._zlevelList;
  8640. var layer;
  8641. var z;
  8642. var i;
  8643. for (i = 0; i < zlevelList.length; i++) {
  8644. z = zlevelList[i];
  8645. layer = this._layers[z];
  8646. if (!layer.__builtin__) {
  8647. cb.call(context, layer, z);
  8648. }
  8649. }
  8650. },
  8651. /**
  8652. * 获取所有已创建的层
  8653. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8654. */
  8655. getLayers: function () {
  8656. return this._layers;
  8657. },
  8658. _updateLayerStatus: function (list) {
  8659. this.eachBuiltinLayer(function (layer, z) {
  8660. layer.__dirty = layer.__used = false;
  8661. });
  8662. function updatePrevLayer(idx) {
  8663. if (prevLayer) {
  8664. if (prevLayer.__endIndex !== idx) {
  8665. prevLayer.__dirty = true;
  8666. }
  8667. prevLayer.__endIndex = idx;
  8668. }
  8669. }
  8670. if (this._singleCanvas) {
  8671. for (var i = 1; i < list.length; i++) {
  8672. var el = list[i];
  8673. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8674. this._needsManuallyCompositing = true;
  8675. break;
  8676. }
  8677. }
  8678. }
  8679. var prevLayer = null;
  8680. var incrementalLayerCount = 0;
  8681. for (var i = 0; i < list.length; i++) {
  8682. var el = list[i];
  8683. var zlevel = el.zlevel;
  8684. var layer;
  8685. // PENDING If change one incremental element style ?
  8686. // TODO Where there are non-incremental elements between incremental elements.
  8687. if (el.incremental) {
  8688. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8689. layer.incremental = true;
  8690. incrementalLayerCount = 1;
  8691. }
  8692. else {
  8693. layer = this.getLayer(
  8694. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8695. this._needsManuallyCompositing
  8696. );
  8697. }
  8698. if (!layer.__builtin__) {
  8699. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8700. }
  8701. if (layer !== prevLayer) {
  8702. layer.__used = true;
  8703. if (layer.__startIndex !== i) {
  8704. layer.__dirty = true;
  8705. }
  8706. layer.__startIndex = i;
  8707. if (!layer.incremental) {
  8708. layer.__drawIndex = i;
  8709. }
  8710. else {
  8711. // Mark layer draw index needs to update.
  8712. layer.__drawIndex = -1;
  8713. }
  8714. updatePrevLayer(i);
  8715. prevLayer = layer;
  8716. }
  8717. if (el.__dirty) {
  8718. layer.__dirty = true;
  8719. if (layer.incremental && layer.__drawIndex < 0) {
  8720. // Start draw from the first dirty element.
  8721. layer.__drawIndex = i;
  8722. }
  8723. }
  8724. }
  8725. updatePrevLayer(i);
  8726. this.eachBuiltinLayer(function (layer, z) {
  8727. // Used in last frame but not in this frame. Needs clear
  8728. if (!layer.__used && layer.getElementCount() > 0) {
  8729. layer.__dirty = true;
  8730. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8731. }
  8732. // For incremental layer. In case start index changed and no elements are dirty.
  8733. if (layer.__dirty && layer.__drawIndex < 0) {
  8734. layer.__drawIndex = layer.__startIndex;
  8735. }
  8736. });
  8737. },
  8738. /**
  8739. * 清除hover层外所有内容
  8740. */
  8741. clear: function () {
  8742. this.eachBuiltinLayer(this._clearLayer);
  8743. return this;
  8744. },
  8745. _clearLayer: function (layer) {
  8746. layer.clear();
  8747. },
  8748. setBackgroundColor: function (backgroundColor) {
  8749. this._backgroundColor = backgroundColor;
  8750. },
  8751. /**
  8752. * 修改指定zlevel的绘制参数
  8753. *
  8754. * @param {string} zlevel
  8755. * @param {Object} config 配置对象
  8756. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8757. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8758. * @param {number} [config.lastFrameAlpha=0.7]
  8759. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8760. */
  8761. configLayer: function (zlevel, config) {
  8762. if (config) {
  8763. var layerConfig = this._layerConfig;
  8764. if (!layerConfig[zlevel]) {
  8765. layerConfig[zlevel] = config;
  8766. }
  8767. else {
  8768. merge(layerConfig[zlevel], config, true);
  8769. }
  8770. for (var i = 0; i < this._zlevelList.length; i++) {
  8771. var _zlevel = this._zlevelList[i];
  8772. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8773. var layer = this._layers[_zlevel];
  8774. merge(layer, layerConfig[zlevel], true);
  8775. }
  8776. }
  8777. }
  8778. },
  8779. /**
  8780. * 删除指定层
  8781. * @param {number} zlevel 层所在的zlevel
  8782. */
  8783. delLayer: function (zlevel) {
  8784. var layers = this._layers;
  8785. var zlevelList = this._zlevelList;
  8786. var layer = layers[zlevel];
  8787. if (!layer) {
  8788. return;
  8789. }
  8790. layer.dom.parentNode.removeChild(layer.dom);
  8791. delete layers[zlevel];
  8792. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8793. },
  8794. /**
  8795. * 区域大小变化后重绘
  8796. */
  8797. resize: function (width, height) {
  8798. if (!this._domRoot.style) { // Maybe in node or worker
  8799. if (width == null || height == null) {
  8800. return;
  8801. }
  8802. this._width = width;
  8803. this._height = height;
  8804. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8805. }
  8806. else {
  8807. var domRoot = this._domRoot;
  8808. // FIXME Why ?
  8809. domRoot.style.display = 'none';
  8810. // Save input w/h
  8811. var opts = this._opts;
  8812. width != null && (opts.width = width);
  8813. height != null && (opts.height = height);
  8814. width = this._getSize(0);
  8815. height = this._getSize(1);
  8816. domRoot.style.display = '';
  8817. // 优化没有实际改变的resize
  8818. if (this._width !== width || height !== this._height) {
  8819. domRoot.style.width = width + 'px';
  8820. domRoot.style.height = height + 'px';
  8821. for (var id in this._layers) {
  8822. if (this._layers.hasOwnProperty(id)) {
  8823. this._layers[id].resize(width, height);
  8824. }
  8825. }
  8826. each$1(this._progressiveLayers, function (layer) {
  8827. layer.resize(width, height);
  8828. });
  8829. this.refresh(true);
  8830. }
  8831. this._width = width;
  8832. this._height = height;
  8833. }
  8834. return this;
  8835. },
  8836. /**
  8837. * 清除单独的一个层
  8838. * @param {number} zlevel
  8839. */
  8840. clearLayer: function (zlevel) {
  8841. var layer = this._layers[zlevel];
  8842. if (layer) {
  8843. layer.clear();
  8844. }
  8845. },
  8846. /**
  8847. * 释放
  8848. */
  8849. dispose: function () {
  8850. this.root.innerHTML = '';
  8851. this.root =
  8852. this.storage =
  8853. this._domRoot =
  8854. this._layers = null;
  8855. },
  8856. /**
  8857. * Get canvas which has all thing rendered
  8858. * @param {Object} opts
  8859. * @param {string} [opts.backgroundColor]
  8860. * @param {number} [opts.pixelRatio]
  8861. */
  8862. getRenderedCanvas: function (opts) {
  8863. opts = opts || {};
  8864. if (this._singleCanvas && !this._compositeManually) {
  8865. return this._layers[CANVAS_ZLEVEL].dom;
  8866. }
  8867. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8868. imageLayer.initContext();
  8869. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8870. if (opts.pixelRatio <= this.dpr) {
  8871. this.refresh();
  8872. var width = imageLayer.dom.width;
  8873. var height = imageLayer.dom.height;
  8874. var ctx = imageLayer.ctx;
  8875. this.eachLayer(function (layer) {
  8876. if (layer.__builtin__) {
  8877. ctx.drawImage(layer.dom, 0, 0, width, height);
  8878. }
  8879. else if (layer.renderToCanvas) {
  8880. imageLayer.ctx.save();
  8881. layer.renderToCanvas(imageLayer.ctx);
  8882. imageLayer.ctx.restore();
  8883. }
  8884. });
  8885. }
  8886. else {
  8887. // PENDING, echarts-gl and incremental rendering.
  8888. var scope = {};
  8889. var displayList = this.storage.getDisplayList(true);
  8890. for (var i = 0; i < displayList.length; i++) {
  8891. var el = displayList[i];
  8892. this._doPaintEl(el, imageLayer, true, scope);
  8893. }
  8894. }
  8895. return imageLayer.dom;
  8896. },
  8897. /**
  8898. * 获取绘图区域宽度
  8899. */
  8900. getWidth: function () {
  8901. return this._width;
  8902. },
  8903. /**
  8904. * 获取绘图区域高度
  8905. */
  8906. getHeight: function () {
  8907. return this._height;
  8908. },
  8909. _getSize: function (whIdx) {
  8910. var opts = this._opts;
  8911. var wh = ['width', 'height'][whIdx];
  8912. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8913. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8914. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8915. if (opts[wh] != null && opts[wh] !== 'auto') {
  8916. return parseFloat(opts[wh]);
  8917. }
  8918. var root = this.root;
  8919. // IE8 does not support getComputedStyle, but it use VML.
  8920. var stl = document.defaultView.getComputedStyle(root);
  8921. return (
  8922. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8923. - (parseInt10(stl[plt]) || 0)
  8924. - (parseInt10(stl[prb]) || 0)
  8925. ) | 0;
  8926. },
  8927. pathToImage: function (path, dpr) {
  8928. dpr = dpr || this.dpr;
  8929. var canvas = document.createElement('canvas');
  8930. var ctx = canvas.getContext('2d');
  8931. var rect = path.getBoundingRect();
  8932. var style = path.style;
  8933. var shadowBlurSize = style.shadowBlur * dpr;
  8934. var shadowOffsetX = style.shadowOffsetX * dpr;
  8935. var shadowOffsetY = style.shadowOffsetY * dpr;
  8936. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8937. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8938. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8939. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8940. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8941. var width = rect.width + leftMargin + rightMargin;
  8942. var height = rect.height + topMargin + bottomMargin;
  8943. canvas.width = width * dpr;
  8944. canvas.height = height * dpr;
  8945. ctx.scale(dpr, dpr);
  8946. ctx.clearRect(0, 0, width, height);
  8947. ctx.dpr = dpr;
  8948. var pathTransform = {
  8949. position: path.position,
  8950. rotation: path.rotation,
  8951. scale: path.scale
  8952. };
  8953. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8954. path.rotation = 0;
  8955. path.scale = [1, 1];
  8956. path.updateTransform();
  8957. if (path) {
  8958. path.brush(ctx);
  8959. }
  8960. var ImageShape = ZImage;
  8961. var imgShape = new ImageShape({
  8962. style: {
  8963. x: 0,
  8964. y: 0,
  8965. image: canvas
  8966. }
  8967. });
  8968. if (pathTransform.position != null) {
  8969. imgShape.position = path.position = pathTransform.position;
  8970. }
  8971. if (pathTransform.rotation != null) {
  8972. imgShape.rotation = path.rotation = pathTransform.rotation;
  8973. }
  8974. if (pathTransform.scale != null) {
  8975. imgShape.scale = path.scale = pathTransform.scale;
  8976. }
  8977. return imgShape;
  8978. }
  8979. };
  8980. /**
  8981. * 动画主类, 调度和管理所有动画控制器
  8982. *
  8983. * @module zrender/animation/Animation
  8984. * @author pissang(https://github.com/pissang)
  8985. */
  8986. // TODO Additive animation
  8987. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8988. // https://developer.apple.com/videos/wwdc2014/#236
  8989. /**
  8990. * @typedef {Object} IZRenderStage
  8991. * @property {Function} update
  8992. */
  8993. /**
  8994. * @alias module:zrender/animation/Animation
  8995. * @constructor
  8996. * @param {Object} [options]
  8997. * @param {Function} [options.onframe]
  8998. * @param {IZRenderStage} [options.stage]
  8999. * @example
  9000. * var animation = new Animation();
  9001. * var obj = {
  9002. * x: 100,
  9003. * y: 100
  9004. * };
  9005. * animation.animate(node.position)
  9006. * .when(1000, {
  9007. * x: 500,
  9008. * y: 500
  9009. * })
  9010. * .when(2000, {
  9011. * x: 100,
  9012. * y: 100
  9013. * })
  9014. * .start('spline');
  9015. */
  9016. var Animation = function (options) {
  9017. options = options || {};
  9018. this.stage = options.stage || {};
  9019. this.onframe = options.onframe || function () {};
  9020. // private properties
  9021. this._clips = [];
  9022. this._running = false;
  9023. this._time;
  9024. this._pausedTime;
  9025. this._pauseStart;
  9026. this._paused = false;
  9027. Eventful.call(this);
  9028. };
  9029. Animation.prototype = {
  9030. constructor: Animation,
  9031. /**
  9032. * 添加 clip
  9033. * @param {module:zrender/animation/Clip} clip
  9034. */
  9035. addClip: function (clip) {
  9036. this._clips.push(clip);
  9037. },
  9038. /**
  9039. * 添加 animator
  9040. * @param {module:zrender/animation/Animator} animator
  9041. */
  9042. addAnimator: function (animator) {
  9043. animator.animation = this;
  9044. var clips = animator.getClips();
  9045. for (var i = 0; i < clips.length; i++) {
  9046. this.addClip(clips[i]);
  9047. }
  9048. },
  9049. /**
  9050. * 删除动画片段
  9051. * @param {module:zrender/animation/Clip} clip
  9052. */
  9053. removeClip: function (clip) {
  9054. var idx = indexOf(this._clips, clip);
  9055. if (idx >= 0) {
  9056. this._clips.splice(idx, 1);
  9057. }
  9058. },
  9059. /**
  9060. * 删除动画片段
  9061. * @param {module:zrender/animation/Animator} animator
  9062. */
  9063. removeAnimator: function (animator) {
  9064. var clips = animator.getClips();
  9065. for (var i = 0; i < clips.length; i++) {
  9066. this.removeClip(clips[i]);
  9067. }
  9068. animator.animation = null;
  9069. },
  9070. _update: function () {
  9071. var time = new Date().getTime() - this._pausedTime;
  9072. var delta = time - this._time;
  9073. var clips = this._clips;
  9074. var len = clips.length;
  9075. var deferredEvents = [];
  9076. var deferredClips = [];
  9077. for (var i = 0; i < len; i++) {
  9078. var clip = clips[i];
  9079. var e = clip.step(time, delta);
  9080. // Throw out the events need to be called after
  9081. // stage.update, like destroy
  9082. if (e) {
  9083. deferredEvents.push(e);
  9084. deferredClips.push(clip);
  9085. }
  9086. }
  9087. // Remove the finished clip
  9088. for (var i = 0; i < len;) {
  9089. if (clips[i]._needsRemove) {
  9090. clips[i] = clips[len - 1];
  9091. clips.pop();
  9092. len--;
  9093. }
  9094. else {
  9095. i++;
  9096. }
  9097. }
  9098. len = deferredEvents.length;
  9099. for (var i = 0; i < len; i++) {
  9100. deferredClips[i].fire(deferredEvents[i]);
  9101. }
  9102. this._time = time;
  9103. this.onframe(delta);
  9104. // 'frame' should be triggered before stage, because upper application
  9105. // depends on the sequence (e.g., echarts-stream and finish
  9106. // event judge)
  9107. this.trigger('frame', delta);
  9108. if (this.stage.update) {
  9109. this.stage.update();
  9110. }
  9111. },
  9112. _startLoop: function () {
  9113. var self = this;
  9114. this._running = true;
  9115. function step() {
  9116. if (self._running) {
  9117. requestAnimationFrame(step);
  9118. !self._paused && self._update();
  9119. }
  9120. }
  9121. requestAnimationFrame(step);
  9122. },
  9123. /**
  9124. * Start animation.
  9125. */
  9126. start: function () {
  9127. this._time = new Date().getTime();
  9128. this._pausedTime = 0;
  9129. this._startLoop();
  9130. },
  9131. /**
  9132. * Stop animation.
  9133. */
  9134. stop: function () {
  9135. this._running = false;
  9136. },
  9137. /**
  9138. * Pause animation.
  9139. */
  9140. pause: function () {
  9141. if (!this._paused) {
  9142. this._pauseStart = new Date().getTime();
  9143. this._paused = true;
  9144. }
  9145. },
  9146. /**
  9147. * Resume animation.
  9148. */
  9149. resume: function () {
  9150. if (this._paused) {
  9151. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9152. this._paused = false;
  9153. }
  9154. },
  9155. /**
  9156. * Clear animation.
  9157. */
  9158. clear: function () {
  9159. this._clips = [];
  9160. },
  9161. /**
  9162. * Whether animation finished.
  9163. */
  9164. isFinished: function () {
  9165. return !this._clips.length;
  9166. },
  9167. /**
  9168. * Creat animator for a target, whose props can be animated.
  9169. *
  9170. * @param {Object} target
  9171. * @param {Object} options
  9172. * @param {boolean} [options.loop=false] Whether loop animation.
  9173. * @param {Function} [options.getter=null] Get value from target.
  9174. * @param {Function} [options.setter=null] Set value to target.
  9175. * @return {module:zrender/animation/Animation~Animator}
  9176. */
  9177. // TODO Gap
  9178. animate: function (target, options) {
  9179. options = options || {};
  9180. var animator = new Animator(
  9181. target,
  9182. options.loop,
  9183. options.getter,
  9184. options.setter
  9185. );
  9186. this.addAnimator(animator);
  9187. return animator;
  9188. }
  9189. };
  9190. mixin(Animation, Eventful);
  9191. /* global document */
  9192. var TOUCH_CLICK_DELAY = 300;
  9193. var globalEventSupported = env$1.domSupported;
  9194. var localNativeListenerNames = (function () {
  9195. var mouseHandlerNames = [
  9196. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9197. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9198. ];
  9199. var touchHandlerNames = [
  9200. 'touchstart', 'touchend', 'touchmove'
  9201. ];
  9202. var pointerEventNameMap = {
  9203. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9204. };
  9205. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9206. var nm = name.replace('mouse', 'pointer');
  9207. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9208. });
  9209. return {
  9210. mouse: mouseHandlerNames,
  9211. touch: touchHandlerNames,
  9212. pointer: pointerHandlerNames
  9213. };
  9214. })();
  9215. var globalNativeListenerNames = {
  9216. mouse: ['mousemove', 'mouseup'],
  9217. pointer: ['pointermove', 'pointerup']
  9218. };
  9219. function eventNameFix(name) {
  9220. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9221. }
  9222. function isPointerFromTouch(event) {
  9223. var pointerType = event.pointerType;
  9224. return pointerType === 'pen' || pointerType === 'touch';
  9225. }
  9226. // function useMSGuesture(handlerProxy, event) {
  9227. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9228. // }
  9229. // function onMSGestureChange(proxy, event) {
  9230. // if (event.translationX || event.translationY) {
  9231. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9232. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9233. // }
  9234. // if (event.scale !== 1) {
  9235. // event.pinchX = event.offsetX;
  9236. // event.pinchY = event.offsetY;
  9237. // event.pinchScale = event.scale;
  9238. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9239. // }
  9240. // }
  9241. /**
  9242. * Prevent mouse event from being dispatched after Touch Events action
  9243. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9244. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9245. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9246. * Result: Blocking Mouse Events for 700ms.
  9247. *
  9248. * @param {DOMHandlerScope} scope
  9249. */
  9250. function setTouchTimer(scope) {
  9251. scope.touching = true;
  9252. if (scope.touchTimer != null) {
  9253. clearTimeout(scope.touchTimer);
  9254. scope.touchTimer = null;
  9255. }
  9256. scope.touchTimer = setTimeout(function () {
  9257. scope.touching = false;
  9258. scope.touchTimer = null;
  9259. }, 700);
  9260. }
  9261. // Mark touch, which is useful in distinguish touch and
  9262. // mouse event in upper applicatoin.
  9263. function markTouch(event) {
  9264. event && (event.zrByTouch = true);
  9265. }
  9266. // function markTriggeredFromLocal(event) {
  9267. // event && (event.__zrIsFromLocal = true);
  9268. // }
  9269. // function isTriggeredFromLocal(instance, event) {
  9270. // return !!(event && event.__zrIsFromLocal);
  9271. // }
  9272. function normalizeGlobalEvent(instance, event) {
  9273. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9274. // handlers of the upper applications. Set `true` to force calculate them.
  9275. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9276. }
  9277. /**
  9278. * Detect whether the given el is in `painterRoot`.
  9279. */
  9280. function isLocalEl(instance, el) {
  9281. var isLocal = false;
  9282. do {
  9283. el = el && el.parentNode;
  9284. }
  9285. while (el && el.nodeType !== 9 && !(
  9286. isLocal = el === instance.painterRoot
  9287. ));
  9288. return isLocal;
  9289. }
  9290. /**
  9291. * Make a fake event but not change the original event,
  9292. * becuase the global event probably be used by other
  9293. * listeners not belonging to zrender.
  9294. * @class
  9295. */
  9296. function FakeGlobalEvent(instance, event) {
  9297. this.type = event.type;
  9298. this.target = this.currentTarget = instance.dom;
  9299. this.pointerType = event.pointerType;
  9300. // Necessray for the force calculation of zrX, zrY
  9301. this.clientX = event.clientX;
  9302. this.clientY = event.clientY;
  9303. // Because we do not mount global listeners to touch events,
  9304. // we do not copy `targetTouches` and `changedTouches` here.
  9305. }
  9306. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9307. // we make the default methods on the event do nothing,
  9308. // otherwise it is dangerous. See more details in
  9309. // [Drag outside] in `Handler.js`.
  9310. fakeGlobalEventProto.stopPropagation =
  9311. fakeGlobalEventProto.stopImmediatePropagation =
  9312. fakeGlobalEventProto.preventDefault = noop;
  9313. /**
  9314. * Local DOM Handlers
  9315. * @this {HandlerProxy}
  9316. */
  9317. var localDOMHandlers = {
  9318. mousedown: function (event) {
  9319. event = normalizeEvent(this.dom, event);
  9320. this._mayPointerCapture = [event.zrX, event.zrY];
  9321. this.trigger('mousedown', event);
  9322. },
  9323. mousemove: function (event) {
  9324. event = normalizeEvent(this.dom, event);
  9325. var downPoint = this._mayPointerCapture;
  9326. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9327. togglePointerCapture(this, true);
  9328. }
  9329. this.trigger('mousemove', event);
  9330. },
  9331. mouseup: function (event) {
  9332. event = normalizeEvent(this.dom, event);
  9333. togglePointerCapture(this, false);
  9334. this.trigger('mouseup', event);
  9335. },
  9336. mouseout: function (event) {
  9337. event = normalizeEvent(this.dom, event);
  9338. // Similarly to the browser did on `document` and touch event,
  9339. // `globalout` will be delayed to final pointer cature release.
  9340. if (this._pointerCapturing) {
  9341. event.zrEventControl = 'no_globalout';
  9342. }
  9343. // There might be some doms created by upper layer application
  9344. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9345. // dom created by echarts), where 'globalout' event should not
  9346. // be triggered when mouse enters these doms. (But 'mouseout'
  9347. // should be triggered at the original hovered element as usual).
  9348. var element = event.toElement || event.relatedTarget;
  9349. event.zrIsToLocalDOM = isLocalEl(this, element);
  9350. this.trigger('mouseout', event);
  9351. },
  9352. touchstart: function (event) {
  9353. // Default mouse behaviour should not be disabled here.
  9354. // For example, page may needs to be slided.
  9355. event = normalizeEvent(this.dom, event);
  9356. markTouch(event);
  9357. this._lastTouchMoment = new Date();
  9358. this.handler.processGesture(event, 'start');
  9359. // For consistent event listener for both touch device and mouse device,
  9360. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9361. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9362. // `mousedown`.
  9363. localDOMHandlers.mousemove.call(this, event);
  9364. localDOMHandlers.mousedown.call(this, event);
  9365. },
  9366. touchmove: function (event) {
  9367. event = normalizeEvent(this.dom, event);
  9368. markTouch(event);
  9369. this.handler.processGesture(event, 'change');
  9370. // Mouse move should always be triggered no matter whether
  9371. // there is gestrue event, because mouse move and pinch may
  9372. // be used at the same time.
  9373. localDOMHandlers.mousemove.call(this, event);
  9374. },
  9375. touchend: function (event) {
  9376. event = normalizeEvent(this.dom, event);
  9377. markTouch(event);
  9378. this.handler.processGesture(event, 'end');
  9379. localDOMHandlers.mouseup.call(this, event);
  9380. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9381. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9382. // we can conveniently implement "hover style" in both PC and touch device just
  9383. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9384. // to remove "hover style" on an element, without any additional code for
  9385. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9386. // style" will remain for user view)
  9387. // click event should always be triggered no matter whether
  9388. // there is gestrue event. System click can not be prevented.
  9389. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9390. localDOMHandlers.click.call(this, event);
  9391. }
  9392. },
  9393. pointerdown: function (event) {
  9394. localDOMHandlers.mousedown.call(this, event);
  9395. // if (useMSGuesture(this, event)) {
  9396. // this._msGesture.addPointer(event.pointerId);
  9397. // }
  9398. },
  9399. pointermove: function (event) {
  9400. // FIXME
  9401. // pointermove is so sensitive that it always triggered when
  9402. // tap(click) on touch screen, which affect some judgement in
  9403. // upper application. So, we dont support mousemove on MS touch
  9404. // device yet.
  9405. if (!isPointerFromTouch(event)) {
  9406. localDOMHandlers.mousemove.call(this, event);
  9407. }
  9408. },
  9409. pointerup: function (event) {
  9410. localDOMHandlers.mouseup.call(this, event);
  9411. },
  9412. pointerout: function (event) {
  9413. // pointerout will be triggered when tap on touch screen
  9414. // (IE11+/Edge on MS Surface) after click event triggered,
  9415. // which is inconsistent with the mousout behavior we defined
  9416. // in touchend. So we unify them.
  9417. // (check localDOMHandlers.touchend for detailed explanation)
  9418. if (!isPointerFromTouch(event)) {
  9419. localDOMHandlers.mouseout.call(this, event);
  9420. }
  9421. }
  9422. };
  9423. /**
  9424. * Othere DOM UI Event handlers for zr dom.
  9425. * @this {HandlerProxy}
  9426. */
  9427. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9428. localDOMHandlers[name] = function (event) {
  9429. event = normalizeEvent(this.dom, event);
  9430. this.trigger(name, event);
  9431. };
  9432. });
  9433. /**
  9434. * DOM UI Event handlers for global page.
  9435. *
  9436. * [Caution]:
  9437. * those handlers should both support in capture phase and bubble phase!
  9438. *
  9439. * @this {HandlerProxy}
  9440. */
  9441. var globalDOMHandlers = {
  9442. pointermove: function (event) {
  9443. // FIXME
  9444. // pointermove is so sensitive that it always triggered when
  9445. // tap(click) on touch screen, which affect some judgement in
  9446. // upper application. So, we dont support mousemove on MS touch
  9447. // device yet.
  9448. if (!isPointerFromTouch(event)) {
  9449. globalDOMHandlers.mousemove.call(this, event);
  9450. }
  9451. },
  9452. pointerup: function (event) {
  9453. globalDOMHandlers.mouseup.call(this, event);
  9454. },
  9455. mousemove: function (event) {
  9456. this.trigger('mousemove', event);
  9457. },
  9458. mouseup: function (event) {
  9459. var pointerCaptureReleasing = this._pointerCapturing;
  9460. togglePointerCapture(this, false);
  9461. this.trigger('mouseup', event);
  9462. if (pointerCaptureReleasing) {
  9463. event.zrEventControl = 'only_globalout';
  9464. this.trigger('mouseout', event);
  9465. }
  9466. }
  9467. };
  9468. /**
  9469. * @param {HandlerProxy} instance
  9470. * @param {DOMHandlerScope} scope
  9471. */
  9472. function mountLocalDOMEventListeners(instance, scope) {
  9473. var domHandlers = scope.domHandlers;
  9474. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9475. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9476. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9477. // at the same time.
  9478. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9479. // screen, which do not occurs in pointer event.
  9480. // So we use pointer event to both detect touch gesture and mouse behavior.
  9481. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9482. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9483. // markTriggeredFromLocal(event);
  9484. domHandlers[nativeEventName].call(instance, event);
  9485. });
  9486. });
  9487. // FIXME
  9488. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9489. // which does not prevent defuault behavior occasionally (which may cause view port
  9490. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9491. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9492. // touch screen. And we only support click behavior on MS touch screen now.
  9493. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9494. // We dont support touch on IE on win7.
  9495. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9496. // if (typeof MSGesture === 'function') {
  9497. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9498. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9499. // }
  9500. }
  9501. else {
  9502. if (env$1.touchEventsSupported) {
  9503. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9504. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9505. // markTriggeredFromLocal(event);
  9506. domHandlers[nativeEventName].call(instance, event);
  9507. setTouchTimer(scope);
  9508. });
  9509. });
  9510. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9511. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9512. }
  9513. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9514. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9515. // mouse event can not be handle in those devices.
  9516. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9517. // mouseevent after touch event triggered, see `setTouchTimer`.
  9518. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9519. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9520. event = getNativeEvent(event);
  9521. if (!scope.touching) {
  9522. // markTriggeredFromLocal(event);
  9523. domHandlers[nativeEventName].call(instance, event);
  9524. }
  9525. });
  9526. });
  9527. }
  9528. }
  9529. /**
  9530. * @param {HandlerProxy} instance
  9531. * @param {DOMHandlerScope} scope
  9532. */
  9533. function mountGlobalDOMEventListeners(instance, scope) {
  9534. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9535. if (env$1.pointerEventsSupported) {
  9536. each$1(globalNativeListenerNames.pointer, mount);
  9537. }
  9538. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9539. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9540. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9541. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9542. else if (!env$1.touchEventsSupported) {
  9543. each$1(globalNativeListenerNames.mouse, mount);
  9544. }
  9545. function mount(nativeEventName) {
  9546. function nativeEventListener(event) {
  9547. event = getNativeEvent(event);
  9548. // See the reason in [Drag outside] in `Handler.js`
  9549. // This checking supports both `useCapture` or not.
  9550. // PENDING: if there is performance issue in some devices,
  9551. // we probably can not use `useCapture` and change a easier
  9552. // to judes whether local (mark).
  9553. if (!isLocalEl(instance, event.target)) {
  9554. event = normalizeGlobalEvent(instance, event);
  9555. scope.domHandlers[nativeEventName].call(instance, event);
  9556. }
  9557. }
  9558. mountSingleDOMEventListener(
  9559. scope, nativeEventName, nativeEventListener,
  9560. {capture: true} // See [Drag Outside] in `Handler.js`
  9561. );
  9562. }
  9563. }
  9564. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9565. scope.mounted[nativeEventName] = listener;
  9566. scope.listenerOpts[nativeEventName] = opt;
  9567. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9568. }
  9569. function unmountDOMEventListeners(scope) {
  9570. var mounted = scope.mounted;
  9571. for (var nativeEventName in mounted) {
  9572. if (mounted.hasOwnProperty(nativeEventName)) {
  9573. removeEventListener(
  9574. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9575. scope.listenerOpts[nativeEventName]
  9576. );
  9577. }
  9578. }
  9579. scope.mounted = {};
  9580. }
  9581. /**
  9582. * See [Drag Outside] in `Handler.js`.
  9583. * @implement
  9584. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9585. * `true`: start to capture pointer if it is not capturing.
  9586. * `false`: end the capture if it is capturing.
  9587. */
  9588. function togglePointerCapture(instance, isPointerCapturing) {
  9589. instance._mayPointerCapture = null;
  9590. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9591. instance._pointerCapturing = isPointerCapturing;
  9592. var globalHandlerScope = instance._globalHandlerScope;
  9593. isPointerCapturing
  9594. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9595. : unmountDOMEventListeners(globalHandlerScope);
  9596. }
  9597. }
  9598. /**
  9599. * @inner
  9600. * @class
  9601. */
  9602. function DOMHandlerScope(domTarget, domHandlers) {
  9603. this.domTarget = domTarget;
  9604. this.domHandlers = domHandlers;
  9605. // Key: eventName, value: mounted handler funcitons.
  9606. // Used for unmount.
  9607. this.mounted = {};
  9608. this.listenerOpts = {};
  9609. this.touchTimer = null;
  9610. this.touching = false;
  9611. }
  9612. /**
  9613. * @public
  9614. * @class
  9615. */
  9616. function HandlerDomProxy(dom, painterRoot) {
  9617. Eventful.call(this);
  9618. this.dom = dom;
  9619. this.painterRoot = painterRoot;
  9620. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9621. if (globalEventSupported) {
  9622. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9623. }
  9624. /**
  9625. * @type {boolean}
  9626. */
  9627. this._pointerCapturing = false;
  9628. /**
  9629. * @type {Array.<number>} [x, y] or null.
  9630. */
  9631. this._mayPointerCapture = null;
  9632. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9633. }
  9634. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9635. handlerDomProxyProto.dispose = function () {
  9636. unmountDOMEventListeners(this._localHandlerScope);
  9637. if (globalEventSupported) {
  9638. unmountDOMEventListeners(this._globalHandlerScope);
  9639. }
  9640. };
  9641. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9642. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9643. };
  9644. mixin(HandlerDomProxy, Eventful);
  9645. /*!
  9646. * ZRender, a high performance 2d drawing library.
  9647. *
  9648. * Copyright (c) 2013, Baidu Inc.
  9649. * All rights reserved.
  9650. *
  9651. * LICENSE
  9652. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9653. */
  9654. var useVML = !env$1.canvasSupported;
  9655. var painterCtors = {
  9656. canvas: Painter
  9657. };
  9658. /**
  9659. * @type {string}
  9660. */
  9661. var version$1 = '4.2.0';
  9662. /**
  9663. * Initializing a zrender instance
  9664. * @param {HTMLElement} dom
  9665. * @param {Object} [opts]
  9666. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9667. * @param {number} [opts.devicePixelRatio]
  9668. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9669. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9670. * @return {module:zrender/ZRender}
  9671. */
  9672. function init$1(dom, opts) {
  9673. var zr = new ZRender(guid(), dom, opts);
  9674. return zr;
  9675. }
  9676. /**
  9677. * Dispose zrender instance
  9678. * @param {module:zrender/ZRender} zr
  9679. */
  9680. /**
  9681. * Get zrender instance by id
  9682. * @param {string} id zrender instance id
  9683. * @return {module:zrender/ZRender}
  9684. */
  9685. /**
  9686. * @module zrender/ZRender
  9687. */
  9688. /**
  9689. * @constructor
  9690. * @alias module:zrender/ZRender
  9691. * @param {string} id
  9692. * @param {HTMLElement} dom
  9693. * @param {Object} opts
  9694. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9695. * @param {number} [opts.devicePixelRatio]
  9696. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9697. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9698. */
  9699. var ZRender = function (id, dom, opts) {
  9700. opts = opts || {};
  9701. /**
  9702. * @type {HTMLDomElement}
  9703. */
  9704. this.dom = dom;
  9705. /**
  9706. * @type {string}
  9707. */
  9708. this.id = id;
  9709. var self = this;
  9710. var storage = new Storage();
  9711. var rendererType = opts.renderer;
  9712. // TODO WebGL
  9713. if (useVML) {
  9714. if (!painterCtors.vml) {
  9715. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9716. }
  9717. rendererType = 'vml';
  9718. }
  9719. else if (!rendererType || !painterCtors[rendererType]) {
  9720. rendererType = 'canvas';
  9721. }
  9722. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9723. this.storage = storage;
  9724. this.painter = painter;
  9725. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  9726. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9727. /**
  9728. * @type {module:zrender/animation/Animation}
  9729. */
  9730. this.animation = new Animation({
  9731. stage: {
  9732. update: bind(this.flush, this)
  9733. }
  9734. });
  9735. this.animation.start();
  9736. /**
  9737. * @type {boolean}
  9738. * @private
  9739. */
  9740. this._needsRefresh;
  9741. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9742. // FIXME 有点ugly
  9743. var oldDelFromStorage = storage.delFromStorage;
  9744. var oldAddToStorage = storage.addToStorage;
  9745. storage.delFromStorage = function (el) {
  9746. oldDelFromStorage.call(storage, el);
  9747. el && el.removeSelfFromZr(self);
  9748. };
  9749. storage.addToStorage = function (el) {
  9750. oldAddToStorage.call(storage, el);
  9751. el.addSelfToZr(self);
  9752. };
  9753. };
  9754. ZRender.prototype = {
  9755. constructor: ZRender,
  9756. /**
  9757. * 获取实例唯一标识
  9758. * @return {string}
  9759. */
  9760. getId: function () {
  9761. return this.id;
  9762. },
  9763. /**
  9764. * 添加元素
  9765. * @param {module:zrender/Element} el
  9766. */
  9767. add: function (el) {
  9768. this.storage.addRoot(el);
  9769. this._needsRefresh = true;
  9770. },
  9771. /**
  9772. * 删除元素
  9773. * @param {module:zrender/Element} el
  9774. */
  9775. remove: function (el) {
  9776. this.storage.delRoot(el);
  9777. this._needsRefresh = true;
  9778. },
  9779. /**
  9780. * Change configuration of layer
  9781. * @param {string} zLevel
  9782. * @param {Object} config
  9783. * @param {string} [config.clearColor=0] Clear color
  9784. * @param {string} [config.motionBlur=false] If enable motion blur
  9785. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9786. */
  9787. configLayer: function (zLevel, config) {
  9788. if (this.painter.configLayer) {
  9789. this.painter.configLayer(zLevel, config);
  9790. }
  9791. this._needsRefresh = true;
  9792. },
  9793. /**
  9794. * Set background color
  9795. * @param {string} backgroundColor
  9796. */
  9797. setBackgroundColor: function (backgroundColor) {
  9798. if (this.painter.setBackgroundColor) {
  9799. this.painter.setBackgroundColor(backgroundColor);
  9800. }
  9801. this._needsRefresh = true;
  9802. },
  9803. /**
  9804. * Repaint the canvas immediately
  9805. */
  9806. refreshImmediately: function () {
  9807. // var start = new Date();
  9808. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9809. // Or it will cause zrender refreshes again and again.
  9810. this._needsRefresh = this._needsRefreshHover = false;
  9811. this.painter.refresh();
  9812. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  9813. this._needsRefresh = this._needsRefreshHover = false;
  9814. // var end = new Date();
  9815. // var log = document.getElementById('log');
  9816. // if (log) {
  9817. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9818. // }
  9819. },
  9820. /**
  9821. * Mark and repaint the canvas in the next frame of browser
  9822. */
  9823. refresh: function () {
  9824. this._needsRefresh = true;
  9825. },
  9826. /**
  9827. * Perform all refresh
  9828. */
  9829. flush: function () {
  9830. var triggerRendered;
  9831. if (this._needsRefresh) {
  9832. triggerRendered = true;
  9833. this.refreshImmediately();
  9834. }
  9835. if (this._needsRefreshHover) {
  9836. triggerRendered = true;
  9837. this.refreshHoverImmediately();
  9838. }
  9839. triggerRendered && this.trigger('rendered');
  9840. },
  9841. /**
  9842. * Add element to hover layer
  9843. * @param {module:zrender/Element} el
  9844. * @param {Object} style
  9845. */
  9846. addHover: function (el, style) {
  9847. if (this.painter.addHover) {
  9848. var elMirror = this.painter.addHover(el, style);
  9849. this.refreshHover();
  9850. return elMirror;
  9851. }
  9852. },
  9853. /**
  9854. * Add element from hover layer
  9855. * @param {module:zrender/Element} el
  9856. */
  9857. removeHover: function (el) {
  9858. if (this.painter.removeHover) {
  9859. this.painter.removeHover(el);
  9860. this.refreshHover();
  9861. }
  9862. },
  9863. /**
  9864. * Clear all hover elements in hover layer
  9865. * @param {module:zrender/Element} el
  9866. */
  9867. clearHover: function () {
  9868. if (this.painter.clearHover) {
  9869. this.painter.clearHover();
  9870. this.refreshHover();
  9871. }
  9872. },
  9873. /**
  9874. * Refresh hover in next frame
  9875. */
  9876. refreshHover: function () {
  9877. this._needsRefreshHover = true;
  9878. },
  9879. /**
  9880. * Refresh hover immediately
  9881. */
  9882. refreshHoverImmediately: function () {
  9883. this._needsRefreshHover = false;
  9884. this.painter.refreshHover && this.painter.refreshHover();
  9885. },
  9886. /**
  9887. * Resize the canvas.
  9888. * Should be invoked when container size is changed
  9889. * @param {Object} [opts]
  9890. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9891. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9892. */
  9893. resize: function (opts) {
  9894. opts = opts || {};
  9895. this.painter.resize(opts.width, opts.height);
  9896. this.handler.resize();
  9897. },
  9898. /**
  9899. * Stop and clear all animation immediately
  9900. */
  9901. clearAnimation: function () {
  9902. this.animation.clear();
  9903. },
  9904. /**
  9905. * Get container width
  9906. */
  9907. getWidth: function () {
  9908. return this.painter.getWidth();
  9909. },
  9910. /**
  9911. * Get container height
  9912. */
  9913. getHeight: function () {
  9914. return this.painter.getHeight();
  9915. },
  9916. /**
  9917. * Export the canvas as Base64 URL
  9918. * @param {string} type
  9919. * @param {string} [backgroundColor='#fff']
  9920. * @return {string} Base64 URL
  9921. */
  9922. // toDataURL: function(type, backgroundColor) {
  9923. // return this.painter.getRenderedCanvas({
  9924. // backgroundColor: backgroundColor
  9925. // }).toDataURL(type);
  9926. // },
  9927. /**
  9928. * Converting a path to image.
  9929. * It has much better performance of drawing image rather than drawing a vector path.
  9930. * @param {module:zrender/graphic/Path} e
  9931. * @param {number} width
  9932. * @param {number} height
  9933. */
  9934. pathToImage: function (e, dpr) {
  9935. return this.painter.pathToImage(e, dpr);
  9936. },
  9937. /**
  9938. * Set default cursor
  9939. * @param {string} [cursorStyle='default'] 例如 crosshair
  9940. */
  9941. setCursorStyle: function (cursorStyle) {
  9942. this.handler.setCursorStyle(cursorStyle);
  9943. },
  9944. /**
  9945. * Find hovered element
  9946. * @param {number} x
  9947. * @param {number} y
  9948. * @return {Object} {target, topTarget}
  9949. */
  9950. findHover: function (x, y) {
  9951. return this.handler.findHover(x, y);
  9952. },
  9953. /**
  9954. * Bind event
  9955. *
  9956. * @param {string} eventName Event name
  9957. * @param {Function} eventHandler Handler function
  9958. * @param {Object} [context] Context object
  9959. */
  9960. on: function (eventName, eventHandler, context) {
  9961. this.handler.on(eventName, eventHandler, context);
  9962. },
  9963. /**
  9964. * Unbind event
  9965. * @param {string} eventName Event name
  9966. * @param {Function} [eventHandler] Handler function
  9967. */
  9968. off: function (eventName, eventHandler) {
  9969. this.handler.off(eventName, eventHandler);
  9970. },
  9971. /**
  9972. * Trigger event manually
  9973. *
  9974. * @param {string} eventName Event name
  9975. * @param {event=} event Event object
  9976. */
  9977. trigger: function (eventName, event) {
  9978. this.handler.trigger(eventName, event);
  9979. },
  9980. /**
  9981. * Clear all objects and the canvas.
  9982. */
  9983. clear: function () {
  9984. this.storage.delRoot();
  9985. this.painter.clear();
  9986. },
  9987. /**
  9988. * Dispose self.
  9989. */
  9990. dispose: function () {
  9991. this.animation.stop();
  9992. this.clear();
  9993. this.storage.dispose();
  9994. this.painter.dispose();
  9995. this.handler.dispose();
  9996. this.animation =
  9997. this.storage =
  9998. this.painter =
  9999. this.handler = null;
  10000. }
  10001. };
  10002. /*
  10003. * Licensed to the Apache Software Foundation (ASF) under one
  10004. * or more contributor license agreements. See the NOTICE file
  10005. * distributed with this work for additional information
  10006. * regarding copyright ownership. The ASF licenses this file
  10007. * to you under the Apache License, Version 2.0 (the
  10008. * "License"); you may not use this file except in compliance
  10009. * with the License. You may obtain a copy of the License at
  10010. *
  10011. * http://www.apache.org/licenses/LICENSE-2.0
  10012. *
  10013. * Unless required by applicable law or agreed to in writing,
  10014. * software distributed under the License is distributed on an
  10015. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10016. * KIND, either express or implied. See the License for the
  10017. * specific language governing permissions and limitations
  10018. * under the License.
  10019. */
  10020. var each$2 = each$1;
  10021. var isObject$2 = isObject$1;
  10022. var isArray$1 = isArray;
  10023. /**
  10024. * Make the name displayable. But we should
  10025. * make sure it is not duplicated with user
  10026. * specified name, so use '\0';
  10027. */
  10028. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  10029. /**
  10030. * If value is not array, then translate it to array.
  10031. * @param {*} value
  10032. * @return {Array} [value] or value
  10033. */
  10034. function normalizeToArray(value) {
  10035. return value instanceof Array
  10036. ? value
  10037. : value == null
  10038. ? []
  10039. : [value];
  10040. }
  10041. /**
  10042. * Sync default option between normal and emphasis like `position` and `show`
  10043. * In case some one will write code like
  10044. * label: {
  10045. * show: false,
  10046. * position: 'outside',
  10047. * fontSize: 18
  10048. * },
  10049. * emphasis: {
  10050. * label: { show: true }
  10051. * }
  10052. * @param {Object} opt
  10053. * @param {string} key
  10054. * @param {Array.<string>} subOpts
  10055. */
  10056. function defaultEmphasis(opt, key, subOpts) {
  10057. // Caution: performance sensitive.
  10058. if (opt) {
  10059. opt[key] = opt[key] || {};
  10060. opt.emphasis = opt.emphasis || {};
  10061. opt.emphasis[key] = opt.emphasis[key] || {};
  10062. // Default emphasis option from normal
  10063. for (var i = 0, len = subOpts.length; i < len; i++) {
  10064. var subOptName = subOpts[i];
  10065. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  10066. && opt[key].hasOwnProperty(subOptName)
  10067. ) {
  10068. opt.emphasis[key][subOptName] = opt[key][subOptName];
  10069. }
  10070. }
  10071. }
  10072. }
  10073. var TEXT_STYLE_OPTIONS = [
  10074. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10075. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  10076. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  10077. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  10078. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  10079. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  10080. ];
  10081. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  10082. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  10083. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  10084. // // FIXME: deprecated, check and remove it.
  10085. // 'textStyle'
  10086. // ]);
  10087. /**
  10088. * The method do not ensure performance.
  10089. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10090. * This helper method retieves value from data.
  10091. * @param {string|number|Date|Array|Object} dataItem
  10092. * @return {number|string|Date|Array.<number|string|Date>}
  10093. */
  10094. function getDataItemValue(dataItem) {
  10095. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  10096. ? dataItem.value : dataItem;
  10097. }
  10098. /**
  10099. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  10100. * This helper method determine if dataItem has extra option besides value
  10101. * @param {string|number|Date|Array|Object} dataItem
  10102. */
  10103. function isDataItemOption(dataItem) {
  10104. return isObject$2(dataItem)
  10105. && !(dataItem instanceof Array);
  10106. // // markLine data can be array
  10107. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  10108. }
  10109. /**
  10110. * Mapping to exists for merge.
  10111. *
  10112. * @public
  10113. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  10114. * @param {Object|Array.<Object>} newCptOptions
  10115. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10116. * index of which is the same as exists.
  10117. */
  10118. function mappingToExists(exists, newCptOptions) {
  10119. // Mapping by the order by original option (but not order of
  10120. // new option) in merge mode. Because we should ensure
  10121. // some specified index (like xAxisIndex) is consistent with
  10122. // original option, which is easy to understand, espatially in
  10123. // media query. And in most case, merge option is used to
  10124. // update partial option but not be expected to change order.
  10125. newCptOptions = (newCptOptions || []).slice();
  10126. var result = map(exists || [], function (obj, index) {
  10127. return {exist: obj};
  10128. });
  10129. // Mapping by id or name if specified.
  10130. each$2(newCptOptions, function (cptOption, index) {
  10131. if (!isObject$2(cptOption)) {
  10132. return;
  10133. }
  10134. // id has highest priority.
  10135. for (var i = 0; i < result.length; i++) {
  10136. if (!result[i].option // Consider name: two map to one.
  10137. && cptOption.id != null
  10138. && result[i].exist.id === cptOption.id + ''
  10139. ) {
  10140. result[i].option = cptOption;
  10141. newCptOptions[index] = null;
  10142. return;
  10143. }
  10144. }
  10145. for (var i = 0; i < result.length; i++) {
  10146. var exist = result[i].exist;
  10147. if (!result[i].option // Consider name: two map to one.
  10148. // Can not match when both ids exist but different.
  10149. && (exist.id == null || cptOption.id == null)
  10150. && cptOption.name != null
  10151. && !isIdInner(cptOption)
  10152. && !isIdInner(exist)
  10153. && exist.name === cptOption.name + ''
  10154. ) {
  10155. result[i].option = cptOption;
  10156. newCptOptions[index] = null;
  10157. return;
  10158. }
  10159. }
  10160. });
  10161. // Otherwise mapping by index.
  10162. each$2(newCptOptions, function (cptOption, index) {
  10163. if (!isObject$2(cptOption)) {
  10164. return;
  10165. }
  10166. var i = 0;
  10167. for (; i < result.length; i++) {
  10168. var exist = result[i].exist;
  10169. if (!result[i].option
  10170. // Existing model that already has id should be able to
  10171. // mapped to (because after mapping performed model may
  10172. // be assigned with a id, whish should not affect next
  10173. // mapping), except those has inner id.
  10174. && !isIdInner(exist)
  10175. // Caution:
  10176. // Do not overwrite id. But name can be overwritten,
  10177. // because axis use name as 'show label text'.
  10178. // 'exist' always has id and name and we dont
  10179. // need to check it.
  10180. && cptOption.id == null
  10181. ) {
  10182. result[i].option = cptOption;
  10183. break;
  10184. }
  10185. }
  10186. if (i >= result.length) {
  10187. result.push({option: cptOption});
  10188. }
  10189. });
  10190. return result;
  10191. }
  10192. /**
  10193. * Make id and name for mapping result (result of mappingToExists)
  10194. * into `keyInfo` field.
  10195. *
  10196. * @public
  10197. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  10198. * which order is the same as exists.
  10199. * @return {Array.<Object>} The input.
  10200. */
  10201. function makeIdAndName(mapResult) {
  10202. // We use this id to hash component models and view instances
  10203. // in echarts. id can be specified by user, or auto generated.
  10204. // The id generation rule ensures new view instance are able
  10205. // to mapped to old instance when setOption are called in
  10206. // no-merge mode. So we generate model id by name and plus
  10207. // type in view id.
  10208. // name can be duplicated among components, which is convenient
  10209. // to specify multi components (like series) by one name.
  10210. // Ensure that each id is distinct.
  10211. var idMap = createHashMap();
  10212. each$2(mapResult, function (item, index) {
  10213. var existCpt = item.exist;
  10214. existCpt && idMap.set(existCpt.id, item);
  10215. });
  10216. each$2(mapResult, function (item, index) {
  10217. var opt = item.option;
  10218. assert$1(
  10219. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  10220. 'id duplicates: ' + (opt && opt.id)
  10221. );
  10222. opt && opt.id != null && idMap.set(opt.id, item);
  10223. !item.keyInfo && (item.keyInfo = {});
  10224. });
  10225. // Make name and id.
  10226. each$2(mapResult, function (item, index) {
  10227. var existCpt = item.exist;
  10228. var opt = item.option;
  10229. var keyInfo = item.keyInfo;
  10230. if (!isObject$2(opt)) {
  10231. return;
  10232. }
  10233. // name can be overwitten. Consider case: axis.name = '20km'.
  10234. // But id generated by name will not be changed, which affect
  10235. // only in that case: setOption with 'not merge mode' and view
  10236. // instance will be recreated, which can be accepted.
  10237. keyInfo.name = opt.name != null
  10238. ? opt.name + ''
  10239. : existCpt
  10240. ? existCpt.name
  10241. // Avoid diffferent series has the same name,
  10242. // because name may be used like in color pallet.
  10243. : DUMMY_COMPONENT_NAME_PREFIX + index;
  10244. if (existCpt) {
  10245. keyInfo.id = existCpt.id;
  10246. }
  10247. else if (opt.id != null) {
  10248. keyInfo.id = opt.id + '';
  10249. }
  10250. else {
  10251. // Consider this situatoin:
  10252. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  10253. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  10254. // Series with the same name between optionA and optionB
  10255. // should be mapped.
  10256. var idNum = 0;
  10257. do {
  10258. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  10259. }
  10260. while (idMap.get(keyInfo.id));
  10261. }
  10262. idMap.set(keyInfo.id, item);
  10263. });
  10264. }
  10265. function isNameSpecified(componentModel) {
  10266. var name = componentModel.name;
  10267. // Is specified when `indexOf` get -1 or > 0.
  10268. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10269. }
  10270. /**
  10271. * @public
  10272. * @param {Object} cptOption
  10273. * @return {boolean}
  10274. */
  10275. function isIdInner(cptOption) {
  10276. return isObject$2(cptOption)
  10277. && cptOption.id
  10278. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10279. }
  10280. /**
  10281. * A helper for removing duplicate items between batchA and batchB,
  10282. * and in themselves, and categorize by series.
  10283. *
  10284. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10285. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10286. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10287. */
  10288. /**
  10289. * @param {module:echarts/data/List} data
  10290. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10291. * each of which can be Array or primary type.
  10292. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10293. */
  10294. function queryDataIndex(data, payload) {
  10295. if (payload.dataIndexInside != null) {
  10296. return payload.dataIndexInside;
  10297. }
  10298. else if (payload.dataIndex != null) {
  10299. return isArray(payload.dataIndex)
  10300. ? map(payload.dataIndex, function (value) {
  10301. return data.indexOfRawIndex(value);
  10302. })
  10303. : data.indexOfRawIndex(payload.dataIndex);
  10304. }
  10305. else if (payload.name != null) {
  10306. return isArray(payload.name)
  10307. ? map(payload.name, function (value) {
  10308. return data.indexOfName(value);
  10309. })
  10310. : data.indexOfName(payload.name);
  10311. }
  10312. }
  10313. /**
  10314. * Enable property storage to any host object.
  10315. * Notice: Serialization is not supported.
  10316. *
  10317. * For example:
  10318. * var inner = zrUitl.makeInner();
  10319. *
  10320. * function some1(hostObj) {
  10321. * inner(hostObj).someProperty = 1212;
  10322. * ...
  10323. * }
  10324. * function some2() {
  10325. * var fields = inner(this);
  10326. * fields.someProperty1 = 1212;
  10327. * fields.someProperty2 = 'xx';
  10328. * ...
  10329. * }
  10330. *
  10331. * @return {Function}
  10332. */
  10333. function makeInner() {
  10334. // Consider different scope by es module import.
  10335. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10336. return function (hostObj) {
  10337. return hostObj[key] || (hostObj[key] = {});
  10338. };
  10339. }
  10340. var innerUniqueIndex = 0;
  10341. /**
  10342. * @param {module:echarts/model/Global} ecModel
  10343. * @param {string|Object} finder
  10344. * If string, e.g., 'geo', means {geoIndex: 0}.
  10345. * If Object, could contain some of these properties below:
  10346. * {
  10347. * seriesIndex, seriesId, seriesName,
  10348. * geoIndex, geoId, geoName,
  10349. * bmapIndex, bmapId, bmapName,
  10350. * xAxisIndex, xAxisId, xAxisName,
  10351. * yAxisIndex, yAxisId, yAxisName,
  10352. * gridIndex, gridId, gridName,
  10353. * ... (can be extended)
  10354. * }
  10355. * Each properties can be number|string|Array.<number>|Array.<string>
  10356. * For example, a finder could be
  10357. * {
  10358. * seriesIndex: 3,
  10359. * geoId: ['aa', 'cc'],
  10360. * gridName: ['xx', 'rr']
  10361. * }
  10362. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10363. * If nothing or null/undefined specified, return nothing.
  10364. * @param {Object} [opt]
  10365. * @param {string} [opt.defaultMainType]
  10366. * @param {Array.<string>} [opt.includeMainTypes]
  10367. * @return {Object} result like:
  10368. * {
  10369. * seriesModels: [seriesModel1, seriesModel2],
  10370. * seriesModel: seriesModel1, // The first model
  10371. * geoModels: [geoModel1, geoModel2],
  10372. * geoModel: geoModel1, // The first model
  10373. * ...
  10374. * }
  10375. */
  10376. function parseFinder(ecModel, finder, opt) {
  10377. if (isString(finder)) {
  10378. var obj = {};
  10379. obj[finder + 'Index'] = 0;
  10380. finder = obj;
  10381. }
  10382. var defaultMainType = opt && opt.defaultMainType;
  10383. if (defaultMainType
  10384. && !has(finder, defaultMainType + 'Index')
  10385. && !has(finder, defaultMainType + 'Id')
  10386. && !has(finder, defaultMainType + 'Name')
  10387. ) {
  10388. finder[defaultMainType + 'Index'] = 0;
  10389. }
  10390. var result = {};
  10391. each$2(finder, function (value, key) {
  10392. var value = finder[key];
  10393. // Exclude 'dataIndex' and other illgal keys.
  10394. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10395. result[key] = value;
  10396. return;
  10397. }
  10398. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10399. var mainType = parsedKey[1];
  10400. var queryType = (parsedKey[2] || '').toLowerCase();
  10401. if (!mainType
  10402. || !queryType
  10403. || value == null
  10404. || (queryType === 'index' && value === 'none')
  10405. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  10406. ) {
  10407. return;
  10408. }
  10409. var queryParam = {mainType: mainType};
  10410. if (queryType !== 'index' || value !== 'all') {
  10411. queryParam[queryType] = value;
  10412. }
  10413. var models = ecModel.queryComponents(queryParam);
  10414. result[mainType + 'Models'] = models;
  10415. result[mainType + 'Model'] = models[0];
  10416. });
  10417. return result;
  10418. }
  10419. function has(obj, prop) {
  10420. return obj && obj.hasOwnProperty(prop);
  10421. }
  10422. function setAttribute(dom, key, value) {
  10423. dom.setAttribute
  10424. ? dom.setAttribute(key, value)
  10425. : (dom[key] = value);
  10426. }
  10427. function getAttribute(dom, key) {
  10428. return dom.getAttribute
  10429. ? dom.getAttribute(key)
  10430. : dom[key];
  10431. }
  10432. function getTooltipRenderMode(renderModeOption) {
  10433. if (renderModeOption === 'auto') {
  10434. // Using html when `document` exists, use richText otherwise
  10435. return env$1.domSupported ? 'html' : 'richText';
  10436. }
  10437. else {
  10438. return renderModeOption || 'html';
  10439. }
  10440. }
  10441. /**
  10442. * Group a list by key.
  10443. *
  10444. * @param {Array} array
  10445. * @param {Function} getKey
  10446. * param {*} Array item
  10447. * return {string} key
  10448. * @return {Object} Result
  10449. * {Array}: keys,
  10450. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10451. */
  10452. /*
  10453. * Licensed to the Apache Software Foundation (ASF) under one
  10454. * or more contributor license agreements. See the NOTICE file
  10455. * distributed with this work for additional information
  10456. * regarding copyright ownership. The ASF licenses this file
  10457. * to you under the Apache License, Version 2.0 (the
  10458. * "License"); you may not use this file except in compliance
  10459. * with the License. You may obtain a copy of the License at
  10460. *
  10461. * http://www.apache.org/licenses/LICENSE-2.0
  10462. *
  10463. * Unless required by applicable law or agreed to in writing,
  10464. * software distributed under the License is distributed on an
  10465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10466. * KIND, either express or implied. See the License for the
  10467. * specific language governing permissions and limitations
  10468. * under the License.
  10469. */
  10470. var TYPE_DELIMITER = '.';
  10471. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10472. /**
  10473. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10474. * @public
  10475. */
  10476. function parseClassType$1(componentType) {
  10477. var ret = {main: '', sub: ''};
  10478. if (componentType) {
  10479. componentType = componentType.split(TYPE_DELIMITER);
  10480. ret.main = componentType[0] || '';
  10481. ret.sub = componentType[1] || '';
  10482. }
  10483. return ret;
  10484. }
  10485. /**
  10486. * @public
  10487. */
  10488. function checkClassType(componentType) {
  10489. assert$1(
  10490. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10491. 'componentType "' + componentType + '" illegal'
  10492. );
  10493. }
  10494. /**
  10495. * @public
  10496. */
  10497. function enableClassExtend(RootClass, mandatoryMethods) {
  10498. RootClass.$constructor = RootClass;
  10499. RootClass.extend = function (proto) {
  10500. if (__DEV__) {
  10501. each$1(mandatoryMethods, function (method) {
  10502. if (!proto[method]) {
  10503. console.warn(
  10504. 'Method `' + method + '` should be implemented'
  10505. + (proto.type ? ' in ' + proto.type : '') + '.'
  10506. );
  10507. }
  10508. });
  10509. }
  10510. var superClass = this;
  10511. var ExtendedClass = function () {
  10512. if (!proto.$constructor) {
  10513. superClass.apply(this, arguments);
  10514. }
  10515. else {
  10516. proto.$constructor.apply(this, arguments);
  10517. }
  10518. };
  10519. extend(ExtendedClass.prototype, proto);
  10520. ExtendedClass.extend = this.extend;
  10521. ExtendedClass.superCall = superCall;
  10522. ExtendedClass.superApply = superApply;
  10523. inherits(ExtendedClass, this);
  10524. ExtendedClass.superClass = superClass;
  10525. return ExtendedClass;
  10526. };
  10527. }
  10528. var classBase = 0;
  10529. /**
  10530. * Can not use instanceof, consider different scope by
  10531. * cross domain or es module import in ec extensions.
  10532. * Mount a method "isInstance()" to Clz.
  10533. */
  10534. function enableClassCheck(Clz) {
  10535. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10536. Clz.prototype[classAttr] = true;
  10537. if (__DEV__) {
  10538. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10539. }
  10540. Clz.isInstance = function (obj) {
  10541. return !!(obj && obj[classAttr]);
  10542. };
  10543. }
  10544. // superCall should have class info, which can not be fetch from 'this'.
  10545. // Consider this case:
  10546. // class A has method f,
  10547. // class B inherits class A, overrides method f, f call superApply('f'),
  10548. // class C inherits class B, do not overrides method f,
  10549. // then when method of class C is called, dead loop occured.
  10550. function superCall(context, methodName) {
  10551. var args = slice(arguments, 2);
  10552. return this.superClass.prototype[methodName].apply(context, args);
  10553. }
  10554. function superApply(context, methodName, args) {
  10555. return this.superClass.prototype[methodName].apply(context, args);
  10556. }
  10557. /**
  10558. * @param {Object} entity
  10559. * @param {Object} options
  10560. * @param {boolean} [options.registerWhenExtend]
  10561. * @public
  10562. */
  10563. function enableClassManagement(entity, options) {
  10564. options = options || {};
  10565. /**
  10566. * Component model classes
  10567. * key: componentType,
  10568. * value:
  10569. * componentClass, when componentType is 'xxx'
  10570. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10571. * @type {Object}
  10572. */
  10573. var storage = {};
  10574. entity.registerClass = function (Clazz, componentType) {
  10575. if (componentType) {
  10576. checkClassType(componentType);
  10577. componentType = parseClassType$1(componentType);
  10578. if (!componentType.sub) {
  10579. if (__DEV__) {
  10580. if (storage[componentType.main]) {
  10581. console.warn(componentType.main + ' exists.');
  10582. }
  10583. }
  10584. storage[componentType.main] = Clazz;
  10585. }
  10586. else if (componentType.sub !== IS_CONTAINER) {
  10587. var container = makeContainer(componentType);
  10588. container[componentType.sub] = Clazz;
  10589. }
  10590. }
  10591. return Clazz;
  10592. };
  10593. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10594. var Clazz = storage[componentMainType];
  10595. if (Clazz && Clazz[IS_CONTAINER]) {
  10596. Clazz = subType ? Clazz[subType] : null;
  10597. }
  10598. if (throwWhenNotFound && !Clazz) {
  10599. throw new Error(
  10600. !subType
  10601. ? componentMainType + '.' + 'type should be specified.'
  10602. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10603. );
  10604. }
  10605. return Clazz;
  10606. };
  10607. entity.getClassesByMainType = function (componentType) {
  10608. componentType = parseClassType$1(componentType);
  10609. var result = [];
  10610. var obj = storage[componentType.main];
  10611. if (obj && obj[IS_CONTAINER]) {
  10612. each$1(obj, function (o, type) {
  10613. type !== IS_CONTAINER && result.push(o);
  10614. });
  10615. }
  10616. else {
  10617. result.push(obj);
  10618. }
  10619. return result;
  10620. };
  10621. entity.hasClass = function (componentType) {
  10622. // Just consider componentType.main.
  10623. componentType = parseClassType$1(componentType);
  10624. return !!storage[componentType.main];
  10625. };
  10626. /**
  10627. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10628. */
  10629. entity.getAllClassMainTypes = function () {
  10630. var types = [];
  10631. each$1(storage, function (obj, type) {
  10632. types.push(type);
  10633. });
  10634. return types;
  10635. };
  10636. /**
  10637. * If a main type is container and has sub types
  10638. * @param {string} mainType
  10639. * @return {boolean}
  10640. */
  10641. entity.hasSubTypes = function (componentType) {
  10642. componentType = parseClassType$1(componentType);
  10643. var obj = storage[componentType.main];
  10644. return obj && obj[IS_CONTAINER];
  10645. };
  10646. entity.parseClassType = parseClassType$1;
  10647. function makeContainer(componentType) {
  10648. var container = storage[componentType.main];
  10649. if (!container || !container[IS_CONTAINER]) {
  10650. container = storage[componentType.main] = {};
  10651. container[IS_CONTAINER] = true;
  10652. }
  10653. return container;
  10654. }
  10655. if (options.registerWhenExtend) {
  10656. var originalExtend = entity.extend;
  10657. if (originalExtend) {
  10658. entity.extend = function (proto) {
  10659. var ExtendedClass = originalExtend.call(this, proto);
  10660. return entity.registerClass(ExtendedClass, proto.type);
  10661. };
  10662. }
  10663. }
  10664. return entity;
  10665. }
  10666. /**
  10667. * @param {string|Array.<string>} properties
  10668. */
  10669. /*
  10670. * Licensed to the Apache Software Foundation (ASF) under one
  10671. * or more contributor license agreements. See the NOTICE file
  10672. * distributed with this work for additional information
  10673. * regarding copyright ownership. The ASF licenses this file
  10674. * to you under the Apache License, Version 2.0 (the
  10675. * "License"); you may not use this file except in compliance
  10676. * with the License. You may obtain a copy of the License at
  10677. *
  10678. * http://www.apache.org/licenses/LICENSE-2.0
  10679. *
  10680. * Unless required by applicable law or agreed to in writing,
  10681. * software distributed under the License is distributed on an
  10682. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10683. * KIND, either express or implied. See the License for the
  10684. * specific language governing permissions and limitations
  10685. * under the License.
  10686. */
  10687. // TODO Parse shadow style
  10688. // TODO Only shallow path support
  10689. var makeStyleMapper = function (properties) {
  10690. // Normalize
  10691. for (var i = 0; i < properties.length; i++) {
  10692. if (!properties[i][1]) {
  10693. properties[i][1] = properties[i][0];
  10694. }
  10695. }
  10696. return function (model, excludes, includes) {
  10697. var style = {};
  10698. for (var i = 0; i < properties.length; i++) {
  10699. var propName = properties[i][1];
  10700. if ((excludes && indexOf(excludes, propName) >= 0)
  10701. || (includes && indexOf(includes, propName) < 0)
  10702. ) {
  10703. continue;
  10704. }
  10705. var val = model.getShallow(propName);
  10706. if (val != null) {
  10707. style[properties[i][0]] = val;
  10708. }
  10709. }
  10710. return style;
  10711. };
  10712. };
  10713. /*
  10714. * Licensed to the Apache Software Foundation (ASF) under one
  10715. * or more contributor license agreements. See the NOTICE file
  10716. * distributed with this work for additional information
  10717. * regarding copyright ownership. The ASF licenses this file
  10718. * to you under the Apache License, Version 2.0 (the
  10719. * "License"); you may not use this file except in compliance
  10720. * with the License. You may obtain a copy of the License at
  10721. *
  10722. * http://www.apache.org/licenses/LICENSE-2.0
  10723. *
  10724. * Unless required by applicable law or agreed to in writing,
  10725. * software distributed under the License is distributed on an
  10726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10727. * KIND, either express or implied. See the License for the
  10728. * specific language governing permissions and limitations
  10729. * under the License.
  10730. */
  10731. var getLineStyle = makeStyleMapper(
  10732. [
  10733. ['lineWidth', 'width'],
  10734. ['stroke', 'color'],
  10735. ['opacity'],
  10736. ['shadowBlur'],
  10737. ['shadowOffsetX'],
  10738. ['shadowOffsetY'],
  10739. ['shadowColor']
  10740. ]
  10741. );
  10742. var lineStyleMixin = {
  10743. getLineStyle: function (excludes) {
  10744. var style = getLineStyle(this, excludes);
  10745. // Always set lineDash whether dashed, otherwise we can not
  10746. // erase the previous style when assigning to el.style.
  10747. style.lineDash = this.getLineDash(style.lineWidth);
  10748. return style;
  10749. },
  10750. getLineDash: function (lineWidth) {
  10751. if (lineWidth == null) {
  10752. lineWidth = 1;
  10753. }
  10754. var lineType = this.get('type');
  10755. var dotSize = Math.max(lineWidth, 2);
  10756. var dashSize = lineWidth * 4;
  10757. return (lineType === 'solid' || lineType == null)
  10758. // Use `false` but not `null` for the solid line here, because `null` might be
  10759. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  10760. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  10761. // `lineDash` gotten form the latter one is not able to erase that from the former
  10762. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  10763. ? false
  10764. : lineType === 'dashed'
  10765. ? [dashSize, dashSize]
  10766. : [dotSize, dotSize];
  10767. }
  10768. };
  10769. /*
  10770. * Licensed to the Apache Software Foundation (ASF) under one
  10771. * or more contributor license agreements. See the NOTICE file
  10772. * distributed with this work for additional information
  10773. * regarding copyright ownership. The ASF licenses this file
  10774. * to you under the Apache License, Version 2.0 (the
  10775. * "License"); you may not use this file except in compliance
  10776. * with the License. You may obtain a copy of the License at
  10777. *
  10778. * http://www.apache.org/licenses/LICENSE-2.0
  10779. *
  10780. * Unless required by applicable law or agreed to in writing,
  10781. * software distributed under the License is distributed on an
  10782. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10783. * KIND, either express or implied. See the License for the
  10784. * specific language governing permissions and limitations
  10785. * under the License.
  10786. */
  10787. var getAreaStyle = makeStyleMapper(
  10788. [
  10789. ['fill', 'color'],
  10790. ['shadowBlur'],
  10791. ['shadowOffsetX'],
  10792. ['shadowOffsetY'],
  10793. ['opacity'],
  10794. ['shadowColor']
  10795. ]
  10796. );
  10797. var areaStyleMixin = {
  10798. getAreaStyle: function (excludes, includes) {
  10799. return getAreaStyle(this, excludes, includes);
  10800. }
  10801. };
  10802. /**
  10803. * 曲线辅助模块
  10804. * @module zrender/core/curve
  10805. * @author pissang(https://www.github.com/pissang)
  10806. */
  10807. var mathPow = Math.pow;
  10808. var mathSqrt$2 = Math.sqrt;
  10809. var EPSILON$1 = 1e-8;
  10810. var EPSILON_NUMERIC = 1e-4;
  10811. var THREE_SQRT = mathSqrt$2(3);
  10812. var ONE_THIRD = 1 / 3;
  10813. // 临时变量
  10814. var _v0 = create();
  10815. var _v1 = create();
  10816. var _v2 = create();
  10817. function isAroundZero(val) {
  10818. return val > -EPSILON$1 && val < EPSILON$1;
  10819. }
  10820. function isNotAroundZero$1(val) {
  10821. return val > EPSILON$1 || val < -EPSILON$1;
  10822. }
  10823. /**
  10824. * 计算三次贝塞尔值
  10825. * @memberOf module:zrender/core/curve
  10826. * @param {number} p0
  10827. * @param {number} p1
  10828. * @param {number} p2
  10829. * @param {number} p3
  10830. * @param {number} t
  10831. * @return {number}
  10832. */
  10833. function cubicAt(p0, p1, p2, p3, t) {
  10834. var onet = 1 - t;
  10835. return onet * onet * (onet * p0 + 3 * t * p1)
  10836. + t * t * (t * p3 + 3 * onet * p2);
  10837. }
  10838. /**
  10839. * 计算三次贝塞尔导数值
  10840. * @memberOf module:zrender/core/curve
  10841. * @param {number} p0
  10842. * @param {number} p1
  10843. * @param {number} p2
  10844. * @param {number} p3
  10845. * @param {number} t
  10846. * @return {number}
  10847. */
  10848. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10849. var onet = 1 - t;
  10850. return 3 * (
  10851. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10852. + (p3 - p2) * t * t
  10853. );
  10854. }
  10855. /**
  10856. * 计算三次贝塞尔方程根,使用盛金公式
  10857. * @memberOf module:zrender/core/curve
  10858. * @param {number} p0
  10859. * @param {number} p1
  10860. * @param {number} p2
  10861. * @param {number} p3
  10862. * @param {number} val
  10863. * @param {Array.<number>} roots
  10864. * @return {number} 有效根数目
  10865. */
  10866. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10867. // Evaluate roots of cubic functions
  10868. var a = p3 + 3 * (p1 - p2) - p0;
  10869. var b = 3 * (p2 - p1 * 2 + p0);
  10870. var c = 3 * (p1 - p0);
  10871. var d = p0 - val;
  10872. var A = b * b - 3 * a * c;
  10873. var B = b * c - 9 * a * d;
  10874. var C = c * c - 3 * b * d;
  10875. var n = 0;
  10876. if (isAroundZero(A) && isAroundZero(B)) {
  10877. if (isAroundZero(b)) {
  10878. roots[0] = 0;
  10879. }
  10880. else {
  10881. var t1 = -c / b; //t1, t2, t3, b is not zero
  10882. if (t1 >= 0 && t1 <= 1) {
  10883. roots[n++] = t1;
  10884. }
  10885. }
  10886. }
  10887. else {
  10888. var disc = B * B - 4 * A * C;
  10889. if (isAroundZero(disc)) {
  10890. var K = B / A;
  10891. var t1 = -b / a + K; // t1, a is not zero
  10892. var t2 = -K / 2; // t2, t3
  10893. if (t1 >= 0 && t1 <= 1) {
  10894. roots[n++] = t1;
  10895. }
  10896. if (t2 >= 0 && t2 <= 1) {
  10897. roots[n++] = t2;
  10898. }
  10899. }
  10900. else if (disc > 0) {
  10901. var discSqrt = mathSqrt$2(disc);
  10902. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10903. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10904. if (Y1 < 0) {
  10905. Y1 = -mathPow(-Y1, ONE_THIRD);
  10906. }
  10907. else {
  10908. Y1 = mathPow(Y1, ONE_THIRD);
  10909. }
  10910. if (Y2 < 0) {
  10911. Y2 = -mathPow(-Y2, ONE_THIRD);
  10912. }
  10913. else {
  10914. Y2 = mathPow(Y2, ONE_THIRD);
  10915. }
  10916. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10917. if (t1 >= 0 && t1 <= 1) {
  10918. roots[n++] = t1;
  10919. }
  10920. }
  10921. else {
  10922. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10923. var theta = Math.acos(T) / 3;
  10924. var ASqrt = mathSqrt$2(A);
  10925. var tmp = Math.cos(theta);
  10926. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10927. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10928. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10929. if (t1 >= 0 && t1 <= 1) {
  10930. roots[n++] = t1;
  10931. }
  10932. if (t2 >= 0 && t2 <= 1) {
  10933. roots[n++] = t2;
  10934. }
  10935. if (t3 >= 0 && t3 <= 1) {
  10936. roots[n++] = t3;
  10937. }
  10938. }
  10939. }
  10940. return n;
  10941. }
  10942. /**
  10943. * 计算三次贝塞尔方程极限值的位置
  10944. * @memberOf module:zrender/core/curve
  10945. * @param {number} p0
  10946. * @param {number} p1
  10947. * @param {number} p2
  10948. * @param {number} p3
  10949. * @param {Array.<number>} extrema
  10950. * @return {number} 有效数目
  10951. */
  10952. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10953. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10954. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10955. var c = 3 * p1 - 3 * p0;
  10956. var n = 0;
  10957. if (isAroundZero(a)) {
  10958. if (isNotAroundZero$1(b)) {
  10959. var t1 = -c / b;
  10960. if (t1 >= 0 && t1 <= 1) {
  10961. extrema[n++] = t1;
  10962. }
  10963. }
  10964. }
  10965. else {
  10966. var disc = b * b - 4 * a * c;
  10967. if (isAroundZero(disc)) {
  10968. extrema[0] = -b / (2 * a);
  10969. }
  10970. else if (disc > 0) {
  10971. var discSqrt = mathSqrt$2(disc);
  10972. var t1 = (-b + discSqrt) / (2 * a);
  10973. var t2 = (-b - discSqrt) / (2 * a);
  10974. if (t1 >= 0 && t1 <= 1) {
  10975. extrema[n++] = t1;
  10976. }
  10977. if (t2 >= 0 && t2 <= 1) {
  10978. extrema[n++] = t2;
  10979. }
  10980. }
  10981. }
  10982. return n;
  10983. }
  10984. /**
  10985. * 细分三次贝塞尔曲线
  10986. * @memberOf module:zrender/core/curve
  10987. * @param {number} p0
  10988. * @param {number} p1
  10989. * @param {number} p2
  10990. * @param {number} p3
  10991. * @param {number} t
  10992. * @param {Array.<number>} out
  10993. */
  10994. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10995. var p01 = (p1 - p0) * t + p0;
  10996. var p12 = (p2 - p1) * t + p1;
  10997. var p23 = (p3 - p2) * t + p2;
  10998. var p012 = (p12 - p01) * t + p01;
  10999. var p123 = (p23 - p12) * t + p12;
  11000. var p0123 = (p123 - p012) * t + p012;
  11001. // Seg0
  11002. out[0] = p0;
  11003. out[1] = p01;
  11004. out[2] = p012;
  11005. out[3] = p0123;
  11006. // Seg1
  11007. out[4] = p0123;
  11008. out[5] = p123;
  11009. out[6] = p23;
  11010. out[7] = p3;
  11011. }
  11012. /**
  11013. * 投射点到三次贝塞尔曲线上,返回投射距离。
  11014. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11015. * @param {number} x0
  11016. * @param {number} y0
  11017. * @param {number} x1
  11018. * @param {number} y1
  11019. * @param {number} x2
  11020. * @param {number} y2
  11021. * @param {number} x3
  11022. * @param {number} y3
  11023. * @param {number} x
  11024. * @param {number} y
  11025. * @param {Array.<number>} [out] 投射点
  11026. * @return {number}
  11027. */
  11028. function cubicProjectPoint(
  11029. x0, y0, x1, y1, x2, y2, x3, y3,
  11030. x, y, out
  11031. ) {
  11032. // http://pomax.github.io/bezierinfo/#projections
  11033. var t;
  11034. var interval = 0.005;
  11035. var d = Infinity;
  11036. var prev;
  11037. var next;
  11038. var d1;
  11039. var d2;
  11040. _v0[0] = x;
  11041. _v0[1] = y;
  11042. // 先粗略估计一下可能的最小距离的 t 值
  11043. // PENDING
  11044. for (var _t = 0; _t < 1; _t += 0.05) {
  11045. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  11046. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  11047. d1 = distSquare(_v0, _v1);
  11048. if (d1 < d) {
  11049. t = _t;
  11050. d = d1;
  11051. }
  11052. }
  11053. d = Infinity;
  11054. // At most 32 iteration
  11055. for (var i = 0; i < 32; i++) {
  11056. if (interval < EPSILON_NUMERIC) {
  11057. break;
  11058. }
  11059. prev = t - interval;
  11060. next = t + interval;
  11061. // t - interval
  11062. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  11063. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  11064. d1 = distSquare(_v1, _v0);
  11065. if (prev >= 0 && d1 < d) {
  11066. t = prev;
  11067. d = d1;
  11068. }
  11069. else {
  11070. // t + interval
  11071. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  11072. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  11073. d2 = distSquare(_v2, _v0);
  11074. if (next <= 1 && d2 < d) {
  11075. t = next;
  11076. d = d2;
  11077. }
  11078. else {
  11079. interval *= 0.5;
  11080. }
  11081. }
  11082. }
  11083. // t
  11084. if (out) {
  11085. out[0] = cubicAt(x0, x1, x2, x3, t);
  11086. out[1] = cubicAt(y0, y1, y2, y3, t);
  11087. }
  11088. // console.log(interval, i);
  11089. return mathSqrt$2(d);
  11090. }
  11091. /**
  11092. * 计算二次方贝塞尔值
  11093. * @param {number} p0
  11094. * @param {number} p1
  11095. * @param {number} p2
  11096. * @param {number} t
  11097. * @return {number}
  11098. */
  11099. function quadraticAt(p0, p1, p2, t) {
  11100. var onet = 1 - t;
  11101. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  11102. }
  11103. /**
  11104. * 计算二次方贝塞尔导数值
  11105. * @param {number} p0
  11106. * @param {number} p1
  11107. * @param {number} p2
  11108. * @param {number} t
  11109. * @return {number}
  11110. */
  11111. function quadraticDerivativeAt(p0, p1, p2, t) {
  11112. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  11113. }
  11114. /**
  11115. * 计算二次方贝塞尔方程根
  11116. * @param {number} p0
  11117. * @param {number} p1
  11118. * @param {number} p2
  11119. * @param {number} t
  11120. * @param {Array.<number>} roots
  11121. * @return {number} 有效根数目
  11122. */
  11123. function quadraticRootAt(p0, p1, p2, val, roots) {
  11124. var a = p0 - 2 * p1 + p2;
  11125. var b = 2 * (p1 - p0);
  11126. var c = p0 - val;
  11127. var n = 0;
  11128. if (isAroundZero(a)) {
  11129. if (isNotAroundZero$1(b)) {
  11130. var t1 = -c / b;
  11131. if (t1 >= 0 && t1 <= 1) {
  11132. roots[n++] = t1;
  11133. }
  11134. }
  11135. }
  11136. else {
  11137. var disc = b * b - 4 * a * c;
  11138. if (isAroundZero(disc)) {
  11139. var t1 = -b / (2 * a);
  11140. if (t1 >= 0 && t1 <= 1) {
  11141. roots[n++] = t1;
  11142. }
  11143. }
  11144. else if (disc > 0) {
  11145. var discSqrt = mathSqrt$2(disc);
  11146. var t1 = (-b + discSqrt) / (2 * a);
  11147. var t2 = (-b - discSqrt) / (2 * a);
  11148. if (t1 >= 0 && t1 <= 1) {
  11149. roots[n++] = t1;
  11150. }
  11151. if (t2 >= 0 && t2 <= 1) {
  11152. roots[n++] = t2;
  11153. }
  11154. }
  11155. }
  11156. return n;
  11157. }
  11158. /**
  11159. * 计算二次贝塞尔方程极限值
  11160. * @memberOf module:zrender/core/curve
  11161. * @param {number} p0
  11162. * @param {number} p1
  11163. * @param {number} p2
  11164. * @return {number}
  11165. */
  11166. function quadraticExtremum(p0, p1, p2) {
  11167. var divider = p0 + p2 - 2 * p1;
  11168. if (divider === 0) {
  11169. // p1 is center of p0 and p2
  11170. return 0.5;
  11171. }
  11172. else {
  11173. return (p0 - p1) / divider;
  11174. }
  11175. }
  11176. /**
  11177. * 细分二次贝塞尔曲线
  11178. * @memberOf module:zrender/core/curve
  11179. * @param {number} p0
  11180. * @param {number} p1
  11181. * @param {number} p2
  11182. * @param {number} t
  11183. * @param {Array.<number>} out
  11184. */
  11185. function quadraticSubdivide(p0, p1, p2, t, out) {
  11186. var p01 = (p1 - p0) * t + p0;
  11187. var p12 = (p2 - p1) * t + p1;
  11188. var p012 = (p12 - p01) * t + p01;
  11189. // Seg0
  11190. out[0] = p0;
  11191. out[1] = p01;
  11192. out[2] = p012;
  11193. // Seg1
  11194. out[3] = p012;
  11195. out[4] = p12;
  11196. out[5] = p2;
  11197. }
  11198. /**
  11199. * 投射点到二次贝塞尔曲线上,返回投射距离。
  11200. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  11201. * @param {number} x0
  11202. * @param {number} y0
  11203. * @param {number} x1
  11204. * @param {number} y1
  11205. * @param {number} x2
  11206. * @param {number} y2
  11207. * @param {number} x
  11208. * @param {number} y
  11209. * @param {Array.<number>} out 投射点
  11210. * @return {number}
  11211. */
  11212. function quadraticProjectPoint(
  11213. x0, y0, x1, y1, x2, y2,
  11214. x, y, out
  11215. ) {
  11216. // http://pomax.github.io/bezierinfo/#projections
  11217. var t;
  11218. var interval = 0.005;
  11219. var d = Infinity;
  11220. _v0[0] = x;
  11221. _v0[1] = y;
  11222. // 先粗略估计一下可能的最小距离的 t 值
  11223. // PENDING
  11224. for (var _t = 0; _t < 1; _t += 0.05) {
  11225. _v1[0] = quadraticAt(x0, x1, x2, _t);
  11226. _v1[1] = quadraticAt(y0, y1, y2, _t);
  11227. var d1 = distSquare(_v0, _v1);
  11228. if (d1 < d) {
  11229. t = _t;
  11230. d = d1;
  11231. }
  11232. }
  11233. d = Infinity;
  11234. // At most 32 iteration
  11235. for (var i = 0; i < 32; i++) {
  11236. if (interval < EPSILON_NUMERIC) {
  11237. break;
  11238. }
  11239. var prev = t - interval;
  11240. var next = t + interval;
  11241. // t - interval
  11242. _v1[0] = quadraticAt(x0, x1, x2, prev);
  11243. _v1[1] = quadraticAt(y0, y1, y2, prev);
  11244. var d1 = distSquare(_v1, _v0);
  11245. if (prev >= 0 && d1 < d) {
  11246. t = prev;
  11247. d = d1;
  11248. }
  11249. else {
  11250. // t + interval
  11251. _v2[0] = quadraticAt(x0, x1, x2, next);
  11252. _v2[1] = quadraticAt(y0, y1, y2, next);
  11253. var d2 = distSquare(_v2, _v0);
  11254. if (next <= 1 && d2 < d) {
  11255. t = next;
  11256. d = d2;
  11257. }
  11258. else {
  11259. interval *= 0.5;
  11260. }
  11261. }
  11262. }
  11263. // t
  11264. if (out) {
  11265. out[0] = quadraticAt(x0, x1, x2, t);
  11266. out[1] = quadraticAt(y0, y1, y2, t);
  11267. }
  11268. // console.log(interval, i);
  11269. return mathSqrt$2(d);
  11270. }
  11271. /**
  11272. * @author Yi Shen(https://github.com/pissang)
  11273. */
  11274. var mathMin$3 = Math.min;
  11275. var mathMax$3 = Math.max;
  11276. var mathSin$2 = Math.sin;
  11277. var mathCos$2 = Math.cos;
  11278. var PI2 = Math.PI * 2;
  11279. var start = create();
  11280. var end = create();
  11281. var extremity = create();
  11282. /**
  11283. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  11284. * @module zrender/core/bbox
  11285. * @param {Array<Object>} points 顶点数组
  11286. * @param {number} min
  11287. * @param {number} max
  11288. */
  11289. /**
  11290. * @memberOf module:zrender/core/bbox
  11291. * @param {number} x0
  11292. * @param {number} y0
  11293. * @param {number} x1
  11294. * @param {number} y1
  11295. * @param {Array.<number>} min
  11296. * @param {Array.<number>} max
  11297. */
  11298. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  11299. min$$1[0] = mathMin$3(x0, x1);
  11300. min$$1[1] = mathMin$3(y0, y1);
  11301. max$$1[0] = mathMax$3(x0, x1);
  11302. max$$1[1] = mathMax$3(y0, y1);
  11303. }
  11304. var xDim = [];
  11305. var yDim = [];
  11306. /**
  11307. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11308. * @memberOf module:zrender/core/bbox
  11309. * @param {number} x0
  11310. * @param {number} y0
  11311. * @param {number} x1
  11312. * @param {number} y1
  11313. * @param {number} x2
  11314. * @param {number} y2
  11315. * @param {number} x3
  11316. * @param {number} y3
  11317. * @param {Array.<number>} min
  11318. * @param {Array.<number>} max
  11319. */
  11320. function fromCubic(
  11321. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  11322. ) {
  11323. var cubicExtrema$$1 = cubicExtrema;
  11324. var cubicAt$$1 = cubicAt;
  11325. var i;
  11326. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11327. min$$1[0] = Infinity;
  11328. min$$1[1] = Infinity;
  11329. max$$1[0] = -Infinity;
  11330. max$$1[1] = -Infinity;
  11331. for (i = 0; i < n; i++) {
  11332. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11333. min$$1[0] = mathMin$3(x, min$$1[0]);
  11334. max$$1[0] = mathMax$3(x, max$$1[0]);
  11335. }
  11336. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11337. for (i = 0; i < n; i++) {
  11338. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11339. min$$1[1] = mathMin$3(y, min$$1[1]);
  11340. max$$1[1] = mathMax$3(y, max$$1[1]);
  11341. }
  11342. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11343. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11344. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11345. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11346. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11347. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11348. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11349. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11350. }
  11351. /**
  11352. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11353. * @memberOf module:zrender/core/bbox
  11354. * @param {number} x0
  11355. * @param {number} y0
  11356. * @param {number} x1
  11357. * @param {number} y1
  11358. * @param {number} x2
  11359. * @param {number} y2
  11360. * @param {Array.<number>} min
  11361. * @param {Array.<number>} max
  11362. */
  11363. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11364. var quadraticExtremum$$1 = quadraticExtremum;
  11365. var quadraticAt$$1 = quadraticAt;
  11366. // Find extremities, where derivative in x dim or y dim is zero
  11367. var tx =
  11368. mathMax$3(
  11369. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  11370. );
  11371. var ty =
  11372. mathMax$3(
  11373. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  11374. );
  11375. var x = quadraticAt$$1(x0, x1, x2, tx);
  11376. var y = quadraticAt$$1(y0, y1, y2, ty);
  11377. min$$1[0] = mathMin$3(x0, x2, x);
  11378. min$$1[1] = mathMin$3(y0, y2, y);
  11379. max$$1[0] = mathMax$3(x0, x2, x);
  11380. max$$1[1] = mathMax$3(y0, y2, y);
  11381. }
  11382. /**
  11383. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11384. * @method
  11385. * @memberOf module:zrender/core/bbox
  11386. * @param {number} x
  11387. * @param {number} y
  11388. * @param {number} rx
  11389. * @param {number} ry
  11390. * @param {number} startAngle
  11391. * @param {number} endAngle
  11392. * @param {number} anticlockwise
  11393. * @param {Array.<number>} min
  11394. * @param {Array.<number>} max
  11395. */
  11396. function fromArc(
  11397. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  11398. ) {
  11399. var vec2Min = min;
  11400. var vec2Max = max;
  11401. var diff = Math.abs(startAngle - endAngle);
  11402. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11403. // Is a circle
  11404. min$$1[0] = x - rx;
  11405. min$$1[1] = y - ry;
  11406. max$$1[0] = x + rx;
  11407. max$$1[1] = y + ry;
  11408. return;
  11409. }
  11410. start[0] = mathCos$2(startAngle) * rx + x;
  11411. start[1] = mathSin$2(startAngle) * ry + y;
  11412. end[0] = mathCos$2(endAngle) * rx + x;
  11413. end[1] = mathSin$2(endAngle) * ry + y;
  11414. vec2Min(min$$1, start, end);
  11415. vec2Max(max$$1, start, end);
  11416. // Thresh to [0, Math.PI * 2]
  11417. startAngle = startAngle % (PI2);
  11418. if (startAngle < 0) {
  11419. startAngle = startAngle + PI2;
  11420. }
  11421. endAngle = endAngle % (PI2);
  11422. if (endAngle < 0) {
  11423. endAngle = endAngle + PI2;
  11424. }
  11425. if (startAngle > endAngle && !anticlockwise) {
  11426. endAngle += PI2;
  11427. }
  11428. else if (startAngle < endAngle && anticlockwise) {
  11429. startAngle += PI2;
  11430. }
  11431. if (anticlockwise) {
  11432. var tmp = endAngle;
  11433. endAngle = startAngle;
  11434. startAngle = tmp;
  11435. }
  11436. // var number = 0;
  11437. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11438. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11439. if (angle > startAngle) {
  11440. extremity[0] = mathCos$2(angle) * rx + x;
  11441. extremity[1] = mathSin$2(angle) * ry + y;
  11442. vec2Min(min$$1, extremity, min$$1);
  11443. vec2Max(max$$1, extremity, max$$1);
  11444. }
  11445. }
  11446. }
  11447. /**
  11448. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11449. * 可以用于 isInsidePath 判断以及获取boundingRect
  11450. *
  11451. * @module zrender/core/PathProxy
  11452. * @author Yi Shen (http://www.github.com/pissang)
  11453. */
  11454. // TODO getTotalLength, getPointAtLength
  11455. /* global Float32Array */
  11456. var CMD = {
  11457. M: 1,
  11458. L: 2,
  11459. C: 3,
  11460. Q: 4,
  11461. A: 5,
  11462. Z: 6,
  11463. // Rect
  11464. R: 7
  11465. };
  11466. // var CMD_MEM_SIZE = {
  11467. // M: 3,
  11468. // L: 3,
  11469. // C: 7,
  11470. // Q: 5,
  11471. // A: 9,
  11472. // R: 5,
  11473. // Z: 1
  11474. // };
  11475. var min$1 = [];
  11476. var max$1 = [];
  11477. var min2 = [];
  11478. var max2 = [];
  11479. var mathMin$2 = Math.min;
  11480. var mathMax$2 = Math.max;
  11481. var mathCos$1 = Math.cos;
  11482. var mathSin$1 = Math.sin;
  11483. var mathSqrt$1 = Math.sqrt;
  11484. var mathAbs = Math.abs;
  11485. var hasTypedArray = typeof Float32Array !== 'undefined';
  11486. /**
  11487. * @alias module:zrender/core/PathProxy
  11488. * @constructor
  11489. */
  11490. var PathProxy = function (notSaveData) {
  11491. this._saveData = !(notSaveData || false);
  11492. if (this._saveData) {
  11493. /**
  11494. * Path data. Stored as flat array
  11495. * @type {Array.<Object>}
  11496. */
  11497. this.data = [];
  11498. }
  11499. this._ctx = null;
  11500. };
  11501. /**
  11502. * 快速计算Path包围盒(并不是最小包围盒)
  11503. * @return {Object}
  11504. */
  11505. PathProxy.prototype = {
  11506. constructor: PathProxy,
  11507. _xi: 0,
  11508. _yi: 0,
  11509. _x0: 0,
  11510. _y0: 0,
  11511. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11512. _ux: 0,
  11513. _uy: 0,
  11514. _len: 0,
  11515. _lineDash: null,
  11516. _dashOffset: 0,
  11517. _dashIdx: 0,
  11518. _dashSum: 0,
  11519. /**
  11520. * @readOnly
  11521. */
  11522. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11523. // Compat. Previously there is no segmentIgnoreThreshold.
  11524. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11525. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11526. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11527. },
  11528. getContext: function () {
  11529. return this._ctx;
  11530. },
  11531. /**
  11532. * @param {CanvasRenderingContext2D} ctx
  11533. * @return {module:zrender/core/PathProxy}
  11534. */
  11535. beginPath: function (ctx) {
  11536. this._ctx = ctx;
  11537. ctx && ctx.beginPath();
  11538. ctx && (this.dpr = ctx.dpr);
  11539. // Reset
  11540. if (this._saveData) {
  11541. this._len = 0;
  11542. }
  11543. if (this._lineDash) {
  11544. this._lineDash = null;
  11545. this._dashOffset = 0;
  11546. }
  11547. return this;
  11548. },
  11549. /**
  11550. * @param {number} x
  11551. * @param {number} y
  11552. * @return {module:zrender/core/PathProxy}
  11553. */
  11554. moveTo: function (x, y) {
  11555. this.addData(CMD.M, x, y);
  11556. this._ctx && this._ctx.moveTo(x, y);
  11557. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11558. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11559. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11560. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11561. this._x0 = x;
  11562. this._y0 = y;
  11563. this._xi = x;
  11564. this._yi = y;
  11565. return this;
  11566. },
  11567. /**
  11568. * @param {number} x
  11569. * @param {number} y
  11570. * @return {module:zrender/core/PathProxy}
  11571. */
  11572. lineTo: function (x, y) {
  11573. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11574. || mathAbs(y - this._yi) > this._uy
  11575. // Force draw the first segment
  11576. || this._len < 5;
  11577. this.addData(CMD.L, x, y);
  11578. if (this._ctx && exceedUnit) {
  11579. this._needsDash() ? this._dashedLineTo(x, y)
  11580. : this._ctx.lineTo(x, y);
  11581. }
  11582. if (exceedUnit) {
  11583. this._xi = x;
  11584. this._yi = y;
  11585. }
  11586. return this;
  11587. },
  11588. /**
  11589. * @param {number} x1
  11590. * @param {number} y1
  11591. * @param {number} x2
  11592. * @param {number} y2
  11593. * @param {number} x3
  11594. * @param {number} y3
  11595. * @return {module:zrender/core/PathProxy}
  11596. */
  11597. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11598. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11599. if (this._ctx) {
  11600. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11601. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11602. }
  11603. this._xi = x3;
  11604. this._yi = y3;
  11605. return this;
  11606. },
  11607. /**
  11608. * @param {number} x1
  11609. * @param {number} y1
  11610. * @param {number} x2
  11611. * @param {number} y2
  11612. * @return {module:zrender/core/PathProxy}
  11613. */
  11614. quadraticCurveTo: function (x1, y1, x2, y2) {
  11615. this.addData(CMD.Q, x1, y1, x2, y2);
  11616. if (this._ctx) {
  11617. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11618. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11619. }
  11620. this._xi = x2;
  11621. this._yi = y2;
  11622. return this;
  11623. },
  11624. /**
  11625. * @param {number} cx
  11626. * @param {number} cy
  11627. * @param {number} r
  11628. * @param {number} startAngle
  11629. * @param {number} endAngle
  11630. * @param {boolean} anticlockwise
  11631. * @return {module:zrender/core/PathProxy}
  11632. */
  11633. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11634. this.addData(
  11635. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11636. );
  11637. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11638. this._xi = mathCos$1(endAngle) * r + cx;
  11639. this._yi = mathSin$1(endAngle) * r + cy;
  11640. return this;
  11641. },
  11642. // TODO
  11643. arcTo: function (x1, y1, x2, y2, radius) {
  11644. if (this._ctx) {
  11645. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11646. }
  11647. return this;
  11648. },
  11649. // TODO
  11650. rect: function (x, y, w, h) {
  11651. this._ctx && this._ctx.rect(x, y, w, h);
  11652. this.addData(CMD.R, x, y, w, h);
  11653. return this;
  11654. },
  11655. /**
  11656. * @return {module:zrender/core/PathProxy}
  11657. */
  11658. closePath: function () {
  11659. this.addData(CMD.Z);
  11660. var ctx = this._ctx;
  11661. var x0 = this._x0;
  11662. var y0 = this._y0;
  11663. if (ctx) {
  11664. this._needsDash() && this._dashedLineTo(x0, y0);
  11665. ctx.closePath();
  11666. }
  11667. this._xi = x0;
  11668. this._yi = y0;
  11669. return this;
  11670. },
  11671. /**
  11672. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11673. * stroke 同样
  11674. * @param {CanvasRenderingContext2D} ctx
  11675. * @return {module:zrender/core/PathProxy}
  11676. */
  11677. fill: function (ctx) {
  11678. ctx && ctx.fill();
  11679. this.toStatic();
  11680. },
  11681. /**
  11682. * @param {CanvasRenderingContext2D} ctx
  11683. * @return {module:zrender/core/PathProxy}
  11684. */
  11685. stroke: function (ctx) {
  11686. ctx && ctx.stroke();
  11687. this.toStatic();
  11688. },
  11689. /**
  11690. * 必须在其它绘制命令前调用
  11691. * Must be invoked before all other path drawing methods
  11692. * @return {module:zrender/core/PathProxy}
  11693. */
  11694. setLineDash: function (lineDash) {
  11695. if (lineDash instanceof Array) {
  11696. this._lineDash = lineDash;
  11697. this._dashIdx = 0;
  11698. var lineDashSum = 0;
  11699. for (var i = 0; i < lineDash.length; i++) {
  11700. lineDashSum += lineDash[i];
  11701. }
  11702. this._dashSum = lineDashSum;
  11703. }
  11704. return this;
  11705. },
  11706. /**
  11707. * 必须在其它绘制命令前调用
  11708. * Must be invoked before all other path drawing methods
  11709. * @return {module:zrender/core/PathProxy}
  11710. */
  11711. setLineDashOffset: function (offset) {
  11712. this._dashOffset = offset;
  11713. return this;
  11714. },
  11715. /**
  11716. *
  11717. * @return {boolean}
  11718. */
  11719. len: function () {
  11720. return this._len;
  11721. },
  11722. /**
  11723. * 直接设置 Path 数据
  11724. */
  11725. setData: function (data) {
  11726. var len$$1 = data.length;
  11727. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11728. this.data = new Float32Array(len$$1);
  11729. }
  11730. for (var i = 0; i < len$$1; i++) {
  11731. this.data[i] = data[i];
  11732. }
  11733. this._len = len$$1;
  11734. },
  11735. /**
  11736. * 添加子路径
  11737. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11738. */
  11739. appendPath: function (path) {
  11740. if (!(path instanceof Array)) {
  11741. path = [path];
  11742. }
  11743. var len$$1 = path.length;
  11744. var appendSize = 0;
  11745. var offset = this._len;
  11746. for (var i = 0; i < len$$1; i++) {
  11747. appendSize += path[i].len();
  11748. }
  11749. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11750. this.data = new Float32Array(offset + appendSize);
  11751. }
  11752. for (var i = 0; i < len$$1; i++) {
  11753. var appendPathData = path[i].data;
  11754. for (var k = 0; k < appendPathData.length; k++) {
  11755. this.data[offset++] = appendPathData[k];
  11756. }
  11757. }
  11758. this._len = offset;
  11759. },
  11760. /**
  11761. * 填充 Path 数据。
  11762. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11763. */
  11764. addData: function (cmd) {
  11765. if (!this._saveData) {
  11766. return;
  11767. }
  11768. var data = this.data;
  11769. if (this._len + arguments.length > data.length) {
  11770. // 因为之前的数组已经转换成静态的 Float32Array
  11771. // 所以不够用时需要扩展一个新的动态数组
  11772. this._expandData();
  11773. data = this.data;
  11774. }
  11775. for (var i = 0; i < arguments.length; i++) {
  11776. data[this._len++] = arguments[i];
  11777. }
  11778. this._prevCmd = cmd;
  11779. },
  11780. _expandData: function () {
  11781. // Only if data is Float32Array
  11782. if (!(this.data instanceof Array)) {
  11783. var newData = [];
  11784. for (var i = 0; i < this._len; i++) {
  11785. newData[i] = this.data[i];
  11786. }
  11787. this.data = newData;
  11788. }
  11789. },
  11790. /**
  11791. * If needs js implemented dashed line
  11792. * @return {boolean}
  11793. * @private
  11794. */
  11795. _needsDash: function () {
  11796. return this._lineDash;
  11797. },
  11798. _dashedLineTo: function (x1, y1) {
  11799. var dashSum = this._dashSum;
  11800. var offset = this._dashOffset;
  11801. var lineDash = this._lineDash;
  11802. var ctx = this._ctx;
  11803. var x0 = this._xi;
  11804. var y0 = this._yi;
  11805. var dx = x1 - x0;
  11806. var dy = y1 - y0;
  11807. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11808. var x = x0;
  11809. var y = y0;
  11810. var dash;
  11811. var nDash = lineDash.length;
  11812. var idx;
  11813. dx /= dist$$1;
  11814. dy /= dist$$1;
  11815. if (offset < 0) {
  11816. // Convert to positive offset
  11817. offset = dashSum + offset;
  11818. }
  11819. offset %= dashSum;
  11820. x -= offset * dx;
  11821. y -= offset * dy;
  11822. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11823. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11824. idx = this._dashIdx;
  11825. dash = lineDash[idx];
  11826. x += dx * dash;
  11827. y += dy * dash;
  11828. this._dashIdx = (idx + 1) % nDash;
  11829. // Skip positive offset
  11830. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11831. continue;
  11832. }
  11833. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11834. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11835. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11836. );
  11837. }
  11838. // Offset for next lineTo
  11839. dx = x - x1;
  11840. dy = y - y1;
  11841. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11842. },
  11843. // Not accurate dashed line to
  11844. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11845. var dashSum = this._dashSum;
  11846. var offset = this._dashOffset;
  11847. var lineDash = this._lineDash;
  11848. var ctx = this._ctx;
  11849. var x0 = this._xi;
  11850. var y0 = this._yi;
  11851. var t;
  11852. var dx;
  11853. var dy;
  11854. var cubicAt$$1 = cubicAt;
  11855. var bezierLen = 0;
  11856. var idx = this._dashIdx;
  11857. var nDash = lineDash.length;
  11858. var x;
  11859. var y;
  11860. var tmpLen = 0;
  11861. if (offset < 0) {
  11862. // Convert to positive offset
  11863. offset = dashSum + offset;
  11864. }
  11865. offset %= dashSum;
  11866. // Bezier approx length
  11867. for (t = 0; t < 1; t += 0.1) {
  11868. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11869. - cubicAt$$1(x0, x1, x2, x3, t);
  11870. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11871. - cubicAt$$1(y0, y1, y2, y3, t);
  11872. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11873. }
  11874. // Find idx after add offset
  11875. for (; idx < nDash; idx++) {
  11876. tmpLen += lineDash[idx];
  11877. if (tmpLen > offset) {
  11878. break;
  11879. }
  11880. }
  11881. t = (tmpLen - offset) / bezierLen;
  11882. while (t <= 1) {
  11883. x = cubicAt$$1(x0, x1, x2, x3, t);
  11884. y = cubicAt$$1(y0, y1, y2, y3, t);
  11885. // Use line to approximate dashed bezier
  11886. // Bad result if dash is long
  11887. idx % 2 ? ctx.moveTo(x, y)
  11888. : ctx.lineTo(x, y);
  11889. t += lineDash[idx] / bezierLen;
  11890. idx = (idx + 1) % nDash;
  11891. }
  11892. // Finish the last segment and calculate the new offset
  11893. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11894. dx = x3 - x;
  11895. dy = y3 - y;
  11896. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11897. },
  11898. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11899. // Convert quadratic to cubic using degree elevation
  11900. var x3 = x2;
  11901. var y3 = y2;
  11902. x2 = (x2 + 2 * x1) / 3;
  11903. y2 = (y2 + 2 * y1) / 3;
  11904. x1 = (this._xi + 2 * x1) / 3;
  11905. y1 = (this._yi + 2 * y1) / 3;
  11906. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11907. },
  11908. /**
  11909. * 转成静态的 Float32Array 减少堆内存占用
  11910. * Convert dynamic array to static Float32Array
  11911. */
  11912. toStatic: function () {
  11913. var data = this.data;
  11914. if (data instanceof Array) {
  11915. data.length = this._len;
  11916. if (hasTypedArray) {
  11917. this.data = new Float32Array(data);
  11918. }
  11919. }
  11920. },
  11921. /**
  11922. * @return {module:zrender/core/BoundingRect}
  11923. */
  11924. getBoundingRect: function () {
  11925. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11926. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11927. var data = this.data;
  11928. var xi = 0;
  11929. var yi = 0;
  11930. var x0 = 0;
  11931. var y0 = 0;
  11932. for (var i = 0; i < data.length;) {
  11933. var cmd = data[i++];
  11934. if (i === 1) {
  11935. // 如果第一个命令是 L, C, Q
  11936. // 则 previous point 同绘制命令的第一个 point
  11937. //
  11938. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11939. xi = data[i];
  11940. yi = data[i + 1];
  11941. x0 = xi;
  11942. y0 = yi;
  11943. }
  11944. switch (cmd) {
  11945. case CMD.M:
  11946. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11947. // 在 closePath 的时候使用
  11948. x0 = data[i++];
  11949. y0 = data[i++];
  11950. xi = x0;
  11951. yi = y0;
  11952. min2[0] = x0;
  11953. min2[1] = y0;
  11954. max2[0] = x0;
  11955. max2[1] = y0;
  11956. break;
  11957. case CMD.L:
  11958. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11959. xi = data[i++];
  11960. yi = data[i++];
  11961. break;
  11962. case CMD.C:
  11963. fromCubic(
  11964. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11965. min2, max2
  11966. );
  11967. xi = data[i++];
  11968. yi = data[i++];
  11969. break;
  11970. case CMD.Q:
  11971. fromQuadratic(
  11972. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11973. min2, max2
  11974. );
  11975. xi = data[i++];
  11976. yi = data[i++];
  11977. break;
  11978. case CMD.A:
  11979. // TODO Arc 判断的开销比较大
  11980. var cx = data[i++];
  11981. var cy = data[i++];
  11982. var rx = data[i++];
  11983. var ry = data[i++];
  11984. var startAngle = data[i++];
  11985. var endAngle = data[i++] + startAngle;
  11986. // TODO Arc 旋转
  11987. i += 1;
  11988. var anticlockwise = 1 - data[i++];
  11989. if (i === 1) {
  11990. // 直接使用 arc 命令
  11991. // 第一个命令起点还未定义
  11992. x0 = mathCos$1(startAngle) * rx + cx;
  11993. y0 = mathSin$1(startAngle) * ry + cy;
  11994. }
  11995. fromArc(
  11996. cx, cy, rx, ry, startAngle, endAngle,
  11997. anticlockwise, min2, max2
  11998. );
  11999. xi = mathCos$1(endAngle) * rx + cx;
  12000. yi = mathSin$1(endAngle) * ry + cy;
  12001. break;
  12002. case CMD.R:
  12003. x0 = xi = data[i++];
  12004. y0 = yi = data[i++];
  12005. var width = data[i++];
  12006. var height = data[i++];
  12007. // Use fromLine
  12008. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  12009. break;
  12010. case CMD.Z:
  12011. xi = x0;
  12012. yi = y0;
  12013. break;
  12014. }
  12015. // Union
  12016. min(min$1, min$1, min2);
  12017. max(max$1, max$1, max2);
  12018. }
  12019. // No data
  12020. if (i === 0) {
  12021. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  12022. }
  12023. return new BoundingRect(
  12024. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  12025. );
  12026. },
  12027. /**
  12028. * Rebuild path from current data
  12029. * Rebuild path will not consider javascript implemented line dash.
  12030. * @param {CanvasRenderingContext2D} ctx
  12031. */
  12032. rebuildPath: function (ctx) {
  12033. var d = this.data;
  12034. var x0;
  12035. var y0;
  12036. var xi;
  12037. var yi;
  12038. var x;
  12039. var y;
  12040. var ux = this._ux;
  12041. var uy = this._uy;
  12042. var len$$1 = this._len;
  12043. for (var i = 0; i < len$$1;) {
  12044. var cmd = d[i++];
  12045. if (i === 1) {
  12046. // 如果第一个命令是 L, C, Q
  12047. // 则 previous point 同绘制命令的第一个 point
  12048. //
  12049. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12050. xi = d[i];
  12051. yi = d[i + 1];
  12052. x0 = xi;
  12053. y0 = yi;
  12054. }
  12055. switch (cmd) {
  12056. case CMD.M:
  12057. x0 = xi = d[i++];
  12058. y0 = yi = d[i++];
  12059. ctx.moveTo(xi, yi);
  12060. break;
  12061. case CMD.L:
  12062. x = d[i++];
  12063. y = d[i++];
  12064. // Not draw too small seg between
  12065. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  12066. ctx.lineTo(x, y);
  12067. xi = x;
  12068. yi = y;
  12069. }
  12070. break;
  12071. case CMD.C:
  12072. ctx.bezierCurveTo(
  12073. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  12074. );
  12075. xi = d[i - 2];
  12076. yi = d[i - 1];
  12077. break;
  12078. case CMD.Q:
  12079. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  12080. xi = d[i - 2];
  12081. yi = d[i - 1];
  12082. break;
  12083. case CMD.A:
  12084. var cx = d[i++];
  12085. var cy = d[i++];
  12086. var rx = d[i++];
  12087. var ry = d[i++];
  12088. var theta = d[i++];
  12089. var dTheta = d[i++];
  12090. var psi = d[i++];
  12091. var fs = d[i++];
  12092. var r = (rx > ry) ? rx : ry;
  12093. var scaleX = (rx > ry) ? 1 : rx / ry;
  12094. var scaleY = (rx > ry) ? ry / rx : 1;
  12095. var isEllipse = Math.abs(rx - ry) > 1e-3;
  12096. var endAngle = theta + dTheta;
  12097. if (isEllipse) {
  12098. ctx.translate(cx, cy);
  12099. ctx.rotate(psi);
  12100. ctx.scale(scaleX, scaleY);
  12101. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  12102. ctx.scale(1 / scaleX, 1 / scaleY);
  12103. ctx.rotate(-psi);
  12104. ctx.translate(-cx, -cy);
  12105. }
  12106. else {
  12107. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  12108. }
  12109. if (i === 1) {
  12110. // 直接使用 arc 命令
  12111. // 第一个命令起点还未定义
  12112. x0 = mathCos$1(theta) * rx + cx;
  12113. y0 = mathSin$1(theta) * ry + cy;
  12114. }
  12115. xi = mathCos$1(endAngle) * rx + cx;
  12116. yi = mathSin$1(endAngle) * ry + cy;
  12117. break;
  12118. case CMD.R:
  12119. x0 = xi = d[i];
  12120. y0 = yi = d[i + 1];
  12121. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  12122. break;
  12123. case CMD.Z:
  12124. ctx.closePath();
  12125. xi = x0;
  12126. yi = y0;
  12127. }
  12128. }
  12129. }
  12130. };
  12131. PathProxy.CMD = CMD;
  12132. /**
  12133. * 线段包含判断
  12134. * @param {number} x0
  12135. * @param {number} y0
  12136. * @param {number} x1
  12137. * @param {number} y1
  12138. * @param {number} lineWidth
  12139. * @param {number} x
  12140. * @param {number} y
  12141. * @return {boolean}
  12142. */
  12143. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  12144. if (lineWidth === 0) {
  12145. return false;
  12146. }
  12147. var _l = lineWidth;
  12148. var _a = 0;
  12149. var _b = x0;
  12150. // Quick reject
  12151. if (
  12152. (y > y0 + _l && y > y1 + _l)
  12153. || (y < y0 - _l && y < y1 - _l)
  12154. || (x > x0 + _l && x > x1 + _l)
  12155. || (x < x0 - _l && x < x1 - _l)
  12156. ) {
  12157. return false;
  12158. }
  12159. if (x0 !== x1) {
  12160. _a = (y0 - y1) / (x0 - x1);
  12161. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  12162. }
  12163. else {
  12164. return Math.abs(x - x0) <= _l / 2;
  12165. }
  12166. var tmp = _a * x - y + _b;
  12167. var _s = tmp * tmp / (_a * _a + 1);
  12168. return _s <= _l / 2 * _l / 2;
  12169. }
  12170. /**
  12171. * 三次贝塞尔曲线描边包含判断
  12172. * @param {number} x0
  12173. * @param {number} y0
  12174. * @param {number} x1
  12175. * @param {number} y1
  12176. * @param {number} x2
  12177. * @param {number} y2
  12178. * @param {number} x3
  12179. * @param {number} y3
  12180. * @param {number} lineWidth
  12181. * @param {number} x
  12182. * @param {number} y
  12183. * @return {boolean}
  12184. */
  12185. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  12186. if (lineWidth === 0) {
  12187. return false;
  12188. }
  12189. var _l = lineWidth;
  12190. // Quick reject
  12191. if (
  12192. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  12193. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  12194. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  12195. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  12196. ) {
  12197. return false;
  12198. }
  12199. var d = cubicProjectPoint(
  12200. x0, y0, x1, y1, x2, y2, x3, y3,
  12201. x, y, null
  12202. );
  12203. return d <= _l / 2;
  12204. }
  12205. /**
  12206. * 二次贝塞尔曲线描边包含判断
  12207. * @param {number} x0
  12208. * @param {number} y0
  12209. * @param {number} x1
  12210. * @param {number} y1
  12211. * @param {number} x2
  12212. * @param {number} y2
  12213. * @param {number} lineWidth
  12214. * @param {number} x
  12215. * @param {number} y
  12216. * @return {boolean}
  12217. */
  12218. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  12219. if (lineWidth === 0) {
  12220. return false;
  12221. }
  12222. var _l = lineWidth;
  12223. // Quick reject
  12224. if (
  12225. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  12226. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  12227. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  12228. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  12229. ) {
  12230. return false;
  12231. }
  12232. var d = quadraticProjectPoint(
  12233. x0, y0, x1, y1, x2, y2,
  12234. x, y, null
  12235. );
  12236. return d <= _l / 2;
  12237. }
  12238. var PI2$3 = Math.PI * 2;
  12239. function normalizeRadian(angle) {
  12240. angle %= PI2$3;
  12241. if (angle < 0) {
  12242. angle += PI2$3;
  12243. }
  12244. return angle;
  12245. }
  12246. var PI2$2 = Math.PI * 2;
  12247. /**
  12248. * 圆弧描边包含判断
  12249. * @param {number} cx
  12250. * @param {number} cy
  12251. * @param {number} r
  12252. * @param {number} startAngle
  12253. * @param {number} endAngle
  12254. * @param {boolean} anticlockwise
  12255. * @param {number} lineWidth
  12256. * @param {number} x
  12257. * @param {number} y
  12258. * @return {Boolean}
  12259. */
  12260. function containStroke$4(
  12261. cx, cy, r, startAngle, endAngle, anticlockwise,
  12262. lineWidth, x, y
  12263. ) {
  12264. if (lineWidth === 0) {
  12265. return false;
  12266. }
  12267. var _l = lineWidth;
  12268. x -= cx;
  12269. y -= cy;
  12270. var d = Math.sqrt(x * x + y * y);
  12271. if ((d - _l > r) || (d + _l < r)) {
  12272. return false;
  12273. }
  12274. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  12275. // Is a circle
  12276. return true;
  12277. }
  12278. if (anticlockwise) {
  12279. var tmp = startAngle;
  12280. startAngle = normalizeRadian(endAngle);
  12281. endAngle = normalizeRadian(tmp);
  12282. }
  12283. else {
  12284. startAngle = normalizeRadian(startAngle);
  12285. endAngle = normalizeRadian(endAngle);
  12286. }
  12287. if (startAngle > endAngle) {
  12288. endAngle += PI2$2;
  12289. }
  12290. var angle = Math.atan2(y, x);
  12291. if (angle < 0) {
  12292. angle += PI2$2;
  12293. }
  12294. return (angle >= startAngle && angle <= endAngle)
  12295. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  12296. }
  12297. function windingLine(x0, y0, x1, y1, x, y) {
  12298. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  12299. return 0;
  12300. }
  12301. // Ignore horizontal line
  12302. if (y1 === y0) {
  12303. return 0;
  12304. }
  12305. var dir = y1 < y0 ? 1 : -1;
  12306. var t = (y - y0) / (y1 - y0);
  12307. // Avoid winding error when intersection point is the connect point of two line of polygon
  12308. if (t === 1 || t === 0) {
  12309. dir = y1 < y0 ? 0.5 : -0.5;
  12310. }
  12311. var x_ = t * (x1 - x0) + x0;
  12312. // If (x, y) on the line, considered as "contain".
  12313. return x_ === x ? Infinity : x_ > x ? dir : 0;
  12314. }
  12315. var CMD$1 = PathProxy.CMD;
  12316. var PI2$1 = Math.PI * 2;
  12317. var EPSILON$2 = 1e-4;
  12318. function isAroundEqual(a, b) {
  12319. return Math.abs(a - b) < EPSILON$2;
  12320. }
  12321. // 临时数组
  12322. var roots = [-1, -1, -1];
  12323. var extrema = [-1, -1];
  12324. function swapExtrema() {
  12325. var tmp = extrema[0];
  12326. extrema[0] = extrema[1];
  12327. extrema[1] = tmp;
  12328. }
  12329. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  12330. // Quick reject
  12331. if (
  12332. (y > y0 && y > y1 && y > y2 && y > y3)
  12333. || (y < y0 && y < y1 && y < y2 && y < y3)
  12334. ) {
  12335. return 0;
  12336. }
  12337. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  12338. if (nRoots === 0) {
  12339. return 0;
  12340. }
  12341. else {
  12342. var w = 0;
  12343. var nExtrema = -1;
  12344. var y0_;
  12345. var y1_;
  12346. for (var i = 0; i < nRoots; i++) {
  12347. var t = roots[i];
  12348. // Avoid winding error when intersection point is the connect point of two line of polygon
  12349. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  12350. var x_ = cubicAt(x0, x1, x2, x3, t);
  12351. if (x_ < x) { // Quick reject
  12352. continue;
  12353. }
  12354. if (nExtrema < 0) {
  12355. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  12356. if (extrema[1] < extrema[0] && nExtrema > 1) {
  12357. swapExtrema();
  12358. }
  12359. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  12360. if (nExtrema > 1) {
  12361. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  12362. }
  12363. }
  12364. if (nExtrema === 2) {
  12365. // 分成三段单调函数
  12366. if (t < extrema[0]) {
  12367. w += y0_ < y0 ? unit : -unit;
  12368. }
  12369. else if (t < extrema[1]) {
  12370. w += y1_ < y0_ ? unit : -unit;
  12371. }
  12372. else {
  12373. w += y3 < y1_ ? unit : -unit;
  12374. }
  12375. }
  12376. else {
  12377. // 分成两段单调函数
  12378. if (t < extrema[0]) {
  12379. w += y0_ < y0 ? unit : -unit;
  12380. }
  12381. else {
  12382. w += y3 < y0_ ? unit : -unit;
  12383. }
  12384. }
  12385. }
  12386. return w;
  12387. }
  12388. }
  12389. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  12390. // Quick reject
  12391. if (
  12392. (y > y0 && y > y1 && y > y2)
  12393. || (y < y0 && y < y1 && y < y2)
  12394. ) {
  12395. return 0;
  12396. }
  12397. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  12398. if (nRoots === 0) {
  12399. return 0;
  12400. }
  12401. else {
  12402. var t = quadraticExtremum(y0, y1, y2);
  12403. if (t >= 0 && t <= 1) {
  12404. var w = 0;
  12405. var y_ = quadraticAt(y0, y1, y2, t);
  12406. for (var i = 0; i < nRoots; i++) {
  12407. // Remove one endpoint.
  12408. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  12409. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12410. if (x_ < x) { // Quick reject
  12411. continue;
  12412. }
  12413. if (roots[i] < t) {
  12414. w += y_ < y0 ? unit : -unit;
  12415. }
  12416. else {
  12417. w += y2 < y_ ? unit : -unit;
  12418. }
  12419. }
  12420. return w;
  12421. }
  12422. else {
  12423. // Remove one endpoint.
  12424. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  12425. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12426. if (x_ < x) { // Quick reject
  12427. return 0;
  12428. }
  12429. return y2 < y0 ? unit : -unit;
  12430. }
  12431. }
  12432. }
  12433. // TODO
  12434. // Arc 旋转
  12435. function windingArc(
  12436. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  12437. ) {
  12438. y -= cy;
  12439. if (y > r || y < -r) {
  12440. return 0;
  12441. }
  12442. var tmp = Math.sqrt(r * r - y * y);
  12443. roots[0] = -tmp;
  12444. roots[1] = tmp;
  12445. var diff = Math.abs(startAngle - endAngle);
  12446. if (diff < 1e-4) {
  12447. return 0;
  12448. }
  12449. if (diff % PI2$1 < 1e-4) {
  12450. // Is a circle
  12451. startAngle = 0;
  12452. endAngle = PI2$1;
  12453. var dir = anticlockwise ? 1 : -1;
  12454. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12455. return dir;
  12456. }
  12457. else {
  12458. return 0;
  12459. }
  12460. }
  12461. if (anticlockwise) {
  12462. var tmp = startAngle;
  12463. startAngle = normalizeRadian(endAngle);
  12464. endAngle = normalizeRadian(tmp);
  12465. }
  12466. else {
  12467. startAngle = normalizeRadian(startAngle);
  12468. endAngle = normalizeRadian(endAngle);
  12469. }
  12470. if (startAngle > endAngle) {
  12471. endAngle += PI2$1;
  12472. }
  12473. var w = 0;
  12474. for (var i = 0; i < 2; i++) {
  12475. var x_ = roots[i];
  12476. if (x_ + cx > x) {
  12477. var angle = Math.atan2(y, x_);
  12478. var dir = anticlockwise ? 1 : -1;
  12479. if (angle < 0) {
  12480. angle = PI2$1 + angle;
  12481. }
  12482. if (
  12483. (angle >= startAngle && angle <= endAngle)
  12484. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12485. ) {
  12486. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12487. dir = -dir;
  12488. }
  12489. w += dir;
  12490. }
  12491. }
  12492. }
  12493. return w;
  12494. }
  12495. function containPath(data, lineWidth, isStroke, x, y) {
  12496. var w = 0;
  12497. var xi = 0;
  12498. var yi = 0;
  12499. var x0 = 0;
  12500. var y0 = 0;
  12501. for (var i = 0; i < data.length;) {
  12502. var cmd = data[i++];
  12503. // Begin a new subpath
  12504. if (cmd === CMD$1.M && i > 1) {
  12505. // Close previous subpath
  12506. if (!isStroke) {
  12507. w += windingLine(xi, yi, x0, y0, x, y);
  12508. }
  12509. // 如果被任何一个 subpath 包含
  12510. // if (w !== 0) {
  12511. // return true;
  12512. // }
  12513. }
  12514. if (i === 1) {
  12515. // 如果第一个命令是 L, C, Q
  12516. // 则 previous point 同绘制命令的第一个 point
  12517. //
  12518. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12519. xi = data[i];
  12520. yi = data[i + 1];
  12521. x0 = xi;
  12522. y0 = yi;
  12523. }
  12524. switch (cmd) {
  12525. case CMD$1.M:
  12526. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12527. // 在 closePath 的时候使用
  12528. x0 = data[i++];
  12529. y0 = data[i++];
  12530. xi = x0;
  12531. yi = y0;
  12532. break;
  12533. case CMD$1.L:
  12534. if (isStroke) {
  12535. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12536. return true;
  12537. }
  12538. }
  12539. else {
  12540. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12541. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12542. }
  12543. xi = data[i++];
  12544. yi = data[i++];
  12545. break;
  12546. case CMD$1.C:
  12547. if (isStroke) {
  12548. if (containStroke$2(xi, yi,
  12549. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12550. lineWidth, x, y
  12551. )) {
  12552. return true;
  12553. }
  12554. }
  12555. else {
  12556. w += windingCubic(
  12557. xi, yi,
  12558. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12559. x, y
  12560. ) || 0;
  12561. }
  12562. xi = data[i++];
  12563. yi = data[i++];
  12564. break;
  12565. case CMD$1.Q:
  12566. if (isStroke) {
  12567. if (containStroke$3(xi, yi,
  12568. data[i++], data[i++], data[i], data[i + 1],
  12569. lineWidth, x, y
  12570. )) {
  12571. return true;
  12572. }
  12573. }
  12574. else {
  12575. w += windingQuadratic(
  12576. xi, yi,
  12577. data[i++], data[i++], data[i], data[i + 1],
  12578. x, y
  12579. ) || 0;
  12580. }
  12581. xi = data[i++];
  12582. yi = data[i++];
  12583. break;
  12584. case CMD$1.A:
  12585. // TODO Arc 判断的开销比较大
  12586. var cx = data[i++];
  12587. var cy = data[i++];
  12588. var rx = data[i++];
  12589. var ry = data[i++];
  12590. var theta = data[i++];
  12591. var dTheta = data[i++];
  12592. // TODO Arc 旋转
  12593. i += 1;
  12594. var anticlockwise = 1 - data[i++];
  12595. var x1 = Math.cos(theta) * rx + cx;
  12596. var y1 = Math.sin(theta) * ry + cy;
  12597. // 不是直接使用 arc 命令
  12598. if (i > 1) {
  12599. w += windingLine(xi, yi, x1, y1, x, y);
  12600. }
  12601. else {
  12602. // 第一个命令起点还未定义
  12603. x0 = x1;
  12604. y0 = y1;
  12605. }
  12606. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12607. var _x = (x - cx) * ry / rx + cx;
  12608. if (isStroke) {
  12609. if (containStroke$4(
  12610. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12611. lineWidth, _x, y
  12612. )) {
  12613. return true;
  12614. }
  12615. }
  12616. else {
  12617. w += windingArc(
  12618. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12619. _x, y
  12620. );
  12621. }
  12622. xi = Math.cos(theta + dTheta) * rx + cx;
  12623. yi = Math.sin(theta + dTheta) * ry + cy;
  12624. break;
  12625. case CMD$1.R:
  12626. x0 = xi = data[i++];
  12627. y0 = yi = data[i++];
  12628. var width = data[i++];
  12629. var height = data[i++];
  12630. var x1 = x0 + width;
  12631. var y1 = y0 + height;
  12632. if (isStroke) {
  12633. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12634. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12635. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12636. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12637. ) {
  12638. return true;
  12639. }
  12640. }
  12641. else {
  12642. // FIXME Clockwise ?
  12643. w += windingLine(x1, y0, x1, y1, x, y);
  12644. w += windingLine(x0, y1, x0, y0, x, y);
  12645. }
  12646. break;
  12647. case CMD$1.Z:
  12648. if (isStroke) {
  12649. if (containStroke$1(
  12650. xi, yi, x0, y0, lineWidth, x, y
  12651. )) {
  12652. return true;
  12653. }
  12654. }
  12655. else {
  12656. // Close a subpath
  12657. w += windingLine(xi, yi, x0, y0, x, y);
  12658. // 如果被任何一个 subpath 包含
  12659. // FIXME subpaths may overlap
  12660. // if (w !== 0) {
  12661. // return true;
  12662. // }
  12663. }
  12664. xi = x0;
  12665. yi = y0;
  12666. break;
  12667. }
  12668. }
  12669. if (!isStroke && !isAroundEqual(yi, y0)) {
  12670. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12671. }
  12672. return w !== 0;
  12673. }
  12674. function contain(pathData, x, y) {
  12675. return containPath(pathData, 0, false, x, y);
  12676. }
  12677. function containStroke(pathData, lineWidth, x, y) {
  12678. return containPath(pathData, lineWidth, true, x, y);
  12679. }
  12680. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12681. var abs = Math.abs;
  12682. var pathProxyForDraw = new PathProxy(true);
  12683. /**
  12684. * @alias module:zrender/graphic/Path
  12685. * @extends module:zrender/graphic/Displayable
  12686. * @constructor
  12687. * @param {Object} opts
  12688. */
  12689. function Path(opts) {
  12690. Displayable.call(this, opts);
  12691. /**
  12692. * @type {module:zrender/core/PathProxy}
  12693. * @readOnly
  12694. */
  12695. this.path = null;
  12696. }
  12697. Path.prototype = {
  12698. constructor: Path,
  12699. type: 'path',
  12700. __dirtyPath: true,
  12701. strokeContainThreshold: 5,
  12702. // This item default to be false. But in map series in echarts,
  12703. // in order to improve performance, it should be set to true,
  12704. // so the shorty segment won't draw.
  12705. segmentIgnoreThreshold: 0,
  12706. /**
  12707. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12708. * @type {boolean}
  12709. */
  12710. subPixelOptimize: false,
  12711. brush: function (ctx, prevEl) {
  12712. var style = this.style;
  12713. var path = this.path || pathProxyForDraw;
  12714. var hasStroke = style.hasStroke();
  12715. var hasFill = style.hasFill();
  12716. var fill = style.fill;
  12717. var stroke = style.stroke;
  12718. var hasFillGradient = hasFill && !!(fill.colorStops);
  12719. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12720. var hasFillPattern = hasFill && !!(fill.image);
  12721. var hasStrokePattern = hasStroke && !!(stroke.image);
  12722. style.bind(ctx, this, prevEl);
  12723. this.setTransform(ctx);
  12724. if (this.__dirty) {
  12725. var rect;
  12726. // Update gradient because bounding rect may changed
  12727. if (hasFillGradient) {
  12728. rect = rect || this.getBoundingRect();
  12729. this._fillGradient = style.getGradient(ctx, fill, rect);
  12730. }
  12731. if (hasStrokeGradient) {
  12732. rect = rect || this.getBoundingRect();
  12733. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12734. }
  12735. }
  12736. // Use the gradient or pattern
  12737. if (hasFillGradient) {
  12738. // PENDING If may have affect the state
  12739. ctx.fillStyle = this._fillGradient;
  12740. }
  12741. else if (hasFillPattern) {
  12742. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12743. }
  12744. if (hasStrokeGradient) {
  12745. ctx.strokeStyle = this._strokeGradient;
  12746. }
  12747. else if (hasStrokePattern) {
  12748. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12749. }
  12750. var lineDash = style.lineDash;
  12751. var lineDashOffset = style.lineDashOffset;
  12752. var ctxLineDash = !!ctx.setLineDash;
  12753. // Update path sx, sy
  12754. var scale = this.getGlobalScale();
  12755. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  12756. // Proxy context
  12757. // Rebuild path in following 2 cases
  12758. // 1. Path is dirty
  12759. // 2. Path needs javascript implemented lineDash stroking.
  12760. // In this case, lineDash information will not be saved in PathProxy
  12761. if (this.__dirtyPath
  12762. || (lineDash && !ctxLineDash && hasStroke)
  12763. ) {
  12764. path.beginPath(ctx);
  12765. // Setting line dash before build path
  12766. if (lineDash && !ctxLineDash) {
  12767. path.setLineDash(lineDash);
  12768. path.setLineDashOffset(lineDashOffset);
  12769. }
  12770. this.buildPath(path, this.shape, false);
  12771. // Clear path dirty flag
  12772. if (this.path) {
  12773. this.__dirtyPath = false;
  12774. }
  12775. }
  12776. else {
  12777. // Replay path building
  12778. ctx.beginPath();
  12779. this.path.rebuildPath(ctx);
  12780. }
  12781. if (hasFill) {
  12782. if (style.fillOpacity != null) {
  12783. var originalGlobalAlpha = ctx.globalAlpha;
  12784. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12785. path.fill(ctx);
  12786. ctx.globalAlpha = originalGlobalAlpha;
  12787. }
  12788. else {
  12789. path.fill(ctx);
  12790. }
  12791. }
  12792. if (lineDash && ctxLineDash) {
  12793. ctx.setLineDash(lineDash);
  12794. ctx.lineDashOffset = lineDashOffset;
  12795. }
  12796. if (hasStroke) {
  12797. if (style.strokeOpacity != null) {
  12798. var originalGlobalAlpha = ctx.globalAlpha;
  12799. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12800. path.stroke(ctx);
  12801. ctx.globalAlpha = originalGlobalAlpha;
  12802. }
  12803. else {
  12804. path.stroke(ctx);
  12805. }
  12806. }
  12807. if (lineDash && ctxLineDash) {
  12808. // PENDING
  12809. // Remove lineDash
  12810. ctx.setLineDash([]);
  12811. }
  12812. // Draw rect text
  12813. if (style.text != null) {
  12814. // Only restore transform when needs draw text.
  12815. this.restoreTransform(ctx);
  12816. this.drawRectText(ctx, this.getBoundingRect());
  12817. }
  12818. },
  12819. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12820. // Like in circle
  12821. buildPath: function (ctx, shapeCfg, inBundle) {},
  12822. createPathProxy: function () {
  12823. this.path = new PathProxy();
  12824. },
  12825. getBoundingRect: function () {
  12826. var rect = this._rect;
  12827. var style = this.style;
  12828. var needsUpdateRect = !rect;
  12829. if (needsUpdateRect) {
  12830. var path = this.path;
  12831. if (!path) {
  12832. // Create path on demand.
  12833. path = this.path = new PathProxy();
  12834. }
  12835. if (this.__dirtyPath) {
  12836. path.beginPath();
  12837. this.buildPath(path, this.shape, false);
  12838. }
  12839. rect = path.getBoundingRect();
  12840. }
  12841. this._rect = rect;
  12842. if (style.hasStroke()) {
  12843. // Needs update rect with stroke lineWidth when
  12844. // 1. Element changes scale or lineWidth
  12845. // 2. Shape is changed
  12846. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12847. if (this.__dirty || needsUpdateRect) {
  12848. rectWithStroke.copy(rect);
  12849. // FIXME Must after updateTransform
  12850. var w = style.lineWidth;
  12851. // PENDING, Min line width is needed when line is horizontal or vertical
  12852. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12853. // Only add extra hover lineWidth when there are no fill
  12854. if (!style.hasFill()) {
  12855. w = Math.max(w, this.strokeContainThreshold || 4);
  12856. }
  12857. // Consider line width
  12858. // Line scale can't be 0;
  12859. if (lineScale > 1e-10) {
  12860. rectWithStroke.width += w / lineScale;
  12861. rectWithStroke.height += w / lineScale;
  12862. rectWithStroke.x -= w / lineScale / 2;
  12863. rectWithStroke.y -= w / lineScale / 2;
  12864. }
  12865. }
  12866. // Return rect with stroke
  12867. return rectWithStroke;
  12868. }
  12869. return rect;
  12870. },
  12871. contain: function (x, y) {
  12872. var localPos = this.transformCoordToLocal(x, y);
  12873. var rect = this.getBoundingRect();
  12874. var style = this.style;
  12875. x = localPos[0];
  12876. y = localPos[1];
  12877. if (rect.contain(x, y)) {
  12878. var pathData = this.path.data;
  12879. if (style.hasStroke()) {
  12880. var lineWidth = style.lineWidth;
  12881. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12882. // Line scale can't be 0;
  12883. if (lineScale > 1e-10) {
  12884. // Only add extra hover lineWidth when there are no fill
  12885. if (!style.hasFill()) {
  12886. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12887. }
  12888. if (containStroke(
  12889. pathData, lineWidth / lineScale, x, y
  12890. )) {
  12891. return true;
  12892. }
  12893. }
  12894. }
  12895. if (style.hasFill()) {
  12896. return contain(pathData, x, y);
  12897. }
  12898. }
  12899. return false;
  12900. },
  12901. /**
  12902. * @param {boolean} dirtyPath
  12903. */
  12904. dirty: function (dirtyPath) {
  12905. if (dirtyPath == null) {
  12906. dirtyPath = true;
  12907. }
  12908. // Only mark dirty, not mark clean
  12909. if (dirtyPath) {
  12910. this.__dirtyPath = dirtyPath;
  12911. this._rect = null;
  12912. }
  12913. this.__dirty = this.__dirtyText = true;
  12914. this.__zr && this.__zr.refresh();
  12915. // Used as a clipping path
  12916. if (this.__clipTarget) {
  12917. this.__clipTarget.dirty();
  12918. }
  12919. },
  12920. /**
  12921. * Alias for animate('shape')
  12922. * @param {boolean} loop
  12923. */
  12924. animateShape: function (loop) {
  12925. return this.animate('shape', loop);
  12926. },
  12927. // Overwrite attrKV
  12928. attrKV: function (key, value) {
  12929. // FIXME
  12930. if (key === 'shape') {
  12931. this.setShape(value);
  12932. this.__dirtyPath = true;
  12933. this._rect = null;
  12934. }
  12935. else {
  12936. Displayable.prototype.attrKV.call(this, key, value);
  12937. }
  12938. },
  12939. /**
  12940. * @param {Object|string} key
  12941. * @param {*} value
  12942. */
  12943. setShape: function (key, value) {
  12944. var shape = this.shape;
  12945. // Path from string may not have shape
  12946. if (shape) {
  12947. if (isObject$1(key)) {
  12948. for (var name in key) {
  12949. if (key.hasOwnProperty(name)) {
  12950. shape[name] = key[name];
  12951. }
  12952. }
  12953. }
  12954. else {
  12955. shape[key] = value;
  12956. }
  12957. this.dirty(true);
  12958. }
  12959. return this;
  12960. },
  12961. getLineScale: function () {
  12962. var m = this.transform;
  12963. // Get the line scale.
  12964. // Determinant of `m` means how much the area is enlarged by the
  12965. // transformation. So its square root can be used as a scale factor
  12966. // for width.
  12967. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12968. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12969. : 1;
  12970. }
  12971. };
  12972. /**
  12973. * 扩展一个 Path element, 比如星形,圆等。
  12974. * Extend a path element
  12975. * @param {Object} props
  12976. * @param {string} props.type Path type
  12977. * @param {Function} props.init Initialize
  12978. * @param {Function} props.buildPath Overwrite buildPath method
  12979. * @param {Object} [props.style] Extended default style config
  12980. * @param {Object} [props.shape] Extended default shape config
  12981. */
  12982. Path.extend = function (defaults$$1) {
  12983. var Sub = function (opts) {
  12984. Path.call(this, opts);
  12985. if (defaults$$1.style) {
  12986. // Extend default style
  12987. this.style.extendFrom(defaults$$1.style, false);
  12988. }
  12989. // Extend default shape
  12990. var defaultShape = defaults$$1.shape;
  12991. if (defaultShape) {
  12992. this.shape = this.shape || {};
  12993. var thisShape = this.shape;
  12994. for (var name in defaultShape) {
  12995. if (
  12996. !thisShape.hasOwnProperty(name)
  12997. && defaultShape.hasOwnProperty(name)
  12998. ) {
  12999. thisShape[name] = defaultShape[name];
  13000. }
  13001. }
  13002. }
  13003. defaults$$1.init && defaults$$1.init.call(this, opts);
  13004. };
  13005. inherits(Sub, Path);
  13006. // FIXME 不能 extend position, rotation 等引用对象
  13007. for (var name in defaults$$1) {
  13008. // Extending prototype values and methods
  13009. if (name !== 'style' && name !== 'shape') {
  13010. Sub.prototype[name] = defaults$$1[name];
  13011. }
  13012. }
  13013. return Sub;
  13014. };
  13015. inherits(Path, Displayable);
  13016. var CMD$2 = PathProxy.CMD;
  13017. var points = [[], [], []];
  13018. var mathSqrt$3 = Math.sqrt;
  13019. var mathAtan2 = Math.atan2;
  13020. var transformPath = function (path, m) {
  13021. var data = path.data;
  13022. var cmd;
  13023. var nPoint;
  13024. var i;
  13025. var j;
  13026. var k;
  13027. var p;
  13028. var M = CMD$2.M;
  13029. var C = CMD$2.C;
  13030. var L = CMD$2.L;
  13031. var R = CMD$2.R;
  13032. var A = CMD$2.A;
  13033. var Q = CMD$2.Q;
  13034. for (i = 0, j = 0; i < data.length;) {
  13035. cmd = data[i++];
  13036. j = i;
  13037. nPoint = 0;
  13038. switch (cmd) {
  13039. case M:
  13040. nPoint = 1;
  13041. break;
  13042. case L:
  13043. nPoint = 1;
  13044. break;
  13045. case C:
  13046. nPoint = 3;
  13047. break;
  13048. case Q:
  13049. nPoint = 2;
  13050. break;
  13051. case A:
  13052. var x = m[4];
  13053. var y = m[5];
  13054. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  13055. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  13056. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  13057. // cx
  13058. data[i] *= sx;
  13059. data[i++] += x;
  13060. // cy
  13061. data[i] *= sy;
  13062. data[i++] += y;
  13063. // Scale rx and ry
  13064. // FIXME Assume psi is 0 here
  13065. data[i++] *= sx;
  13066. data[i++] *= sy;
  13067. // Start angle
  13068. data[i++] += angle;
  13069. // end angle
  13070. data[i++] += angle;
  13071. // FIXME psi
  13072. i += 2;
  13073. j = i;
  13074. break;
  13075. case R:
  13076. // x0, y0
  13077. p[0] = data[i++];
  13078. p[1] = data[i++];
  13079. applyTransform(p, p, m);
  13080. data[j++] = p[0];
  13081. data[j++] = p[1];
  13082. // x1, y1
  13083. p[0] += data[i++];
  13084. p[1] += data[i++];
  13085. applyTransform(p, p, m);
  13086. data[j++] = p[0];
  13087. data[j++] = p[1];
  13088. }
  13089. for (k = 0; k < nPoint; k++) {
  13090. var p = points[k];
  13091. p[0] = data[i++];
  13092. p[1] = data[i++];
  13093. applyTransform(p, p, m);
  13094. // Write back
  13095. data[j++] = p[0];
  13096. data[j++] = p[1];
  13097. }
  13098. }
  13099. };
  13100. // command chars
  13101. // var cc = [
  13102. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  13103. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  13104. // ];
  13105. var mathSqrt = Math.sqrt;
  13106. var mathSin = Math.sin;
  13107. var mathCos = Math.cos;
  13108. var PI = Math.PI;
  13109. var vMag = function (v) {
  13110. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  13111. };
  13112. var vRatio = function (u, v) {
  13113. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  13114. };
  13115. var vAngle = function (u, v) {
  13116. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  13117. * Math.acos(vRatio(u, v));
  13118. };
  13119. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  13120. var psi = psiDeg * (PI / 180.0);
  13121. var xp = mathCos(psi) * (x1 - x2) / 2.0
  13122. + mathSin(psi) * (y1 - y2) / 2.0;
  13123. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  13124. + mathCos(psi) * (y1 - y2) / 2.0;
  13125. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  13126. if (lambda > 1) {
  13127. rx *= mathSqrt(lambda);
  13128. ry *= mathSqrt(lambda);
  13129. }
  13130. var f = (fa === fs ? -1 : 1)
  13131. * mathSqrt((((rx * rx) * (ry * ry))
  13132. - ((rx * rx) * (yp * yp))
  13133. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  13134. + (ry * ry) * (xp * xp))
  13135. ) || 0;
  13136. var cxp = f * rx * yp / ry;
  13137. var cyp = f * -ry * xp / rx;
  13138. var cx = (x1 + x2) / 2.0
  13139. + mathCos(psi) * cxp
  13140. - mathSin(psi) * cyp;
  13141. var cy = (y1 + y2) / 2.0
  13142. + mathSin(psi) * cxp
  13143. + mathCos(psi) * cyp;
  13144. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  13145. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  13146. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  13147. var dTheta = vAngle(u, v);
  13148. if (vRatio(u, v) <= -1) {
  13149. dTheta = PI;
  13150. }
  13151. if (vRatio(u, v) >= 1) {
  13152. dTheta = 0;
  13153. }
  13154. if (fs === 0 && dTheta > 0) {
  13155. dTheta = dTheta - 2 * PI;
  13156. }
  13157. if (fs === 1 && dTheta < 0) {
  13158. dTheta = dTheta + 2 * PI;
  13159. }
  13160. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  13161. }
  13162. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  13163. // Consider case:
  13164. // (1) delimiter can be comma or space, where continuous commas
  13165. // or spaces should be seen as one comma.
  13166. // (2) value can be like:
  13167. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  13168. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  13169. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  13170. // var valueSplitReg = /[\s,]+/;
  13171. function createPathProxyFromString(data) {
  13172. if (!data) {
  13173. return new PathProxy();
  13174. }
  13175. // var data = data.replace(/-/g, ' -')
  13176. // .replace(/ /g, ' ')
  13177. // .replace(/ /g, ',')
  13178. // .replace(/,,/g, ',');
  13179. // var n;
  13180. // create pipes so that we can split the data
  13181. // for (n = 0; n < cc.length; n++) {
  13182. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  13183. // }
  13184. // data = data.replace(/-/g, ',-');
  13185. // create array
  13186. // var arr = cs.split('|');
  13187. // init context point
  13188. var cpx = 0;
  13189. var cpy = 0;
  13190. var subpathX = cpx;
  13191. var subpathY = cpy;
  13192. var prevCmd;
  13193. var path = new PathProxy();
  13194. var CMD = PathProxy.CMD;
  13195. // commandReg.lastIndex = 0;
  13196. // var cmdResult;
  13197. // while ((cmdResult = commandReg.exec(data)) != null) {
  13198. // var cmdStr = cmdResult[1];
  13199. // var cmdContent = cmdResult[2];
  13200. var cmdList = data.match(commandReg);
  13201. for (var l = 0; l < cmdList.length; l++) {
  13202. var cmdText = cmdList[l];
  13203. var cmdStr = cmdText.charAt(0);
  13204. var cmd;
  13205. // String#split is faster a little bit than String#replace or RegExp#exec.
  13206. // var p = cmdContent.split(valueSplitReg);
  13207. // var pLen = 0;
  13208. // for (var i = 0; i < p.length; i++) {
  13209. // // '' and other invalid str => NaN
  13210. // var val = parseFloat(p[i]);
  13211. // !isNaN(val) && (p[pLen++] = val);
  13212. // }
  13213. var p = cmdText.match(numberReg) || [];
  13214. var pLen = p.length;
  13215. for (var i = 0; i < pLen; i++) {
  13216. p[i] = parseFloat(p[i]);
  13217. }
  13218. var off = 0;
  13219. while (off < pLen) {
  13220. var ctlPtx;
  13221. var ctlPty;
  13222. var rx;
  13223. var ry;
  13224. var psi;
  13225. var fa;
  13226. var fs;
  13227. var x1 = cpx;
  13228. var y1 = cpy;
  13229. // convert l, H, h, V, and v to L
  13230. switch (cmdStr) {
  13231. case 'l':
  13232. cpx += p[off++];
  13233. cpy += p[off++];
  13234. cmd = CMD.L;
  13235. path.addData(cmd, cpx, cpy);
  13236. break;
  13237. case 'L':
  13238. cpx = p[off++];
  13239. cpy = p[off++];
  13240. cmd = CMD.L;
  13241. path.addData(cmd, cpx, cpy);
  13242. break;
  13243. case 'm':
  13244. cpx += p[off++];
  13245. cpy += p[off++];
  13246. cmd = CMD.M;
  13247. path.addData(cmd, cpx, cpy);
  13248. subpathX = cpx;
  13249. subpathY = cpy;
  13250. cmdStr = 'l';
  13251. break;
  13252. case 'M':
  13253. cpx = p[off++];
  13254. cpy = p[off++];
  13255. cmd = CMD.M;
  13256. path.addData(cmd, cpx, cpy);
  13257. subpathX = cpx;
  13258. subpathY = cpy;
  13259. cmdStr = 'L';
  13260. break;
  13261. case 'h':
  13262. cpx += p[off++];
  13263. cmd = CMD.L;
  13264. path.addData(cmd, cpx, cpy);
  13265. break;
  13266. case 'H':
  13267. cpx = p[off++];
  13268. cmd = CMD.L;
  13269. path.addData(cmd, cpx, cpy);
  13270. break;
  13271. case 'v':
  13272. cpy += p[off++];
  13273. cmd = CMD.L;
  13274. path.addData(cmd, cpx, cpy);
  13275. break;
  13276. case 'V':
  13277. cpy = p[off++];
  13278. cmd = CMD.L;
  13279. path.addData(cmd, cpx, cpy);
  13280. break;
  13281. case 'C':
  13282. cmd = CMD.C;
  13283. path.addData(
  13284. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  13285. );
  13286. cpx = p[off - 2];
  13287. cpy = p[off - 1];
  13288. break;
  13289. case 'c':
  13290. cmd = CMD.C;
  13291. path.addData(
  13292. cmd,
  13293. p[off++] + cpx, p[off++] + cpy,
  13294. p[off++] + cpx, p[off++] + cpy,
  13295. p[off++] + cpx, p[off++] + cpy
  13296. );
  13297. cpx += p[off - 2];
  13298. cpy += p[off - 1];
  13299. break;
  13300. case 'S':
  13301. ctlPtx = cpx;
  13302. ctlPty = cpy;
  13303. var len = path.len();
  13304. var pathData = path.data;
  13305. if (prevCmd === CMD.C) {
  13306. ctlPtx += cpx - pathData[len - 4];
  13307. ctlPty += cpy - pathData[len - 3];
  13308. }
  13309. cmd = CMD.C;
  13310. x1 = p[off++];
  13311. y1 = p[off++];
  13312. cpx = p[off++];
  13313. cpy = p[off++];
  13314. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13315. break;
  13316. case 's':
  13317. ctlPtx = cpx;
  13318. ctlPty = cpy;
  13319. var len = path.len();
  13320. var pathData = path.data;
  13321. if (prevCmd === CMD.C) {
  13322. ctlPtx += cpx - pathData[len - 4];
  13323. ctlPty += cpy - pathData[len - 3];
  13324. }
  13325. cmd = CMD.C;
  13326. x1 = cpx + p[off++];
  13327. y1 = cpy + p[off++];
  13328. cpx += p[off++];
  13329. cpy += p[off++];
  13330. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  13331. break;
  13332. case 'Q':
  13333. x1 = p[off++];
  13334. y1 = p[off++];
  13335. cpx = p[off++];
  13336. cpy = p[off++];
  13337. cmd = CMD.Q;
  13338. path.addData(cmd, x1, y1, cpx, cpy);
  13339. break;
  13340. case 'q':
  13341. x1 = p[off++] + cpx;
  13342. y1 = p[off++] + cpy;
  13343. cpx += p[off++];
  13344. cpy += p[off++];
  13345. cmd = CMD.Q;
  13346. path.addData(cmd, x1, y1, cpx, cpy);
  13347. break;
  13348. case 'T':
  13349. ctlPtx = cpx;
  13350. ctlPty = cpy;
  13351. var len = path.len();
  13352. var pathData = path.data;
  13353. if (prevCmd === CMD.Q) {
  13354. ctlPtx += cpx - pathData[len - 4];
  13355. ctlPty += cpy - pathData[len - 3];
  13356. }
  13357. cpx = p[off++];
  13358. cpy = p[off++];
  13359. cmd = CMD.Q;
  13360. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13361. break;
  13362. case 't':
  13363. ctlPtx = cpx;
  13364. ctlPty = cpy;
  13365. var len = path.len();
  13366. var pathData = path.data;
  13367. if (prevCmd === CMD.Q) {
  13368. ctlPtx += cpx - pathData[len - 4];
  13369. ctlPty += cpy - pathData[len - 3];
  13370. }
  13371. cpx += p[off++];
  13372. cpy += p[off++];
  13373. cmd = CMD.Q;
  13374. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  13375. break;
  13376. case 'A':
  13377. rx = p[off++];
  13378. ry = p[off++];
  13379. psi = p[off++];
  13380. fa = p[off++];
  13381. fs = p[off++];
  13382. x1 = cpx, y1 = cpy;
  13383. cpx = p[off++];
  13384. cpy = p[off++];
  13385. cmd = CMD.A;
  13386. processArc(
  13387. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13388. );
  13389. break;
  13390. case 'a':
  13391. rx = p[off++];
  13392. ry = p[off++];
  13393. psi = p[off++];
  13394. fa = p[off++];
  13395. fs = p[off++];
  13396. x1 = cpx, y1 = cpy;
  13397. cpx += p[off++];
  13398. cpy += p[off++];
  13399. cmd = CMD.A;
  13400. processArc(
  13401. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  13402. );
  13403. break;
  13404. }
  13405. }
  13406. if (cmdStr === 'z' || cmdStr === 'Z') {
  13407. cmd = CMD.Z;
  13408. path.addData(cmd);
  13409. // z may be in the middle of the path.
  13410. cpx = subpathX;
  13411. cpy = subpathY;
  13412. }
  13413. prevCmd = cmd;
  13414. }
  13415. path.toStatic();
  13416. return path;
  13417. }
  13418. // TODO Optimize double memory cost problem
  13419. function createPathOptions(str, opts) {
  13420. var pathProxy = createPathProxyFromString(str);
  13421. opts = opts || {};
  13422. opts.buildPath = function (path) {
  13423. if (path.setData) {
  13424. path.setData(pathProxy.data);
  13425. // Svg and vml renderer don't have context
  13426. var ctx = path.getContext();
  13427. if (ctx) {
  13428. path.rebuildPath(ctx);
  13429. }
  13430. }
  13431. else {
  13432. var ctx = path;
  13433. pathProxy.rebuildPath(ctx);
  13434. }
  13435. };
  13436. opts.applyTransform = function (m) {
  13437. transformPath(pathProxy, m);
  13438. this.dirty(true);
  13439. };
  13440. return opts;
  13441. }
  13442. /**
  13443. * Create a Path object from path string data
  13444. * http://www.w3.org/TR/SVG/paths.html#PathData
  13445. * @param {Object} opts Other options
  13446. */
  13447. function createFromString(str, opts) {
  13448. return new Path(createPathOptions(str, opts));
  13449. }
  13450. /**
  13451. * Create a Path class from path string data
  13452. * @param {string} str
  13453. * @param {Object} opts Other options
  13454. */
  13455. function extendFromString(str, opts) {
  13456. return Path.extend(createPathOptions(str, opts));
  13457. }
  13458. /**
  13459. * Merge multiple paths
  13460. */
  13461. // TODO Apply transform
  13462. // TODO stroke dash
  13463. // TODO Optimize double memory cost problem
  13464. function mergePath$1(pathEls, opts) {
  13465. var pathList = [];
  13466. var len = pathEls.length;
  13467. for (var i = 0; i < len; i++) {
  13468. var pathEl = pathEls[i];
  13469. if (!pathEl.path) {
  13470. pathEl.createPathProxy();
  13471. }
  13472. if (pathEl.__dirtyPath) {
  13473. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  13474. }
  13475. pathList.push(pathEl.path);
  13476. }
  13477. var pathBundle = new Path(opts);
  13478. // Need path proxy.
  13479. pathBundle.createPathProxy();
  13480. pathBundle.buildPath = function (path) {
  13481. path.appendPath(pathList);
  13482. // Svg and vml renderer don't have context
  13483. var ctx = path.getContext();
  13484. if (ctx) {
  13485. path.rebuildPath(ctx);
  13486. }
  13487. };
  13488. return pathBundle;
  13489. }
  13490. /**
  13491. * @alias zrender/graphic/Text
  13492. * @extends module:zrender/graphic/Displayable
  13493. * @constructor
  13494. * @param {Object} opts
  13495. */
  13496. var Text = function (opts) { // jshint ignore:line
  13497. Displayable.call(this, opts);
  13498. };
  13499. Text.prototype = {
  13500. constructor: Text,
  13501. type: 'text',
  13502. brush: function (ctx, prevEl) {
  13503. var style = this.style;
  13504. // Optimize, avoid normalize every time.
  13505. this.__dirty && normalizeTextStyle(style, true);
  13506. // Use props with prefix 'text'.
  13507. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  13508. style.shadowOffsetX = style.shadowOffsetY = null;
  13509. var text = style.text;
  13510. // Convert to string
  13511. text != null && (text += '');
  13512. // Do not apply style.bind in Text node. Because the real bind job
  13513. // is in textHelper.renderText, and performance of text render should
  13514. // be considered.
  13515. // style.bind(ctx, this, prevEl);
  13516. if (!needDrawText(text, style)) {
  13517. // The current el.style is not applied
  13518. // and should not be used as cache.
  13519. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13520. return;
  13521. }
  13522. this.setTransform(ctx);
  13523. renderText(this, ctx, text, style, null, prevEl);
  13524. this.restoreTransform(ctx);
  13525. },
  13526. getBoundingRect: function () {
  13527. var style = this.style;
  13528. // Optimize, avoid normalize every time.
  13529. this.__dirty && normalizeTextStyle(style, true);
  13530. if (!this._rect) {
  13531. var text = style.text;
  13532. text != null ? (text += '') : (text = '');
  13533. var rect = getBoundingRect(
  13534. style.text + '',
  13535. style.font,
  13536. style.textAlign,
  13537. style.textVerticalAlign,
  13538. style.textPadding,
  13539. style.textLineHeight,
  13540. style.rich
  13541. );
  13542. rect.x += style.x || 0;
  13543. rect.y += style.y || 0;
  13544. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13545. var w = style.textStrokeWidth;
  13546. rect.x -= w / 2;
  13547. rect.y -= w / 2;
  13548. rect.width += w;
  13549. rect.height += w;
  13550. }
  13551. this._rect = rect;
  13552. }
  13553. return this._rect;
  13554. }
  13555. };
  13556. inherits(Text, Displayable);
  13557. /**
  13558. * 圆形
  13559. * @module zrender/shape/Circle
  13560. */
  13561. var Circle = Path.extend({
  13562. type: 'circle',
  13563. shape: {
  13564. cx: 0,
  13565. cy: 0,
  13566. r: 0
  13567. },
  13568. buildPath: function (ctx, shape, inBundle) {
  13569. // Better stroking in ShapeBundle
  13570. // Always do it may have performence issue ( fill may be 2x more cost)
  13571. if (inBundle) {
  13572. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13573. }
  13574. // else {
  13575. // if (ctx.allocate && !ctx.data.length) {
  13576. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13577. // }
  13578. // }
  13579. // Better stroking in ShapeBundle
  13580. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13581. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13582. }
  13583. });
  13584. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13585. // where exception "unexpected call to method or property access"
  13586. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13587. // whose area size is zero is drawn and ctx.clip() is called and
  13588. // shadowBlur is set. See #4572, #3112, #5777.
  13589. // (e.g.,
  13590. // ctx.moveTo(10, 10);
  13591. // ctx.lineTo(20, 10);
  13592. // ctx.closePath();
  13593. // ctx.clip();
  13594. // ctx.shadowBlur = 10;
  13595. // ...
  13596. // ctx.fill();
  13597. // )
  13598. var shadowTemp = [
  13599. ['shadowBlur', 0],
  13600. ['shadowColor', '#000'],
  13601. ['shadowOffsetX', 0],
  13602. ['shadowOffsetY', 0]
  13603. ];
  13604. var fixClipWithShadow = function (orignalBrush) {
  13605. // version string can be: '11.0'
  13606. return (env$1.browser.ie && env$1.browser.version >= 11)
  13607. ? function () {
  13608. var clipPaths = this.__clipPaths;
  13609. var style = this.style;
  13610. var modified;
  13611. if (clipPaths) {
  13612. for (var i = 0; i < clipPaths.length; i++) {
  13613. var clipPath = clipPaths[i];
  13614. var shape = clipPath && clipPath.shape;
  13615. var type = clipPath && clipPath.type;
  13616. if (shape && (
  13617. (type === 'sector' && shape.startAngle === shape.endAngle)
  13618. || (type === 'rect' && (!shape.width || !shape.height))
  13619. )) {
  13620. for (var j = 0; j < shadowTemp.length; j++) {
  13621. // It is save to put shadowTemp static, because shadowTemp
  13622. // will be all modified each item brush called.
  13623. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13624. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13625. }
  13626. modified = true;
  13627. break;
  13628. }
  13629. }
  13630. }
  13631. orignalBrush.apply(this, arguments);
  13632. if (modified) {
  13633. for (var j = 0; j < shadowTemp.length; j++) {
  13634. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13635. }
  13636. }
  13637. }
  13638. : orignalBrush;
  13639. };
  13640. /**
  13641. * 扇形
  13642. * @module zrender/graphic/shape/Sector
  13643. */
  13644. var Sector = Path.extend({
  13645. type: 'sector',
  13646. shape: {
  13647. cx: 0,
  13648. cy: 0,
  13649. r0: 0,
  13650. r: 0,
  13651. startAngle: 0,
  13652. endAngle: Math.PI * 2,
  13653. clockwise: true
  13654. },
  13655. brush: fixClipWithShadow(Path.prototype.brush),
  13656. buildPath: function (ctx, shape) {
  13657. var x = shape.cx;
  13658. var y = shape.cy;
  13659. var r0 = Math.max(shape.r0 || 0, 0);
  13660. var r = Math.max(shape.r, 0);
  13661. var startAngle = shape.startAngle;
  13662. var endAngle = shape.endAngle;
  13663. var clockwise = shape.clockwise;
  13664. var unitX = Math.cos(startAngle);
  13665. var unitY = Math.sin(startAngle);
  13666. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13667. ctx.lineTo(unitX * r + x, unitY * r + y);
  13668. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13669. ctx.lineTo(
  13670. Math.cos(endAngle) * r0 + x,
  13671. Math.sin(endAngle) * r0 + y
  13672. );
  13673. if (r0 !== 0) {
  13674. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13675. }
  13676. ctx.closePath();
  13677. }
  13678. });
  13679. /**
  13680. * 圆环
  13681. * @module zrender/graphic/shape/Ring
  13682. */
  13683. var Ring = Path.extend({
  13684. type: 'ring',
  13685. shape: {
  13686. cx: 0,
  13687. cy: 0,
  13688. r: 0,
  13689. r0: 0
  13690. },
  13691. buildPath: function (ctx, shape) {
  13692. var x = shape.cx;
  13693. var y = shape.cy;
  13694. var PI2 = Math.PI * 2;
  13695. ctx.moveTo(x + shape.r, y);
  13696. ctx.arc(x, y, shape.r, 0, PI2, false);
  13697. ctx.moveTo(x + shape.r0, y);
  13698. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13699. }
  13700. });
  13701. /**
  13702. * Catmull-Rom spline 插值折线
  13703. * @module zrender/shape/util/smoothSpline
  13704. * @author pissang (https://www.github.com/pissang)
  13705. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13706. * errorrik (errorrik@gmail.com)
  13707. */
  13708. /**
  13709. * @inner
  13710. */
  13711. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13712. var v0 = (p2 - p0) * 0.5;
  13713. var v1 = (p3 - p1) * 0.5;
  13714. return (2 * (p1 - p2) + v0 + v1) * t3
  13715. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13716. + v0 * t + p1;
  13717. }
  13718. /**
  13719. * @alias module:zrender/shape/util/smoothSpline
  13720. * @param {Array} points 线段顶点数组
  13721. * @param {boolean} isLoop
  13722. * @return {Array}
  13723. */
  13724. var smoothSpline = function (points, isLoop) {
  13725. var len$$1 = points.length;
  13726. var ret = [];
  13727. var distance$$1 = 0;
  13728. for (var i = 1; i < len$$1; i++) {
  13729. distance$$1 += distance(points[i - 1], points[i]);
  13730. }
  13731. var segs = distance$$1 / 2;
  13732. segs = segs < len$$1 ? len$$1 : segs;
  13733. for (var i = 0; i < segs; i++) {
  13734. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13735. var idx = Math.floor(pos);
  13736. var w = pos - idx;
  13737. var p0;
  13738. var p1 = points[idx % len$$1];
  13739. var p2;
  13740. var p3;
  13741. if (!isLoop) {
  13742. p0 = points[idx === 0 ? idx : idx - 1];
  13743. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13744. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13745. }
  13746. else {
  13747. p0 = points[(idx - 1 + len$$1) % len$$1];
  13748. p2 = points[(idx + 1) % len$$1];
  13749. p3 = points[(idx + 2) % len$$1];
  13750. }
  13751. var w2 = w * w;
  13752. var w3 = w * w2;
  13753. ret.push([
  13754. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13755. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13756. ]);
  13757. }
  13758. return ret;
  13759. };
  13760. /**
  13761. * 贝塞尔平滑曲线
  13762. * @module zrender/shape/util/smoothBezier
  13763. * @author pissang (https://www.github.com/pissang)
  13764. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13765. * errorrik (errorrik@gmail.com)
  13766. */
  13767. /**
  13768. * 贝塞尔平滑曲线
  13769. * @alias module:zrender/shape/util/smoothBezier
  13770. * @param {Array} points 线段顶点数组
  13771. * @param {number} smooth 平滑等级, 0-1
  13772. * @param {boolean} isLoop
  13773. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13774. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13775. * 整个折线的包围盒做一个并集用来约束控制点。
  13776. * @param {Array} 计算出来的控制点数组
  13777. */
  13778. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13779. var cps = [];
  13780. var v = [];
  13781. var v1 = [];
  13782. var v2 = [];
  13783. var prevPoint;
  13784. var nextPoint;
  13785. var min$$1;
  13786. var max$$1;
  13787. if (constraint) {
  13788. min$$1 = [Infinity, Infinity];
  13789. max$$1 = [-Infinity, -Infinity];
  13790. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13791. min(min$$1, min$$1, points[i]);
  13792. max(max$$1, max$$1, points[i]);
  13793. }
  13794. // 与指定的包围盒做并集
  13795. min(min$$1, min$$1, constraint[0]);
  13796. max(max$$1, max$$1, constraint[1]);
  13797. }
  13798. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13799. var point = points[i];
  13800. if (isLoop) {
  13801. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13802. nextPoint = points[(i + 1) % len$$1];
  13803. }
  13804. else {
  13805. if (i === 0 || i === len$$1 - 1) {
  13806. cps.push(clone$1(points[i]));
  13807. continue;
  13808. }
  13809. else {
  13810. prevPoint = points[i - 1];
  13811. nextPoint = points[i + 1];
  13812. }
  13813. }
  13814. sub(v, nextPoint, prevPoint);
  13815. // use degree to scale the handle length
  13816. scale(v, v, smooth);
  13817. var d0 = distance(point, prevPoint);
  13818. var d1 = distance(point, nextPoint);
  13819. var sum = d0 + d1;
  13820. if (sum !== 0) {
  13821. d0 /= sum;
  13822. d1 /= sum;
  13823. }
  13824. scale(v1, v, -d0);
  13825. scale(v2, v, d1);
  13826. var cp0 = add([], point, v1);
  13827. var cp1 = add([], point, v2);
  13828. if (constraint) {
  13829. max(cp0, cp0, min$$1);
  13830. min(cp0, cp0, max$$1);
  13831. max(cp1, cp1, min$$1);
  13832. min(cp1, cp1, max$$1);
  13833. }
  13834. cps.push(cp0);
  13835. cps.push(cp1);
  13836. }
  13837. if (isLoop) {
  13838. cps.push(cps.shift());
  13839. }
  13840. return cps;
  13841. };
  13842. function buildPath$1(ctx, shape, closePath) {
  13843. var points = shape.points;
  13844. var smooth = shape.smooth;
  13845. if (points && points.length >= 2) {
  13846. if (smooth && smooth !== 'spline') {
  13847. var controlPoints = smoothBezier(
  13848. points, smooth, closePath, shape.smoothConstraint
  13849. );
  13850. ctx.moveTo(points[0][0], points[0][1]);
  13851. var len = points.length;
  13852. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13853. var cp1 = controlPoints[i * 2];
  13854. var cp2 = controlPoints[i * 2 + 1];
  13855. var p = points[(i + 1) % len];
  13856. ctx.bezierCurveTo(
  13857. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13858. );
  13859. }
  13860. }
  13861. else {
  13862. if (smooth === 'spline') {
  13863. points = smoothSpline(points, closePath);
  13864. }
  13865. ctx.moveTo(points[0][0], points[0][1]);
  13866. for (var i = 1, l = points.length; i < l; i++) {
  13867. ctx.lineTo(points[i][0], points[i][1]);
  13868. }
  13869. }
  13870. closePath && ctx.closePath();
  13871. }
  13872. }
  13873. /**
  13874. * 多边形
  13875. * @module zrender/shape/Polygon
  13876. */
  13877. var Polygon = Path.extend({
  13878. type: 'polygon',
  13879. shape: {
  13880. points: null,
  13881. smooth: false,
  13882. smoothConstraint: null
  13883. },
  13884. buildPath: function (ctx, shape) {
  13885. buildPath$1(ctx, shape, true);
  13886. }
  13887. });
  13888. /**
  13889. * @module zrender/graphic/shape/Polyline
  13890. */
  13891. var Polyline = Path.extend({
  13892. type: 'polyline',
  13893. shape: {
  13894. points: null,
  13895. smooth: false,
  13896. smoothConstraint: null
  13897. },
  13898. style: {
  13899. stroke: '#000',
  13900. fill: null
  13901. },
  13902. buildPath: function (ctx, shape) {
  13903. buildPath$1(ctx, shape, false);
  13904. }
  13905. });
  13906. /**
  13907. * Sub-pixel optimize for canvas rendering, prevent from blur
  13908. * when rendering a thin vertical/horizontal line.
  13909. */
  13910. var round = Math.round;
  13911. /**
  13912. * Sub pixel optimize line for canvas
  13913. *
  13914. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13915. * `outputShape` and `inputShape` can be the same object.
  13916. * `outputShape` object can be used repeatly, because all of
  13917. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13918. * @param {Object} [inputShape]
  13919. * @param {number} [inputShape.x1]
  13920. * @param {number} [inputShape.y1]
  13921. * @param {number} [inputShape.x2]
  13922. * @param {number} [inputShape.y2]
  13923. * @param {Object} [style]
  13924. * @param {number} [style.lineWidth]
  13925. */
  13926. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13927. var lineWidth = style && style.lineWidth;
  13928. if (!inputShape || !lineWidth) {
  13929. return;
  13930. }
  13931. var x1 = inputShape.x1;
  13932. var x2 = inputShape.x2;
  13933. var y1 = inputShape.y1;
  13934. var y2 = inputShape.y2;
  13935. if (round(x1 * 2) === round(x2 * 2)) {
  13936. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13937. }
  13938. else {
  13939. outputShape.x1 = x1;
  13940. outputShape.x2 = x2;
  13941. }
  13942. if (round(y1 * 2) === round(y2 * 2)) {
  13943. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13944. }
  13945. else {
  13946. outputShape.y1 = y1;
  13947. outputShape.y2 = y2;
  13948. }
  13949. }
  13950. /**
  13951. * Sub pixel optimize rect for canvas
  13952. *
  13953. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13954. * `outputShape` and `inputShape` can be the same object.
  13955. * `outputShape` object can be used repeatly, because all of
  13956. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13957. * @param {Object} [inputShape]
  13958. * @param {number} [inputShape.x]
  13959. * @param {number} [inputShape.y]
  13960. * @param {number} [inputShape.width]
  13961. * @param {number} [inputShape.height]
  13962. * @param {Object} [style]
  13963. * @param {number} [style.lineWidth]
  13964. */
  13965. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13966. var lineWidth = style && style.lineWidth;
  13967. if (!inputShape || !lineWidth) {
  13968. return;
  13969. }
  13970. var originX = inputShape.x;
  13971. var originY = inputShape.y;
  13972. var originWidth = inputShape.width;
  13973. var originHeight = inputShape.height;
  13974. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13975. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13976. outputShape.width = Math.max(
  13977. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13978. originWidth === 0 ? 0 : 1
  13979. );
  13980. outputShape.height = Math.max(
  13981. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13982. originHeight === 0 ? 0 : 1
  13983. );
  13984. }
  13985. /**
  13986. * Sub pixel optimize for canvas
  13987. *
  13988. * @param {number} position Coordinate, such as x, y
  13989. * @param {number} lineWidth Should be nonnegative integer.
  13990. * @param {boolean=} positiveOrNegative Default false (negative).
  13991. * @return {number} Optimized position.
  13992. */
  13993. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13994. // Assure that (position + lineWidth / 2) is near integer edge,
  13995. // otherwise line will be fuzzy in canvas.
  13996. var doubledPosition = round(position * 2);
  13997. return (doubledPosition + round(lineWidth)) % 2 === 0
  13998. ? doubledPosition / 2
  13999. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14000. }
  14001. /**
  14002. * 矩形
  14003. * @module zrender/graphic/shape/Rect
  14004. */
  14005. // Avoid create repeatly.
  14006. var subPixelOptimizeOutputShape = {};
  14007. var Rect = Path.extend({
  14008. type: 'rect',
  14009. shape: {
  14010. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  14011. // r缩写为1 相当于 [1, 1, 1, 1]
  14012. // r缩写为[1] 相当于 [1, 1, 1, 1]
  14013. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  14014. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  14015. r: 0,
  14016. x: 0,
  14017. y: 0,
  14018. width: 0,
  14019. height: 0
  14020. },
  14021. buildPath: function (ctx, shape) {
  14022. var x;
  14023. var y;
  14024. var width;
  14025. var height;
  14026. if (this.subPixelOptimize) {
  14027. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  14028. x = subPixelOptimizeOutputShape.x;
  14029. y = subPixelOptimizeOutputShape.y;
  14030. width = subPixelOptimizeOutputShape.width;
  14031. height = subPixelOptimizeOutputShape.height;
  14032. subPixelOptimizeOutputShape.r = shape.r;
  14033. shape = subPixelOptimizeOutputShape;
  14034. }
  14035. else {
  14036. x = shape.x;
  14037. y = shape.y;
  14038. width = shape.width;
  14039. height = shape.height;
  14040. }
  14041. if (!shape.r) {
  14042. ctx.rect(x, y, width, height);
  14043. }
  14044. else {
  14045. buildPath(ctx, shape);
  14046. }
  14047. ctx.closePath();
  14048. return;
  14049. }
  14050. });
  14051. /**
  14052. * 直线
  14053. * @module zrender/graphic/shape/Line
  14054. */
  14055. // Avoid create repeatly.
  14056. var subPixelOptimizeOutputShape$1 = {};
  14057. var Line = Path.extend({
  14058. type: 'line',
  14059. shape: {
  14060. // Start point
  14061. x1: 0,
  14062. y1: 0,
  14063. // End point
  14064. x2: 0,
  14065. y2: 0,
  14066. percent: 1
  14067. },
  14068. style: {
  14069. stroke: '#000',
  14070. fill: null
  14071. },
  14072. buildPath: function (ctx, shape) {
  14073. var x1;
  14074. var y1;
  14075. var x2;
  14076. var y2;
  14077. if (this.subPixelOptimize) {
  14078. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  14079. x1 = subPixelOptimizeOutputShape$1.x1;
  14080. y1 = subPixelOptimizeOutputShape$1.y1;
  14081. x2 = subPixelOptimizeOutputShape$1.x2;
  14082. y2 = subPixelOptimizeOutputShape$1.y2;
  14083. }
  14084. else {
  14085. x1 = shape.x1;
  14086. y1 = shape.y1;
  14087. x2 = shape.x2;
  14088. y2 = shape.y2;
  14089. }
  14090. var percent = shape.percent;
  14091. if (percent === 0) {
  14092. return;
  14093. }
  14094. ctx.moveTo(x1, y1);
  14095. if (percent < 1) {
  14096. x2 = x1 * (1 - percent) + x2 * percent;
  14097. y2 = y1 * (1 - percent) + y2 * percent;
  14098. }
  14099. ctx.lineTo(x2, y2);
  14100. },
  14101. /**
  14102. * Get point at percent
  14103. * @param {number} percent
  14104. * @return {Array.<number>}
  14105. */
  14106. pointAt: function (p) {
  14107. var shape = this.shape;
  14108. return [
  14109. shape.x1 * (1 - p) + shape.x2 * p,
  14110. shape.y1 * (1 - p) + shape.y2 * p
  14111. ];
  14112. }
  14113. });
  14114. /**
  14115. * 贝塞尔曲线
  14116. * @module zrender/shape/BezierCurve
  14117. */
  14118. var out = [];
  14119. function someVectorAt(shape, t, isTangent) {
  14120. var cpx2 = shape.cpx2;
  14121. var cpy2 = shape.cpy2;
  14122. if (cpx2 === null || cpy2 === null) {
  14123. return [
  14124. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14125. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14126. ];
  14127. }
  14128. else {
  14129. return [
  14130. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14131. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14132. ];
  14133. }
  14134. }
  14135. var BezierCurve = Path.extend({
  14136. type: 'bezier-curve',
  14137. shape: {
  14138. x1: 0,
  14139. y1: 0,
  14140. x2: 0,
  14141. y2: 0,
  14142. cpx1: 0,
  14143. cpy1: 0,
  14144. // cpx2: 0,
  14145. // cpy2: 0
  14146. // Curve show percent, for animating
  14147. percent: 1
  14148. },
  14149. style: {
  14150. stroke: '#000',
  14151. fill: null
  14152. },
  14153. buildPath: function (ctx, shape) {
  14154. var x1 = shape.x1;
  14155. var y1 = shape.y1;
  14156. var x2 = shape.x2;
  14157. var y2 = shape.y2;
  14158. var cpx1 = shape.cpx1;
  14159. var cpy1 = shape.cpy1;
  14160. var cpx2 = shape.cpx2;
  14161. var cpy2 = shape.cpy2;
  14162. var percent = shape.percent;
  14163. if (percent === 0) {
  14164. return;
  14165. }
  14166. ctx.moveTo(x1, y1);
  14167. if (cpx2 == null || cpy2 == null) {
  14168. if (percent < 1) {
  14169. quadraticSubdivide(
  14170. x1, cpx1, x2, percent, out
  14171. );
  14172. cpx1 = out[1];
  14173. x2 = out[2];
  14174. quadraticSubdivide(
  14175. y1, cpy1, y2, percent, out
  14176. );
  14177. cpy1 = out[1];
  14178. y2 = out[2];
  14179. }
  14180. ctx.quadraticCurveTo(
  14181. cpx1, cpy1,
  14182. x2, y2
  14183. );
  14184. }
  14185. else {
  14186. if (percent < 1) {
  14187. cubicSubdivide(
  14188. x1, cpx1, cpx2, x2, percent, out
  14189. );
  14190. cpx1 = out[1];
  14191. cpx2 = out[2];
  14192. x2 = out[3];
  14193. cubicSubdivide(
  14194. y1, cpy1, cpy2, y2, percent, out
  14195. );
  14196. cpy1 = out[1];
  14197. cpy2 = out[2];
  14198. y2 = out[3];
  14199. }
  14200. ctx.bezierCurveTo(
  14201. cpx1, cpy1,
  14202. cpx2, cpy2,
  14203. x2, y2
  14204. );
  14205. }
  14206. },
  14207. /**
  14208. * Get point at percent
  14209. * @param {number} t
  14210. * @return {Array.<number>}
  14211. */
  14212. pointAt: function (t) {
  14213. return someVectorAt(this.shape, t, false);
  14214. },
  14215. /**
  14216. * Get tangent at percent
  14217. * @param {number} t
  14218. * @return {Array.<number>}
  14219. */
  14220. tangentAt: function (t) {
  14221. var p = someVectorAt(this.shape, t, true);
  14222. return normalize(p, p);
  14223. }
  14224. });
  14225. /**
  14226. * 圆弧
  14227. * @module zrender/graphic/shape/Arc
  14228. */
  14229. var Arc = Path.extend({
  14230. type: 'arc',
  14231. shape: {
  14232. cx: 0,
  14233. cy: 0,
  14234. r: 0,
  14235. startAngle: 0,
  14236. endAngle: Math.PI * 2,
  14237. clockwise: true
  14238. },
  14239. style: {
  14240. stroke: '#000',
  14241. fill: null
  14242. },
  14243. buildPath: function (ctx, shape) {
  14244. var x = shape.cx;
  14245. var y = shape.cy;
  14246. var r = Math.max(shape.r, 0);
  14247. var startAngle = shape.startAngle;
  14248. var endAngle = shape.endAngle;
  14249. var clockwise = shape.clockwise;
  14250. var unitX = Math.cos(startAngle);
  14251. var unitY = Math.sin(startAngle);
  14252. ctx.moveTo(unitX * r + x, unitY * r + y);
  14253. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14254. }
  14255. });
  14256. // CompoundPath to improve performance
  14257. var CompoundPath = Path.extend({
  14258. type: 'compound',
  14259. shape: {
  14260. paths: null
  14261. },
  14262. _updatePathDirty: function () {
  14263. var dirtyPath = this.__dirtyPath;
  14264. var paths = this.shape.paths;
  14265. for (var i = 0; i < paths.length; i++) {
  14266. // Mark as dirty if any subpath is dirty
  14267. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14268. }
  14269. this.__dirtyPath = dirtyPath;
  14270. this.__dirty = this.__dirty || dirtyPath;
  14271. },
  14272. beforeBrush: function () {
  14273. this._updatePathDirty();
  14274. var paths = this.shape.paths || [];
  14275. var scale = this.getGlobalScale();
  14276. // Update path scale
  14277. for (var i = 0; i < paths.length; i++) {
  14278. if (!paths[i].path) {
  14279. paths[i].createPathProxy();
  14280. }
  14281. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14282. }
  14283. },
  14284. buildPath: function (ctx, shape) {
  14285. var paths = shape.paths || [];
  14286. for (var i = 0; i < paths.length; i++) {
  14287. paths[i].buildPath(ctx, paths[i].shape, true);
  14288. }
  14289. },
  14290. afterBrush: function () {
  14291. var paths = this.shape.paths || [];
  14292. for (var i = 0; i < paths.length; i++) {
  14293. paths[i].__dirtyPath = false;
  14294. }
  14295. },
  14296. getBoundingRect: function () {
  14297. this._updatePathDirty();
  14298. return Path.prototype.getBoundingRect.call(this);
  14299. }
  14300. });
  14301. /**
  14302. * @param {Array.<Object>} colorStops
  14303. */
  14304. var Gradient = function (colorStops) {
  14305. this.colorStops = colorStops || [];
  14306. };
  14307. Gradient.prototype = {
  14308. constructor: Gradient,
  14309. addColorStop: function (offset, color) {
  14310. this.colorStops.push({
  14311. offset: offset,
  14312. color: color
  14313. });
  14314. }
  14315. };
  14316. /**
  14317. * x, y, x2, y2 are all percent from 0 to 1
  14318. * @param {number} [x=0]
  14319. * @param {number} [y=0]
  14320. * @param {number} [x2=1]
  14321. * @param {number} [y2=0]
  14322. * @param {Array.<Object>} colorStops
  14323. * @param {boolean} [globalCoord=false]
  14324. */
  14325. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  14326. // Should do nothing more in this constructor. Because gradient can be
  14327. // declard by `color: {type: 'linear', colorStops: ...}`, where
  14328. // this constructor will not be called.
  14329. this.x = x == null ? 0 : x;
  14330. this.y = y == null ? 0 : y;
  14331. this.x2 = x2 == null ? 1 : x2;
  14332. this.y2 = y2 == null ? 0 : y2;
  14333. // Can be cloned
  14334. this.type = 'linear';
  14335. // If use global coord
  14336. this.global = globalCoord || false;
  14337. Gradient.call(this, colorStops);
  14338. };
  14339. LinearGradient.prototype = {
  14340. constructor: LinearGradient
  14341. };
  14342. inherits(LinearGradient, Gradient);
  14343. /**
  14344. * x, y, r are all percent from 0 to 1
  14345. * @param {number} [x=0.5]
  14346. * @param {number} [y=0.5]
  14347. * @param {number} [r=0.5]
  14348. * @param {Array.<Object>} [colorStops]
  14349. * @param {boolean} [globalCoord=false]
  14350. */
  14351. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14352. // Should do nothing more in this constructor. Because gradient can be
  14353. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14354. // this constructor will not be called.
  14355. this.x = x == null ? 0.5 : x;
  14356. this.y = y == null ? 0.5 : y;
  14357. this.r = r == null ? 0.5 : r;
  14358. // Can be cloned
  14359. this.type = 'radial';
  14360. // If use global coord
  14361. this.global = globalCoord || false;
  14362. Gradient.call(this, colorStops);
  14363. };
  14364. RadialGradient.prototype = {
  14365. constructor: RadialGradient
  14366. };
  14367. inherits(RadialGradient, Gradient);
  14368. /**
  14369. * Displayable for incremental rendering. It will be rendered in a separate layer
  14370. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14371. * addDisplayables will render the added displayables incremetally.
  14372. *
  14373. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14374. */
  14375. // TODO Style override ?
  14376. function IncrementalDisplayble(opts) {
  14377. Displayable.call(this, opts);
  14378. this._displayables = [];
  14379. this._temporaryDisplayables = [];
  14380. this._cursor = 0;
  14381. this.notClear = true;
  14382. }
  14383. IncrementalDisplayble.prototype.incremental = true;
  14384. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14385. this._displayables = [];
  14386. this._temporaryDisplayables = [];
  14387. this._cursor = 0;
  14388. this.dirty();
  14389. this.notClear = false;
  14390. };
  14391. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14392. if (notPersistent) {
  14393. this._temporaryDisplayables.push(displayable);
  14394. }
  14395. else {
  14396. this._displayables.push(displayable);
  14397. }
  14398. this.dirty();
  14399. };
  14400. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14401. notPersistent = notPersistent || false;
  14402. for (var i = 0; i < displayables.length; i++) {
  14403. this.addDisplayable(displayables[i], notPersistent);
  14404. }
  14405. };
  14406. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14407. for (var i = this._cursor; i < this._displayables.length; i++) {
  14408. cb && cb(this._displayables[i]);
  14409. }
  14410. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14411. cb && cb(this._temporaryDisplayables[i]);
  14412. }
  14413. };
  14414. IncrementalDisplayble.prototype.update = function () {
  14415. this.updateTransform();
  14416. for (var i = this._cursor; i < this._displayables.length; i++) {
  14417. var displayable = this._displayables[i];
  14418. // PENDING
  14419. displayable.parent = this;
  14420. displayable.update();
  14421. displayable.parent = null;
  14422. }
  14423. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14424. var displayable = this._temporaryDisplayables[i];
  14425. // PENDING
  14426. displayable.parent = this;
  14427. displayable.update();
  14428. displayable.parent = null;
  14429. }
  14430. };
  14431. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14432. // Render persistant displayables.
  14433. for (var i = this._cursor; i < this._displayables.length; i++) {
  14434. var displayable = this._displayables[i];
  14435. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14436. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14437. displayable.afterBrush && displayable.afterBrush(ctx);
  14438. }
  14439. this._cursor = i;
  14440. // Render temporary displayables.
  14441. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14442. var displayable = this._temporaryDisplayables[i];
  14443. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14444. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14445. displayable.afterBrush && displayable.afterBrush(ctx);
  14446. }
  14447. this._temporaryDisplayables = [];
  14448. this.notClear = true;
  14449. };
  14450. var m = [];
  14451. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14452. if (!this._rect) {
  14453. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14454. for (var i = 0; i < this._displayables.length; i++) {
  14455. var displayable = this._displayables[i];
  14456. var childRect = displayable.getBoundingRect().clone();
  14457. if (displayable.needLocalTransform()) {
  14458. childRect.applyTransform(displayable.getLocalTransform(m));
  14459. }
  14460. rect.union(childRect);
  14461. }
  14462. this._rect = rect;
  14463. }
  14464. return this._rect;
  14465. };
  14466. IncrementalDisplayble.prototype.contain = function (x, y) {
  14467. var localPos = this.transformCoordToLocal(x, y);
  14468. var rect = this.getBoundingRect();
  14469. if (rect.contain(localPos[0], localPos[1])) {
  14470. for (var i = 0; i < this._displayables.length; i++) {
  14471. var displayable = this._displayables[i];
  14472. if (displayable.contain(x, y)) {
  14473. return true;
  14474. }
  14475. }
  14476. }
  14477. return false;
  14478. };
  14479. inherits(IncrementalDisplayble, Displayable);
  14480. /*
  14481. * Licensed to the Apache Software Foundation (ASF) under one
  14482. * or more contributor license agreements. See the NOTICE file
  14483. * distributed with this work for additional information
  14484. * regarding copyright ownership. The ASF licenses this file
  14485. * to you under the Apache License, Version 2.0 (the
  14486. * "License"); you may not use this file except in compliance
  14487. * with the License. You may obtain a copy of the License at
  14488. *
  14489. * http://www.apache.org/licenses/LICENSE-2.0
  14490. *
  14491. * Unless required by applicable law or agreed to in writing,
  14492. * software distributed under the License is distributed on an
  14493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14494. * KIND, either express or implied. See the License for the
  14495. * specific language governing permissions and limitations
  14496. * under the License.
  14497. */
  14498. var mathMax$1 = Math.max;
  14499. var mathMin$1 = Math.min;
  14500. var EMPTY_OBJ = {};
  14501. var Z2_EMPHASIS_LIFT = 1;
  14502. // key: label model property nane, value: style property name.
  14503. var CACHED_LABEL_STYLE_PROPERTIES = {
  14504. color: 'textFill',
  14505. textBorderColor: 'textStroke',
  14506. textBorderWidth: 'textStrokeWidth'
  14507. };
  14508. var EMPHASIS = 'emphasis';
  14509. var NORMAL = 'normal';
  14510. // Reserve 0 as default.
  14511. var _highlightNextDigit = 1;
  14512. var _highlightKeyMap = {};
  14513. var _customShapeMap = {};
  14514. /**
  14515. * Extend shape with parameters
  14516. */
  14517. function extendShape(opts) {
  14518. return Path.extend(opts);
  14519. }
  14520. /**
  14521. * Extend path
  14522. */
  14523. function extendPath(pathData, opts) {
  14524. return extendFromString(pathData, opts);
  14525. }
  14526. /**
  14527. * Register a user defined shape.
  14528. * The shape class can be fetched by `getShapeClass`
  14529. * This method will overwrite the registered shapes, including
  14530. * the registered built-in shapes, if using the same `name`.
  14531. * The shape can be used in `custom series` and
  14532. * `graphic component` by declaring `{type: name}`.
  14533. *
  14534. * @param {string} name
  14535. * @param {Object} ShapeClass Can be generated by `extendShape`.
  14536. */
  14537. function registerShape(name, ShapeClass) {
  14538. _customShapeMap[name] = ShapeClass;
  14539. }
  14540. /**
  14541. * Find shape class registered by `registerShape`. Usually used in
  14542. * fetching user defined shape.
  14543. *
  14544. * [Caution]:
  14545. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14546. * to use user registered shapes.
  14547. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14548. * `registerShape` by default. That enables users to get both built-in
  14549. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14550. * the built-in shapes by using names like 'circle', 'rect' via calling
  14551. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14552. * in case that it is overwritten by users, except that some features, like
  14553. * `custom series`, `graphic component`, do it deliberately.
  14554. *
  14555. * (2) In the features like `custom series`, `graphic component`, the user input
  14556. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14557. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14558. * are reserved names, that is, if some user register a shape named `'image'`,
  14559. * the shape will not be used. If we intending to add some more reserved names
  14560. * in feature, that might bring break changes (disable some existing user shape
  14561. * names). But that case probably rearly happen. So we dont make more mechanism
  14562. * to resolve this issue here.
  14563. *
  14564. * @param {string} name
  14565. * @return {Object} The shape class. If not found, return nothing.
  14566. */
  14567. function getShapeClass(name) {
  14568. if (_customShapeMap.hasOwnProperty(name)) {
  14569. return _customShapeMap[name];
  14570. }
  14571. }
  14572. /**
  14573. * Create a path element from path data string
  14574. * @param {string} pathData
  14575. * @param {Object} opts
  14576. * @param {module:zrender/core/BoundingRect} rect
  14577. * @param {string} [layout=cover] 'center' or 'cover'
  14578. */
  14579. function makePath(pathData, opts, rect, layout) {
  14580. var path = createFromString(pathData, opts);
  14581. if (rect) {
  14582. if (layout === 'center') {
  14583. rect = centerGraphic(rect, path.getBoundingRect());
  14584. }
  14585. resizePath(path, rect);
  14586. }
  14587. return path;
  14588. }
  14589. /**
  14590. * Create a image element from image url
  14591. * @param {string} imageUrl image url
  14592. * @param {Object} opts options
  14593. * @param {module:zrender/core/BoundingRect} rect constrain rect
  14594. * @param {string} [layout=cover] 'center' or 'cover'
  14595. */
  14596. function makeImage(imageUrl, rect, layout) {
  14597. var path = new ZImage({
  14598. style: {
  14599. image: imageUrl,
  14600. x: rect.x,
  14601. y: rect.y,
  14602. width: rect.width,
  14603. height: rect.height
  14604. },
  14605. onload: function (img) {
  14606. if (layout === 'center') {
  14607. var boundingRect = {
  14608. width: img.width,
  14609. height: img.height
  14610. };
  14611. path.setStyle(centerGraphic(rect, boundingRect));
  14612. }
  14613. }
  14614. });
  14615. return path;
  14616. }
  14617. /**
  14618. * Get position of centered element in bounding box.
  14619. *
  14620. * @param {Object} rect element local bounding box
  14621. * @param {Object} boundingRect constraint bounding box
  14622. * @return {Object} element position containing x, y, width, and height
  14623. */
  14624. function centerGraphic(rect, boundingRect) {
  14625. // Set rect to center, keep width / height ratio.
  14626. var aspect = boundingRect.width / boundingRect.height;
  14627. var width = rect.height * aspect;
  14628. var height;
  14629. if (width <= rect.width) {
  14630. height = rect.height;
  14631. }
  14632. else {
  14633. width = rect.width;
  14634. height = width / aspect;
  14635. }
  14636. var cx = rect.x + rect.width / 2;
  14637. var cy = rect.y + rect.height / 2;
  14638. return {
  14639. x: cx - width / 2,
  14640. y: cy - height / 2,
  14641. width: width,
  14642. height: height
  14643. };
  14644. }
  14645. var mergePath = mergePath$1;
  14646. /**
  14647. * Resize a path to fit the rect
  14648. * @param {module:zrender/graphic/Path} path
  14649. * @param {Object} rect
  14650. */
  14651. function resizePath(path, rect) {
  14652. if (!path.applyTransform) {
  14653. return;
  14654. }
  14655. var pathRect = path.getBoundingRect();
  14656. var m = pathRect.calculateTransform(rect);
  14657. path.applyTransform(m);
  14658. }
  14659. /**
  14660. * Sub pixel optimize line for canvas
  14661. *
  14662. * @param {Object} param
  14663. * @param {Object} [param.shape]
  14664. * @param {number} [param.shape.x1]
  14665. * @param {number} [param.shape.y1]
  14666. * @param {number} [param.shape.x2]
  14667. * @param {number} [param.shape.y2]
  14668. * @param {Object} [param.style]
  14669. * @param {number} [param.style.lineWidth]
  14670. * @return {Object} Modified param
  14671. */
  14672. function subPixelOptimizeLine(param) {
  14673. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  14674. return param;
  14675. }
  14676. /**
  14677. * Sub pixel optimize rect for canvas
  14678. *
  14679. * @param {Object} param
  14680. * @param {Object} [param.shape]
  14681. * @param {number} [param.shape.x]
  14682. * @param {number} [param.shape.y]
  14683. * @param {number} [param.shape.width]
  14684. * @param {number} [param.shape.height]
  14685. * @param {Object} [param.style]
  14686. * @param {number} [param.style.lineWidth]
  14687. * @return {Object} Modified param
  14688. */
  14689. function subPixelOptimizeRect(param) {
  14690. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  14691. return param;
  14692. }
  14693. /**
  14694. * Sub pixel optimize for canvas
  14695. *
  14696. * @param {number} position Coordinate, such as x, y
  14697. * @param {number} lineWidth Should be nonnegative integer.
  14698. * @param {boolean=} positiveOrNegative Default false (negative).
  14699. * @return {number} Optimized position.
  14700. */
  14701. var subPixelOptimize = subPixelOptimize$1;
  14702. function hasFillOrStroke(fillOrStroke) {
  14703. return fillOrStroke != null && fillOrStroke !== 'none';
  14704. }
  14705. // Most lifted color are duplicated.
  14706. var liftedColorMap = createHashMap();
  14707. var liftedColorCount = 0;
  14708. function liftColor(color) {
  14709. if (typeof color !== 'string') {
  14710. return color;
  14711. }
  14712. var liftedColor = liftedColorMap.get(color);
  14713. if (!liftedColor) {
  14714. liftedColor = lift(color, -0.1);
  14715. if (liftedColorCount < 10000) {
  14716. liftedColorMap.set(color, liftedColor);
  14717. liftedColorCount++;
  14718. }
  14719. }
  14720. return liftedColor;
  14721. }
  14722. function cacheElementStl(el) {
  14723. if (!el.__hoverStlDirty) {
  14724. return;
  14725. }
  14726. el.__hoverStlDirty = false;
  14727. var hoverStyle = el.__hoverStl;
  14728. if (!hoverStyle) {
  14729. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14730. return;
  14731. }
  14732. var normalStyle = el.__cachedNormalStl = {};
  14733. el.__cachedNormalZ2 = el.z2;
  14734. var elStyle = el.style;
  14735. for (var name in hoverStyle) {
  14736. // See comment in `singleEnterEmphasis`.
  14737. if (hoverStyle[name] != null) {
  14738. normalStyle[name] = elStyle[name];
  14739. }
  14740. }
  14741. // Always cache fill and stroke to normalStyle for lifting color.
  14742. normalStyle.fill = elStyle.fill;
  14743. normalStyle.stroke = elStyle.stroke;
  14744. }
  14745. function singleEnterEmphasis(el) {
  14746. var hoverStl = el.__hoverStl;
  14747. if (!hoverStl || el.__highlighted) {
  14748. return;
  14749. }
  14750. var zr = el.__zr;
  14751. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  14752. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14753. if (el.isGroup || (!zr && el.useHoverLayer)) {
  14754. return;
  14755. }
  14756. var elTarget = el;
  14757. var targetStyle = el.style;
  14758. if (useHoverLayer) {
  14759. elTarget = zr.addHover(el);
  14760. targetStyle = elTarget.style;
  14761. }
  14762. rollbackDefaultTextStyle(targetStyle);
  14763. if (!useHoverLayer) {
  14764. cacheElementStl(elTarget);
  14765. }
  14766. // styles can be:
  14767. // {
  14768. // label: {
  14769. // show: false,
  14770. // position: 'outside',
  14771. // fontSize: 18
  14772. // },
  14773. // emphasis: {
  14774. // label: {
  14775. // show: true
  14776. // }
  14777. // }
  14778. // },
  14779. // where properties of `emphasis` may not appear in `normal`. We previously use
  14780. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14781. // But consider rich text and setOption in merge mode, it is impossible to cover
  14782. // all properties in merge. So we use merge mode when setting style here.
  14783. // But we choose the merge strategy that only properties that is not `null/undefined`.
  14784. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  14785. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  14786. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  14787. // style any more in `emphasis`. Users can both set properties directly on normal and
  14788. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  14789. targetStyle.extendFrom(hoverStl);
  14790. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14791. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14792. applyDefaultTextStyle(targetStyle);
  14793. if (!useHoverLayer) {
  14794. el.dirty(false);
  14795. el.z2 += Z2_EMPHASIS_LIFT;
  14796. }
  14797. }
  14798. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14799. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14800. targetStyle[prop] = liftColor(targetStyle[prop]);
  14801. }
  14802. }
  14803. function singleEnterNormal(el) {
  14804. var highlighted = el.__highlighted;
  14805. if (!highlighted) {
  14806. return;
  14807. }
  14808. el.__highlighted = false;
  14809. if (el.isGroup) {
  14810. return;
  14811. }
  14812. if (highlighted === 'layer') {
  14813. el.__zr && el.__zr.removeHover(el);
  14814. }
  14815. else {
  14816. var style = el.style;
  14817. var normalStl = el.__cachedNormalStl;
  14818. if (normalStl) {
  14819. rollbackDefaultTextStyle(style);
  14820. el.setStyle(normalStl);
  14821. applyDefaultTextStyle(style);
  14822. }
  14823. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14824. // when `el` is on emphasis state. So here by comparing with 1, we try
  14825. // hard to make the bug case rare.
  14826. var normalZ2 = el.__cachedNormalZ2;
  14827. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14828. el.z2 = normalZ2;
  14829. }
  14830. }
  14831. }
  14832. function traverseUpdate(el, updater, commonParam) {
  14833. // If root is group, also enter updater for `highDownOnUpdate`.
  14834. var fromState = NORMAL;
  14835. var toState = NORMAL;
  14836. var trigger;
  14837. // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  14838. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  14839. updater(el, commonParam);
  14840. el.__highlighted && (toState = EMPHASIS, trigger = true);
  14841. el.isGroup && el.traverse(function (child) {
  14842. !child.isGroup && updater(child, commonParam);
  14843. });
  14844. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  14845. }
  14846. /**
  14847. * Set hover style (namely "emphasis style") of element, based on the current
  14848. * style of the given `el`.
  14849. * This method should be called after all of the normal styles have been adopted
  14850. * to the `el`. See the reason on `setHoverStyle`.
  14851. *
  14852. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14853. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  14854. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  14855. * Often used when item group has a label element and it's hoverStyle is different.
  14856. * @param {Object|boolean} [hoverStl] The specified hover style.
  14857. * If set as `false`, disable the hover style.
  14858. * Similarly, The `el.hoverStyle` can alse be set
  14859. * as `false` to disable the hover style.
  14860. * Otherwise, use the default hover style if not provided.
  14861. */
  14862. function setElementHoverStyle(el, hoverStl) {
  14863. // For performance consideration, it might be better to make the "hover style" only the
  14864. // difference properties from the "normal style", but not a entire copy of all styles.
  14865. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  14866. el.__hoverStlDirty = true;
  14867. // FIXME
  14868. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14869. // It probably should be saved on `data` of series. Consider the cases:
  14870. // (1) A highlighted elements are moved out of the view port and re-enter
  14871. // again by dataZoom.
  14872. // (2) call `setOption` and replace elements totally when they are highlighted.
  14873. if (el.__highlighted) {
  14874. // Consider the case:
  14875. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14876. // should be adapted to the `el`. Notice here new "normal styles" should have
  14877. // been set outside and the cached "normal style" is out of date.
  14878. el.__cachedNormalStl = null;
  14879. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14880. // of this method. In most cases, `z2` is not set and hover style should be able
  14881. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14882. // `doSingleLeaveHover` for details.
  14883. singleEnterNormal(el);
  14884. singleEnterEmphasis(el);
  14885. }
  14886. }
  14887. function onElementMouseOver(e) {
  14888. !shouldSilent(this, e)
  14889. // "emphasis" event highlight has higher priority than mouse highlight.
  14890. && !this.__highByOuter
  14891. && traverseUpdate(this, singleEnterEmphasis);
  14892. }
  14893. function onElementMouseOut(e) {
  14894. !shouldSilent(this, e)
  14895. // "emphasis" event highlight has higher priority than mouse highlight.
  14896. && !this.__highByOuter
  14897. && traverseUpdate(this, singleEnterNormal);
  14898. }
  14899. function onElementEmphasisEvent(highlightDigit) {
  14900. this.__highByOuter |= 1 << (highlightDigit || 0);
  14901. traverseUpdate(this, singleEnterEmphasis);
  14902. }
  14903. function onElementNormalEvent(highlightDigit) {
  14904. !(this.__highByOuter &= ~(1 << (highlightDigit || 0)))
  14905. && traverseUpdate(this, singleEnterNormal);
  14906. }
  14907. function shouldSilent(el, e) {
  14908. return el.__highDownSilentOnTouch && e.zrByTouch;
  14909. }
  14910. /**
  14911. * Set hover style (namely "emphasis style") of element,
  14912. * based on the current style of the given `el`.
  14913. *
  14914. * (1)
  14915. * **CONSTRAINTS** for this method:
  14916. * <A> This method MUST be called after all of the normal styles having been adopted
  14917. * to the `el`.
  14918. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14919. * "normal style" having been set to the el.
  14920. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14921. * a default hover style).
  14922. *
  14923. * The reason: this method treat the current style of the `el` as the "normal style"
  14924. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14925. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14926. * logic, where the el should shift from the original emphasis style to the new
  14927. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14928. *
  14929. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14930. * not found a better solution yet to fit the backward compatibility, performance and
  14931. * the current programming style.
  14932. *
  14933. * (2)
  14934. * Call the method for a "root" element once. Do not call it for each descendants.
  14935. * If the descendants elemenets of a group has itself hover style different from the
  14936. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14937. * not call this method for them.
  14938. *
  14939. * (3) These input parameters can be set directly on `el`:
  14940. *
  14941. * @param {module:zrender/Element} el
  14942. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  14943. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  14944. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  14945. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14946. */
  14947. function setHoverStyle(el, hoverStyle) {
  14948. setAsHighDownDispatcher(el, true);
  14949. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  14950. }
  14951. /**
  14952. * @param {module:zrender/Element} el
  14953. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  14954. * Since `setHoverStyle` has the constraint that it must be called after
  14955. * all of the normal style updated, `highDownOnUpdate` is not needed to
  14956. * trigger if both `fromState` and `toState` is 'normal', and needed to
  14957. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  14958. * to sync outside style settings to "emphasis" state.
  14959. * @this {string} This dispatcher `el`.
  14960. * @param {string} fromState Can be "normal" or "emphasis".
  14961. * `fromState` might equal to `toState`,
  14962. * for example, when this method is called when `el` is
  14963. * on "emphasis" state.
  14964. * @param {string} toState Can be "normal" or "emphasis".
  14965. *
  14966. * FIXME
  14967. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  14968. * Because it is not a complete solution. The update
  14969. * listener should not have been mount in element,
  14970. * and the normal/emphasis state should not have
  14971. * mantained on elements.
  14972. *
  14973. * @param {boolean} [el.highDownSilentOnTouch=false]
  14974. * In touch device, mouseover event will be trigger on touchstart event
  14975. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14976. * conveniently use hoverStyle when tap on touch screen without additional
  14977. * code for compatibility.
  14978. * But if the chart/component has select feature, which usually also use
  14979. * hoverStyle, there might be conflict between 'select-highlight' and
  14980. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14981. * In this case, `highDownSilentOnTouch` should be used to disable
  14982. * hover-highlight on touch device.
  14983. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  14984. */
  14985. function setAsHighDownDispatcher(el, asDispatcher) {
  14986. var disable = asDispatcher === false;
  14987. // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  14988. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  14989. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  14990. el.__highDownOnUpdate = el.highDownOnUpdate;
  14991. // Simple optimize, since this method might be
  14992. // called for each elements of a group in some cases.
  14993. if (!disable || el.__highDownDispatcher) {
  14994. var method = disable ? 'off' : 'on';
  14995. // Duplicated function will be auto-ignored, see Eventful.js.
  14996. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14997. // Emphasis, normal can be triggered manually by API or other components like hover link.
  14998. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  14999. // Also keep previous record.
  15000. el.__highByOuter = el.__highByOuter || 0;
  15001. el.__highDownDispatcher = !disable;
  15002. }
  15003. }
  15004. /**
  15005. * @param {module:zrender/src/Element} el
  15006. * @return {boolean}
  15007. */
  15008. function isHighDownDispatcher(el) {
  15009. return !!(el && el.__highDownDispatcher);
  15010. }
  15011. /**
  15012. * Support hightlight/downplay record on each elements.
  15013. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  15014. * user triggerred hightlight/downplay should not conflict.
  15015. * Only all of the highlightDigit cleared, return to normal.
  15016. * @param {string} highlightKey
  15017. * @return {number} highlightDigit
  15018. */
  15019. function getHighlightDigit(highlightKey) {
  15020. var highlightDigit = _highlightKeyMap[highlightKey];
  15021. if (highlightDigit == null && _highlightNextDigit <= 32) {
  15022. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  15023. }
  15024. return highlightDigit;
  15025. }
  15026. /**
  15027. * See more info in `setTextStyleCommon`.
  15028. * @param {Object|module:zrender/graphic/Style} normalStyle
  15029. * @param {Object} emphasisStyle
  15030. * @param {module:echarts/model/Model} normalModel
  15031. * @param {module:echarts/model/Model} emphasisModel
  15032. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  15033. * @param {string|Function} [opt.defaultText]
  15034. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  15035. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15036. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  15037. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15038. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  15039. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  15040. * @param {Object} [normalSpecified]
  15041. * @param {Object} [emphasisSpecified]
  15042. */
  15043. function setLabelStyle(
  15044. normalStyle, emphasisStyle,
  15045. normalModel, emphasisModel,
  15046. opt,
  15047. normalSpecified, emphasisSpecified
  15048. ) {
  15049. opt = opt || EMPTY_OBJ;
  15050. var labelFetcher = opt.labelFetcher;
  15051. var labelDataIndex = opt.labelDataIndex;
  15052. var labelDimIndex = opt.labelDimIndex;
  15053. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  15054. // is not supported util someone requests.
  15055. var showNormal = normalModel.getShallow('show');
  15056. var showEmphasis = emphasisModel.getShallow('show');
  15057. // Consider performance, only fetch label when necessary.
  15058. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  15059. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  15060. var baseText;
  15061. if (showNormal || showEmphasis) {
  15062. if (labelFetcher) {
  15063. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  15064. }
  15065. if (baseText == null) {
  15066. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  15067. }
  15068. }
  15069. var normalStyleText = showNormal ? baseText : null;
  15070. var emphasisStyleText = showEmphasis
  15071. ? retrieve2(
  15072. labelFetcher
  15073. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  15074. : null,
  15075. baseText
  15076. )
  15077. : null;
  15078. // Optimize: If style.text is null, text will not be drawn.
  15079. if (normalStyleText != null || emphasisStyleText != null) {
  15080. // Always set `textStyle` even if `normalStyle.text` is null, because default
  15081. // values have to be set on `normalStyle`.
  15082. // If we set default values on `emphasisStyle`, consider case:
  15083. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  15084. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  15085. // Then the 'red' will not work on emphasis.
  15086. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  15087. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  15088. }
  15089. normalStyle.text = normalStyleText;
  15090. emphasisStyle.text = emphasisStyleText;
  15091. }
  15092. /**
  15093. * Modify label style manually.
  15094. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  15095. *
  15096. * @param {module:zrender/src/Element} el
  15097. * @param {Object} [normalStyleProps] optional
  15098. * @param {Object} [emphasisStyleProps] optional
  15099. */
  15100. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  15101. var elStyle = el.style;
  15102. if (normalStyleProps) {
  15103. rollbackDefaultTextStyle(elStyle);
  15104. el.setStyle(normalStyleProps);
  15105. applyDefaultTextStyle(elStyle);
  15106. }
  15107. elStyle = el.__hoverStl;
  15108. if (emphasisStyleProps && elStyle) {
  15109. rollbackDefaultTextStyle(elStyle);
  15110. extend(elStyle, emphasisStyleProps);
  15111. applyDefaultTextStyle(elStyle);
  15112. }
  15113. }
  15114. /**
  15115. * Set basic textStyle properties.
  15116. * See more info in `setTextStyleCommon`.
  15117. * @param {Object|module:zrender/graphic/Style} textStyle
  15118. * @param {module:echarts/model/Model} model
  15119. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  15120. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  15121. * @param {boolean} [isEmphasis]
  15122. */
  15123. function setTextStyle(
  15124. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  15125. ) {
  15126. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  15127. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  15128. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15129. return textStyle;
  15130. }
  15131. /**
  15132. * Set text option in the style.
  15133. * See more info in `setTextStyleCommon`.
  15134. * @deprecated
  15135. * @param {Object} textStyle
  15136. * @param {module:echarts/model/Model} labelModel
  15137. * @param {string|boolean} defaultColor Default text color.
  15138. * If set as false, it will be processed as a emphasis style.
  15139. */
  15140. function setText(textStyle, labelModel, defaultColor) {
  15141. var opt = {isRectText: true};
  15142. var isEmphasis;
  15143. if (defaultColor === false) {
  15144. isEmphasis = true;
  15145. }
  15146. else {
  15147. // Support setting color as 'auto' to get visual color.
  15148. opt.autoColor = defaultColor;
  15149. }
  15150. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  15151. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  15152. }
  15153. /**
  15154. * The uniform entry of set text style, that is, retrieve style definitions
  15155. * from `model` and set to `textStyle` object.
  15156. *
  15157. * Never in merge mode, but in overwrite mode, that is, all of the text style
  15158. * properties will be set. (Consider the states of normal and emphasis and
  15159. * default value can be adopted, merge would make the logic too complicated
  15160. * to manage.)
  15161. *
  15162. * The `textStyle` object can either be a plain object or an instance of
  15163. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  15164. * After this mothod called, the `textStyle` object can then be used in
  15165. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  15166. *
  15167. * Default value will be adopted and `insideRollbackOpt` will be created.
  15168. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  15169. *
  15170. * opt: {
  15171. * disableBox: boolean, Whether diable drawing box of block (outer most).
  15172. * isRectText: boolean,
  15173. * autoColor: string, specify a color when color is 'auto',
  15174. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  15175. * If autoColor specified, it is used as default textFill.
  15176. * useInsideStyle:
  15177. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  15178. * if `textFill` is not specified.
  15179. * `false`: Do not use inside style.
  15180. * `null/undefined`: use inside style if `isRectText` is true and
  15181. * `textFill` is not specified and textPosition contains `'inside'`.
  15182. * forceRich: boolean
  15183. * }
  15184. */
  15185. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  15186. // Consider there will be abnormal when merge hover style to normal style if given default value.
  15187. opt = opt || EMPTY_OBJ;
  15188. if (opt.isRectText) {
  15189. var textPosition;
  15190. if (opt.getTextPosition) {
  15191. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  15192. }
  15193. else {
  15194. textPosition = textStyleModel.getShallow('position')
  15195. || (isEmphasis ? null : 'inside');
  15196. // 'outside' is not a valid zr textPostion value, but used
  15197. // in bar series, and magric type should be considered.
  15198. textPosition === 'outside' && (textPosition = 'top');
  15199. }
  15200. textStyle.textPosition = textPosition;
  15201. textStyle.textOffset = textStyleModel.getShallow('offset');
  15202. var labelRotate = textStyleModel.getShallow('rotate');
  15203. labelRotate != null && (labelRotate *= Math.PI / 180);
  15204. textStyle.textRotation = labelRotate;
  15205. textStyle.textDistance = retrieve2(
  15206. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  15207. );
  15208. }
  15209. var ecModel = textStyleModel.ecModel;
  15210. var globalTextStyle = ecModel && ecModel.option.textStyle;
  15211. // Consider case:
  15212. // {
  15213. // data: [{
  15214. // value: 12,
  15215. // label: {
  15216. // rich: {
  15217. // // no 'a' here but using parent 'a'.
  15218. // }
  15219. // }
  15220. // }],
  15221. // rich: {
  15222. // a: { ... }
  15223. // }
  15224. // }
  15225. var richItemNames = getRichItemNames(textStyleModel);
  15226. var richResult;
  15227. if (richItemNames) {
  15228. richResult = {};
  15229. for (var name in richItemNames) {
  15230. if (richItemNames.hasOwnProperty(name)) {
  15231. // Cascade is supported in rich.
  15232. var richTextStyle = textStyleModel.getModel(['rich', name]);
  15233. // In rich, never `disableBox`.
  15234. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  15235. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  15236. // That might confuses users. So probably we should put `textStyleModel` as the
  15237. // root ancestor of the `richTextStyle`. But that would be a break change.
  15238. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  15239. }
  15240. }
  15241. }
  15242. textStyle.rich = richResult;
  15243. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  15244. if (opt.forceRich && !opt.textStyle) {
  15245. opt.textStyle = {};
  15246. }
  15247. return textStyle;
  15248. }
  15249. // Consider case:
  15250. // {
  15251. // data: [{
  15252. // value: 12,
  15253. // label: {
  15254. // rich: {
  15255. // // no 'a' here but using parent 'a'.
  15256. // }
  15257. // }
  15258. // }],
  15259. // rich: {
  15260. // a: { ... }
  15261. // }
  15262. // }
  15263. function getRichItemNames(textStyleModel) {
  15264. // Use object to remove duplicated names.
  15265. var richItemNameMap;
  15266. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15267. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15268. if (rich) {
  15269. richItemNameMap = richItemNameMap || {};
  15270. for (var name in rich) {
  15271. if (rich.hasOwnProperty(name)) {
  15272. richItemNameMap[name] = 1;
  15273. }
  15274. }
  15275. }
  15276. textStyleModel = textStyleModel.parentModel;
  15277. }
  15278. return richItemNameMap;
  15279. }
  15280. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  15281. // In merge mode, default value should not be given.
  15282. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  15283. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  15284. || globalTextStyle.color;
  15285. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  15286. || globalTextStyle.textBorderColor;
  15287. textStyle.textStrokeWidth = retrieve2(
  15288. textStyleModel.getShallow('textBorderWidth'),
  15289. globalTextStyle.textBorderWidth
  15290. );
  15291. if (!isEmphasis) {
  15292. if (isBlock) {
  15293. textStyle.insideRollbackOpt = opt;
  15294. applyDefaultTextStyle(textStyle);
  15295. }
  15296. // Set default finally.
  15297. if (textStyle.textFill == null) {
  15298. textStyle.textFill = opt.autoColor;
  15299. }
  15300. }
  15301. // Do not use `getFont` here, because merge should be supported, where
  15302. // part of these properties may be changed in emphasis style, and the
  15303. // others should remain their original value got from normal style.
  15304. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  15305. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  15306. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  15307. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  15308. textStyle.textAlign = textStyleModel.getShallow('align');
  15309. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  15310. || textStyleModel.getShallow('baseline');
  15311. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  15312. textStyle.textWidth = textStyleModel.getShallow('width');
  15313. textStyle.textHeight = textStyleModel.getShallow('height');
  15314. textStyle.textTag = textStyleModel.getShallow('tag');
  15315. if (!isBlock || !opt.disableBox) {
  15316. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  15317. textStyle.textPadding = textStyleModel.getShallow('padding');
  15318. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  15319. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  15320. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  15321. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  15322. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  15323. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  15324. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  15325. }
  15326. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  15327. || globalTextStyle.textShadowColor;
  15328. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  15329. || globalTextStyle.textShadowBlur;
  15330. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  15331. || globalTextStyle.textShadowOffsetX;
  15332. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  15333. || globalTextStyle.textShadowOffsetY;
  15334. }
  15335. function getAutoColor(color, opt) {
  15336. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  15337. }
  15338. /**
  15339. * Give some default value to the input `textStyle` object, based on the current settings
  15340. * in this `textStyle` object.
  15341. *
  15342. * The Scenario:
  15343. * when text position is `inside` and `textFill` is not specified, we show
  15344. * text border by default for better view. But it should be considered that text position
  15345. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  15346. * restore the style.
  15347. *
  15348. * Usage (& NOTICE):
  15349. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  15350. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  15351. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  15352. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  15353. * does, `rollbackDefaultTextStyle` is not needed to be called).
  15354. */
  15355. function applyDefaultTextStyle(textStyle) {
  15356. var textPosition = textStyle.textPosition;
  15357. var opt = textStyle.insideRollbackOpt;
  15358. var insideRollback;
  15359. if (opt && textStyle.textFill == null) {
  15360. var autoColor = opt.autoColor;
  15361. var isRectText = opt.isRectText;
  15362. var useInsideStyle = opt.useInsideStyle;
  15363. var useInsideStyleCache = useInsideStyle !== false
  15364. && (useInsideStyle === true
  15365. || (isRectText
  15366. && textPosition
  15367. // textPosition can be [10, 30]
  15368. && typeof textPosition === 'string'
  15369. && textPosition.indexOf('inside') >= 0
  15370. )
  15371. );
  15372. var useAutoColorCache = !useInsideStyleCache && autoColor != null;
  15373. // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  15374. if (useInsideStyleCache || useAutoColorCache) {
  15375. insideRollback = {
  15376. textFill: textStyle.textFill,
  15377. textStroke: textStyle.textStroke,
  15378. textStrokeWidth: textStyle.textStrokeWidth
  15379. };
  15380. }
  15381. if (useInsideStyleCache) {
  15382. textStyle.textFill = '#fff';
  15383. // Consider text with #fff overflow its container.
  15384. if (textStyle.textStroke == null) {
  15385. textStyle.textStroke = autoColor;
  15386. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  15387. }
  15388. }
  15389. if (useAutoColorCache) {
  15390. textStyle.textFill = autoColor;
  15391. }
  15392. }
  15393. // Always set `insideRollback`, so that the previous one can be cleared.
  15394. textStyle.insideRollback = insideRollback;
  15395. }
  15396. /**
  15397. * Consider the case: in a scatter,
  15398. * label: {
  15399. * normal: {position: 'inside'},
  15400. * emphasis: {position: 'top'}
  15401. * }
  15402. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  15403. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  15404. * should be retured to 'autoColor', but not keep '#fff'.
  15405. */
  15406. function rollbackDefaultTextStyle(style) {
  15407. var insideRollback = style.insideRollback;
  15408. if (insideRollback) {
  15409. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  15410. style.textFill = insideRollback.textFill;
  15411. style.textStroke = insideRollback.textStroke;
  15412. style.textStrokeWidth = insideRollback.textStrokeWidth;
  15413. style.insideRollback = null;
  15414. }
  15415. }
  15416. function getFont(opt, ecModel) {
  15417. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15418. return trim([
  15419. // FIXME in node-canvas fontWeight is before fontStyle
  15420. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  15421. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  15422. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  15423. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  15424. ].join(' '));
  15425. }
  15426. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  15427. if (typeof dataIndex === 'function') {
  15428. cb = dataIndex;
  15429. dataIndex = null;
  15430. }
  15431. // Do not check 'animation' property directly here. Consider this case:
  15432. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  15433. // but its parent model (`seriesModel`) does.
  15434. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  15435. if (animationEnabled) {
  15436. var postfix = isUpdate ? 'Update' : '';
  15437. var duration = animatableModel.getShallow('animationDuration' + postfix);
  15438. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  15439. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  15440. if (typeof animationDelay === 'function') {
  15441. animationDelay = animationDelay(
  15442. dataIndex,
  15443. animatableModel.getAnimationDelayParams
  15444. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  15445. : null
  15446. );
  15447. }
  15448. if (typeof duration === 'function') {
  15449. duration = duration(dataIndex);
  15450. }
  15451. duration > 0
  15452. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  15453. : (el.stopAnimation(), el.attr(props), cb && cb());
  15454. }
  15455. else {
  15456. el.stopAnimation();
  15457. el.attr(props);
  15458. cb && cb();
  15459. }
  15460. }
  15461. /**
  15462. * Update graphic element properties with or without animation according to the
  15463. * configuration in series.
  15464. *
  15465. * Caution: this method will stop previous animation.
  15466. * So if do not use this method to one element twice before
  15467. * animation starts, unless you know what you are doing.
  15468. *
  15469. * @param {module:zrender/Element} el
  15470. * @param {Object} props
  15471. * @param {module:echarts/model/Model} [animatableModel]
  15472. * @param {number} [dataIndex]
  15473. * @param {Function} [cb]
  15474. * @example
  15475. * graphic.updateProps(el, {
  15476. * position: [100, 100]
  15477. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  15478. * // Or
  15479. * graphic.updateProps(el, {
  15480. * position: [100, 100]
  15481. * }, seriesModel, function () { console.log('Animation done!'); });
  15482. */
  15483. function updateProps(el, props, animatableModel, dataIndex, cb) {
  15484. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  15485. }
  15486. /**
  15487. * Init graphic element properties with or without animation according to the
  15488. * configuration in series.
  15489. *
  15490. * Caution: this method will stop previous animation.
  15491. * So if do not use this method to one element twice before
  15492. * animation starts, unless you know what you are doing.
  15493. *
  15494. * @param {module:zrender/Element} el
  15495. * @param {Object} props
  15496. * @param {module:echarts/model/Model} [animatableModel]
  15497. * @param {number} [dataIndex]
  15498. * @param {Function} cb
  15499. */
  15500. function initProps(el, props, animatableModel, dataIndex, cb) {
  15501. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  15502. }
  15503. /**
  15504. * Get transform matrix of target (param target),
  15505. * in coordinate of its ancestor (param ancestor)
  15506. *
  15507. * @param {module:zrender/mixin/Transformable} target
  15508. * @param {module:zrender/mixin/Transformable} [ancestor]
  15509. */
  15510. function getTransform(target, ancestor) {
  15511. var mat = identity([]);
  15512. while (target && target !== ancestor) {
  15513. mul$1(mat, target.getLocalTransform(), mat);
  15514. target = target.parent;
  15515. }
  15516. return mat;
  15517. }
  15518. /**
  15519. * Apply transform to an vertex.
  15520. * @param {Array.<number>} target [x, y]
  15521. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  15522. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  15523. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  15524. * @param {boolean=} invert Whether use invert matrix.
  15525. * @return {Array.<number>} [x, y]
  15526. */
  15527. function applyTransform$1(target, transform, invert$$1) {
  15528. if (transform && !isArrayLike(transform)) {
  15529. transform = Transformable.getLocalTransform(transform);
  15530. }
  15531. if (invert$$1) {
  15532. transform = invert([], transform);
  15533. }
  15534. return applyTransform([], target, transform);
  15535. }
  15536. /**
  15537. * @param {string} direction 'left' 'right' 'top' 'bottom'
  15538. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  15539. * @param {boolean=} invert Whether use invert matrix.
  15540. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  15541. */
  15542. function transformDirection(direction, transform, invert$$1) {
  15543. // Pick a base, ensure that transform result will not be (0, 0).
  15544. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  15545. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  15546. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  15547. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  15548. var vertex = [
  15549. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  15550. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  15551. ];
  15552. vertex = applyTransform$1(vertex, transform, invert$$1);
  15553. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  15554. ? (vertex[0] > 0 ? 'right' : 'left')
  15555. : (vertex[1] > 0 ? 'bottom' : 'top');
  15556. }
  15557. /**
  15558. * Apply group transition animation from g1 to g2.
  15559. * If no animatableModel, no animation.
  15560. */
  15561. function groupTransition(g1, g2, animatableModel, cb) {
  15562. if (!g1 || !g2) {
  15563. return;
  15564. }
  15565. function getElMap(g) {
  15566. var elMap = {};
  15567. g.traverse(function (el) {
  15568. if (!el.isGroup && el.anid) {
  15569. elMap[el.anid] = el;
  15570. }
  15571. });
  15572. return elMap;
  15573. }
  15574. function getAnimatableProps(el) {
  15575. var obj = {
  15576. position: clone$1(el.position),
  15577. rotation: el.rotation
  15578. };
  15579. if (el.shape) {
  15580. obj.shape = extend({}, el.shape);
  15581. }
  15582. return obj;
  15583. }
  15584. var elMap1 = getElMap(g1);
  15585. g2.traverse(function (el) {
  15586. if (!el.isGroup && el.anid) {
  15587. var oldEl = elMap1[el.anid];
  15588. if (oldEl) {
  15589. var newProp = getAnimatableProps(el);
  15590. el.attr(getAnimatableProps(oldEl));
  15591. updateProps(el, newProp, animatableModel, el.dataIndex);
  15592. }
  15593. // else {
  15594. // if (el.previousProps) {
  15595. // graphic.updateProps
  15596. // }
  15597. // }
  15598. }
  15599. });
  15600. }
  15601. /**
  15602. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  15603. * @param {Object} rect {x, y, width, height}
  15604. * @return {Array.<Array.<number>>} A new clipped points.
  15605. */
  15606. function clipPointsByRect(points, rect) {
  15607. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  15608. // and when element have border.
  15609. return map(points, function (point) {
  15610. var x = point[0];
  15611. x = mathMax$1(x, rect.x);
  15612. x = mathMin$1(x, rect.x + rect.width);
  15613. var y = point[1];
  15614. y = mathMax$1(y, rect.y);
  15615. y = mathMin$1(y, rect.y + rect.height);
  15616. return [x, y];
  15617. });
  15618. }
  15619. /**
  15620. * @param {Object} targetRect {x, y, width, height}
  15621. * @param {Object} rect {x, y, width, height}
  15622. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  15623. */
  15624. function clipRectByRect(targetRect, rect) {
  15625. var x = mathMax$1(targetRect.x, rect.x);
  15626. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  15627. var y = mathMax$1(targetRect.y, rect.y);
  15628. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  15629. // If the total rect is cliped, nothing, including the border,
  15630. // should be painted. So return undefined.
  15631. if (x2 >= x && y2 >= y) {
  15632. return {
  15633. x: x,
  15634. y: y,
  15635. width: x2 - x,
  15636. height: y2 - y
  15637. };
  15638. }
  15639. }
  15640. /**
  15641. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  15642. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  15643. * @param {Object} [rect] {x, y, width, height}
  15644. * @return {module:zrender/Element} Icon path or image element.
  15645. */
  15646. function createIcon(iconStr, opt, rect) {
  15647. opt = extend({rectHover: true}, opt);
  15648. var style = opt.style = {strokeNoScale: true};
  15649. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  15650. if (iconStr) {
  15651. return iconStr.indexOf('image://') === 0
  15652. ? (
  15653. style.image = iconStr.slice(8),
  15654. defaults(style, rect),
  15655. new ZImage(opt)
  15656. )
  15657. : (
  15658. makePath(
  15659. iconStr.replace('path://', ''),
  15660. opt,
  15661. rect,
  15662. 'center'
  15663. )
  15664. );
  15665. }
  15666. }
  15667. /**
  15668. * Return `true` if the given line (line `a`) and the given polygon
  15669. * are intersect.
  15670. * Note that we do not count colinear as intersect here because no
  15671. * requirement for that. We could do that if required in future.
  15672. *
  15673. * @param {number} a1x
  15674. * @param {number} a1y
  15675. * @param {number} a2x
  15676. * @param {number} a2y
  15677. * @param {Array.<Array.<number>>} points Points of the polygon.
  15678. * @return {boolean}
  15679. */
  15680. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  15681. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  15682. var p = points[i];
  15683. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  15684. return true;
  15685. }
  15686. p2 = p;
  15687. }
  15688. }
  15689. /**
  15690. * Return `true` if the given two lines (line `a` and line `b`)
  15691. * are intersect.
  15692. * Note that we do not count colinear as intersect here because no
  15693. * requirement for that. We could do that if required in future.
  15694. *
  15695. * @param {number} a1x
  15696. * @param {number} a1y
  15697. * @param {number} a2x
  15698. * @param {number} a2y
  15699. * @param {number} b1x
  15700. * @param {number} b1y
  15701. * @param {number} b2x
  15702. * @param {number} b2y
  15703. * @return {boolean}
  15704. */
  15705. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  15706. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  15707. var mx = a2x - a1x;
  15708. var my = a2y - a1y;
  15709. var nx = b2x - b1x;
  15710. var ny = b2y - b1y;
  15711. // `vec_m` and `vec_n` are parallel iff
  15712. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  15713. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  15714. if (nearZero(nmCrossProduct)) {
  15715. return false;
  15716. }
  15717. // `vec_m` and `vec_n` are intersect iff
  15718. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  15719. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  15720. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  15721. var b1a1x = a1x - b1x;
  15722. var b1a1y = a1y - b1y;
  15723. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  15724. if (q < 0 || q > 1) {
  15725. return false;
  15726. }
  15727. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  15728. if (p < 0 || p > 1) {
  15729. return false;
  15730. }
  15731. return true;
  15732. }
  15733. /**
  15734. * Cross product of 2-dimension vector.
  15735. */
  15736. function crossProduct2d(x1, y1, x2, y2) {
  15737. return x1 * y2 - x2 * y1;
  15738. }
  15739. function nearZero(val) {
  15740. return val <= (1e-6) && val >= -(1e-6);
  15741. }
  15742. // Register built-in shapes. These shapes might be overwirtten
  15743. // by users, although we do not recommend that.
  15744. registerShape('circle', Circle);
  15745. registerShape('sector', Sector);
  15746. registerShape('ring', Ring);
  15747. registerShape('polygon', Polygon);
  15748. registerShape('polyline', Polyline);
  15749. registerShape('rect', Rect);
  15750. registerShape('line', Line);
  15751. registerShape('bezierCurve', BezierCurve);
  15752. registerShape('arc', Arc);
  15753. var graphic = (Object.freeze || Object)({
  15754. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15755. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  15756. extendShape: extendShape,
  15757. extendPath: extendPath,
  15758. registerShape: registerShape,
  15759. getShapeClass: getShapeClass,
  15760. makePath: makePath,
  15761. makeImage: makeImage,
  15762. mergePath: mergePath,
  15763. resizePath: resizePath,
  15764. subPixelOptimizeLine: subPixelOptimizeLine,
  15765. subPixelOptimizeRect: subPixelOptimizeRect,
  15766. subPixelOptimize: subPixelOptimize,
  15767. setElementHoverStyle: setElementHoverStyle,
  15768. setHoverStyle: setHoverStyle,
  15769. setAsHighDownDispatcher: setAsHighDownDispatcher,
  15770. isHighDownDispatcher: isHighDownDispatcher,
  15771. getHighlightDigit: getHighlightDigit,
  15772. setLabelStyle: setLabelStyle,
  15773. modifyLabelStyle: modifyLabelStyle,
  15774. setTextStyle: setTextStyle,
  15775. setText: setText,
  15776. getFont: getFont,
  15777. updateProps: updateProps,
  15778. initProps: initProps,
  15779. getTransform: getTransform,
  15780. applyTransform: applyTransform$1,
  15781. transformDirection: transformDirection,
  15782. groupTransition: groupTransition,
  15783. clipPointsByRect: clipPointsByRect,
  15784. clipRectByRect: clipRectByRect,
  15785. createIcon: createIcon,
  15786. linePolygonIntersect: linePolygonIntersect,
  15787. lineLineIntersect: lineLineIntersect,
  15788. Group: Group,
  15789. Image: ZImage,
  15790. Text: Text,
  15791. Circle: Circle,
  15792. Sector: Sector,
  15793. Ring: Ring,
  15794. Polygon: Polygon,
  15795. Polyline: Polyline,
  15796. Rect: Rect,
  15797. Line: Line,
  15798. BezierCurve: BezierCurve,
  15799. Arc: Arc,
  15800. IncrementalDisplayable: IncrementalDisplayble,
  15801. CompoundPath: CompoundPath,
  15802. LinearGradient: LinearGradient,
  15803. RadialGradient: RadialGradient,
  15804. BoundingRect: BoundingRect
  15805. });
  15806. /*
  15807. * Licensed to the Apache Software Foundation (ASF) under one
  15808. * or more contributor license agreements. See the NOTICE file
  15809. * distributed with this work for additional information
  15810. * regarding copyright ownership. The ASF licenses this file
  15811. * to you under the Apache License, Version 2.0 (the
  15812. * "License"); you may not use this file except in compliance
  15813. * with the License. You may obtain a copy of the License at
  15814. *
  15815. * http://www.apache.org/licenses/LICENSE-2.0
  15816. *
  15817. * Unless required by applicable law or agreed to in writing,
  15818. * software distributed under the License is distributed on an
  15819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15820. * KIND, either express or implied. See the License for the
  15821. * specific language governing permissions and limitations
  15822. * under the License.
  15823. */
  15824. var PATH_COLOR = ['textStyle', 'color'];
  15825. var textStyleMixin = {
  15826. /**
  15827. * Get color property or get color from option.textStyle.color
  15828. * @param {boolean} [isEmphasis]
  15829. * @return {string}
  15830. */
  15831. getTextColor: function (isEmphasis) {
  15832. var ecModel = this.ecModel;
  15833. return this.getShallow('color')
  15834. || (
  15835. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15836. );
  15837. },
  15838. /**
  15839. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15840. * @return {string}
  15841. */
  15842. getFont: function () {
  15843. return getFont({
  15844. fontStyle: this.getShallow('fontStyle'),
  15845. fontWeight: this.getShallow('fontWeight'),
  15846. fontSize: this.getShallow('fontSize'),
  15847. fontFamily: this.getShallow('fontFamily')
  15848. }, this.ecModel);
  15849. },
  15850. getTextRect: function (text) {
  15851. return getBoundingRect(
  15852. text,
  15853. this.getFont(),
  15854. this.getShallow('align'),
  15855. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15856. this.getShallow('padding'),
  15857. this.getShallow('lineHeight'),
  15858. this.getShallow('rich'),
  15859. this.getShallow('truncateText')
  15860. );
  15861. }
  15862. };
  15863. /*
  15864. * Licensed to the Apache Software Foundation (ASF) under one
  15865. * or more contributor license agreements. See the NOTICE file
  15866. * distributed with this work for additional information
  15867. * regarding copyright ownership. The ASF licenses this file
  15868. * to you under the Apache License, Version 2.0 (the
  15869. * "License"); you may not use this file except in compliance
  15870. * with the License. You may obtain a copy of the License at
  15871. *
  15872. * http://www.apache.org/licenses/LICENSE-2.0
  15873. *
  15874. * Unless required by applicable law or agreed to in writing,
  15875. * software distributed under the License is distributed on an
  15876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15877. * KIND, either express or implied. See the License for the
  15878. * specific language governing permissions and limitations
  15879. * under the License.
  15880. */
  15881. var getItemStyle = makeStyleMapper(
  15882. [
  15883. ['fill', 'color'],
  15884. ['stroke', 'borderColor'],
  15885. ['lineWidth', 'borderWidth'],
  15886. ['opacity'],
  15887. ['shadowBlur'],
  15888. ['shadowOffsetX'],
  15889. ['shadowOffsetY'],
  15890. ['shadowColor'],
  15891. ['textPosition'],
  15892. ['textAlign']
  15893. ]
  15894. );
  15895. var itemStyleMixin = {
  15896. getItemStyle: function (excludes, includes) {
  15897. var style = getItemStyle(this, excludes, includes);
  15898. var lineDash = this.getBorderLineDash();
  15899. lineDash && (style.lineDash = lineDash);
  15900. return style;
  15901. },
  15902. getBorderLineDash: function () {
  15903. var lineType = this.get('borderType');
  15904. return (lineType === 'solid' || lineType == null) ? null
  15905. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15906. }
  15907. };
  15908. /*
  15909. * Licensed to the Apache Software Foundation (ASF) under one
  15910. * or more contributor license agreements. See the NOTICE file
  15911. * distributed with this work for additional information
  15912. * regarding copyright ownership. The ASF licenses this file
  15913. * to you under the Apache License, Version 2.0 (the
  15914. * "License"); you may not use this file except in compliance
  15915. * with the License. You may obtain a copy of the License at
  15916. *
  15917. * http://www.apache.org/licenses/LICENSE-2.0
  15918. *
  15919. * Unless required by applicable law or agreed to in writing,
  15920. * software distributed under the License is distributed on an
  15921. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15922. * KIND, either express or implied. See the License for the
  15923. * specific language governing permissions and limitations
  15924. * under the License.
  15925. */
  15926. /**
  15927. * @module echarts/model/Model
  15928. */
  15929. var mixin$1 = mixin;
  15930. var inner = makeInner();
  15931. /**
  15932. * @alias module:echarts/model/Model
  15933. * @constructor
  15934. * @param {Object} [option]
  15935. * @param {module:echarts/model/Model} [parentModel]
  15936. * @param {module:echarts/model/Global} [ecModel]
  15937. */
  15938. function Model(option, parentModel, ecModel) {
  15939. /**
  15940. * @type {module:echarts/model/Model}
  15941. * @readOnly
  15942. */
  15943. this.parentModel = parentModel;
  15944. /**
  15945. * @type {module:echarts/model/Global}
  15946. * @readOnly
  15947. */
  15948. this.ecModel = ecModel;
  15949. /**
  15950. * @type {Object}
  15951. * @protected
  15952. */
  15953. this.option = option;
  15954. // Simple optimization
  15955. // if (this.init) {
  15956. // if (arguments.length <= 4) {
  15957. // this.init(option, parentModel, ecModel, extraOpt);
  15958. // }
  15959. // else {
  15960. // this.init.apply(this, arguments);
  15961. // }
  15962. // }
  15963. }
  15964. Model.prototype = {
  15965. constructor: Model,
  15966. /**
  15967. * Model 的初始化函数
  15968. * @param {Object} option
  15969. */
  15970. init: null,
  15971. /**
  15972. * 从新的 Option merge
  15973. */
  15974. mergeOption: function (option) {
  15975. merge(this.option, option, true);
  15976. },
  15977. /**
  15978. * @param {string|Array.<string>} path
  15979. * @param {boolean} [ignoreParent=false]
  15980. * @return {*}
  15981. */
  15982. get: function (path, ignoreParent) {
  15983. if (path == null) {
  15984. return this.option;
  15985. }
  15986. return doGet(
  15987. this.option,
  15988. this.parsePath(path),
  15989. !ignoreParent && getParent(this, path)
  15990. );
  15991. },
  15992. /**
  15993. * @param {string} key
  15994. * @param {boolean} [ignoreParent=false]
  15995. * @return {*}
  15996. */
  15997. getShallow: function (key, ignoreParent) {
  15998. var option = this.option;
  15999. var val = option == null ? option : option[key];
  16000. var parentModel = !ignoreParent && getParent(this, key);
  16001. if (val == null && parentModel) {
  16002. val = parentModel.getShallow(key);
  16003. }
  16004. return val;
  16005. },
  16006. /**
  16007. * @param {string|Array.<string>} [path]
  16008. * @param {module:echarts/model/Model} [parentModel]
  16009. * @return {module:echarts/model/Model}
  16010. */
  16011. getModel: function (path, parentModel) {
  16012. var obj = path == null
  16013. ? this.option
  16014. : doGet(this.option, path = this.parsePath(path));
  16015. var thisParentModel;
  16016. parentModel = parentModel || (
  16017. (thisParentModel = getParent(this, path))
  16018. && thisParentModel.getModel(path)
  16019. );
  16020. return new Model(obj, parentModel, this.ecModel);
  16021. },
  16022. /**
  16023. * If model has option
  16024. */
  16025. isEmpty: function () {
  16026. return this.option == null;
  16027. },
  16028. restoreData: function () {},
  16029. // Pending
  16030. clone: function () {
  16031. var Ctor = this.constructor;
  16032. return new Ctor(clone(this.option));
  16033. },
  16034. setReadOnly: function (properties) {
  16035. // clazzUtil.setReadOnly(this, properties);
  16036. },
  16037. // If path is null/undefined, return null/undefined.
  16038. parsePath: function (path) {
  16039. if (typeof path === 'string') {
  16040. path = path.split('.');
  16041. }
  16042. return path;
  16043. },
  16044. /**
  16045. * @param {Function} getParentMethod
  16046. * param {Array.<string>|string} path
  16047. * return {module:echarts/model/Model}
  16048. */
  16049. customizeGetParent: function (getParentMethod) {
  16050. inner(this).getParent = getParentMethod;
  16051. },
  16052. isAnimationEnabled: function () {
  16053. if (!env$1.node) {
  16054. if (this.option.animation != null) {
  16055. return !!this.option.animation;
  16056. }
  16057. else if (this.parentModel) {
  16058. return this.parentModel.isAnimationEnabled();
  16059. }
  16060. }
  16061. }
  16062. };
  16063. function doGet(obj, pathArr, parentModel) {
  16064. for (var i = 0; i < pathArr.length; i++) {
  16065. // Ignore empty
  16066. if (!pathArr[i]) {
  16067. continue;
  16068. }
  16069. // obj could be number/string/... (like 0)
  16070. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  16071. if (obj == null) {
  16072. break;
  16073. }
  16074. }
  16075. if (obj == null && parentModel) {
  16076. obj = parentModel.get(pathArr);
  16077. }
  16078. return obj;
  16079. }
  16080. // `path` can be null/undefined
  16081. function getParent(model, path) {
  16082. var getParentMethod = inner(model).getParent;
  16083. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  16084. }
  16085. // Enable Model.extend.
  16086. enableClassExtend(Model);
  16087. enableClassCheck(Model);
  16088. mixin$1(Model, lineStyleMixin);
  16089. mixin$1(Model, areaStyleMixin);
  16090. mixin$1(Model, textStyleMixin);
  16091. mixin$1(Model, itemStyleMixin);
  16092. /*
  16093. * Licensed to the Apache Software Foundation (ASF) under one
  16094. * or more contributor license agreements. See the NOTICE file
  16095. * distributed with this work for additional information
  16096. * regarding copyright ownership. The ASF licenses this file
  16097. * to you under the Apache License, Version 2.0 (the
  16098. * "License"); you may not use this file except in compliance
  16099. * with the License. You may obtain a copy of the License at
  16100. *
  16101. * http://www.apache.org/licenses/LICENSE-2.0
  16102. *
  16103. * Unless required by applicable law or agreed to in writing,
  16104. * software distributed under the License is distributed on an
  16105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16106. * KIND, either express or implied. See the License for the
  16107. * specific language governing permissions and limitations
  16108. * under the License.
  16109. */
  16110. var base = 0;
  16111. /**
  16112. * @public
  16113. * @param {string} type
  16114. * @return {string}
  16115. */
  16116. function getUID(type) {
  16117. // Considering the case of crossing js context,
  16118. // use Math.random to make id as unique as possible.
  16119. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  16120. }
  16121. /**
  16122. * @inner
  16123. */
  16124. function enableSubTypeDefaulter(entity) {
  16125. var subTypeDefaulters = {};
  16126. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  16127. componentType = parseClassType$1(componentType);
  16128. subTypeDefaulters[componentType.main] = defaulter;
  16129. };
  16130. entity.determineSubType = function (componentType, option) {
  16131. var type = option.type;
  16132. if (!type) {
  16133. var componentTypeMain = parseClassType$1(componentType).main;
  16134. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  16135. type = subTypeDefaulters[componentTypeMain](option);
  16136. }
  16137. }
  16138. return type;
  16139. };
  16140. return entity;
  16141. }
  16142. /**
  16143. * Topological travel on Activity Network (Activity On Vertices).
  16144. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  16145. *
  16146. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  16147. *
  16148. * If there is circle dependencey, Error will be thrown.
  16149. *
  16150. */
  16151. function enableTopologicalTravel(entity, dependencyGetter) {
  16152. /**
  16153. * @public
  16154. * @param {Array.<string>} targetNameList Target Component type list.
  16155. * Can be ['aa', 'bb', 'aa.xx']
  16156. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  16157. * @param {Function} callback Params: componentType, dependencies.
  16158. * @param {Object} context Scope of callback.
  16159. */
  16160. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  16161. if (!targetNameList.length) {
  16162. return;
  16163. }
  16164. var result = makeDepndencyGraph(fullNameList);
  16165. var graph = result.graph;
  16166. var stack = result.noEntryList;
  16167. var targetNameSet = {};
  16168. each$1(targetNameList, function (name) {
  16169. targetNameSet[name] = true;
  16170. });
  16171. while (stack.length) {
  16172. var currComponentType = stack.pop();
  16173. var currVertex = graph[currComponentType];
  16174. var isInTargetNameSet = !!targetNameSet[currComponentType];
  16175. if (isInTargetNameSet) {
  16176. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  16177. delete targetNameSet[currComponentType];
  16178. }
  16179. each$1(
  16180. currVertex.successor,
  16181. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  16182. );
  16183. }
  16184. each$1(targetNameSet, function () {
  16185. throw new Error('Circle dependency may exists');
  16186. });
  16187. function removeEdge(succComponentType) {
  16188. graph[succComponentType].entryCount--;
  16189. if (graph[succComponentType].entryCount === 0) {
  16190. stack.push(succComponentType);
  16191. }
  16192. }
  16193. // Consider this case: legend depends on series, and we call
  16194. // chart.setOption({series: [...]}), where only series is in option.
  16195. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  16196. // not be called, but only sereis.mergeOption is called. Thus legend
  16197. // have no chance to update its local record about series (like which
  16198. // name of series is available in legend).
  16199. function removeEdgeAndAdd(succComponentType) {
  16200. targetNameSet[succComponentType] = true;
  16201. removeEdge(succComponentType);
  16202. }
  16203. };
  16204. /**
  16205. * DepndencyGraph: {Object}
  16206. * key: conponentType,
  16207. * value: {
  16208. * successor: [conponentTypes...],
  16209. * originalDeps: [conponentTypes...],
  16210. * entryCount: {number}
  16211. * }
  16212. */
  16213. function makeDepndencyGraph(fullNameList) {
  16214. var graph = {};
  16215. var noEntryList = [];
  16216. each$1(fullNameList, function (name) {
  16217. var thisItem = createDependencyGraphItem(graph, name);
  16218. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  16219. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  16220. thisItem.entryCount = availableDeps.length;
  16221. if (thisItem.entryCount === 0) {
  16222. noEntryList.push(name);
  16223. }
  16224. each$1(availableDeps, function (dependentName) {
  16225. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  16226. thisItem.predecessor.push(dependentName);
  16227. }
  16228. var thatItem = createDependencyGraphItem(graph, dependentName);
  16229. if (indexOf(thatItem.successor, dependentName) < 0) {
  16230. thatItem.successor.push(name);
  16231. }
  16232. });
  16233. });
  16234. return {graph: graph, noEntryList: noEntryList};
  16235. }
  16236. function createDependencyGraphItem(graph, name) {
  16237. if (!graph[name]) {
  16238. graph[name] = {predecessor: [], successor: []};
  16239. }
  16240. return graph[name];
  16241. }
  16242. function getAvailableDependencies(originalDeps, fullNameList) {
  16243. var availableDeps = [];
  16244. each$1(originalDeps, function (dep) {
  16245. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  16246. });
  16247. return availableDeps;
  16248. }
  16249. }
  16250. /*
  16251. * Licensed to the Apache Software Foundation (ASF) under one
  16252. * or more contributor license agreements. See the NOTICE file
  16253. * distributed with this work for additional information
  16254. * regarding copyright ownership. The ASF licenses this file
  16255. * to you under the Apache License, Version 2.0 (the
  16256. * "License"); you may not use this file except in compliance
  16257. * with the License. You may obtain a copy of the License at
  16258. *
  16259. * http://www.apache.org/licenses/LICENSE-2.0
  16260. *
  16261. * Unless required by applicable law or agreed to in writing,
  16262. * software distributed under the License is distributed on an
  16263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16264. * KIND, either express or implied. See the License for the
  16265. * specific language governing permissions and limitations
  16266. * under the License.
  16267. */
  16268. /*
  16269. * A third-party license is embeded for some of the code in this file:
  16270. * The method "quantile" was copied from "d3.js".
  16271. * (See more details in the comment of the method below.)
  16272. * The use of the source code of this file is also subject to the terms
  16273. * and consitions of the license of "d3.js" (BSD-3Clause, see
  16274. * </licenses/LICENSE-d3>).
  16275. */
  16276. var RADIAN_EPSILON = 1e-4;
  16277. function _trim(str) {
  16278. return str.replace(/^\s+|\s+$/g, '');
  16279. }
  16280. /**
  16281. * Linear mapping a value from domain to range
  16282. * @memberOf module:echarts/util/number
  16283. * @param {(number|Array.<number>)} val
  16284. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  16285. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  16286. * @param {boolean} clamp
  16287. * @return {(number|Array.<number>}
  16288. */
  16289. function linearMap(val, domain, range, clamp) {
  16290. var subDomain = domain[1] - domain[0];
  16291. var subRange = range[1] - range[0];
  16292. if (subDomain === 0) {
  16293. return subRange === 0
  16294. ? range[0]
  16295. : (range[0] + range[1]) / 2;
  16296. }
  16297. // Avoid accuracy problem in edge, such as
  16298. // 146.39 - 62.83 === 83.55999999999999.
  16299. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  16300. // It is a little verbose for efficiency considering this method
  16301. // is a hotspot.
  16302. if (clamp) {
  16303. if (subDomain > 0) {
  16304. if (val <= domain[0]) {
  16305. return range[0];
  16306. }
  16307. else if (val >= domain[1]) {
  16308. return range[1];
  16309. }
  16310. }
  16311. else {
  16312. if (val >= domain[0]) {
  16313. return range[0];
  16314. }
  16315. else if (val <= domain[1]) {
  16316. return range[1];
  16317. }
  16318. }
  16319. }
  16320. else {
  16321. if (val === domain[0]) {
  16322. return range[0];
  16323. }
  16324. if (val === domain[1]) {
  16325. return range[1];
  16326. }
  16327. }
  16328. return (val - domain[0]) / subDomain * subRange + range[0];
  16329. }
  16330. /**
  16331. * Convert a percent string to absolute number.
  16332. * Returns NaN if percent is not a valid string or number
  16333. * @memberOf module:echarts/util/number
  16334. * @param {string|number} percent
  16335. * @param {number} all
  16336. * @return {number}
  16337. */
  16338. function parsePercent$1(percent, all) {
  16339. switch (percent) {
  16340. case 'center':
  16341. case 'middle':
  16342. percent = '50%';
  16343. break;
  16344. case 'left':
  16345. case 'top':
  16346. percent = '0%';
  16347. break;
  16348. case 'right':
  16349. case 'bottom':
  16350. percent = '100%';
  16351. break;
  16352. }
  16353. if (typeof percent === 'string') {
  16354. if (_trim(percent).match(/%$/)) {
  16355. return parseFloat(percent) / 100 * all;
  16356. }
  16357. return parseFloat(percent);
  16358. }
  16359. return percent == null ? NaN : +percent;
  16360. }
  16361. /**
  16362. * (1) Fix rounding error of float numbers.
  16363. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  16364. *
  16365. * @param {number} x
  16366. * @param {number} [precision]
  16367. * @param {boolean} [returnStr]
  16368. * @return {number|string}
  16369. */
  16370. function round$1(x, precision, returnStr) {
  16371. if (precision == null) {
  16372. precision = 10;
  16373. }
  16374. // Avoid range error
  16375. precision = Math.min(Math.max(0, precision), 20);
  16376. x = (+x).toFixed(precision);
  16377. return returnStr ? x : +x;
  16378. }
  16379. /**
  16380. * asc sort arr.
  16381. * The input arr will be modified.
  16382. *
  16383. * @param {Array} arr
  16384. * @return {Array} The input arr.
  16385. */
  16386. /**
  16387. * Get precision
  16388. * @param {number} val
  16389. */
  16390. /**
  16391. * @param {string|number} val
  16392. * @return {number}
  16393. */
  16394. function getPrecisionSafe(val) {
  16395. var str = val.toString();
  16396. // Consider scientific notation: '3.4e-12' '3.4e+12'
  16397. var eIndex = str.indexOf('e');
  16398. if (eIndex > 0) {
  16399. var precision = +str.slice(eIndex + 1);
  16400. return precision < 0 ? -precision : 0;
  16401. }
  16402. else {
  16403. var dotIndex = str.indexOf('.');
  16404. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  16405. }
  16406. }
  16407. /**
  16408. * Minimal dicernible data precisioin according to a single pixel.
  16409. *
  16410. * @param {Array.<number>} dataExtent
  16411. * @param {Array.<number>} pixelExtent
  16412. * @return {number} precision
  16413. */
  16414. function getPixelPrecision(dataExtent, pixelExtent) {
  16415. var log = Math.log;
  16416. var LN10 = Math.LN10;
  16417. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  16418. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  16419. // toFixed() digits argument must be between 0 and 20.
  16420. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  16421. return !isFinite(precision) ? 20 : precision;
  16422. }
  16423. /**
  16424. * Get a data of given precision, assuring the sum of percentages
  16425. * in valueList is 1.
  16426. * The largest remainer method is used.
  16427. * https://en.wikipedia.org/wiki/Largest_remainder_method
  16428. *
  16429. * @param {Array.<number>} valueList a list of all data
  16430. * @param {number} idx index of the data to be processed in valueList
  16431. * @param {number} precision integer number showing digits of precision
  16432. * @return {number} percent ranging from 0 to 100
  16433. */
  16434. function getPercentWithPrecision(valueList, idx, precision) {
  16435. if (!valueList[idx]) {
  16436. return 0;
  16437. }
  16438. var sum = reduce(valueList, function (acc, val) {
  16439. return acc + (isNaN(val) ? 0 : val);
  16440. }, 0);
  16441. if (sum === 0) {
  16442. return 0;
  16443. }
  16444. var digits = Math.pow(10, precision);
  16445. var votesPerQuota = map(valueList, function (val) {
  16446. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  16447. });
  16448. var targetSeats = digits * 100;
  16449. var seats = map(votesPerQuota, function (votes) {
  16450. // Assign automatic seats.
  16451. return Math.floor(votes);
  16452. });
  16453. var currentSum = reduce(seats, function (acc, val) {
  16454. return acc + val;
  16455. }, 0);
  16456. var remainder = map(votesPerQuota, function (votes, idx) {
  16457. return votes - seats[idx];
  16458. });
  16459. // Has remainding votes.
  16460. while (currentSum < targetSeats) {
  16461. // Find next largest remainder.
  16462. var max = Number.NEGATIVE_INFINITY;
  16463. var maxId = null;
  16464. for (var i = 0, len = remainder.length; i < len; ++i) {
  16465. if (remainder[i] > max) {
  16466. max = remainder[i];
  16467. maxId = i;
  16468. }
  16469. }
  16470. // Add a vote to max remainder.
  16471. ++seats[maxId];
  16472. remainder[maxId] = 0;
  16473. ++currentSum;
  16474. }
  16475. return seats[idx] / digits;
  16476. }
  16477. // Number.MAX_SAFE_INTEGER, ie do not support.
  16478. /**
  16479. * To 0 - 2 * PI, considering negative radian.
  16480. * @param {number} radian
  16481. * @return {number}
  16482. */
  16483. function remRadian(radian) {
  16484. var pi2 = Math.PI * 2;
  16485. return (radian % pi2 + pi2) % pi2;
  16486. }
  16487. /**
  16488. * @param {type} radian
  16489. * @return {boolean}
  16490. */
  16491. function isRadianAroundZero(val) {
  16492. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  16493. }
  16494. /* eslint-disable */
  16495. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  16496. /* eslint-enable */
  16497. /**
  16498. * @param {string|Date|number} value These values can be accepted:
  16499. * + An instance of Date, represent a time in its own time zone.
  16500. * + Or string in a subset of ISO 8601, only including:
  16501. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  16502. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  16503. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  16504. * all of which will be treated as local time if time zone is not specified
  16505. * (see <https://momentjs.com/>).
  16506. * + Or other string format, including (all of which will be treated as loacal time):
  16507. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  16508. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  16509. * + a timestamp, which represent a time in UTC.
  16510. * @return {Date} date
  16511. */
  16512. function parseDate(value) {
  16513. if (value instanceof Date) {
  16514. return value;
  16515. }
  16516. else if (typeof value === 'string') {
  16517. // Different browsers parse date in different way, so we parse it manually.
  16518. // Some other issues:
  16519. // new Date('1970-01-01') is UTC,
  16520. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  16521. // See issue #3623
  16522. var match = TIME_REG.exec(value);
  16523. if (!match) {
  16524. // return Invalid Date.
  16525. return new Date(NaN);
  16526. }
  16527. // Use local time when no timezone offset specifed.
  16528. if (!match[8]) {
  16529. // match[n] can only be string or undefined.
  16530. // But take care of '12' + 1 => '121'.
  16531. return new Date(
  16532. +match[1],
  16533. +(match[2] || 1) - 1,
  16534. +match[3] || 1,
  16535. +match[4] || 0,
  16536. +(match[5] || 0),
  16537. +match[6] || 0,
  16538. +match[7] || 0
  16539. );
  16540. }
  16541. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  16542. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  16543. // For example, system timezone is set as "Time Zone: America/Toronto",
  16544. // then these code will get different result:
  16545. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  16546. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  16547. // So we should not use `new Date`, but use `Date.UTC`.
  16548. else {
  16549. var hour = +match[4] || 0;
  16550. if (match[8].toUpperCase() !== 'Z') {
  16551. hour -= match[8].slice(0, 3);
  16552. }
  16553. return new Date(Date.UTC(
  16554. +match[1],
  16555. +(match[2] || 1) - 1,
  16556. +match[3] || 1,
  16557. hour,
  16558. +(match[5] || 0),
  16559. +match[6] || 0,
  16560. +match[7] || 0
  16561. ));
  16562. }
  16563. }
  16564. else if (value == null) {
  16565. return new Date(NaN);
  16566. }
  16567. return new Date(Math.round(value));
  16568. }
  16569. /**
  16570. * Quantity of a number. e.g. 0.1, 1, 10, 100
  16571. *
  16572. * @param {number} val
  16573. * @return {number}
  16574. */
  16575. function quantity(val) {
  16576. return Math.pow(10, quantityExponent(val));
  16577. }
  16578. /**
  16579. * Exponent of the quantity of a number
  16580. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  16581. *
  16582. * @param {number} val non-negative value
  16583. * @return {number}
  16584. */
  16585. function quantityExponent(val) {
  16586. if (val === 0) {
  16587. return 0;
  16588. }
  16589. var exp = Math.floor(Math.log(val) / Math.LN10);
  16590. /**
  16591. * exp is expected to be the rounded-down result of the base-10 log of val.
  16592. * But due to the precision loss with Math.log(val), we need to restore it
  16593. * using 10^exp to make sure we can get val back from exp. #11249
  16594. */
  16595. if (val / Math.pow(10, exp) >= 10) {
  16596. exp++;
  16597. }
  16598. return exp;
  16599. }
  16600. /**
  16601. * find a “nice” number approximately equal to x. Round the number if round = true,
  16602. * take ceiling if round = false. The primary observation is that the “nicest”
  16603. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  16604. *
  16605. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  16606. *
  16607. * @param {number} val Non-negative value.
  16608. * @param {boolean} round
  16609. * @return {number}
  16610. */
  16611. function nice(val, round) {
  16612. var exponent = quantityExponent(val);
  16613. var exp10 = Math.pow(10, exponent);
  16614. var f = val / exp10; // 1 <= f < 10
  16615. var nf;
  16616. if (round) {
  16617. if (f < 1.5) {
  16618. nf = 1;
  16619. }
  16620. else if (f < 2.5) {
  16621. nf = 2;
  16622. }
  16623. else if (f < 4) {
  16624. nf = 3;
  16625. }
  16626. else if (f < 7) {
  16627. nf = 5;
  16628. }
  16629. else {
  16630. nf = 10;
  16631. }
  16632. }
  16633. else {
  16634. if (f < 1) {
  16635. nf = 1;
  16636. }
  16637. else if (f < 2) {
  16638. nf = 2;
  16639. }
  16640. else if (f < 3) {
  16641. nf = 3;
  16642. }
  16643. else if (f < 5) {
  16644. nf = 5;
  16645. }
  16646. else {
  16647. nf = 10;
  16648. }
  16649. }
  16650. val = nf * exp10;
  16651. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  16652. // 20 is the uppper bound of toFixed.
  16653. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  16654. }
  16655. /**
  16656. * This code was copied from "d3.js"
  16657. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  16658. * See the license statement at the head of this file.
  16659. * @param {Array.<number>} ascArr
  16660. */
  16661. /**
  16662. * Order intervals asc, and split them when overlap.
  16663. * expect(numberUtil.reformIntervals([
  16664. * {interval: [18, 62], close: [1, 1]},
  16665. * {interval: [-Infinity, -70], close: [0, 0]},
  16666. * {interval: [-70, -26], close: [1, 1]},
  16667. * {interval: [-26, 18], close: [1, 1]},
  16668. * {interval: [62, 150], close: [1, 1]},
  16669. * {interval: [106, 150], close: [1, 1]},
  16670. * {interval: [150, Infinity], close: [0, 0]}
  16671. * ])).toEqual([
  16672. * {interval: [-Infinity, -70], close: [0, 0]},
  16673. * {interval: [-70, -26], close: [1, 1]},
  16674. * {interval: [-26, 18], close: [0, 1]},
  16675. * {interval: [18, 62], close: [0, 1]},
  16676. * {interval: [62, 150], close: [0, 1]},
  16677. * {interval: [150, Infinity], close: [0, 0]}
  16678. * ]);
  16679. * @param {Array.<Object>} list, where `close` mean open or close
  16680. * of the interval, and Infinity can be used.
  16681. * @return {Array.<Object>} The origin list, which has been reformed.
  16682. */
  16683. /**
  16684. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  16685. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  16686. * subtraction forces infinities to NaN
  16687. *
  16688. * @param {*} v
  16689. * @return {boolean}
  16690. */
  16691. /*
  16692. * Licensed to the Apache Software Foundation (ASF) under one
  16693. * or more contributor license agreements. See the NOTICE file
  16694. * distributed with this work for additional information
  16695. * regarding copyright ownership. The ASF licenses this file
  16696. * to you under the Apache License, Version 2.0 (the
  16697. * "License"); you may not use this file except in compliance
  16698. * with the License. You may obtain a copy of the License at
  16699. *
  16700. * http://www.apache.org/licenses/LICENSE-2.0
  16701. *
  16702. * Unless required by applicable law or agreed to in writing,
  16703. * software distributed under the License is distributed on an
  16704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16705. * KIND, either express or implied. See the License for the
  16706. * specific language governing permissions and limitations
  16707. * under the License.
  16708. */
  16709. // import Text from 'zrender/src/graphic/Text';
  16710. /**
  16711. * 每三位默认加,格式化
  16712. * @param {string|number} x
  16713. * @return {string}
  16714. */
  16715. function addCommas(x) {
  16716. if (isNaN(x)) {
  16717. return '-';
  16718. }
  16719. x = (x + '').split('.');
  16720. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  16721. + (x.length > 1 ? ('.' + x[1]) : '');
  16722. }
  16723. /**
  16724. * @param {string} str
  16725. * @param {boolean} [upperCaseFirst=false]
  16726. * @return {string} str
  16727. */
  16728. var normalizeCssArray$1 = normalizeCssArray;
  16729. var replaceReg = /([&<>"'])/g;
  16730. var replaceMap = {
  16731. '&': '&amp;',
  16732. '<': '&lt;',
  16733. '>': '&gt;',
  16734. '"': '&quot;',
  16735. '\'': '&#39;'
  16736. };
  16737. function encodeHTML(source) {
  16738. return source == null
  16739. ? ''
  16740. : (source + '').replace(replaceReg, function (str, c) {
  16741. return replaceMap[c];
  16742. });
  16743. }
  16744. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16745. var wrapVar = function (varName, seriesIdx) {
  16746. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16747. };
  16748. /**
  16749. * Template formatter
  16750. * @param {string} tpl
  16751. * @param {Array.<Object>|Object} paramsList
  16752. * @param {boolean} [encode=false]
  16753. * @return {string}
  16754. */
  16755. function formatTpl(tpl, paramsList, encode) {
  16756. if (!isArray(paramsList)) {
  16757. paramsList = [paramsList];
  16758. }
  16759. var seriesLen = paramsList.length;
  16760. if (!seriesLen) {
  16761. return '';
  16762. }
  16763. var $vars = paramsList[0].$vars || [];
  16764. for (var i = 0; i < $vars.length; i++) {
  16765. var alias = TPL_VAR_ALIAS[i];
  16766. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16767. }
  16768. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16769. for (var k = 0; k < $vars.length; k++) {
  16770. var val = paramsList[seriesIdx][$vars[k]];
  16771. tpl = tpl.replace(
  16772. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  16773. encode ? encodeHTML(val) : val
  16774. );
  16775. }
  16776. }
  16777. return tpl;
  16778. }
  16779. /**
  16780. * simple Template formatter
  16781. *
  16782. * @param {string} tpl
  16783. * @param {Object} param
  16784. * @param {boolean} [encode=false]
  16785. * @return {string}
  16786. */
  16787. /**
  16788. * @param {Object|string} [opt] If string, means color.
  16789. * @param {string} [opt.color]
  16790. * @param {string} [opt.extraCssText]
  16791. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16792. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16793. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16794. * @return {string}
  16795. */
  16796. function getTooltipMarker(opt, extraCssText) {
  16797. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16798. var color = opt.color;
  16799. var type = opt.type;
  16800. var extraCssText = opt.extraCssText;
  16801. var renderMode = opt.renderMode || 'html';
  16802. var markerId = opt.markerId || 'X';
  16803. if (!color) {
  16804. return '';
  16805. }
  16806. if (renderMode === 'html') {
  16807. return type === 'subItem'
  16808. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16809. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16810. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16811. : '<span style="display:inline-block;margin-right:5px;'
  16812. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16813. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16814. }
  16815. else {
  16816. // Space for rich element marker
  16817. return {
  16818. renderMode: renderMode,
  16819. content: '{marker' + markerId + '|} ',
  16820. style: {
  16821. color: color
  16822. }
  16823. };
  16824. }
  16825. }
  16826. function pad(str, len) {
  16827. str += '';
  16828. return '0000'.substr(0, len - str.length) + str;
  16829. }
  16830. /**
  16831. * ISO Date format
  16832. * @param {string} tpl
  16833. * @param {number} value
  16834. * @param {boolean} [isUTC=false] Default in local time.
  16835. * see `module:echarts/scale/Time`
  16836. * and `module:echarts/util/number#parseDate`.
  16837. * @inner
  16838. */
  16839. function formatTime(tpl, value, isUTC) {
  16840. if (tpl === 'week'
  16841. || tpl === 'month'
  16842. || tpl === 'quarter'
  16843. || tpl === 'half-year'
  16844. || tpl === 'year'
  16845. ) {
  16846. tpl = 'MM-dd\nyyyy';
  16847. }
  16848. var date = parseDate(value);
  16849. var utc = isUTC ? 'UTC' : '';
  16850. var y = date['get' + utc + 'FullYear']();
  16851. var M = date['get' + utc + 'Month']() + 1;
  16852. var d = date['get' + utc + 'Date']();
  16853. var h = date['get' + utc + 'Hours']();
  16854. var m = date['get' + utc + 'Minutes']();
  16855. var s = date['get' + utc + 'Seconds']();
  16856. var S = date['get' + utc + 'Milliseconds']();
  16857. tpl = tpl.replace('MM', pad(M, 2))
  16858. .replace('M', M)
  16859. .replace('yyyy', y)
  16860. .replace('yy', y % 100)
  16861. .replace('dd', pad(d, 2))
  16862. .replace('d', d)
  16863. .replace('hh', pad(h, 2))
  16864. .replace('h', h)
  16865. .replace('mm', pad(m, 2))
  16866. .replace('m', m)
  16867. .replace('ss', pad(s, 2))
  16868. .replace('s', s)
  16869. .replace('SSS', pad(S, 3));
  16870. return tpl;
  16871. }
  16872. /**
  16873. * Capital first
  16874. * @param {string} str
  16875. * @return {string}
  16876. */
  16877. var truncateText$1 = truncateText;
  16878. /**
  16879. * @public
  16880. * @param {Object} opt
  16881. * @param {string} opt.text
  16882. * @param {string} opt.font
  16883. * @param {string} [opt.textAlign='left']
  16884. * @param {string} [opt.textVerticalAlign='top']
  16885. * @param {Array.<number>} [opt.textPadding]
  16886. * @param {number} [opt.textLineHeight]
  16887. * @param {Object} [opt.rich]
  16888. * @param {Object} [opt.truncate]
  16889. * @return {Object} {x, y, width, height, lineHeight}
  16890. */
  16891. /**
  16892. * @deprecated
  16893. * the `textLineHeight` was added later.
  16894. * For backward compatiblility, put it as the last parameter.
  16895. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16896. */
  16897. /*
  16898. * Licensed to the Apache Software Foundation (ASF) under one
  16899. * or more contributor license agreements. See the NOTICE file
  16900. * distributed with this work for additional information
  16901. * regarding copyright ownership. The ASF licenses this file
  16902. * to you under the Apache License, Version 2.0 (the
  16903. * "License"); you may not use this file except in compliance
  16904. * with the License. You may obtain a copy of the License at
  16905. *
  16906. * http://www.apache.org/licenses/LICENSE-2.0
  16907. *
  16908. * Unless required by applicable law or agreed to in writing,
  16909. * software distributed under the License is distributed on an
  16910. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16911. * KIND, either express or implied. See the License for the
  16912. * specific language governing permissions and limitations
  16913. * under the License.
  16914. */
  16915. // Layout helpers for each component positioning
  16916. var each$3 = each$1;
  16917. /**
  16918. * @public
  16919. */
  16920. var LOCATION_PARAMS = [
  16921. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16922. ];
  16923. /**
  16924. * @public
  16925. */
  16926. var HV_NAMES = [
  16927. ['width', 'left', 'right'],
  16928. ['height', 'top', 'bottom']
  16929. ];
  16930. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16931. var x = 0;
  16932. var y = 0;
  16933. if (maxWidth == null) {
  16934. maxWidth = Infinity;
  16935. }
  16936. if (maxHeight == null) {
  16937. maxHeight = Infinity;
  16938. }
  16939. var currentLineMaxSize = 0;
  16940. group.eachChild(function (child, idx) {
  16941. var position = child.position;
  16942. var rect = child.getBoundingRect();
  16943. var nextChild = group.childAt(idx + 1);
  16944. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16945. var nextX;
  16946. var nextY;
  16947. if (orient === 'horizontal') {
  16948. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16949. nextX = x + moveX;
  16950. // Wrap when width exceeds maxWidth or meet a `newline` group
  16951. // FIXME compare before adding gap?
  16952. if (nextX > maxWidth || child.newline) {
  16953. x = 0;
  16954. nextX = moveX;
  16955. y += currentLineMaxSize + gap;
  16956. currentLineMaxSize = rect.height;
  16957. }
  16958. else {
  16959. // FIXME: consider rect.y is not `0`?
  16960. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16961. }
  16962. }
  16963. else {
  16964. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16965. nextY = y + moveY;
  16966. // Wrap when width exceeds maxHeight or meet a `newline` group
  16967. if (nextY > maxHeight || child.newline) {
  16968. x += currentLineMaxSize + gap;
  16969. y = 0;
  16970. nextY = moveY;
  16971. currentLineMaxSize = rect.width;
  16972. }
  16973. else {
  16974. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16975. }
  16976. }
  16977. if (child.newline) {
  16978. return;
  16979. }
  16980. position[0] = x;
  16981. position[1] = y;
  16982. orient === 'horizontal'
  16983. ? (x = nextX + gap)
  16984. : (y = nextY + gap);
  16985. });
  16986. }
  16987. /**
  16988. * VBox or HBox layouting
  16989. * @param {string} orient
  16990. * @param {module:zrender/container/Group} group
  16991. * @param {number} gap
  16992. * @param {number} [width=Infinity]
  16993. * @param {number} [height=Infinity]
  16994. */
  16995. /**
  16996. * VBox layouting
  16997. * @param {module:zrender/container/Group} group
  16998. * @param {number} gap
  16999. * @param {number} [width=Infinity]
  17000. * @param {number} [height=Infinity]
  17001. */
  17002. var vbox = curry(boxLayout, 'vertical');
  17003. /**
  17004. * HBox layouting
  17005. * @param {module:zrender/container/Group} group
  17006. * @param {number} gap
  17007. * @param {number} [width=Infinity]
  17008. * @param {number} [height=Infinity]
  17009. */
  17010. var hbox = curry(boxLayout, 'horizontal');
  17011. /**
  17012. * If x or x2 is not specified or 'center' 'left' 'right',
  17013. * the width would be as long as possible.
  17014. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  17015. * the height would be as long as possible.
  17016. *
  17017. * @param {Object} positionInfo
  17018. * @param {number|string} [positionInfo.x]
  17019. * @param {number|string} [positionInfo.y]
  17020. * @param {number|string} [positionInfo.x2]
  17021. * @param {number|string} [positionInfo.y2]
  17022. * @param {Object} containerRect {width, height}
  17023. * @param {string|number} margin
  17024. * @return {Object} {width, height}
  17025. */
  17026. /**
  17027. * Parse position info.
  17028. *
  17029. * @param {Object} positionInfo
  17030. * @param {number|string} [positionInfo.left]
  17031. * @param {number|string} [positionInfo.top]
  17032. * @param {number|string} [positionInfo.right]
  17033. * @param {number|string} [positionInfo.bottom]
  17034. * @param {number|string} [positionInfo.width]
  17035. * @param {number|string} [positionInfo.height]
  17036. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  17037. * @param {Object} containerRect
  17038. * @param {string|number} [margin]
  17039. *
  17040. * @return {module:zrender/core/BoundingRect}
  17041. */
  17042. function getLayoutRect(
  17043. positionInfo, containerRect, margin
  17044. ) {
  17045. margin = normalizeCssArray$1(margin || 0);
  17046. var containerWidth = containerRect.width;
  17047. var containerHeight = containerRect.height;
  17048. var left = parsePercent$1(positionInfo.left, containerWidth);
  17049. var top = parsePercent$1(positionInfo.top, containerHeight);
  17050. var right = parsePercent$1(positionInfo.right, containerWidth);
  17051. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  17052. var width = parsePercent$1(positionInfo.width, containerWidth);
  17053. var height = parsePercent$1(positionInfo.height, containerHeight);
  17054. var verticalMargin = margin[2] + margin[0];
  17055. var horizontalMargin = margin[1] + margin[3];
  17056. var aspect = positionInfo.aspect;
  17057. // If width is not specified, calculate width from left and right
  17058. if (isNaN(width)) {
  17059. width = containerWidth - right - horizontalMargin - left;
  17060. }
  17061. if (isNaN(height)) {
  17062. height = containerHeight - bottom - verticalMargin - top;
  17063. }
  17064. if (aspect != null) {
  17065. // If width and height are not given
  17066. // 1. Graph should not exceeds the container
  17067. // 2. Aspect must be keeped
  17068. // 3. Graph should take the space as more as possible
  17069. // FIXME
  17070. // Margin is not considered, because there is no case that both
  17071. // using margin and aspect so far.
  17072. if (isNaN(width) && isNaN(height)) {
  17073. if (aspect > containerWidth / containerHeight) {
  17074. width = containerWidth * 0.8;
  17075. }
  17076. else {
  17077. height = containerHeight * 0.8;
  17078. }
  17079. }
  17080. // Calculate width or height with given aspect
  17081. if (isNaN(width)) {
  17082. width = aspect * height;
  17083. }
  17084. if (isNaN(height)) {
  17085. height = width / aspect;
  17086. }
  17087. }
  17088. // If left is not specified, calculate left from right and width
  17089. if (isNaN(left)) {
  17090. left = containerWidth - right - width - horizontalMargin;
  17091. }
  17092. if (isNaN(top)) {
  17093. top = containerHeight - bottom - height - verticalMargin;
  17094. }
  17095. // Align left and top
  17096. switch (positionInfo.left || positionInfo.right) {
  17097. case 'center':
  17098. left = containerWidth / 2 - width / 2 - margin[3];
  17099. break;
  17100. case 'right':
  17101. left = containerWidth - width - horizontalMargin;
  17102. break;
  17103. }
  17104. switch (positionInfo.top || positionInfo.bottom) {
  17105. case 'middle':
  17106. case 'center':
  17107. top = containerHeight / 2 - height / 2 - margin[0];
  17108. break;
  17109. case 'bottom':
  17110. top = containerHeight - height - verticalMargin;
  17111. break;
  17112. }
  17113. // If something is wrong and left, top, width, height are calculated as NaN
  17114. left = left || 0;
  17115. top = top || 0;
  17116. if (isNaN(width)) {
  17117. // Width may be NaN if only one value is given except width
  17118. width = containerWidth - horizontalMargin - left - (right || 0);
  17119. }
  17120. if (isNaN(height)) {
  17121. // Height may be NaN if only one value is given except height
  17122. height = containerHeight - verticalMargin - top - (bottom || 0);
  17123. }
  17124. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  17125. rect.margin = margin;
  17126. return rect;
  17127. }
  17128. /**
  17129. * Position a zr element in viewport
  17130. * Group position is specified by either
  17131. * {left, top}, {right, bottom}
  17132. * If all properties exists, right and bottom will be igonred.
  17133. *
  17134. * Logic:
  17135. * 1. Scale (against origin point in parent coord)
  17136. * 2. Rotate (against origin point in parent coord)
  17137. * 3. Traslate (with el.position by this method)
  17138. * So this method only fixes the last step 'Traslate', which does not affect
  17139. * scaling and rotating.
  17140. *
  17141. * If be called repeatly with the same input el, the same result will be gotten.
  17142. *
  17143. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  17144. * @param {Object} positionInfo
  17145. * @param {number|string} [positionInfo.left]
  17146. * @param {number|string} [positionInfo.top]
  17147. * @param {number|string} [positionInfo.right]
  17148. * @param {number|string} [positionInfo.bottom]
  17149. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  17150. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  17151. * @param {Object} containerRect
  17152. * @param {string|number} margin
  17153. * @param {Object} [opt]
  17154. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  17155. * @param {Array.<number>} [opt.boundingMode='all']
  17156. * Specify how to calculate boundingRect when locating.
  17157. * 'all': Position the boundingRect that is transformed and uioned
  17158. * both itself and its descendants.
  17159. * This mode simplies confine the elements in the bounding
  17160. * of their container (e.g., using 'right: 0').
  17161. * 'raw': Position the boundingRect that is not transformed and only itself.
  17162. * This mode is useful when you want a element can overflow its
  17163. * container. (Consider a rotated circle needs to be located in a corner.)
  17164. * In this mode positionInfo.width/height can only be number.
  17165. */
  17166. /**
  17167. * @param {Object} option Contains some of the properties in HV_NAMES.
  17168. * @param {number} hvIdx 0: horizontal; 1: vertical.
  17169. */
  17170. /**
  17171. * Consider Case:
  17172. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  17173. * through setOption or media query, using normal zrUtil.merge will cause
  17174. * {right: 0} does not take effect.
  17175. *
  17176. * @example
  17177. * ComponentModel.extend({
  17178. * init: function () {
  17179. * ...
  17180. * var inputPositionParams = layout.getLayoutParams(option);
  17181. * this.mergeOption(inputPositionParams);
  17182. * },
  17183. * mergeOption: function (newOption) {
  17184. * newOption && zrUtil.merge(thisOption, newOption, true);
  17185. * layout.mergeLayoutParam(thisOption, newOption);
  17186. * }
  17187. * });
  17188. *
  17189. * @param {Object} targetOption
  17190. * @param {Object} newOption
  17191. * @param {Object|string} [opt]
  17192. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  17193. * that width (or height) should not be calculated by left and right (or top and bottom).
  17194. */
  17195. function mergeLayoutParam(targetOption, newOption, opt) {
  17196. !isObject$1(opt) && (opt = {});
  17197. var ignoreSize = opt.ignoreSize;
  17198. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  17199. var hResult = merge$$1(HV_NAMES[0], 0);
  17200. var vResult = merge$$1(HV_NAMES[1], 1);
  17201. copy(HV_NAMES[0], targetOption, hResult);
  17202. copy(HV_NAMES[1], targetOption, vResult);
  17203. function merge$$1(names, hvIdx) {
  17204. var newParams = {};
  17205. var newValueCount = 0;
  17206. var merged = {};
  17207. var mergedValueCount = 0;
  17208. var enoughParamNumber = 2;
  17209. each$3(names, function (name) {
  17210. merged[name] = targetOption[name];
  17211. });
  17212. each$3(names, function (name) {
  17213. // Consider case: newOption.width is null, which is
  17214. // set by user for removing width setting.
  17215. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  17216. hasValue(newParams, name) && newValueCount++;
  17217. hasValue(merged, name) && mergedValueCount++;
  17218. });
  17219. if (ignoreSize[hvIdx]) {
  17220. // Only one of left/right is premitted to exist.
  17221. if (hasValue(newOption, names[1])) {
  17222. merged[names[2]] = null;
  17223. }
  17224. else if (hasValue(newOption, names[2])) {
  17225. merged[names[1]] = null;
  17226. }
  17227. return merged;
  17228. }
  17229. // Case: newOption: {width: ..., right: ...},
  17230. // or targetOption: {right: ...} and newOption: {width: ...},
  17231. // There is no conflict when merged only has params count
  17232. // little than enoughParamNumber.
  17233. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  17234. return merged;
  17235. }
  17236. // Case: newOption: {width: ..., right: ...},
  17237. // Than we can make sure user only want those two, and ignore
  17238. // all origin params in targetOption.
  17239. else if (newValueCount >= enoughParamNumber) {
  17240. return newParams;
  17241. }
  17242. else {
  17243. // Chose another param from targetOption by priority.
  17244. for (var i = 0; i < names.length; i++) {
  17245. var name = names[i];
  17246. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  17247. newParams[name] = targetOption[name];
  17248. break;
  17249. }
  17250. }
  17251. return newParams;
  17252. }
  17253. }
  17254. function hasProp(obj, name) {
  17255. return obj.hasOwnProperty(name);
  17256. }
  17257. function hasValue(obj, name) {
  17258. return obj[name] != null && obj[name] !== 'auto';
  17259. }
  17260. function copy(names, target, source) {
  17261. each$3(names, function (name) {
  17262. target[name] = source[name];
  17263. });
  17264. }
  17265. }
  17266. /**
  17267. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17268. * @param {Object} source
  17269. * @return {Object} Result contains those props.
  17270. */
  17271. function getLayoutParams(source) {
  17272. return copyLayoutParams({}, source);
  17273. }
  17274. /**
  17275. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  17276. * @param {Object} source
  17277. * @return {Object} Result contains those props.
  17278. */
  17279. function copyLayoutParams(target, source) {
  17280. source && target && each$3(LOCATION_PARAMS, function (name) {
  17281. source.hasOwnProperty(name) && (target[name] = source[name]);
  17282. });
  17283. return target;
  17284. }
  17285. /*
  17286. * Licensed to the Apache Software Foundation (ASF) under one
  17287. * or more contributor license agreements. See the NOTICE file
  17288. * distributed with this work for additional information
  17289. * regarding copyright ownership. The ASF licenses this file
  17290. * to you under the Apache License, Version 2.0 (the
  17291. * "License"); you may not use this file except in compliance
  17292. * with the License. You may obtain a copy of the License at
  17293. *
  17294. * http://www.apache.org/licenses/LICENSE-2.0
  17295. *
  17296. * Unless required by applicable law or agreed to in writing,
  17297. * software distributed under the License is distributed on an
  17298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17299. * KIND, either express or implied. See the License for the
  17300. * specific language governing permissions and limitations
  17301. * under the License.
  17302. */
  17303. var boxLayoutMixin = {
  17304. getBoxLayoutParams: function () {
  17305. return {
  17306. left: this.get('left'),
  17307. top: this.get('top'),
  17308. right: this.get('right'),
  17309. bottom: this.get('bottom'),
  17310. width: this.get('width'),
  17311. height: this.get('height')
  17312. };
  17313. }
  17314. };
  17315. /*
  17316. * Licensed to the Apache Software Foundation (ASF) under one
  17317. * or more contributor license agreements. See the NOTICE file
  17318. * distributed with this work for additional information
  17319. * regarding copyright ownership. The ASF licenses this file
  17320. * to you under the Apache License, Version 2.0 (the
  17321. * "License"); you may not use this file except in compliance
  17322. * with the License. You may obtain a copy of the License at
  17323. *
  17324. * http://www.apache.org/licenses/LICENSE-2.0
  17325. *
  17326. * Unless required by applicable law or agreed to in writing,
  17327. * software distributed under the License is distributed on an
  17328. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17329. * KIND, either express or implied. See the License for the
  17330. * specific language governing permissions and limitations
  17331. * under the License.
  17332. */
  17333. /**
  17334. * Component model
  17335. *
  17336. * @module echarts/model/Component
  17337. */
  17338. var inner$1 = makeInner();
  17339. /**
  17340. * @alias module:echarts/model/Component
  17341. * @constructor
  17342. * @param {Object} option
  17343. * @param {module:echarts/model/Model} parentModel
  17344. * @param {module:echarts/model/Model} ecModel
  17345. */
  17346. var ComponentModel = Model.extend({
  17347. type: 'component',
  17348. /**
  17349. * @readOnly
  17350. * @type {string}
  17351. */
  17352. id: '',
  17353. /**
  17354. * Because simplified concept is probably better, series.name (or component.name)
  17355. * has been having too many resposibilities:
  17356. * (1) Generating id (which requires name in option should not be modified).
  17357. * (2) As an index to mapping series when merging option or calling API (a name
  17358. * can refer to more then one components, which is convinient is some case).
  17359. * (3) Display.
  17360. * @readOnly
  17361. */
  17362. name: '',
  17363. /**
  17364. * @readOnly
  17365. * @type {string}
  17366. */
  17367. mainType: '',
  17368. /**
  17369. * @readOnly
  17370. * @type {string}
  17371. */
  17372. subType: '',
  17373. /**
  17374. * @readOnly
  17375. * @type {number}
  17376. */
  17377. componentIndex: 0,
  17378. /**
  17379. * @type {Object}
  17380. * @protected
  17381. */
  17382. defaultOption: null,
  17383. /**
  17384. * @type {module:echarts/model/Global}
  17385. * @readOnly
  17386. */
  17387. ecModel: null,
  17388. /**
  17389. * key: componentType
  17390. * value: Component model list, can not be null.
  17391. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  17392. * @readOnly
  17393. */
  17394. dependentModels: [],
  17395. /**
  17396. * @type {string}
  17397. * @readOnly
  17398. */
  17399. uid: null,
  17400. /**
  17401. * Support merge layout params.
  17402. * Only support 'box' now (left/right/top/bottom/width/height).
  17403. * @type {string|Object} Object can be {ignoreSize: true}
  17404. * @readOnly
  17405. */
  17406. layoutMode: null,
  17407. $constructor: function (option, parentModel, ecModel, extraOpt) {
  17408. Model.call(this, option, parentModel, ecModel, extraOpt);
  17409. this.uid = getUID('ec_cpt_model');
  17410. },
  17411. init: function (option, parentModel, ecModel, extraOpt) {
  17412. this.mergeDefaultAndTheme(option, ecModel);
  17413. },
  17414. mergeDefaultAndTheme: function (option, ecModel) {
  17415. var layoutMode = this.layoutMode;
  17416. var inputPositionParams = layoutMode
  17417. ? getLayoutParams(option) : {};
  17418. var themeModel = ecModel.getTheme();
  17419. merge(option, themeModel.get(this.mainType));
  17420. merge(option, this.getDefaultOption());
  17421. if (layoutMode) {
  17422. mergeLayoutParam(option, inputPositionParams, layoutMode);
  17423. }
  17424. },
  17425. mergeOption: function (option, extraOpt) {
  17426. merge(this.option, option, true);
  17427. var layoutMode = this.layoutMode;
  17428. if (layoutMode) {
  17429. mergeLayoutParam(this.option, option, layoutMode);
  17430. }
  17431. },
  17432. // Hooker after init or mergeOption
  17433. optionUpdated: function (newCptOption, isInit) {},
  17434. getDefaultOption: function () {
  17435. var fields = inner$1(this);
  17436. if (!fields.defaultOption) {
  17437. var optList = [];
  17438. var Class = this.constructor;
  17439. while (Class) {
  17440. var opt = Class.prototype.defaultOption;
  17441. opt && optList.push(opt);
  17442. Class = Class.superClass;
  17443. }
  17444. var defaultOption = {};
  17445. for (var i = optList.length - 1; i >= 0; i--) {
  17446. defaultOption = merge(defaultOption, optList[i], true);
  17447. }
  17448. fields.defaultOption = defaultOption;
  17449. }
  17450. return fields.defaultOption;
  17451. },
  17452. getReferringComponents: function (mainType) {
  17453. return this.ecModel.queryComponents({
  17454. mainType: mainType,
  17455. index: this.get(mainType + 'Index', true),
  17456. id: this.get(mainType + 'Id', true)
  17457. });
  17458. }
  17459. });
  17460. // Reset ComponentModel.extend, add preConstruct.
  17461. // clazzUtil.enableClassExtend(
  17462. // ComponentModel,
  17463. // function (option, parentModel, ecModel, extraOpt) {
  17464. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  17465. // zrUtil.extend(this, extraOpt);
  17466. // this.uid = componentUtil.getUID('componentModel');
  17467. // // this.setReadOnly([
  17468. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  17469. // // 'dependentModels', 'componentIndex'
  17470. // // ]);
  17471. // }
  17472. // );
  17473. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  17474. enableClassManagement(
  17475. ComponentModel, {registerWhenExtend: true}
  17476. );
  17477. enableSubTypeDefaulter(ComponentModel);
  17478. // Add capability of ComponentModel.topologicalTravel.
  17479. enableTopologicalTravel(ComponentModel, getDependencies);
  17480. function getDependencies(componentType) {
  17481. var deps = [];
  17482. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  17483. deps = deps.concat(Clazz.prototype.dependencies || []);
  17484. });
  17485. // Ensure main type.
  17486. deps = map(deps, function (type) {
  17487. return parseClassType$1(type).main;
  17488. });
  17489. // Hack dataset for convenience.
  17490. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  17491. deps.unshift('dataset');
  17492. }
  17493. return deps;
  17494. }
  17495. mixin(ComponentModel, boxLayoutMixin);
  17496. /*
  17497. * Licensed to the Apache Software Foundation (ASF) under one
  17498. * or more contributor license agreements. See the NOTICE file
  17499. * distributed with this work for additional information
  17500. * regarding copyright ownership. The ASF licenses this file
  17501. * to you under the Apache License, Version 2.0 (the
  17502. * "License"); you may not use this file except in compliance
  17503. * with the License. You may obtain a copy of the License at
  17504. *
  17505. * http://www.apache.org/licenses/LICENSE-2.0
  17506. *
  17507. * Unless required by applicable law or agreed to in writing,
  17508. * software distributed under the License is distributed on an
  17509. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17510. * KIND, either express or implied. See the License for the
  17511. * specific language governing permissions and limitations
  17512. * under the License.
  17513. */
  17514. var platform = '';
  17515. // Navigator not exists in node
  17516. if (typeof navigator !== 'undefined') {
  17517. platform = navigator.platform || '';
  17518. }
  17519. var globalDefault = {
  17520. // backgroundColor: 'rgba(0,0,0,0)',
  17521. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  17522. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  17523. // Light colors:
  17524. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  17525. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  17526. // Dark colors:
  17527. color: [
  17528. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  17529. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  17530. ],
  17531. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  17532. // If xAxis and yAxis declared, grid is created by default.
  17533. // grid: {},
  17534. textStyle: {
  17535. // color: '#000',
  17536. // decoration: 'none',
  17537. // PENDING
  17538. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  17539. // fontFamily: 'Arial, Verdana, sans-serif',
  17540. fontSize: 12,
  17541. fontStyle: 'normal',
  17542. fontWeight: 'normal'
  17543. },
  17544. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  17545. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  17546. // Default is source-over
  17547. blendMode: null,
  17548. animation: 'auto',
  17549. animationDuration: 1000,
  17550. animationDurationUpdate: 300,
  17551. animationEasing: 'exponentialOut',
  17552. animationEasingUpdate: 'cubicOut',
  17553. animationThreshold: 2000,
  17554. // Configuration for progressive/incremental rendering
  17555. progressiveThreshold: 3000,
  17556. progressive: 400,
  17557. // Threshold of if use single hover layer to optimize.
  17558. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  17559. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  17560. // which is unexpected.
  17561. // see example <echarts/test/heatmap-large.html>.
  17562. hoverLayerThreshold: 3000,
  17563. // See: module:echarts/scale/Time
  17564. useUTC: false
  17565. };
  17566. /*
  17567. * Licensed to the Apache Software Foundation (ASF) under one
  17568. * or more contributor license agreements. See the NOTICE file
  17569. * distributed with this work for additional information
  17570. * regarding copyright ownership. The ASF licenses this file
  17571. * to you under the Apache License, Version 2.0 (the
  17572. * "License"); you may not use this file except in compliance
  17573. * with the License. You may obtain a copy of the License at
  17574. *
  17575. * http://www.apache.org/licenses/LICENSE-2.0
  17576. *
  17577. * Unless required by applicable law or agreed to in writing,
  17578. * software distributed under the License is distributed on an
  17579. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17580. * KIND, either express or implied. See the License for the
  17581. * specific language governing permissions and limitations
  17582. * under the License.
  17583. */
  17584. var inner$2 = makeInner();
  17585. function getNearestColorPalette(colors, requestColorNum) {
  17586. var paletteNum = colors.length;
  17587. // TODO colors must be in order
  17588. for (var i = 0; i < paletteNum; i++) {
  17589. if (colors[i].length > requestColorNum) {
  17590. return colors[i];
  17591. }
  17592. }
  17593. return colors[paletteNum - 1];
  17594. }
  17595. var colorPaletteMixin = {
  17596. clearColorPalette: function () {
  17597. inner$2(this).colorIdx = 0;
  17598. inner$2(this).colorNameMap = {};
  17599. },
  17600. /**
  17601. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  17602. * twise with the same parameters will get different result.
  17603. * @param {Object} [scope=this]
  17604. * @param {Object} [requestColorNum]
  17605. * @return {string} color string.
  17606. */
  17607. getColorFromPalette: function (name, scope, requestColorNum) {
  17608. scope = scope || this;
  17609. var scopeFields = inner$2(scope);
  17610. var colorIdx = scopeFields.colorIdx || 0;
  17611. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  17612. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17613. if (colorNameMap.hasOwnProperty(name)) {
  17614. return colorNameMap[name];
  17615. }
  17616. var defaultColorPalette = normalizeToArray(this.get('color', true));
  17617. var layeredColorPalette = this.get('colorLayer', true);
  17618. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  17619. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  17620. // In case can't find in layered color palette.
  17621. colorPalette = colorPalette || defaultColorPalette;
  17622. if (!colorPalette || !colorPalette.length) {
  17623. return;
  17624. }
  17625. var color = colorPalette[colorIdx];
  17626. if (name) {
  17627. colorNameMap[name] = color;
  17628. }
  17629. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  17630. return color;
  17631. }
  17632. };
  17633. /*
  17634. * Licensed to the Apache Software Foundation (ASF) under one
  17635. * or more contributor license agreements. See the NOTICE file
  17636. * distributed with this work for additional information
  17637. * regarding copyright ownership. The ASF licenses this file
  17638. * to you under the Apache License, Version 2.0 (the
  17639. * "License"); you may not use this file except in compliance
  17640. * with the License. You may obtain a copy of the License at
  17641. *
  17642. * http://www.apache.org/licenses/LICENSE-2.0
  17643. *
  17644. * Unless required by applicable law or agreed to in writing,
  17645. * software distributed under the License is distributed on an
  17646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17647. * KIND, either express or implied. See the License for the
  17648. * specific language governing permissions and limitations
  17649. * under the License.
  17650. */
  17651. // Avoid typo.
  17652. var SOURCE_FORMAT_ORIGINAL = 'original';
  17653. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17654. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17655. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17656. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17657. // ??? CHANGE A NAME
  17658. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17659. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17660. var SERIES_LAYOUT_BY_ROW = 'row';
  17661. /*
  17662. * Licensed to the Apache Software Foundation (ASF) under one
  17663. * or more contributor license agreements. See the NOTICE file
  17664. * distributed with this work for additional information
  17665. * regarding copyright ownership. The ASF licenses this file
  17666. * to you under the Apache License, Version 2.0 (the
  17667. * "License"); you may not use this file except in compliance
  17668. * with the License. You may obtain a copy of the License at
  17669. *
  17670. * http://www.apache.org/licenses/LICENSE-2.0
  17671. *
  17672. * Unless required by applicable law or agreed to in writing,
  17673. * software distributed under the License is distributed on an
  17674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17675. * KIND, either express or implied. See the License for the
  17676. * specific language governing permissions and limitations
  17677. * under the License.
  17678. */
  17679. /**
  17680. * [sourceFormat]
  17681. *
  17682. * + "original":
  17683. * This format is only used in series.data, where
  17684. * itemStyle can be specified in data item.
  17685. *
  17686. * + "arrayRows":
  17687. * [
  17688. * ['product', 'score', 'amount'],
  17689. * ['Matcha Latte', 89.3, 95.8],
  17690. * ['Milk Tea', 92.1, 89.4],
  17691. * ['Cheese Cocoa', 94.4, 91.2],
  17692. * ['Walnut Brownie', 85.4, 76.9]
  17693. * ]
  17694. *
  17695. * + "objectRows":
  17696. * [
  17697. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17698. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17699. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17700. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17701. * ]
  17702. *
  17703. * + "keyedColumns":
  17704. * {
  17705. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17706. * 'count': [823, 235, 1042, 988],
  17707. * 'score': [95.8, 81.4, 91.2, 76.9]
  17708. * }
  17709. *
  17710. * + "typedArray"
  17711. *
  17712. * + "unknown"
  17713. */
  17714. /**
  17715. * @constructor
  17716. * @param {Object} fields
  17717. * @param {string} fields.sourceFormat
  17718. * @param {Array|Object} fields.fromDataset
  17719. * @param {Array|Object} [fields.data]
  17720. * @param {string} [seriesLayoutBy='column']
  17721. * @param {Array.<Object|string>} [dimensionsDefine]
  17722. * @param {Objet|HashMap} [encodeDefine]
  17723. * @param {number} [startIndex=0]
  17724. * @param {number} [dimensionsDetectCount]
  17725. */
  17726. function Source(fields) {
  17727. /**
  17728. * @type {boolean}
  17729. */
  17730. this.fromDataset = fields.fromDataset;
  17731. /**
  17732. * Not null/undefined.
  17733. * @type {Array|Object}
  17734. */
  17735. this.data = fields.data || (
  17736. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17737. );
  17738. /**
  17739. * See also "detectSourceFormat".
  17740. * Not null/undefined.
  17741. * @type {string}
  17742. */
  17743. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17744. /**
  17745. * 'row' or 'column'
  17746. * Not null/undefined.
  17747. * @type {string} seriesLayoutBy
  17748. */
  17749. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17750. /**
  17751. * dimensions definition in option.
  17752. * can be null/undefined.
  17753. * @type {Array.<Object|string>}
  17754. */
  17755. this.dimensionsDefine = fields.dimensionsDefine;
  17756. /**
  17757. * encode definition in option.
  17758. * can be null/undefined.
  17759. * @type {Objet|HashMap}
  17760. */
  17761. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17762. /**
  17763. * Not null/undefined, uint.
  17764. * @type {number}
  17765. */
  17766. this.startIndex = fields.startIndex || 0;
  17767. /**
  17768. * Can be null/undefined (when unknown), uint.
  17769. * @type {number}
  17770. */
  17771. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17772. }
  17773. /**
  17774. * Wrap original series data for some compatibility cases.
  17775. */
  17776. Source.seriesDataToSource = function (data) {
  17777. return new Source({
  17778. data: data,
  17779. sourceFormat: isTypedArray(data)
  17780. ? SOURCE_FORMAT_TYPED_ARRAY
  17781. : SOURCE_FORMAT_ORIGINAL,
  17782. fromDataset: false
  17783. });
  17784. };
  17785. enableClassCheck(Source);
  17786. /*
  17787. * Licensed to the Apache Software Foundation (ASF) under one
  17788. * or more contributor license agreements. See the NOTICE file
  17789. * distributed with this work for additional information
  17790. * regarding copyright ownership. The ASF licenses this file
  17791. * to you under the Apache License, Version 2.0 (the
  17792. * "License"); you may not use this file except in compliance
  17793. * with the License. You may obtain a copy of the License at
  17794. *
  17795. * http://www.apache.org/licenses/LICENSE-2.0
  17796. *
  17797. * Unless required by applicable law or agreed to in writing,
  17798. * software distributed under the License is distributed on an
  17799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17800. * KIND, either express or implied. See the License for the
  17801. * specific language governing permissions and limitations
  17802. * under the License.
  17803. */
  17804. // The result of `guessOrdinal`.
  17805. var BE_ORDINAL = {
  17806. Must: 1, // Encounter string but not '-' and not number-like.
  17807. Might: 2, // Encounter string but number-like.
  17808. Not: 3 // Other cases
  17809. };
  17810. var inner$3 = makeInner();
  17811. /**
  17812. * @see {module:echarts/data/Source}
  17813. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17814. * @return {string} sourceFormat
  17815. */
  17816. function detectSourceFormat(datasetModel) {
  17817. var data = datasetModel.option.source;
  17818. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17819. if (isTypedArray(data)) {
  17820. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17821. }
  17822. else if (isArray(data)) {
  17823. // FIXME Whether tolerate null in top level array?
  17824. if (data.length === 0) {
  17825. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17826. }
  17827. for (var i = 0, len = data.length; i < len; i++) {
  17828. var item = data[i];
  17829. if (item == null) {
  17830. continue;
  17831. }
  17832. else if (isArray(item)) {
  17833. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17834. break;
  17835. }
  17836. else if (isObject$1(item)) {
  17837. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17838. break;
  17839. }
  17840. }
  17841. }
  17842. else if (isObject$1(data)) {
  17843. for (var key in data) {
  17844. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17845. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17846. break;
  17847. }
  17848. }
  17849. }
  17850. else if (data != null) {
  17851. throw new Error('Invalid data');
  17852. }
  17853. inner$3(datasetModel).sourceFormat = sourceFormat;
  17854. }
  17855. /**
  17856. * [Scenarios]:
  17857. * (1) Provide source data directly:
  17858. * series: {
  17859. * encode: {...},
  17860. * dimensions: [...]
  17861. * seriesLayoutBy: 'row',
  17862. * data: [[...]]
  17863. * }
  17864. * (2) Refer to datasetModel.
  17865. * series: [{
  17866. * encode: {...}
  17867. * // Ignore datasetIndex means `datasetIndex: 0`
  17868. * // and the dimensions defination in dataset is used
  17869. * }, {
  17870. * encode: {...},
  17871. * seriesLayoutBy: 'column',
  17872. * datasetIndex: 1
  17873. * }]
  17874. *
  17875. * Get data from series itself or datset.
  17876. * @return {module:echarts/data/Source} source
  17877. */
  17878. function getSource(seriesModel) {
  17879. return inner$3(seriesModel).source;
  17880. }
  17881. /**
  17882. * MUST be called before mergeOption of all series.
  17883. * @param {module:echarts/model/Global} ecModel
  17884. */
  17885. function resetSourceDefaulter(ecModel) {
  17886. // `datasetMap` is used to make default encode.
  17887. inner$3(ecModel).datasetMap = createHashMap();
  17888. }
  17889. /**
  17890. * [Caution]:
  17891. * MUST be called after series option merged and
  17892. * before "series.getInitailData()" called.
  17893. *
  17894. * [The rule of making default encode]:
  17895. * Category axis (if exists) alway map to the first dimension.
  17896. * Each other axis occupies a subsequent dimension.
  17897. *
  17898. * [Why make default encode]:
  17899. * Simplify the typing of encode in option, avoiding the case like that:
  17900. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17901. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17902. *
  17903. * @param {module:echarts/model/Series} seriesModel
  17904. */
  17905. function prepareSource(seriesModel) {
  17906. var seriesOption = seriesModel.option;
  17907. var data = seriesOption.data;
  17908. var sourceFormat = isTypedArray(data)
  17909. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17910. var fromDataset = false;
  17911. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17912. var sourceHeader = seriesOption.sourceHeader;
  17913. var dimensionsDefine = seriesOption.dimensions;
  17914. var datasetModel = getDatasetModel(seriesModel);
  17915. if (datasetModel) {
  17916. var datasetOption = datasetModel.option;
  17917. data = datasetOption.source;
  17918. sourceFormat = inner$3(datasetModel).sourceFormat;
  17919. fromDataset = true;
  17920. // These settings from series has higher priority.
  17921. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17922. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17923. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17924. }
  17925. var completeResult = completeBySourceData(
  17926. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17927. );
  17928. inner$3(seriesModel).source = new Source({
  17929. data: data,
  17930. fromDataset: fromDataset,
  17931. seriesLayoutBy: seriesLayoutBy,
  17932. sourceFormat: sourceFormat,
  17933. dimensionsDefine: completeResult.dimensionsDefine,
  17934. startIndex: completeResult.startIndex,
  17935. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17936. // Note: dataset option does not have `encode`.
  17937. encodeDefine: seriesOption.encode
  17938. });
  17939. }
  17940. // return {startIndex, dimensionsDefine, dimensionsCount}
  17941. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17942. if (!data) {
  17943. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17944. }
  17945. var dimensionsDetectCount;
  17946. var startIndex;
  17947. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17948. // Rule: Most of the first line are string: it is header.
  17949. // Caution: consider a line with 5 string and 1 number,
  17950. // it still can not be sure it is a head, because the
  17951. // 5 string may be 5 values of category columns.
  17952. if (sourceHeader === 'auto' || sourceHeader == null) {
  17953. arrayRowsTravelFirst(function (val) {
  17954. // '-' is regarded as null/undefined.
  17955. if (val != null && val !== '-') {
  17956. if (isString(val)) {
  17957. startIndex == null && (startIndex = 1);
  17958. }
  17959. else {
  17960. startIndex = 0;
  17961. }
  17962. }
  17963. // 10 is an experience number, avoid long loop.
  17964. }, seriesLayoutBy, data, 10);
  17965. }
  17966. else {
  17967. startIndex = sourceHeader ? 1 : 0;
  17968. }
  17969. if (!dimensionsDefine && startIndex === 1) {
  17970. dimensionsDefine = [];
  17971. arrayRowsTravelFirst(function (val, index) {
  17972. dimensionsDefine[index] = val != null ? val : '';
  17973. }, seriesLayoutBy, data);
  17974. }
  17975. dimensionsDetectCount = dimensionsDefine
  17976. ? dimensionsDefine.length
  17977. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17978. ? data.length
  17979. : data[0]
  17980. ? data[0].length
  17981. : null;
  17982. }
  17983. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17984. if (!dimensionsDefine) {
  17985. dimensionsDefine = objectRowsCollectDimensions(data);
  17986. }
  17987. }
  17988. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17989. if (!dimensionsDefine) {
  17990. dimensionsDefine = [];
  17991. each$1(data, function (colArr, key) {
  17992. dimensionsDefine.push(key);
  17993. });
  17994. }
  17995. }
  17996. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17997. var value0 = getDataItemValue(data[0]);
  17998. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17999. }
  18000. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18001. if (__DEV__) {
  18002. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18003. }
  18004. }
  18005. return {
  18006. startIndex: startIndex,
  18007. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  18008. dimensionsDetectCount: dimensionsDetectCount
  18009. };
  18010. }
  18011. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18012. // which is reasonable. But dimension name is duplicated.
  18013. // Returns undefined or an array contains only object without null/undefiend or string.
  18014. function normalizeDimensionsDefine(dimensionsDefine) {
  18015. if (!dimensionsDefine) {
  18016. // The meaning of null/undefined is different from empty array.
  18017. return;
  18018. }
  18019. var nameMap = createHashMap();
  18020. return map(dimensionsDefine, function (item, index) {
  18021. item = extend({}, isObject$1(item) ? item : {name: item});
  18022. // User can set null in dimensions.
  18023. // We dont auto specify name, othewise a given name may
  18024. // cause it be refered unexpectedly.
  18025. if (item.name == null) {
  18026. return item;
  18027. }
  18028. // Also consider number form like 2012.
  18029. item.name += '';
  18030. // User may also specify displayName.
  18031. // displayName will always exists except user not
  18032. // specified or dim name is not specified or detected.
  18033. // (A auto generated dim name will not be used as
  18034. // displayName).
  18035. if (item.displayName == null) {
  18036. item.displayName = item.name;
  18037. }
  18038. var exist = nameMap.get(item.name);
  18039. if (!exist) {
  18040. nameMap.set(item.name, {count: 1});
  18041. }
  18042. else {
  18043. item.name += '-' + exist.count++;
  18044. }
  18045. return item;
  18046. });
  18047. }
  18048. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18049. maxLoop == null && (maxLoop = Infinity);
  18050. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18051. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18052. cb(data[i] ? data[i][0] : null, i);
  18053. }
  18054. }
  18055. else {
  18056. var value0 = data[0] || [];
  18057. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18058. cb(value0[i], i);
  18059. }
  18060. }
  18061. }
  18062. function objectRowsCollectDimensions(data) {
  18063. var firstIndex = 0;
  18064. var obj;
  18065. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18066. if (obj) {
  18067. var dimensions = [];
  18068. each$1(obj, function (value, key) {
  18069. dimensions.push(key);
  18070. });
  18071. return dimensions;
  18072. }
  18073. }
  18074. /**
  18075. * [The strategy of the arrengment of data dimensions for dataset]:
  18076. * "value way": all axes are non-category axes. So series one by one take
  18077. * several (the number is coordSysDims.length) dimensions from dataset.
  18078. * The result of data arrengment of data dimensions like:
  18079. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  18080. * "category way": at least one axis is category axis. So the the first data
  18081. * dimension is always mapped to the first category axis and shared by
  18082. * all of the series. The other data dimensions are taken by series like
  18083. * "value way" does.
  18084. * The result of data arrengment of data dimensions like:
  18085. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  18086. *
  18087. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  18088. * @param {module:model/Series} seriesModel
  18089. * @param {module:data/Source} source
  18090. * @return {Object} encode Never be `null/undefined`.
  18091. */
  18092. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  18093. var encode = {};
  18094. var datasetModel = getDatasetModel(seriesModel);
  18095. // Currently only make default when using dataset, util more reqirements occur.
  18096. if (!datasetModel || !coordDimensions) {
  18097. return encode;
  18098. }
  18099. var encodeItemName = [];
  18100. var encodeSeriesName = [];
  18101. var ecModel = seriesModel.ecModel;
  18102. var datasetMap = inner$3(ecModel).datasetMap;
  18103. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  18104. var baseCategoryDimIndex;
  18105. var categoryWayValueDimStart;
  18106. coordDimensions = coordDimensions.slice();
  18107. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18108. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {name: coordDimInfo});
  18109. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  18110. baseCategoryDimIndex = coordDimIdx;
  18111. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  18112. }
  18113. encode[coordDimInfo.name] = [];
  18114. });
  18115. var datasetRecord = datasetMap.get(key)
  18116. || datasetMap.set(key, {categoryWayDim: categoryWayValueDimStart, valueWayDim: 0});
  18117. // TODO
  18118. // Auto detect first time axis and do arrangement.
  18119. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  18120. var coordDimName = coordDimInfo.name;
  18121. var count = getDataDimCountOnCoordDim(coordDimInfo);
  18122. // In value way.
  18123. if (baseCategoryDimIndex == null) {
  18124. var start = datasetRecord.valueWayDim;
  18125. pushDim(encode[coordDimName], start, count);
  18126. pushDim(encodeSeriesName, start, count);
  18127. datasetRecord.valueWayDim += count;
  18128. // ??? TODO give a better default series name rule?
  18129. // especially when encode x y specified.
  18130. // consider: when mutiple series share one dimension
  18131. // category axis, series name should better use
  18132. // the other dimsion name. On the other hand, use
  18133. // both dimensions name.
  18134. }
  18135. // In category way, the first category axis.
  18136. else if (baseCategoryDimIndex === coordDimIdx) {
  18137. pushDim(encode[coordDimName], 0, count);
  18138. pushDim(encodeItemName, 0, count);
  18139. }
  18140. // In category way, the other axis.
  18141. else {
  18142. var start = datasetRecord.categoryWayDim;
  18143. pushDim(encode[coordDimName], start, count);
  18144. pushDim(encodeSeriesName, start, count);
  18145. datasetRecord.categoryWayDim += count;
  18146. }
  18147. });
  18148. function pushDim(dimIdxArr, idxFrom, idxCount) {
  18149. for (var i = 0; i < idxCount; i++) {
  18150. dimIdxArr.push(idxFrom + i);
  18151. }
  18152. }
  18153. function getDataDimCountOnCoordDim(coordDimInfo) {
  18154. var dimsDef = coordDimInfo.dimsDef;
  18155. return dimsDef ? dimsDef.length : 1;
  18156. }
  18157. encodeItemName.length && (encode.itemName = encodeItemName);
  18158. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  18159. return encode;
  18160. }
  18161. /**
  18162. * Work for data like [{name: ..., value: ...}, ...].
  18163. *
  18164. * @param {module:model/Series} seriesModel
  18165. * @param {module:data/Source} source
  18166. * @return {Object} encode Never be `null/undefined`.
  18167. */
  18168. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  18169. var encode = {};
  18170. var datasetModel = getDatasetModel(seriesModel);
  18171. // Currently only make default when using dataset, util more reqirements occur.
  18172. if (!datasetModel) {
  18173. return encode;
  18174. }
  18175. var sourceFormat = source.sourceFormat;
  18176. var dimensionsDefine = source.dimensionsDefine;
  18177. var potentialNameDimIndex;
  18178. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18179. each$1(dimensionsDefine, function (dim, idx) {
  18180. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  18181. potentialNameDimIndex = idx;
  18182. }
  18183. });
  18184. }
  18185. // idxResult: {v, n}.
  18186. var idxResult = (function () {
  18187. var idxRes0 = {};
  18188. var idxRes1 = {};
  18189. var guessRecords = [];
  18190. // 5 is an experience value.
  18191. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  18192. var guessResult = doGuessOrdinal(
  18193. source.data, sourceFormat, source.seriesLayoutBy,
  18194. dimensionsDefine, source.startIndex, i
  18195. );
  18196. guessRecords.push(guessResult);
  18197. var isPureNumber = guessResult === BE_ORDINAL.Not;
  18198. // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  18199. // and then find a name dim with the priority:
  18200. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  18201. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  18202. idxRes0.v = i;
  18203. }
  18204. if (idxRes0.n == null
  18205. || (idxRes0.n === idxRes0.v)
  18206. || (!isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not)
  18207. ) {
  18208. idxRes0.n = i;
  18209. }
  18210. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  18211. return idxRes0;
  18212. }
  18213. // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  18214. // find the first BE_ORDINAL.Might as the value dim,
  18215. // and then find a name dim with the priority:
  18216. // "other dim" > "the value dim itself".
  18217. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  18218. // treated as number.
  18219. if (!isPureNumber) {
  18220. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  18221. idxRes1.v = i;
  18222. }
  18223. if (idxRes1.n == null || (idxRes1.n === idxRes1.v)) {
  18224. idxRes1.n = i;
  18225. }
  18226. }
  18227. }
  18228. function fulfilled(idxResult) {
  18229. return idxResult.v != null && idxResult.n != null;
  18230. }
  18231. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  18232. })();
  18233. if (idxResult) {
  18234. encode.value = idxResult.v;
  18235. // `potentialNameDimIndex` has highest priority.
  18236. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n;
  18237. // By default, label use itemName in charts.
  18238. // So we dont set encodeLabel here.
  18239. encode.itemName = [nameDimIndex];
  18240. encode.seriesName = [nameDimIndex];
  18241. }
  18242. return encode;
  18243. }
  18244. /**
  18245. * If return null/undefined, indicate that should not use datasetModel.
  18246. */
  18247. function getDatasetModel(seriesModel) {
  18248. var option = seriesModel.option;
  18249. // Caution: consider the scenario:
  18250. // A dataset is declared and a series is not expected to use the dataset,
  18251. // and at the beginning `setOption({series: { noData })` (just prepare other
  18252. // option but no data), then `setOption({series: {data: [...]}); In this case,
  18253. // the user should set an empty array to avoid that dataset is used by default.
  18254. var thisData = option.data;
  18255. if (!thisData) {
  18256. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  18257. }
  18258. }
  18259. /**
  18260. * The rule should not be complex, otherwise user might not
  18261. * be able to known where the data is wrong.
  18262. * The code is ugly, but how to make it neat?
  18263. *
  18264. * @param {module:echars/data/Source} source
  18265. * @param {number} dimIndex
  18266. * @return {BE_ORDINAL} guess result.
  18267. */
  18268. function guessOrdinal(source, dimIndex) {
  18269. return doGuessOrdinal(
  18270. source.data,
  18271. source.sourceFormat,
  18272. source.seriesLayoutBy,
  18273. source.dimensionsDefine,
  18274. source.startIndex,
  18275. dimIndex
  18276. );
  18277. }
  18278. // dimIndex may be overflow source data.
  18279. // return {BE_ORDINAL}
  18280. function doGuessOrdinal(
  18281. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  18282. ) {
  18283. var result;
  18284. // Experience value.
  18285. var maxLoop = 5;
  18286. if (isTypedArray(data)) {
  18287. return BE_ORDINAL.Not;
  18288. }
  18289. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  18290. // always exists in source.
  18291. var dimName;
  18292. var dimType;
  18293. if (dimensionsDefine) {
  18294. var dimDefItem = dimensionsDefine[dimIndex];
  18295. if (isObject$1(dimDefItem)) {
  18296. dimName = dimDefItem.name;
  18297. dimType = dimDefItem.type;
  18298. }
  18299. else if (isString(dimDefItem)) {
  18300. dimName = dimDefItem;
  18301. }
  18302. }
  18303. if (dimType != null) {
  18304. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  18305. }
  18306. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18307. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18308. var sample = data[dimIndex];
  18309. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  18310. if ((result = detectValue(sample[startIndex + i])) != null) {
  18311. return result;
  18312. }
  18313. }
  18314. }
  18315. else {
  18316. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18317. var row = data[startIndex + i];
  18318. if (row && (result = detectValue(row[dimIndex])) != null) {
  18319. return result;
  18320. }
  18321. }
  18322. }
  18323. }
  18324. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18325. if (!dimName) {
  18326. return BE_ORDINAL.Not;
  18327. }
  18328. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18329. var item = data[i];
  18330. if (item && (result = detectValue(item[dimName])) != null) {
  18331. return result;
  18332. }
  18333. }
  18334. }
  18335. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18336. if (!dimName) {
  18337. return BE_ORDINAL.Not;
  18338. }
  18339. var sample = data[dimName];
  18340. if (!sample || isTypedArray(sample)) {
  18341. return BE_ORDINAL.Not;
  18342. }
  18343. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  18344. if ((result = detectValue(sample[i])) != null) {
  18345. return result;
  18346. }
  18347. }
  18348. }
  18349. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18350. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18351. var item = data[i];
  18352. var val = getDataItemValue(item);
  18353. if (!isArray(val)) {
  18354. return BE_ORDINAL.Not;
  18355. }
  18356. if ((result = detectValue(val[dimIndex])) != null) {
  18357. return result;
  18358. }
  18359. }
  18360. }
  18361. function detectValue(val) {
  18362. var beStr = isString(val);
  18363. // Consider usage convenience, '1', '2' will be treated as "number".
  18364. // `isFinit('')` get `true`.
  18365. if (val != null && isFinite(val) && val !== '') {
  18366. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  18367. }
  18368. else if (beStr && val !== '-') {
  18369. return BE_ORDINAL.Must;
  18370. }
  18371. }
  18372. return BE_ORDINAL.Not;
  18373. }
  18374. /*
  18375. * Licensed to the Apache Software Foundation (ASF) under one
  18376. * or more contributor license agreements. See the NOTICE file
  18377. * distributed with this work for additional information
  18378. * regarding copyright ownership. The ASF licenses this file
  18379. * to you under the Apache License, Version 2.0 (the
  18380. * "License"); you may not use this file except in compliance
  18381. * with the License. You may obtain a copy of the License at
  18382. *
  18383. * http://www.apache.org/licenses/LICENSE-2.0
  18384. *
  18385. * Unless required by applicable law or agreed to in writing,
  18386. * software distributed under the License is distributed on an
  18387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18388. * KIND, either express or implied. See the License for the
  18389. * specific language governing permissions and limitations
  18390. * under the License.
  18391. */
  18392. /**
  18393. * ECharts global model
  18394. *
  18395. * @module {echarts/model/Global}
  18396. */
  18397. /**
  18398. * Caution: If the mechanism should be changed some day, these cases
  18399. * should be considered:
  18400. *
  18401. * (1) In `merge option` mode, if using the same option to call `setOption`
  18402. * many times, the result should be the same (try our best to ensure that).
  18403. * (2) In `merge option` mode, if a component has no id/name specified, it
  18404. * will be merged by index, and the result sequence of the components is
  18405. * consistent to the original sequence.
  18406. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  18407. * `mergeOption` in module:echarts/model/OptionManager.
  18408. */
  18409. var OPTION_INNER_KEY = '\0_ec_inner';
  18410. /**
  18411. * @alias module:echarts/model/Global
  18412. *
  18413. * @param {Object} option
  18414. * @param {module:echarts/model/Model} parentModel
  18415. * @param {Object} theme
  18416. */
  18417. var GlobalModel = Model.extend({
  18418. init: function (option, parentModel, theme, optionManager) {
  18419. theme = theme || {};
  18420. this.option = null; // Mark as not initialized.
  18421. /**
  18422. * @type {module:echarts/model/Model}
  18423. * @private
  18424. */
  18425. this._theme = new Model(theme);
  18426. /**
  18427. * @type {module:echarts/model/OptionManager}
  18428. */
  18429. this._optionManager = optionManager;
  18430. },
  18431. setOption: function (option, optionPreprocessorFuncs) {
  18432. assert$1(
  18433. !(OPTION_INNER_KEY in option),
  18434. 'please use chart.getOption()'
  18435. );
  18436. this._optionManager.setOption(option, optionPreprocessorFuncs);
  18437. this.resetOption(null);
  18438. },
  18439. /**
  18440. * @param {string} type null/undefined: reset all.
  18441. * 'recreate': force recreate all.
  18442. * 'timeline': only reset timeline option
  18443. * 'media': only reset media query option
  18444. * @return {boolean} Whether option changed.
  18445. */
  18446. resetOption: function (type) {
  18447. var optionChanged = false;
  18448. var optionManager = this._optionManager;
  18449. if (!type || type === 'recreate') {
  18450. var baseOption = optionManager.mountOption(type === 'recreate');
  18451. if (!this.option || type === 'recreate') {
  18452. initBase.call(this, baseOption);
  18453. }
  18454. else {
  18455. this.restoreData();
  18456. this.mergeOption(baseOption);
  18457. }
  18458. optionChanged = true;
  18459. }
  18460. if (type === 'timeline' || type === 'media') {
  18461. this.restoreData();
  18462. }
  18463. if (!type || type === 'recreate' || type === 'timeline') {
  18464. var timelineOption = optionManager.getTimelineOption(this);
  18465. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  18466. }
  18467. if (!type || type === 'recreate' || type === 'media') {
  18468. var mediaOptions = optionManager.getMediaOption(this, this._api);
  18469. if (mediaOptions.length) {
  18470. each$1(mediaOptions, function (mediaOption) {
  18471. this.mergeOption(mediaOption, optionChanged = true);
  18472. }, this);
  18473. }
  18474. }
  18475. return optionChanged;
  18476. },
  18477. /**
  18478. * @protected
  18479. */
  18480. mergeOption: function (newOption) {
  18481. var option = this.option;
  18482. var componentsMap = this._componentsMap;
  18483. var newCptTypes = [];
  18484. resetSourceDefaulter(this);
  18485. // If no component class, merge directly.
  18486. // For example: color, animaiton options, etc.
  18487. each$1(newOption, function (componentOption, mainType) {
  18488. if (componentOption == null) {
  18489. return;
  18490. }
  18491. if (!ComponentModel.hasClass(mainType)) {
  18492. // globalSettingTask.dirty();
  18493. option[mainType] = option[mainType] == null
  18494. ? clone(componentOption)
  18495. : merge(option[mainType], componentOption, true);
  18496. }
  18497. else if (mainType) {
  18498. newCptTypes.push(mainType);
  18499. }
  18500. });
  18501. ComponentModel.topologicalTravel(
  18502. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  18503. );
  18504. function visitComponent(mainType, dependencies) {
  18505. var newCptOptionList = normalizeToArray(newOption[mainType]);
  18506. var mapResult = mappingToExists(
  18507. componentsMap.get(mainType), newCptOptionList
  18508. );
  18509. makeIdAndName(mapResult);
  18510. // Set mainType and complete subType.
  18511. each$1(mapResult, function (item, index) {
  18512. var opt = item.option;
  18513. if (isObject$1(opt)) {
  18514. item.keyInfo.mainType = mainType;
  18515. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  18516. }
  18517. });
  18518. var dependentModels = getComponentsByTypes(
  18519. componentsMap, dependencies
  18520. );
  18521. option[mainType] = [];
  18522. componentsMap.set(mainType, []);
  18523. each$1(mapResult, function (resultItem, index) {
  18524. var componentModel = resultItem.exist;
  18525. var newCptOption = resultItem.option;
  18526. assert$1(
  18527. isObject$1(newCptOption) || componentModel,
  18528. 'Empty component definition'
  18529. );
  18530. // Consider where is no new option and should be merged using {},
  18531. // see removeEdgeAndAdd in topologicalTravel and
  18532. // ComponentModel.getAllClassMainTypes.
  18533. if (!newCptOption) {
  18534. componentModel.mergeOption({}, this);
  18535. componentModel.optionUpdated({}, false);
  18536. }
  18537. else {
  18538. var ComponentModelClass = ComponentModel.getClass(
  18539. mainType, resultItem.keyInfo.subType, true
  18540. );
  18541. if (componentModel && componentModel.constructor === ComponentModelClass) {
  18542. componentModel.name = resultItem.keyInfo.name;
  18543. // componentModel.settingTask && componentModel.settingTask.dirty();
  18544. componentModel.mergeOption(newCptOption, this);
  18545. componentModel.optionUpdated(newCptOption, false);
  18546. }
  18547. else {
  18548. // PENDING Global as parent ?
  18549. var extraOpt = extend(
  18550. {
  18551. dependentModels: dependentModels,
  18552. componentIndex: index
  18553. },
  18554. resultItem.keyInfo
  18555. );
  18556. componentModel = new ComponentModelClass(
  18557. newCptOption, this, this, extraOpt
  18558. );
  18559. extend(componentModel, extraOpt);
  18560. componentModel.init(newCptOption, this, this, extraOpt);
  18561. // Call optionUpdated after init.
  18562. // newCptOption has been used as componentModel.option
  18563. // and may be merged with theme and default, so pass null
  18564. // to avoid confusion.
  18565. componentModel.optionUpdated(null, true);
  18566. }
  18567. }
  18568. componentsMap.get(mainType)[index] = componentModel;
  18569. option[mainType][index] = componentModel.option;
  18570. }, this);
  18571. // Backup series for filtering.
  18572. if (mainType === 'series') {
  18573. createSeriesIndices(this, componentsMap.get('series'));
  18574. }
  18575. }
  18576. this._seriesIndicesMap = createHashMap(
  18577. this._seriesIndices = this._seriesIndices || []
  18578. );
  18579. },
  18580. /**
  18581. * Get option for output (cloned option and inner info removed)
  18582. * @public
  18583. * @return {Object}
  18584. */
  18585. getOption: function () {
  18586. var option = clone(this.option);
  18587. each$1(option, function (opts, mainType) {
  18588. if (ComponentModel.hasClass(mainType)) {
  18589. var opts = normalizeToArray(opts);
  18590. for (var i = opts.length - 1; i >= 0; i--) {
  18591. // Remove options with inner id.
  18592. if (isIdInner(opts[i])) {
  18593. opts.splice(i, 1);
  18594. }
  18595. }
  18596. option[mainType] = opts;
  18597. }
  18598. });
  18599. delete option[OPTION_INNER_KEY];
  18600. return option;
  18601. },
  18602. /**
  18603. * @return {module:echarts/model/Model}
  18604. */
  18605. getTheme: function () {
  18606. return this._theme;
  18607. },
  18608. /**
  18609. * @param {string} mainType
  18610. * @param {number} [idx=0]
  18611. * @return {module:echarts/model/Component}
  18612. */
  18613. getComponent: function (mainType, idx) {
  18614. var list = this._componentsMap.get(mainType);
  18615. if (list) {
  18616. return list[idx || 0];
  18617. }
  18618. },
  18619. /**
  18620. * If none of index and id and name used, return all components with mainType.
  18621. * @param {Object} condition
  18622. * @param {string} condition.mainType
  18623. * @param {string} [condition.subType] If ignore, only query by mainType
  18624. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  18625. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  18626. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  18627. * @return {Array.<module:echarts/model/Component>}
  18628. */
  18629. queryComponents: function (condition) {
  18630. var mainType = condition.mainType;
  18631. if (!mainType) {
  18632. return [];
  18633. }
  18634. var index = condition.index;
  18635. var id = condition.id;
  18636. var name = condition.name;
  18637. var cpts = this._componentsMap.get(mainType);
  18638. if (!cpts || !cpts.length) {
  18639. return [];
  18640. }
  18641. var result;
  18642. if (index != null) {
  18643. if (!isArray(index)) {
  18644. index = [index];
  18645. }
  18646. result = filter(map(index, function (idx) {
  18647. return cpts[idx];
  18648. }), function (val) {
  18649. return !!val;
  18650. });
  18651. }
  18652. else if (id != null) {
  18653. var isIdArray = isArray(id);
  18654. result = filter(cpts, function (cpt) {
  18655. return (isIdArray && indexOf(id, cpt.id) >= 0)
  18656. || (!isIdArray && cpt.id === id);
  18657. });
  18658. }
  18659. else if (name != null) {
  18660. var isNameArray = isArray(name);
  18661. result = filter(cpts, function (cpt) {
  18662. return (isNameArray && indexOf(name, cpt.name) >= 0)
  18663. || (!isNameArray && cpt.name === name);
  18664. });
  18665. }
  18666. else {
  18667. // Return all components with mainType
  18668. result = cpts.slice();
  18669. }
  18670. return filterBySubType(result, condition);
  18671. },
  18672. /**
  18673. * The interface is different from queryComponents,
  18674. * which is convenient for inner usage.
  18675. *
  18676. * @usage
  18677. * var result = findComponents(
  18678. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  18679. * );
  18680. * var result = findComponents(
  18681. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  18682. * );
  18683. * var result = findComponents(
  18684. * {mainType: 'series',
  18685. * filter: function (model, index) {...}}
  18686. * );
  18687. * // result like [component0, componnet1, ...]
  18688. *
  18689. * @param {Object} condition
  18690. * @param {string} condition.mainType Mandatory.
  18691. * @param {string} [condition.subType] Optional.
  18692. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  18693. * where xxx is mainType.
  18694. * If query attribute is null/undefined or has no index/id/name,
  18695. * do not filtering by query conditions, which is convenient for
  18696. * no-payload situations or when target of action is global.
  18697. * @param {Function} [condition.filter] parameter: component, return boolean.
  18698. * @return {Array.<module:echarts/model/Component>}
  18699. */
  18700. findComponents: function (condition) {
  18701. var query = condition.query;
  18702. var mainType = condition.mainType;
  18703. var queryCond = getQueryCond(query);
  18704. var result = queryCond
  18705. ? this.queryComponents(queryCond)
  18706. : this._componentsMap.get(mainType);
  18707. return doFilter(filterBySubType(result, condition));
  18708. function getQueryCond(q) {
  18709. var indexAttr = mainType + 'Index';
  18710. var idAttr = mainType + 'Id';
  18711. var nameAttr = mainType + 'Name';
  18712. return q && (
  18713. q[indexAttr] != null
  18714. || q[idAttr] != null
  18715. || q[nameAttr] != null
  18716. )
  18717. ? {
  18718. mainType: mainType,
  18719. // subType will be filtered finally.
  18720. index: q[indexAttr],
  18721. id: q[idAttr],
  18722. name: q[nameAttr]
  18723. }
  18724. : null;
  18725. }
  18726. function doFilter(res) {
  18727. return condition.filter
  18728. ? filter(res, condition.filter)
  18729. : res;
  18730. }
  18731. },
  18732. /**
  18733. * @usage
  18734. * eachComponent('legend', function (legendModel, index) {
  18735. * ...
  18736. * });
  18737. * eachComponent(function (componentType, model, index) {
  18738. * // componentType does not include subType
  18739. * // (componentType is 'xxx' but not 'xxx.aa')
  18740. * });
  18741. * eachComponent(
  18742. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18743. * function (model, index) {...}
  18744. * );
  18745. * eachComponent(
  18746. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18747. * function (model, index) {...}
  18748. * );
  18749. *
  18750. * @param {string|Object=} mainType When mainType is object, the definition
  18751. * is the same as the method 'findComponents'.
  18752. * @param {Function} cb
  18753. * @param {*} context
  18754. */
  18755. eachComponent: function (mainType, cb, context) {
  18756. var componentsMap = this._componentsMap;
  18757. if (typeof mainType === 'function') {
  18758. context = cb;
  18759. cb = mainType;
  18760. componentsMap.each(function (components, componentType) {
  18761. each$1(components, function (component, index) {
  18762. cb.call(context, componentType, component, index);
  18763. });
  18764. });
  18765. }
  18766. else if (isString(mainType)) {
  18767. each$1(componentsMap.get(mainType), cb, context);
  18768. }
  18769. else if (isObject$1(mainType)) {
  18770. var queryResult = this.findComponents(mainType);
  18771. each$1(queryResult, cb, context);
  18772. }
  18773. },
  18774. /**
  18775. * @param {string} name
  18776. * @return {Array.<module:echarts/model/Series>}
  18777. */
  18778. getSeriesByName: function (name) {
  18779. var series = this._componentsMap.get('series');
  18780. return filter(series, function (oneSeries) {
  18781. return oneSeries.name === name;
  18782. });
  18783. },
  18784. /**
  18785. * @param {number} seriesIndex
  18786. * @return {module:echarts/model/Series}
  18787. */
  18788. getSeriesByIndex: function (seriesIndex) {
  18789. return this._componentsMap.get('series')[seriesIndex];
  18790. },
  18791. /**
  18792. * Get series list before filtered by type.
  18793. * FIXME: rename to getRawSeriesByType?
  18794. *
  18795. * @param {string} subType
  18796. * @return {Array.<module:echarts/model/Series>}
  18797. */
  18798. getSeriesByType: function (subType) {
  18799. var series = this._componentsMap.get('series');
  18800. return filter(series, function (oneSeries) {
  18801. return oneSeries.subType === subType;
  18802. });
  18803. },
  18804. /**
  18805. * @return {Array.<module:echarts/model/Series>}
  18806. */
  18807. getSeries: function () {
  18808. return this._componentsMap.get('series').slice();
  18809. },
  18810. /**
  18811. * @return {number}
  18812. */
  18813. getSeriesCount: function () {
  18814. return this._componentsMap.get('series').length;
  18815. },
  18816. /**
  18817. * After filtering, series may be different
  18818. * frome raw series.
  18819. *
  18820. * @param {Function} cb
  18821. * @param {*} context
  18822. */
  18823. eachSeries: function (cb, context) {
  18824. assertSeriesInitialized(this);
  18825. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18826. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18827. cb.call(context, series, rawSeriesIndex);
  18828. }, this);
  18829. },
  18830. /**
  18831. * Iterate raw series before filtered.
  18832. *
  18833. * @param {Function} cb
  18834. * @param {*} context
  18835. */
  18836. eachRawSeries: function (cb, context) {
  18837. each$1(this._componentsMap.get('series'), cb, context);
  18838. },
  18839. /**
  18840. * After filtering, series may be different.
  18841. * frome raw series.
  18842. *
  18843. * @param {string} subType.
  18844. * @param {Function} cb
  18845. * @param {*} context
  18846. */
  18847. eachSeriesByType: function (subType, cb, context) {
  18848. assertSeriesInitialized(this);
  18849. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18850. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18851. if (series.subType === subType) {
  18852. cb.call(context, series, rawSeriesIndex);
  18853. }
  18854. }, this);
  18855. },
  18856. /**
  18857. * Iterate raw series before filtered of given type.
  18858. *
  18859. * @parma {string} subType
  18860. * @param {Function} cb
  18861. * @param {*} context
  18862. */
  18863. eachRawSeriesByType: function (subType, cb, context) {
  18864. return each$1(this.getSeriesByType(subType), cb, context);
  18865. },
  18866. /**
  18867. * @param {module:echarts/model/Series} seriesModel
  18868. */
  18869. isSeriesFiltered: function (seriesModel) {
  18870. assertSeriesInitialized(this);
  18871. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18872. },
  18873. /**
  18874. * @return {Array.<number>}
  18875. */
  18876. getCurrentSeriesIndices: function () {
  18877. return (this._seriesIndices || []).slice();
  18878. },
  18879. /**
  18880. * @param {Function} cb
  18881. * @param {*} context
  18882. */
  18883. filterSeries: function (cb, context) {
  18884. assertSeriesInitialized(this);
  18885. var filteredSeries = filter(
  18886. this._componentsMap.get('series'), cb, context
  18887. );
  18888. createSeriesIndices(this, filteredSeries);
  18889. },
  18890. restoreData: function (payload) {
  18891. var componentsMap = this._componentsMap;
  18892. createSeriesIndices(this, componentsMap.get('series'));
  18893. var componentTypes = [];
  18894. componentsMap.each(function (components, componentType) {
  18895. componentTypes.push(componentType);
  18896. });
  18897. ComponentModel.topologicalTravel(
  18898. componentTypes,
  18899. ComponentModel.getAllClassMainTypes(),
  18900. function (componentType, dependencies) {
  18901. each$1(componentsMap.get(componentType), function (component) {
  18902. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18903. && component.restoreData();
  18904. });
  18905. }
  18906. );
  18907. }
  18908. });
  18909. function isNotTargetSeries(seriesModel, payload) {
  18910. if (payload) {
  18911. var index = payload.seiresIndex;
  18912. var id = payload.seriesId;
  18913. var name = payload.seriesName;
  18914. return (index != null && seriesModel.componentIndex !== index)
  18915. || (id != null && seriesModel.id !== id)
  18916. || (name != null && seriesModel.name !== name);
  18917. }
  18918. }
  18919. /**
  18920. * @inner
  18921. */
  18922. function mergeTheme(option, theme) {
  18923. // PENDING
  18924. // NOT use `colorLayer` in theme if option has `color`
  18925. var notMergeColorLayer = option.color && !option.colorLayer;
  18926. each$1(theme, function (themeItem, name) {
  18927. if (name === 'colorLayer' && notMergeColorLayer) {
  18928. return;
  18929. }
  18930. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18931. if (!ComponentModel.hasClass(name)) {
  18932. if (typeof themeItem === 'object') {
  18933. option[name] = !option[name]
  18934. ? clone(themeItem)
  18935. : merge(option[name], themeItem, false);
  18936. }
  18937. else {
  18938. if (option[name] == null) {
  18939. option[name] = themeItem;
  18940. }
  18941. }
  18942. }
  18943. });
  18944. }
  18945. function initBase(baseOption) {
  18946. baseOption = baseOption;
  18947. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18948. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18949. this.option = {};
  18950. this.option[OPTION_INNER_KEY] = 1;
  18951. /**
  18952. * Init with series: [], in case of calling findSeries method
  18953. * before series initialized.
  18954. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18955. * @private
  18956. */
  18957. this._componentsMap = createHashMap({series: []});
  18958. /**
  18959. * Mapping between filtered series list and raw series list.
  18960. * key: filtered series indices, value: raw series indices.
  18961. * @type {Array.<nubmer>}
  18962. * @private
  18963. */
  18964. this._seriesIndices;
  18965. this._seriesIndicesMap;
  18966. mergeTheme(baseOption, this._theme.option);
  18967. // TODO Needs clone when merging to the unexisted property
  18968. merge(baseOption, globalDefault, false);
  18969. this.mergeOption(baseOption);
  18970. }
  18971. /**
  18972. * @inner
  18973. * @param {Array.<string>|string} types model types
  18974. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18975. */
  18976. function getComponentsByTypes(componentsMap, types) {
  18977. if (!isArray(types)) {
  18978. types = types ? [types] : [];
  18979. }
  18980. var ret = {};
  18981. each$1(types, function (type) {
  18982. ret[type] = (componentsMap.get(type) || []).slice();
  18983. });
  18984. return ret;
  18985. }
  18986. /**
  18987. * @inner
  18988. */
  18989. function determineSubType(mainType, newCptOption, existComponent) {
  18990. var subType = newCptOption.type
  18991. ? newCptOption.type
  18992. : existComponent
  18993. ? existComponent.subType
  18994. // Use determineSubType only when there is no existComponent.
  18995. : ComponentModel.determineSubType(mainType, newCptOption);
  18996. // tooltip, markline, markpoint may always has no subType
  18997. return subType;
  18998. }
  18999. /**
  19000. * @inner
  19001. */
  19002. function createSeriesIndices(ecModel, seriesModels) {
  19003. ecModel._seriesIndicesMap = createHashMap(
  19004. ecModel._seriesIndices = map(seriesModels, function (series) {
  19005. return series.componentIndex;
  19006. }) || []
  19007. );
  19008. }
  19009. /**
  19010. * @inner
  19011. */
  19012. function filterBySubType(components, condition) {
  19013. // Using hasOwnProperty for restrict. Consider
  19014. // subType is undefined in user payload.
  19015. return condition.hasOwnProperty('subType')
  19016. ? filter(components, function (cpt) {
  19017. return cpt.subType === condition.subType;
  19018. })
  19019. : components;
  19020. }
  19021. /**
  19022. * @inner
  19023. */
  19024. function assertSeriesInitialized(ecModel) {
  19025. // Components that use _seriesIndices should depends on series component,
  19026. // which make sure that their initialization is after series.
  19027. if (__DEV__) {
  19028. if (!ecModel._seriesIndices) {
  19029. throw new Error('Option should contains series.');
  19030. }
  19031. }
  19032. }
  19033. mixin(GlobalModel, colorPaletteMixin);
  19034. /*
  19035. * Licensed to the Apache Software Foundation (ASF) under one
  19036. * or more contributor license agreements. See the NOTICE file
  19037. * distributed with this work for additional information
  19038. * regarding copyright ownership. The ASF licenses this file
  19039. * to you under the Apache License, Version 2.0 (the
  19040. * "License"); you may not use this file except in compliance
  19041. * with the License. You may obtain a copy of the License at
  19042. *
  19043. * http://www.apache.org/licenses/LICENSE-2.0
  19044. *
  19045. * Unless required by applicable law or agreed to in writing,
  19046. * software distributed under the License is distributed on an
  19047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19048. * KIND, either express or implied. See the License for the
  19049. * specific language governing permissions and limitations
  19050. * under the License.
  19051. */
  19052. var echartsAPIList = [
  19053. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  19054. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  19055. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  19056. ];
  19057. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  19058. function ExtensionAPI(chartInstance) {
  19059. each$1(echartsAPIList, function (name) {
  19060. this[name] = bind(chartInstance[name], chartInstance);
  19061. }, this);
  19062. }
  19063. /*
  19064. * Licensed to the Apache Software Foundation (ASF) under one
  19065. * or more contributor license agreements. See the NOTICE file
  19066. * distributed with this work for additional information
  19067. * regarding copyright ownership. The ASF licenses this file
  19068. * to you under the Apache License, Version 2.0 (the
  19069. * "License"); you may not use this file except in compliance
  19070. * with the License. You may obtain a copy of the License at
  19071. *
  19072. * http://www.apache.org/licenses/LICENSE-2.0
  19073. *
  19074. * Unless required by applicable law or agreed to in writing,
  19075. * software distributed under the License is distributed on an
  19076. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19077. * KIND, either express or implied. See the License for the
  19078. * specific language governing permissions and limitations
  19079. * under the License.
  19080. */
  19081. var coordinateSystemCreators = {};
  19082. function CoordinateSystemManager() {
  19083. this._coordinateSystems = [];
  19084. }
  19085. CoordinateSystemManager.prototype = {
  19086. constructor: CoordinateSystemManager,
  19087. create: function (ecModel, api) {
  19088. var coordinateSystems = [];
  19089. each$1(coordinateSystemCreators, function (creater, type) {
  19090. var list = creater.create(ecModel, api);
  19091. coordinateSystems = coordinateSystems.concat(list || []);
  19092. });
  19093. this._coordinateSystems = coordinateSystems;
  19094. },
  19095. update: function (ecModel, api) {
  19096. each$1(this._coordinateSystems, function (coordSys) {
  19097. coordSys.update && coordSys.update(ecModel, api);
  19098. });
  19099. },
  19100. getCoordinateSystems: function () {
  19101. return this._coordinateSystems.slice();
  19102. }
  19103. };
  19104. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  19105. coordinateSystemCreators[type] = coordinateSystemCreator;
  19106. };
  19107. CoordinateSystemManager.get = function (type) {
  19108. return coordinateSystemCreators[type];
  19109. };
  19110. /*
  19111. * Licensed to the Apache Software Foundation (ASF) under one
  19112. * or more contributor license agreements. See the NOTICE file
  19113. * distributed with this work for additional information
  19114. * regarding copyright ownership. The ASF licenses this file
  19115. * to you under the Apache License, Version 2.0 (the
  19116. * "License"); you may not use this file except in compliance
  19117. * with the License. You may obtain a copy of the License at
  19118. *
  19119. * http://www.apache.org/licenses/LICENSE-2.0
  19120. *
  19121. * Unless required by applicable law or agreed to in writing,
  19122. * software distributed under the License is distributed on an
  19123. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19124. * KIND, either express or implied. See the License for the
  19125. * specific language governing permissions and limitations
  19126. * under the License.
  19127. */
  19128. /**
  19129. * ECharts option manager
  19130. *
  19131. * @module {echarts/model/OptionManager}
  19132. */
  19133. var each$4 = each$1;
  19134. var clone$3 = clone;
  19135. var map$1 = map;
  19136. var merge$1 = merge;
  19137. var QUERY_REG = /^(min|max)?(.+)$/;
  19138. /**
  19139. * TERM EXPLANATIONS:
  19140. *
  19141. * [option]:
  19142. *
  19143. * An object that contains definitions of components. For example:
  19144. * var option = {
  19145. * title: {...},
  19146. * legend: {...},
  19147. * visualMap: {...},
  19148. * series: [
  19149. * {data: [...]},
  19150. * {data: [...]},
  19151. * ...
  19152. * ]
  19153. * };
  19154. *
  19155. * [rawOption]:
  19156. *
  19157. * An object input to echarts.setOption. 'rawOption' may be an
  19158. * 'option', or may be an object contains multi-options. For example:
  19159. * var option = {
  19160. * baseOption: {
  19161. * title: {...},
  19162. * legend: {...},
  19163. * series: [
  19164. * {data: [...]},
  19165. * {data: [...]},
  19166. * ...
  19167. * ]
  19168. * },
  19169. * timeline: {...},
  19170. * options: [
  19171. * {title: {...}, series: {data: [...]}},
  19172. * {title: {...}, series: {data: [...]}},
  19173. * ...
  19174. * ],
  19175. * media: [
  19176. * {
  19177. * query: {maxWidth: 320},
  19178. * option: {series: {x: 20}, visualMap: {show: false}}
  19179. * },
  19180. * {
  19181. * query: {minWidth: 320, maxWidth: 720},
  19182. * option: {series: {x: 500}, visualMap: {show: true}}
  19183. * },
  19184. * {
  19185. * option: {series: {x: 1200}, visualMap: {show: true}}
  19186. * }
  19187. * ]
  19188. * };
  19189. *
  19190. * @alias module:echarts/model/OptionManager
  19191. * @param {module:echarts/ExtensionAPI} api
  19192. */
  19193. function OptionManager(api) {
  19194. /**
  19195. * @private
  19196. * @type {module:echarts/ExtensionAPI}
  19197. */
  19198. this._api = api;
  19199. /**
  19200. * @private
  19201. * @type {Array.<number>}
  19202. */
  19203. this._timelineOptions = [];
  19204. /**
  19205. * @private
  19206. * @type {Array.<Object>}
  19207. */
  19208. this._mediaList = [];
  19209. /**
  19210. * @private
  19211. * @type {Object}
  19212. */
  19213. this._mediaDefault;
  19214. /**
  19215. * -1, means default.
  19216. * empty means no media.
  19217. * @private
  19218. * @type {Array.<number>}
  19219. */
  19220. this._currentMediaIndices = [];
  19221. /**
  19222. * @private
  19223. * @type {Object}
  19224. */
  19225. this._optionBackup;
  19226. /**
  19227. * @private
  19228. * @type {Object}
  19229. */
  19230. this._newBaseOption;
  19231. }
  19232. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  19233. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  19234. // rawOption cloned and backuped when timeline changed, which does no
  19235. // good to performance. What's more, that both timeline and setOption
  19236. // method supply 'notMerge' brings complex and some problems.
  19237. // Consider this case:
  19238. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  19239. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  19240. OptionManager.prototype = {
  19241. constructor: OptionManager,
  19242. /**
  19243. * @public
  19244. * @param {Object} rawOption Raw option.
  19245. * @param {module:echarts/model/Global} ecModel
  19246. * @param {Array.<Function>} optionPreprocessorFuncs
  19247. * @return {Object} Init option
  19248. */
  19249. setOption: function (rawOption, optionPreprocessorFuncs) {
  19250. if (rawOption) {
  19251. // That set dat primitive is dangerous if user reuse the data when setOption again.
  19252. each$1(normalizeToArray(rawOption.series), function (series) {
  19253. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  19254. });
  19255. }
  19256. // Caution: some series modify option data, if do not clone,
  19257. // it should ensure that the repeat modify correctly
  19258. // (create a new object when modify itself).
  19259. rawOption = clone$3(rawOption);
  19260. // FIXME
  19261. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  19262. var oldOptionBackup = this._optionBackup;
  19263. var newParsedOption = parseRawOption.call(
  19264. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  19265. );
  19266. this._newBaseOption = newParsedOption.baseOption;
  19267. // For setOption at second time (using merge mode);
  19268. if (oldOptionBackup) {
  19269. // Only baseOption can be merged.
  19270. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  19271. // For simplicity, timeline options and media options do not support merge,
  19272. // that is, if you `setOption` twice and both has timeline options, the latter
  19273. // timeline opitons will not be merged to the formers, but just substitude them.
  19274. if (newParsedOption.timelineOptions.length) {
  19275. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  19276. }
  19277. if (newParsedOption.mediaList.length) {
  19278. oldOptionBackup.mediaList = newParsedOption.mediaList;
  19279. }
  19280. if (newParsedOption.mediaDefault) {
  19281. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  19282. }
  19283. }
  19284. else {
  19285. this._optionBackup = newParsedOption;
  19286. }
  19287. },
  19288. /**
  19289. * @param {boolean} isRecreate
  19290. * @return {Object}
  19291. */
  19292. mountOption: function (isRecreate) {
  19293. var optionBackup = this._optionBackup;
  19294. // TODO
  19295. // 如果没有reset功能则不clone。
  19296. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  19297. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  19298. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  19299. this._currentMediaIndices = [];
  19300. return clone$3(isRecreate
  19301. // this._optionBackup.baseOption, which is created at the first `setOption`
  19302. // called, and is merged into every new option by inner method `mergeOption`
  19303. // each time `setOption` called, can be only used in `isRecreate`, because
  19304. // its reliability is under suspicion. In other cases option merge is
  19305. // performed by `model.mergeOption`.
  19306. ? optionBackup.baseOption : this._newBaseOption
  19307. );
  19308. },
  19309. /**
  19310. * @param {module:echarts/model/Global} ecModel
  19311. * @return {Object}
  19312. */
  19313. getTimelineOption: function (ecModel) {
  19314. var option;
  19315. var timelineOptions = this._timelineOptions;
  19316. if (timelineOptions.length) {
  19317. // getTimelineOption can only be called after ecModel inited,
  19318. // so we can get currentIndex from timelineModel.
  19319. var timelineModel = ecModel.getComponent('timeline');
  19320. if (timelineModel) {
  19321. option = clone$3(
  19322. timelineOptions[timelineModel.getCurrentIndex()],
  19323. true
  19324. );
  19325. }
  19326. }
  19327. return option;
  19328. },
  19329. /**
  19330. * @param {module:echarts/model/Global} ecModel
  19331. * @return {Array.<Object>}
  19332. */
  19333. getMediaOption: function (ecModel) {
  19334. var ecWidth = this._api.getWidth();
  19335. var ecHeight = this._api.getHeight();
  19336. var mediaList = this._mediaList;
  19337. var mediaDefault = this._mediaDefault;
  19338. var indices = [];
  19339. var result = [];
  19340. // No media defined.
  19341. if (!mediaList.length && !mediaDefault) {
  19342. return result;
  19343. }
  19344. // Multi media may be applied, the latter defined media has higher priority.
  19345. for (var i = 0, len = mediaList.length; i < len; i++) {
  19346. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  19347. indices.push(i);
  19348. }
  19349. }
  19350. // FIXME
  19351. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  19352. if (!indices.length && mediaDefault) {
  19353. indices = [-1];
  19354. }
  19355. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  19356. result = map$1(indices, function (index) {
  19357. return clone$3(
  19358. index === -1 ? mediaDefault.option : mediaList[index].option
  19359. );
  19360. });
  19361. }
  19362. // Otherwise return nothing.
  19363. this._currentMediaIndices = indices;
  19364. return result;
  19365. }
  19366. };
  19367. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  19368. var timelineOptions = [];
  19369. var mediaList = [];
  19370. var mediaDefault;
  19371. var baseOption;
  19372. // Compatible with ec2.
  19373. var timelineOpt = rawOption.timeline;
  19374. if (rawOption.baseOption) {
  19375. baseOption = rawOption.baseOption;
  19376. }
  19377. // For timeline
  19378. if (timelineOpt || rawOption.options) {
  19379. baseOption = baseOption || {};
  19380. timelineOptions = (rawOption.options || []).slice();
  19381. }
  19382. // For media query
  19383. if (rawOption.media) {
  19384. baseOption = baseOption || {};
  19385. var media = rawOption.media;
  19386. each$4(media, function (singleMedia) {
  19387. if (singleMedia && singleMedia.option) {
  19388. if (singleMedia.query) {
  19389. mediaList.push(singleMedia);
  19390. }
  19391. else if (!mediaDefault) {
  19392. // Use the first media default.
  19393. mediaDefault = singleMedia;
  19394. }
  19395. }
  19396. });
  19397. }
  19398. // For normal option
  19399. if (!baseOption) {
  19400. baseOption = rawOption;
  19401. }
  19402. // Set timelineOpt to baseOption in ec3,
  19403. // which is convenient for merge option.
  19404. if (!baseOption.timeline) {
  19405. baseOption.timeline = timelineOpt;
  19406. }
  19407. // Preprocess.
  19408. each$4([baseOption].concat(timelineOptions)
  19409. .concat(map(mediaList, function (media) {
  19410. return media.option;
  19411. })),
  19412. function (option) {
  19413. each$4(optionPreprocessorFuncs, function (preProcess) {
  19414. preProcess(option, isNew);
  19415. });
  19416. }
  19417. );
  19418. return {
  19419. baseOption: baseOption,
  19420. timelineOptions: timelineOptions,
  19421. mediaDefault: mediaDefault,
  19422. mediaList: mediaList
  19423. };
  19424. }
  19425. /**
  19426. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  19427. * Support: width, height, aspectRatio
  19428. * Can use max or min as prefix.
  19429. */
  19430. function applyMediaQuery(query, ecWidth, ecHeight) {
  19431. var realMap = {
  19432. width: ecWidth,
  19433. height: ecHeight,
  19434. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  19435. };
  19436. var applicatable = true;
  19437. each$1(query, function (value, attr) {
  19438. var matched = attr.match(QUERY_REG);
  19439. if (!matched || !matched[1] || !matched[2]) {
  19440. return;
  19441. }
  19442. var operator = matched[1];
  19443. var realAttr = matched[2].toLowerCase();
  19444. if (!compare(realMap[realAttr], value, operator)) {
  19445. applicatable = false;
  19446. }
  19447. });
  19448. return applicatable;
  19449. }
  19450. function compare(real, expect, operator) {
  19451. if (operator === 'min') {
  19452. return real >= expect;
  19453. }
  19454. else if (operator === 'max') {
  19455. return real <= expect;
  19456. }
  19457. else { // Equals
  19458. return real === expect;
  19459. }
  19460. }
  19461. function indicesEquals(indices1, indices2) {
  19462. // indices is always order by asc and has only finite number.
  19463. return indices1.join(',') === indices2.join(',');
  19464. }
  19465. /**
  19466. * Consider case:
  19467. * `chart.setOption(opt1);`
  19468. * Then user do some interaction like dataZoom, dataView changing.
  19469. * `chart.setOption(opt2);`
  19470. * Then user press 'reset button' in toolbox.
  19471. *
  19472. * After doing that all of the interaction effects should be reset, the
  19473. * chart should be the same as the result of invoke
  19474. * `chart.setOption(opt1); chart.setOption(opt2);`.
  19475. *
  19476. * Although it is not able ensure that
  19477. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  19478. * `chart.setOption(merge(opt1, opt2));` exactly,
  19479. * this might be the only simple way to implement that feature.
  19480. *
  19481. * MEMO: We've considered some other approaches:
  19482. * 1. Each model handle its self restoration but not uniform treatment.
  19483. * (Too complex in logic and error-prone)
  19484. * 2. Use a shadow ecModel. (Performace expensive)
  19485. */
  19486. function mergeOption(oldOption, newOption) {
  19487. newOption = newOption || {};
  19488. each$4(newOption, function (newCptOpt, mainType) {
  19489. if (newCptOpt == null) {
  19490. return;
  19491. }
  19492. var oldCptOpt = oldOption[mainType];
  19493. if (!ComponentModel.hasClass(mainType)) {
  19494. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  19495. }
  19496. else {
  19497. newCptOpt = normalizeToArray(newCptOpt);
  19498. oldCptOpt = normalizeToArray(oldCptOpt);
  19499. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  19500. oldOption[mainType] = map$1(mapResult, function (item) {
  19501. return (item.option && item.exist)
  19502. ? merge$1(item.exist, item.option, true)
  19503. : (item.exist || item.option);
  19504. });
  19505. }
  19506. });
  19507. }
  19508. /*
  19509. * Licensed to the Apache Software Foundation (ASF) under one
  19510. * or more contributor license agreements. See the NOTICE file
  19511. * distributed with this work for additional information
  19512. * regarding copyright ownership. The ASF licenses this file
  19513. * to you under the Apache License, Version 2.0 (the
  19514. * "License"); you may not use this file except in compliance
  19515. * with the License. You may obtain a copy of the License at
  19516. *
  19517. * http://www.apache.org/licenses/LICENSE-2.0
  19518. *
  19519. * Unless required by applicable law or agreed to in writing,
  19520. * software distributed under the License is distributed on an
  19521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19522. * KIND, either express or implied. See the License for the
  19523. * specific language governing permissions and limitations
  19524. * under the License.
  19525. */
  19526. var each$5 = each$1;
  19527. var isObject$3 = isObject$1;
  19528. var POSSIBLE_STYLES = [
  19529. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  19530. 'chordStyle', 'label', 'labelLine'
  19531. ];
  19532. function compatEC2ItemStyle(opt) {
  19533. var itemStyleOpt = opt && opt.itemStyle;
  19534. if (!itemStyleOpt) {
  19535. return;
  19536. }
  19537. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  19538. var styleName = POSSIBLE_STYLES[i];
  19539. var normalItemStyleOpt = itemStyleOpt.normal;
  19540. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  19541. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  19542. opt[styleName] = opt[styleName] || {};
  19543. if (!opt[styleName].normal) {
  19544. opt[styleName].normal = normalItemStyleOpt[styleName];
  19545. }
  19546. else {
  19547. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  19548. }
  19549. normalItemStyleOpt[styleName] = null;
  19550. }
  19551. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  19552. opt[styleName] = opt[styleName] || {};
  19553. if (!opt[styleName].emphasis) {
  19554. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  19555. }
  19556. else {
  19557. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  19558. }
  19559. emphasisItemStyleOpt[styleName] = null;
  19560. }
  19561. }
  19562. }
  19563. function convertNormalEmphasis(opt, optType, useExtend) {
  19564. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  19565. var normalOpt = opt[optType].normal;
  19566. var emphasisOpt = opt[optType].emphasis;
  19567. if (normalOpt) {
  19568. // Timeline controlStyle has other properties besides normal and emphasis
  19569. if (useExtend) {
  19570. opt[optType].normal = opt[optType].emphasis = null;
  19571. defaults(opt[optType], normalOpt);
  19572. }
  19573. else {
  19574. opt[optType] = normalOpt;
  19575. }
  19576. }
  19577. if (emphasisOpt) {
  19578. opt.emphasis = opt.emphasis || {};
  19579. opt.emphasis[optType] = emphasisOpt;
  19580. }
  19581. }
  19582. }
  19583. function removeEC3NormalStatus(opt) {
  19584. convertNormalEmphasis(opt, 'itemStyle');
  19585. convertNormalEmphasis(opt, 'lineStyle');
  19586. convertNormalEmphasis(opt, 'areaStyle');
  19587. convertNormalEmphasis(opt, 'label');
  19588. convertNormalEmphasis(opt, 'labelLine');
  19589. // treemap
  19590. convertNormalEmphasis(opt, 'upperLabel');
  19591. // graph
  19592. convertNormalEmphasis(opt, 'edgeLabel');
  19593. }
  19594. function compatTextStyle(opt, propName) {
  19595. // Check whether is not object (string\null\undefined ...)
  19596. var labelOptSingle = isObject$3(opt) && opt[propName];
  19597. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  19598. if (textStyle) {
  19599. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  19600. var propName = TEXT_STYLE_OPTIONS[i];
  19601. if (textStyle.hasOwnProperty(propName)) {
  19602. labelOptSingle[propName] = textStyle[propName];
  19603. }
  19604. }
  19605. }
  19606. }
  19607. function compatEC3CommonStyles(opt) {
  19608. if (opt) {
  19609. removeEC3NormalStatus(opt);
  19610. compatTextStyle(opt, 'label');
  19611. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  19612. }
  19613. }
  19614. function processSeries(seriesOpt) {
  19615. if (!isObject$3(seriesOpt)) {
  19616. return;
  19617. }
  19618. compatEC2ItemStyle(seriesOpt);
  19619. removeEC3NormalStatus(seriesOpt);
  19620. compatTextStyle(seriesOpt, 'label');
  19621. // treemap
  19622. compatTextStyle(seriesOpt, 'upperLabel');
  19623. // graph
  19624. compatTextStyle(seriesOpt, 'edgeLabel');
  19625. if (seriesOpt.emphasis) {
  19626. compatTextStyle(seriesOpt.emphasis, 'label');
  19627. // treemap
  19628. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  19629. // graph
  19630. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  19631. }
  19632. var markPoint = seriesOpt.markPoint;
  19633. if (markPoint) {
  19634. compatEC2ItemStyle(markPoint);
  19635. compatEC3CommonStyles(markPoint);
  19636. }
  19637. var markLine = seriesOpt.markLine;
  19638. if (markLine) {
  19639. compatEC2ItemStyle(markLine);
  19640. compatEC3CommonStyles(markLine);
  19641. }
  19642. var markArea = seriesOpt.markArea;
  19643. if (markArea) {
  19644. compatEC3CommonStyles(markArea);
  19645. }
  19646. var data = seriesOpt.data;
  19647. // Break with ec3: if `setOption` again, there may be no `type` in option,
  19648. // then the backward compat based on option type will not be performed.
  19649. if (seriesOpt.type === 'graph') {
  19650. data = data || seriesOpt.nodes;
  19651. var edgeData = seriesOpt.links || seriesOpt.edges;
  19652. if (edgeData && !isTypedArray(edgeData)) {
  19653. for (var i = 0; i < edgeData.length; i++) {
  19654. compatEC3CommonStyles(edgeData[i]);
  19655. }
  19656. }
  19657. each$1(seriesOpt.categories, function (opt) {
  19658. removeEC3NormalStatus(opt);
  19659. });
  19660. }
  19661. if (data && !isTypedArray(data)) {
  19662. for (var i = 0; i < data.length; i++) {
  19663. compatEC3CommonStyles(data[i]);
  19664. }
  19665. }
  19666. // mark point data
  19667. var markPoint = seriesOpt.markPoint;
  19668. if (markPoint && markPoint.data) {
  19669. var mpData = markPoint.data;
  19670. for (var i = 0; i < mpData.length; i++) {
  19671. compatEC3CommonStyles(mpData[i]);
  19672. }
  19673. }
  19674. // mark line data
  19675. var markLine = seriesOpt.markLine;
  19676. if (markLine && markLine.data) {
  19677. var mlData = markLine.data;
  19678. for (var i = 0; i < mlData.length; i++) {
  19679. if (isArray(mlData[i])) {
  19680. compatEC3CommonStyles(mlData[i][0]);
  19681. compatEC3CommonStyles(mlData[i][1]);
  19682. }
  19683. else {
  19684. compatEC3CommonStyles(mlData[i]);
  19685. }
  19686. }
  19687. }
  19688. // Series
  19689. if (seriesOpt.type === 'gauge') {
  19690. compatTextStyle(seriesOpt, 'axisLabel');
  19691. compatTextStyle(seriesOpt, 'title');
  19692. compatTextStyle(seriesOpt, 'detail');
  19693. }
  19694. else if (seriesOpt.type === 'treemap') {
  19695. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  19696. each$1(seriesOpt.levels, function (opt) {
  19697. removeEC3NormalStatus(opt);
  19698. });
  19699. }
  19700. else if (seriesOpt.type === 'tree') {
  19701. removeEC3NormalStatus(seriesOpt.leaves);
  19702. }
  19703. // sunburst starts from ec4, so it does not need to compat levels.
  19704. }
  19705. function toArr(o) {
  19706. return isArray(o) ? o : o ? [o] : [];
  19707. }
  19708. function toObj(o) {
  19709. return (isArray(o) ? o[0] : o) || {};
  19710. }
  19711. var compatStyle = function (option, isTheme) {
  19712. each$5(toArr(option.series), function (seriesOpt) {
  19713. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19714. });
  19715. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19716. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19717. each$5(
  19718. axes,
  19719. function (axisName) {
  19720. each$5(toArr(option[axisName]), function (axisOpt) {
  19721. if (axisOpt) {
  19722. compatTextStyle(axisOpt, 'axisLabel');
  19723. compatTextStyle(axisOpt.axisPointer, 'label');
  19724. }
  19725. });
  19726. }
  19727. );
  19728. each$5(toArr(option.parallel), function (parallelOpt) {
  19729. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19730. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19731. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19732. });
  19733. each$5(toArr(option.calendar), function (calendarOpt) {
  19734. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19735. compatTextStyle(calendarOpt, 'dayLabel');
  19736. compatTextStyle(calendarOpt, 'monthLabel');
  19737. compatTextStyle(calendarOpt, 'yearLabel');
  19738. });
  19739. // radar.name.textStyle
  19740. each$5(toArr(option.radar), function (radarOpt) {
  19741. compatTextStyle(radarOpt, 'name');
  19742. });
  19743. each$5(toArr(option.geo), function (geoOpt) {
  19744. if (isObject$3(geoOpt)) {
  19745. compatEC3CommonStyles(geoOpt);
  19746. each$5(toArr(geoOpt.regions), function (regionObj) {
  19747. compatEC3CommonStyles(regionObj);
  19748. });
  19749. }
  19750. });
  19751. each$5(toArr(option.timeline), function (timelineOpt) {
  19752. compatEC3CommonStyles(timelineOpt);
  19753. convertNormalEmphasis(timelineOpt, 'label');
  19754. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19755. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19756. var data = timelineOpt.data;
  19757. isArray(data) && each$1(data, function (item) {
  19758. if (isObject$1(item)) {
  19759. convertNormalEmphasis(item, 'label');
  19760. convertNormalEmphasis(item, 'itemStyle');
  19761. }
  19762. });
  19763. });
  19764. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19765. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19766. each$5(toolboxOpt.feature, function (featureOpt) {
  19767. convertNormalEmphasis(featureOpt, 'iconStyle');
  19768. });
  19769. });
  19770. compatTextStyle(toObj(option.axisPointer), 'label');
  19771. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19772. };
  19773. /*
  19774. * Licensed to the Apache Software Foundation (ASF) under one
  19775. * or more contributor license agreements. See the NOTICE file
  19776. * distributed with this work for additional information
  19777. * regarding copyright ownership. The ASF licenses this file
  19778. * to you under the Apache License, Version 2.0 (the
  19779. * "License"); you may not use this file except in compliance
  19780. * with the License. You may obtain a copy of the License at
  19781. *
  19782. * http://www.apache.org/licenses/LICENSE-2.0
  19783. *
  19784. * Unless required by applicable law or agreed to in writing,
  19785. * software distributed under the License is distributed on an
  19786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19787. * KIND, either express or implied. See the License for the
  19788. * specific language governing permissions and limitations
  19789. * under the License.
  19790. */
  19791. // Compatitable with 2.0
  19792. function get(opt, path) {
  19793. path = path.split(',');
  19794. var obj = opt;
  19795. for (var i = 0; i < path.length; i++) {
  19796. obj = obj && obj[path[i]];
  19797. if (obj == null) {
  19798. break;
  19799. }
  19800. }
  19801. return obj;
  19802. }
  19803. function set$1(opt, path, val, overwrite) {
  19804. path = path.split(',');
  19805. var obj = opt;
  19806. var key;
  19807. for (var i = 0; i < path.length - 1; i++) {
  19808. key = path[i];
  19809. if (obj[key] == null) {
  19810. obj[key] = {};
  19811. }
  19812. obj = obj[key];
  19813. }
  19814. if (overwrite || obj[path[i]] == null) {
  19815. obj[path[i]] = val;
  19816. }
  19817. }
  19818. function compatLayoutProperties(option) {
  19819. each$1(LAYOUT_PROPERTIES, function (prop) {
  19820. if (prop[0] in option && !(prop[1] in option)) {
  19821. option[prop[1]] = option[prop[0]];
  19822. }
  19823. });
  19824. }
  19825. var LAYOUT_PROPERTIES = [
  19826. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19827. ];
  19828. var COMPATITABLE_COMPONENTS = [
  19829. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19830. ];
  19831. var backwardCompat = function (option, isTheme) {
  19832. compatStyle(option, isTheme);
  19833. // Make sure series array for model initialization.
  19834. option.series = normalizeToArray(option.series);
  19835. each$1(option.series, function (seriesOpt) {
  19836. if (!isObject$1(seriesOpt)) {
  19837. return;
  19838. }
  19839. var seriesType = seriesOpt.type;
  19840. if (seriesType === 'line') {
  19841. if (seriesOpt.clipOverflow != null) {
  19842. seriesOpt.clip = seriesOpt.clipOverflow;
  19843. }
  19844. }
  19845. else if (seriesType === 'pie' || seriesType === 'gauge') {
  19846. if (seriesOpt.clockWise != null) {
  19847. seriesOpt.clockwise = seriesOpt.clockWise;
  19848. }
  19849. }
  19850. else if (seriesType === 'gauge') {
  19851. var pointerColor = get(seriesOpt, 'pointer.color');
  19852. pointerColor != null
  19853. && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  19854. }
  19855. compatLayoutProperties(seriesOpt);
  19856. });
  19857. // dataRange has changed to visualMap
  19858. if (option.dataRange) {
  19859. option.visualMap = option.dataRange;
  19860. }
  19861. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19862. var options = option[componentName];
  19863. if (options) {
  19864. if (!isArray(options)) {
  19865. options = [options];
  19866. }
  19867. each$1(options, function (option) {
  19868. compatLayoutProperties(option);
  19869. });
  19870. }
  19871. });
  19872. };
  19873. /*
  19874. * Licensed to the Apache Software Foundation (ASF) under one
  19875. * or more contributor license agreements. See the NOTICE file
  19876. * distributed with this work for additional information
  19877. * regarding copyright ownership. The ASF licenses this file
  19878. * to you under the Apache License, Version 2.0 (the
  19879. * "License"); you may not use this file except in compliance
  19880. * with the License. You may obtain a copy of the License at
  19881. *
  19882. * http://www.apache.org/licenses/LICENSE-2.0
  19883. *
  19884. * Unless required by applicable law or agreed to in writing,
  19885. * software distributed under the License is distributed on an
  19886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19887. * KIND, either express or implied. See the License for the
  19888. * specific language governing permissions and limitations
  19889. * under the License.
  19890. */
  19891. // (1) [Caution]: the logic is correct based on the premises:
  19892. // data processing stage is blocked in stream.
  19893. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19894. // (2) Only register once when import repeatly.
  19895. // Should be executed after series filtered and before stack calculation.
  19896. var dataStack = function (ecModel) {
  19897. var stackInfoMap = createHashMap();
  19898. ecModel.eachSeries(function (seriesModel) {
  19899. var stack = seriesModel.get('stack');
  19900. // Compatibal: when `stack` is set as '', do not stack.
  19901. if (stack) {
  19902. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19903. var data = seriesModel.getData();
  19904. var stackInfo = {
  19905. // Used for calculate axis extent automatically.
  19906. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19907. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19908. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19909. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19910. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19911. data: data,
  19912. seriesModel: seriesModel
  19913. };
  19914. // If stacked on axis that do not support data stack.
  19915. if (!stackInfo.stackedDimension
  19916. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19917. ) {
  19918. return;
  19919. }
  19920. stackInfoList.length && data.setCalculationInfo(
  19921. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19922. );
  19923. stackInfoList.push(stackInfo);
  19924. }
  19925. });
  19926. stackInfoMap.each(calculateStack);
  19927. };
  19928. function calculateStack(stackInfoList) {
  19929. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19930. var resultVal = [];
  19931. var resultNaN = [NaN, NaN];
  19932. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19933. var targetData = targetStackInfo.data;
  19934. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19935. // Should not write on raw data, because stack series model list changes
  19936. // depending on legend selection.
  19937. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19938. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19939. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19940. // should also be NaN, to draw a appropriate belt area.
  19941. if (isNaN(sum)) {
  19942. return resultNaN;
  19943. }
  19944. var byValue;
  19945. var stackedDataRawIndex;
  19946. if (isStackedByIndex) {
  19947. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19948. }
  19949. else {
  19950. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19951. }
  19952. // If stackOver is NaN, chart view will render point on value start.
  19953. var stackedOver = NaN;
  19954. for (var j = idxInStack - 1; j >= 0; j--) {
  19955. var stackInfo = stackInfoList[j];
  19956. // Has been optimized by inverted indices on `stackedByDimension`.
  19957. if (!isStackedByIndex) {
  19958. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19959. }
  19960. if (stackedDataRawIndex >= 0) {
  19961. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19962. // Considering positive stack, negative stack and empty data
  19963. if ((sum >= 0 && val > 0) // Positive stack
  19964. || (sum <= 0 && val < 0) // Negative stack
  19965. ) {
  19966. sum += val;
  19967. stackedOver = val;
  19968. break;
  19969. }
  19970. }
  19971. }
  19972. resultVal[0] = sum;
  19973. resultVal[1] = stackedOver;
  19974. return resultVal;
  19975. });
  19976. targetData.hostModel.setData(newData);
  19977. // Update for consequent calculation
  19978. targetStackInfo.data = newData;
  19979. });
  19980. }
  19981. /*
  19982. * Licensed to the Apache Software Foundation (ASF) under one
  19983. * or more contributor license agreements. See the NOTICE file
  19984. * distributed with this work for additional information
  19985. * regarding copyright ownership. The ASF licenses this file
  19986. * to you under the Apache License, Version 2.0 (the
  19987. * "License"); you may not use this file except in compliance
  19988. * with the License. You may obtain a copy of the License at
  19989. *
  19990. * http://www.apache.org/licenses/LICENSE-2.0
  19991. *
  19992. * Unless required by applicable law or agreed to in writing,
  19993. * software distributed under the License is distributed on an
  19994. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19995. * KIND, either express or implied. See the License for the
  19996. * specific language governing permissions and limitations
  19997. * under the License.
  19998. */
  19999. // TODO
  20000. // ??? refactor? check the outer usage of data provider.
  20001. // merge with defaultDimValueGetter?
  20002. /**
  20003. * If normal array used, mutable chunk size is supported.
  20004. * If typed array used, chunk size must be fixed.
  20005. */
  20006. function DefaultDataProvider(source, dimSize) {
  20007. if (!Source.isInstance(source)) {
  20008. source = Source.seriesDataToSource(source);
  20009. }
  20010. this._source = source;
  20011. var data = this._data = source.data;
  20012. var sourceFormat = source.sourceFormat;
  20013. // Typed array. TODO IE10+?
  20014. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  20015. if (__DEV__) {
  20016. if (dimSize == null) {
  20017. throw new Error('Typed array data must specify dimension size');
  20018. }
  20019. }
  20020. this._offset = 0;
  20021. this._dimSize = dimSize;
  20022. this._data = data;
  20023. }
  20024. var methods = providerMethods[
  20025. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  20026. ? sourceFormat + '_' + source.seriesLayoutBy
  20027. : sourceFormat
  20028. ];
  20029. if (__DEV__) {
  20030. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  20031. }
  20032. extend(this, methods);
  20033. }
  20034. var providerProto = DefaultDataProvider.prototype;
  20035. // If data is pure without style configuration
  20036. providerProto.pure = false;
  20037. // If data is persistent and will not be released after use.
  20038. providerProto.persistent = true;
  20039. // ???! FIXME legacy data provider do not has method getSource
  20040. providerProto.getSource = function () {
  20041. return this._source;
  20042. };
  20043. var providerMethods = {
  20044. 'arrayRows_column': {
  20045. pure: true,
  20046. count: function () {
  20047. return Math.max(0, this._data.length - this._source.startIndex);
  20048. },
  20049. getItem: function (idx) {
  20050. return this._data[idx + this._source.startIndex];
  20051. },
  20052. appendData: appendDataSimply
  20053. },
  20054. 'arrayRows_row': {
  20055. pure: true,
  20056. count: function () {
  20057. var row = this._data[0];
  20058. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  20059. },
  20060. getItem: function (idx) {
  20061. idx += this._source.startIndex;
  20062. var item = [];
  20063. var data = this._data;
  20064. for (var i = 0; i < data.length; i++) {
  20065. var row = data[i];
  20066. item.push(row ? row[idx] : null);
  20067. }
  20068. return item;
  20069. },
  20070. appendData: function () {
  20071. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  20072. }
  20073. },
  20074. 'objectRows': {
  20075. pure: true,
  20076. count: countSimply,
  20077. getItem: getItemSimply,
  20078. appendData: appendDataSimply
  20079. },
  20080. 'keyedColumns': {
  20081. pure: true,
  20082. count: function () {
  20083. var dimName = this._source.dimensionsDefine[0].name;
  20084. var col = this._data[dimName];
  20085. return col ? col.length : 0;
  20086. },
  20087. getItem: function (idx) {
  20088. var item = [];
  20089. var dims = this._source.dimensionsDefine;
  20090. for (var i = 0; i < dims.length; i++) {
  20091. var col = this._data[dims[i].name];
  20092. item.push(col ? col[idx] : null);
  20093. }
  20094. return item;
  20095. },
  20096. appendData: function (newData) {
  20097. var data = this._data;
  20098. each$1(newData, function (newCol, key) {
  20099. var oldCol = data[key] || (data[key] = []);
  20100. for (var i = 0; i < (newCol || []).length; i++) {
  20101. oldCol.push(newCol[i]);
  20102. }
  20103. });
  20104. }
  20105. },
  20106. 'original': {
  20107. count: countSimply,
  20108. getItem: getItemSimply,
  20109. appendData: appendDataSimply
  20110. },
  20111. 'typedArray': {
  20112. persistent: false,
  20113. pure: true,
  20114. count: function () {
  20115. return this._data ? (this._data.length / this._dimSize) : 0;
  20116. },
  20117. getItem: function (idx, out) {
  20118. idx = idx - this._offset;
  20119. out = out || [];
  20120. var offset = this._dimSize * idx;
  20121. for (var i = 0; i < this._dimSize; i++) {
  20122. out[i] = this._data[offset + i];
  20123. }
  20124. return out;
  20125. },
  20126. appendData: function (newData) {
  20127. if (__DEV__) {
  20128. assert$1(
  20129. isTypedArray(newData),
  20130. 'Added data must be TypedArray if data in initialization is TypedArray'
  20131. );
  20132. }
  20133. this._data = newData;
  20134. },
  20135. // Clean self if data is already used.
  20136. clean: function () {
  20137. // PENDING
  20138. this._offset += this.count();
  20139. this._data = null;
  20140. }
  20141. }
  20142. };
  20143. function countSimply() {
  20144. return this._data.length;
  20145. }
  20146. function getItemSimply(idx) {
  20147. return this._data[idx];
  20148. }
  20149. function appendDataSimply(newData) {
  20150. for (var i = 0; i < newData.length; i++) {
  20151. this._data.push(newData[i]);
  20152. }
  20153. }
  20154. var rawValueGetters = {
  20155. arrayRows: getRawValueSimply,
  20156. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  20157. return dimIndex != null ? dataItem[dimName] : dataItem;
  20158. },
  20159. keyedColumns: getRawValueSimply,
  20160. original: function (dataItem, dataIndex, dimIndex, dimName) {
  20161. // FIXME
  20162. // In some case (markpoint in geo (geo-map.html)), dataItem
  20163. // is {coord: [...]}
  20164. var value = getDataItemValue(dataItem);
  20165. return (dimIndex == null || !(value instanceof Array))
  20166. ? value
  20167. : value[dimIndex];
  20168. },
  20169. typedArray: getRawValueSimply
  20170. };
  20171. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  20172. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  20173. }
  20174. var defaultDimValueGetters = {
  20175. arrayRows: getDimValueSimply,
  20176. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  20177. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  20178. },
  20179. keyedColumns: getDimValueSimply,
  20180. original: function (dataItem, dimName, dataIndex, dimIndex) {
  20181. // Performance sensitive, do not use modelUtil.getDataItemValue.
  20182. // If dataItem is an plain object with no value field, the var `value`
  20183. // will be assigned with the object, but it will be tread correctly
  20184. // in the `convertDataValue`.
  20185. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  20186. // If any dataItem is like { value: 10 }
  20187. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  20188. this.hasItemOption = true;
  20189. }
  20190. return converDataValue(
  20191. (value instanceof Array)
  20192. ? value[dimIndex]
  20193. // If value is a single number or something else not array.
  20194. : value,
  20195. this._dimensionInfos[dimName]
  20196. );
  20197. },
  20198. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  20199. return dataItem[dimIndex];
  20200. }
  20201. };
  20202. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  20203. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  20204. }
  20205. /**
  20206. * This helper method convert value in data.
  20207. * @param {string|number|Date} value
  20208. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  20209. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  20210. */
  20211. function converDataValue(value, dimInfo) {
  20212. // Performance sensitive.
  20213. var dimType = dimInfo && dimInfo.type;
  20214. if (dimType === 'ordinal') {
  20215. // If given value is a category string
  20216. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  20217. return ordinalMeta
  20218. ? ordinalMeta.parseAndCollect(value)
  20219. : value;
  20220. }
  20221. if (dimType === 'time'
  20222. // spead up when using timestamp
  20223. && typeof value !== 'number'
  20224. && value != null
  20225. && value !== '-'
  20226. ) {
  20227. value = +parseDate(value);
  20228. }
  20229. // dimType defaults 'number'.
  20230. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  20231. // parse to NaN.
  20232. return (value == null || value === '')
  20233. ? NaN
  20234. // If string (like '-'), using '+' parse to NaN
  20235. // If object, also parse to NaN
  20236. : +value;
  20237. }
  20238. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  20239. // Consider persistent.
  20240. // Caution: why use raw value to display on label or tooltip?
  20241. // A reason is to avoid format. For example time value we do not know
  20242. // how to format is expected. More over, if stack is used, calculated
  20243. // value may be 0.91000000001, which have brings trouble to display.
  20244. // TODO: consider how to treat null/undefined/NaN when display?
  20245. /**
  20246. * @param {module:echarts/data/List} data
  20247. * @param {number} dataIndex
  20248. * @param {string|number} [dim] dimName or dimIndex
  20249. * @return {Array.<number>|string|number} can be null/undefined.
  20250. */
  20251. function retrieveRawValue(data, dataIndex, dim) {
  20252. if (!data) {
  20253. return;
  20254. }
  20255. // Consider data may be not persistent.
  20256. var dataItem = data.getRawDataItem(dataIndex);
  20257. if (dataItem == null) {
  20258. return;
  20259. }
  20260. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20261. var dimName;
  20262. var dimIndex;
  20263. var dimInfo = data.getDimensionInfo(dim);
  20264. if (dimInfo) {
  20265. dimName = dimInfo.name;
  20266. dimIndex = dimInfo.index;
  20267. }
  20268. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  20269. }
  20270. /**
  20271. * Compatible with some cases (in pie, map) like:
  20272. * data: [{name: 'xx', value: 5, selected: true}, ...]
  20273. * where only sourceFormat is 'original' and 'objectRows' supported.
  20274. *
  20275. * ??? TODO
  20276. * Supported detail options in data item when using 'arrayRows'.
  20277. *
  20278. * @param {module:echarts/data/List} data
  20279. * @param {number} dataIndex
  20280. * @param {string} attr like 'selected'
  20281. */
  20282. function retrieveRawAttr(data, dataIndex, attr) {
  20283. if (!data) {
  20284. return;
  20285. }
  20286. var sourceFormat = data.getProvider().getSource().sourceFormat;
  20287. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  20288. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  20289. ) {
  20290. return;
  20291. }
  20292. var dataItem = data.getRawDataItem(dataIndex);
  20293. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  20294. dataItem = null;
  20295. }
  20296. if (dataItem) {
  20297. return dataItem[attr];
  20298. }
  20299. }
  20300. /*
  20301. * Licensed to the Apache Software Foundation (ASF) under one
  20302. * or more contributor license agreements. See the NOTICE file
  20303. * distributed with this work for additional information
  20304. * regarding copyright ownership. The ASF licenses this file
  20305. * to you under the Apache License, Version 2.0 (the
  20306. * "License"); you may not use this file except in compliance
  20307. * with the License. You may obtain a copy of the License at
  20308. *
  20309. * http://www.apache.org/licenses/LICENSE-2.0
  20310. *
  20311. * Unless required by applicable law or agreed to in writing,
  20312. * software distributed under the License is distributed on an
  20313. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20314. * KIND, either express or implied. See the License for the
  20315. * specific language governing permissions and limitations
  20316. * under the License.
  20317. */
  20318. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  20319. // PENDING A little ugly
  20320. var dataFormatMixin = {
  20321. /**
  20322. * Get params for formatter
  20323. * @param {number} dataIndex
  20324. * @param {string} [dataType]
  20325. * @return {Object}
  20326. */
  20327. getDataParams: function (dataIndex, dataType) {
  20328. var data = this.getData(dataType);
  20329. var rawValue = this.getRawValue(dataIndex, dataType);
  20330. var rawDataIndex = data.getRawIndex(dataIndex);
  20331. var name = data.getName(dataIndex);
  20332. var itemOpt = data.getRawDataItem(dataIndex);
  20333. var color = data.getItemVisual(dataIndex, 'color');
  20334. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  20335. var tooltipModel = this.ecModel.getComponent('tooltip');
  20336. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  20337. var renderMode = getTooltipRenderMode(renderModeOption);
  20338. var mainType = this.mainType;
  20339. var isSeries = mainType === 'series';
  20340. var userOutput = data.userOutput;
  20341. return {
  20342. componentType: mainType,
  20343. componentSubType: this.subType,
  20344. componentIndex: this.componentIndex,
  20345. seriesType: isSeries ? this.subType : null,
  20346. seriesIndex: this.seriesIndex,
  20347. seriesId: isSeries ? this.id : null,
  20348. seriesName: isSeries ? this.name : null,
  20349. name: name,
  20350. dataIndex: rawDataIndex,
  20351. data: itemOpt,
  20352. dataType: dataType,
  20353. value: rawValue,
  20354. color: color,
  20355. borderColor: borderColor,
  20356. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  20357. encode: userOutput ? userOutput.encode : null,
  20358. marker: getTooltipMarker({
  20359. color: color,
  20360. renderMode: renderMode
  20361. }),
  20362. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  20363. $vars: ['seriesName', 'name', 'value']
  20364. };
  20365. },
  20366. /**
  20367. * Format label
  20368. * @param {number} dataIndex
  20369. * @param {string} [status='normal'] 'normal' or 'emphasis'
  20370. * @param {string} [dataType]
  20371. * @param {number} [dimIndex] Only used in some chart that
  20372. * use formatter in different dimensions, like radar.
  20373. * @param {string} [labelProp='label']
  20374. * @return {string} If not formatter, return null/undefined
  20375. */
  20376. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  20377. status = status || 'normal';
  20378. var data = this.getData(dataType);
  20379. var itemModel = data.getItemModel(dataIndex);
  20380. var params = this.getDataParams(dataIndex, dataType);
  20381. if (dimIndex != null && (params.value instanceof Array)) {
  20382. params.value = params.value[dimIndex];
  20383. }
  20384. var formatter = itemModel.get(
  20385. status === 'normal'
  20386. ? [labelProp || 'label', 'formatter']
  20387. : [status, labelProp || 'label', 'formatter']
  20388. );
  20389. if (typeof formatter === 'function') {
  20390. params.status = status;
  20391. params.dimensionIndex = dimIndex;
  20392. return formatter(params);
  20393. }
  20394. else if (typeof formatter === 'string') {
  20395. var str = formatTpl(formatter, params);
  20396. // Support 'aaa{@[3]}bbb{@product}ccc'.
  20397. // Do not support '}' in dim name util have to.
  20398. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  20399. var len = dim.length;
  20400. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  20401. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  20402. }
  20403. return retrieveRawValue(data, dataIndex, dim);
  20404. });
  20405. }
  20406. },
  20407. /**
  20408. * Get raw value in option
  20409. * @param {number} idx
  20410. * @param {string} [dataType]
  20411. * @return {Array|number|string}
  20412. */
  20413. getRawValue: function (idx, dataType) {
  20414. return retrieveRawValue(this.getData(dataType), idx);
  20415. },
  20416. /**
  20417. * Should be implemented.
  20418. * @param {number} dataIndex
  20419. * @param {boolean} [multipleSeries=false]
  20420. * @param {number} [dataType]
  20421. * @return {string} tooltip string
  20422. */
  20423. formatTooltip: function () {
  20424. // Empty function
  20425. }
  20426. };
  20427. /*
  20428. * Licensed to the Apache Software Foundation (ASF) under one
  20429. * or more contributor license agreements. See the NOTICE file
  20430. * distributed with this work for additional information
  20431. * regarding copyright ownership. The ASF licenses this file
  20432. * to you under the Apache License, Version 2.0 (the
  20433. * "License"); you may not use this file except in compliance
  20434. * with the License. You may obtain a copy of the License at
  20435. *
  20436. * http://www.apache.org/licenses/LICENSE-2.0
  20437. *
  20438. * Unless required by applicable law or agreed to in writing,
  20439. * software distributed under the License is distributed on an
  20440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20441. * KIND, either express or implied. See the License for the
  20442. * specific language governing permissions and limitations
  20443. * under the License.
  20444. */
  20445. /**
  20446. * @param {Object} define
  20447. * @return See the return of `createTask`.
  20448. */
  20449. function createTask(define) {
  20450. return new Task(define);
  20451. }
  20452. /**
  20453. * @constructor
  20454. * @param {Object} define
  20455. * @param {Function} define.reset Custom reset
  20456. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  20457. * @param {Function} [define.count] count is used to determin data task.
  20458. * @param {Function} [define.onDirty] count is used to determin data task.
  20459. */
  20460. function Task(define) {
  20461. define = define || {};
  20462. this._reset = define.reset;
  20463. this._plan = define.plan;
  20464. this._count = define.count;
  20465. this._onDirty = define.onDirty;
  20466. this._dirty = true;
  20467. // Context must be specified implicitly, to
  20468. // avoid miss update context when model changed.
  20469. this.context;
  20470. }
  20471. var taskProto = Task.prototype;
  20472. /**
  20473. * @param {Object} performArgs
  20474. * @param {number} [performArgs.step] Specified step.
  20475. * @param {number} [performArgs.skip] Skip customer perform call.
  20476. * @param {number} [performArgs.modBy] Sampling window size.
  20477. * @param {number} [performArgs.modDataCount] Sampling count.
  20478. */
  20479. taskProto.perform = function (performArgs) {
  20480. var upTask = this._upstream;
  20481. var skip = performArgs && performArgs.skip;
  20482. // TODO some refactor.
  20483. // Pull data. Must pull data each time, because context.data
  20484. // may be updated by Series.setData.
  20485. if (this._dirty && upTask) {
  20486. var context = this.context;
  20487. context.data = context.outputData = upTask.context.outputData;
  20488. }
  20489. if (this.__pipeline) {
  20490. this.__pipeline.currentTask = this;
  20491. }
  20492. var planResult;
  20493. if (this._plan && !skip) {
  20494. planResult = this._plan(this.context);
  20495. }
  20496. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  20497. // elements uniformed distributed when progress, especially when moving or zooming.
  20498. var lastModBy = normalizeModBy(this._modBy);
  20499. var lastModDataCount = this._modDataCount || 0;
  20500. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  20501. var modDataCount = performArgs && performArgs.modDataCount || 0;
  20502. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  20503. planResult = 'reset';
  20504. }
  20505. function normalizeModBy(val) {
  20506. !(val >= 1) && (val = 1); // jshint ignore:line
  20507. return val;
  20508. }
  20509. var forceFirstProgress;
  20510. if (this._dirty || planResult === 'reset') {
  20511. this._dirty = false;
  20512. forceFirstProgress = reset(this, skip);
  20513. }
  20514. this._modBy = modBy;
  20515. this._modDataCount = modDataCount;
  20516. var step = performArgs && performArgs.step;
  20517. if (upTask) {
  20518. if (__DEV__) {
  20519. assert$1(upTask._outputDueEnd != null);
  20520. }
  20521. this._dueEnd = upTask._outputDueEnd;
  20522. }
  20523. // DataTask or overallTask
  20524. else {
  20525. if (__DEV__) {
  20526. assert$1(!this._progress || this._count);
  20527. }
  20528. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  20529. }
  20530. // Note: Stubs, that its host overall task let it has progress, has progress.
  20531. // If no progress, pass index from upstream to downstream each time plan called.
  20532. if (this._progress) {
  20533. var start = this._dueIndex;
  20534. var end = Math.min(
  20535. step != null ? this._dueIndex + step : Infinity,
  20536. this._dueEnd
  20537. );
  20538. if (!skip && (forceFirstProgress || start < end)) {
  20539. var progress = this._progress;
  20540. if (isArray(progress)) {
  20541. for (var i = 0; i < progress.length; i++) {
  20542. doProgress(this, progress[i], start, end, modBy, modDataCount);
  20543. }
  20544. }
  20545. else {
  20546. doProgress(this, progress, start, end, modBy, modDataCount);
  20547. }
  20548. }
  20549. this._dueIndex = end;
  20550. // If no `outputDueEnd`, assume that output data and
  20551. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  20552. var outputDueEnd = this._settedOutputEnd != null
  20553. ? this._settedOutputEnd : end;
  20554. if (__DEV__) {
  20555. // ??? Can not rollback.
  20556. assert$1(outputDueEnd >= this._outputDueEnd);
  20557. }
  20558. this._outputDueEnd = outputDueEnd;
  20559. }
  20560. else {
  20561. // (1) Some overall task has no progress.
  20562. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  20563. // This should always be performed so it can be passed to downstream.
  20564. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  20565. ? this._settedOutputEnd : this._dueEnd;
  20566. }
  20567. return this.unfinished();
  20568. };
  20569. var iterator = (function () {
  20570. var end;
  20571. var current;
  20572. var modBy;
  20573. var modDataCount;
  20574. var winCount;
  20575. var it = {
  20576. reset: function (s, e, sStep, sCount) {
  20577. current = s;
  20578. end = e;
  20579. modBy = sStep;
  20580. modDataCount = sCount;
  20581. winCount = Math.ceil(modDataCount / modBy);
  20582. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  20583. }
  20584. };
  20585. return it;
  20586. function sequentialNext() {
  20587. return current < end ? current++ : null;
  20588. }
  20589. function modNext() {
  20590. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  20591. var result = current >= end
  20592. ? null
  20593. : dataIndex < modDataCount
  20594. ? dataIndex
  20595. // If modDataCount is smaller than data.count() (consider `appendData` case),
  20596. // Use normal linear rendering mode.
  20597. : current;
  20598. current++;
  20599. return result;
  20600. }
  20601. })();
  20602. taskProto.dirty = function () {
  20603. this._dirty = true;
  20604. this._onDirty && this._onDirty(this.context);
  20605. };
  20606. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  20607. iterator.reset(start, end, modBy, modDataCount);
  20608. taskIns._callingProgress = progress;
  20609. taskIns._callingProgress({
  20610. start: start, end: end, count: end - start, next: iterator.next
  20611. }, taskIns.context);
  20612. }
  20613. function reset(taskIns, skip) {
  20614. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  20615. taskIns._settedOutputEnd = null;
  20616. var progress;
  20617. var forceFirstProgress;
  20618. if (!skip && taskIns._reset) {
  20619. progress = taskIns._reset(taskIns.context);
  20620. if (progress && progress.progress) {
  20621. forceFirstProgress = progress.forceFirstProgress;
  20622. progress = progress.progress;
  20623. }
  20624. // To simplify no progress checking, array must has item.
  20625. if (isArray(progress) && !progress.length) {
  20626. progress = null;
  20627. }
  20628. }
  20629. taskIns._progress = progress;
  20630. taskIns._modBy = taskIns._modDataCount = null;
  20631. var downstream = taskIns._downstream;
  20632. downstream && downstream.dirty();
  20633. return forceFirstProgress;
  20634. }
  20635. /**
  20636. * @return {boolean}
  20637. */
  20638. taskProto.unfinished = function () {
  20639. return this._progress && this._dueIndex < this._dueEnd;
  20640. };
  20641. /**
  20642. * @param {Object} downTask The downstream task.
  20643. * @return {Object} The downstream task.
  20644. */
  20645. taskProto.pipe = function (downTask) {
  20646. if (__DEV__) {
  20647. assert$1(downTask && !downTask._disposed && downTask !== this);
  20648. }
  20649. // If already downstream, do not dirty downTask.
  20650. if (this._downstream !== downTask || this._dirty) {
  20651. this._downstream = downTask;
  20652. downTask._upstream = this;
  20653. downTask.dirty();
  20654. }
  20655. };
  20656. taskProto.dispose = function () {
  20657. if (this._disposed) {
  20658. return;
  20659. }
  20660. this._upstream && (this._upstream._downstream = null);
  20661. this._downstream && (this._downstream._upstream = null);
  20662. this._dirty = false;
  20663. this._disposed = true;
  20664. };
  20665. taskProto.getUpstream = function () {
  20666. return this._upstream;
  20667. };
  20668. taskProto.getDownstream = function () {
  20669. return this._downstream;
  20670. };
  20671. taskProto.setOutputEnd = function (end) {
  20672. // This only happend in dataTask, dataZoom, map, currently.
  20673. // where dataZoom do not set end each time, but only set
  20674. // when reset. So we should record the setted end, in case
  20675. // that the stub of dataZoom perform again and earse the
  20676. // setted end by upstream.
  20677. this._outputDueEnd = this._settedOutputEnd = end;
  20678. };
  20679. ///////////////////////////////////////////////////////////
  20680. // For stream debug (Should be commented out after used!)
  20681. // Usage: printTask(this, 'begin');
  20682. // Usage: printTask(this, null, {someExtraProp});
  20683. // function printTask(task, prefix, extra) {
  20684. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  20685. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  20686. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  20687. // var props = [];
  20688. // if (task.__pipeline) {
  20689. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  20690. // props.push({text: 'idx', value: val});
  20691. // } else {
  20692. // var stubCount = 0;
  20693. // task.agentStubMap.each(() => stubCount++);
  20694. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  20695. // }
  20696. // props.push({text: 'uid', value: task.uidDebug});
  20697. // if (task.__pipeline) {
  20698. // props.push({text: 'pid', value: task.__pipeline.id});
  20699. // task.agent && props.push(
  20700. // {text: 'stubFor', value: task.agent.uidDebug}
  20701. // );
  20702. // }
  20703. // props.push(
  20704. // {text: 'dirty', value: task._dirty},
  20705. // {text: 'dueIndex', value: task._dueIndex},
  20706. // {text: 'dueEnd', value: task._dueEnd},
  20707. // {text: 'outputDueEnd', value: task._outputDueEnd}
  20708. // );
  20709. // if (extra) {
  20710. // Object.keys(extra).forEach(key => {
  20711. // props.push({text: key, value: extra[key]});
  20712. // });
  20713. // }
  20714. // var args = ['color: blue'];
  20715. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20716. // args.push('color: black', 'color: red'),
  20717. // `${item.text}: %c${item.value}`
  20718. // )).join('%c, ');
  20719. // console.log.apply(console, [msg].concat(args));
  20720. // // console.log(this);
  20721. // }
  20722. /*
  20723. * Licensed to the Apache Software Foundation (ASF) under one
  20724. * or more contributor license agreements. See the NOTICE file
  20725. * distributed with this work for additional information
  20726. * regarding copyright ownership. The ASF licenses this file
  20727. * to you under the Apache License, Version 2.0 (the
  20728. * "License"); you may not use this file except in compliance
  20729. * with the License. You may obtain a copy of the License at
  20730. *
  20731. * http://www.apache.org/licenses/LICENSE-2.0
  20732. *
  20733. * Unless required by applicable law or agreed to in writing,
  20734. * software distributed under the License is distributed on an
  20735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20736. * KIND, either express or implied. See the License for the
  20737. * specific language governing permissions and limitations
  20738. * under the License.
  20739. */
  20740. var inner$4 = makeInner();
  20741. var SeriesModel = ComponentModel.extend({
  20742. type: 'series.__base__',
  20743. /**
  20744. * @readOnly
  20745. */
  20746. seriesIndex: 0,
  20747. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20748. coordinateSystem: null,
  20749. /**
  20750. * @type {Object}
  20751. * @protected
  20752. */
  20753. defaultOption: null,
  20754. /**
  20755. * legend visual provider to the legend component
  20756. * @type {Object}
  20757. */
  20758. // PENDING
  20759. legendVisualProvider: null,
  20760. /**
  20761. * Access path of color for visual
  20762. */
  20763. visualColorAccessPath: 'itemStyle.color',
  20764. /**
  20765. * Access path of borderColor for visual
  20766. */
  20767. visualBorderColorAccessPath: 'itemStyle.borderColor',
  20768. /**
  20769. * Support merge layout params.
  20770. * Only support 'box' now (left/right/top/bottom/width/height).
  20771. * @type {string|Object} Object can be {ignoreSize: true}
  20772. * @readOnly
  20773. */
  20774. layoutMode: null,
  20775. init: function (option, parentModel, ecModel, extraOpt) {
  20776. /**
  20777. * @type {number}
  20778. * @readOnly
  20779. */
  20780. this.seriesIndex = this.componentIndex;
  20781. this.dataTask = createTask({
  20782. count: dataTaskCount,
  20783. reset: dataTaskReset
  20784. });
  20785. this.dataTask.context = {model: this};
  20786. this.mergeDefaultAndTheme(option, ecModel);
  20787. prepareSource(this);
  20788. var data = this.getInitialData(option, ecModel);
  20789. wrapData(data, this);
  20790. this.dataTask.context.data = data;
  20791. if (__DEV__) {
  20792. assert$1(data, 'getInitialData returned invalid data.');
  20793. }
  20794. /**
  20795. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20796. * @private
  20797. */
  20798. inner$4(this).dataBeforeProcessed = data;
  20799. // If we reverse the order (make data firstly, and then make
  20800. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20801. // cause data.graph.data !== data when using
  20802. // module:echarts/data/Graph or module:echarts/data/Tree.
  20803. // See module:echarts/data/helper/linkList
  20804. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20805. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20806. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20807. // Call `seriesModel.getRawData()` instead.
  20808. // this.restoreData();
  20809. autoSeriesName(this);
  20810. },
  20811. /**
  20812. * Util for merge default and theme to option
  20813. * @param {Object} option
  20814. * @param {module:echarts/model/Global} ecModel
  20815. */
  20816. mergeDefaultAndTheme: function (option, ecModel) {
  20817. var layoutMode = this.layoutMode;
  20818. var inputPositionParams = layoutMode
  20819. ? getLayoutParams(option) : {};
  20820. // Backward compat: using subType on theme.
  20821. // But if name duplicate between series subType
  20822. // (for example: parallel) add component mainType,
  20823. // add suffix 'Series'.
  20824. var themeSubType = this.subType;
  20825. if (ComponentModel.hasClass(themeSubType)) {
  20826. themeSubType += 'Series';
  20827. }
  20828. merge(
  20829. option,
  20830. ecModel.getTheme().get(this.subType)
  20831. );
  20832. merge(option, this.getDefaultOption());
  20833. // Default label emphasis `show`
  20834. defaultEmphasis(option, 'label', ['show']);
  20835. this.fillDataTextStyle(option.data);
  20836. if (layoutMode) {
  20837. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20838. }
  20839. },
  20840. mergeOption: function (newSeriesOption, ecModel) {
  20841. // this.settingTask.dirty();
  20842. newSeriesOption = merge(this.option, newSeriesOption, true);
  20843. this.fillDataTextStyle(newSeriesOption.data);
  20844. var layoutMode = this.layoutMode;
  20845. if (layoutMode) {
  20846. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20847. }
  20848. prepareSource(this);
  20849. var data = this.getInitialData(newSeriesOption, ecModel);
  20850. wrapData(data, this);
  20851. this.dataTask.dirty();
  20852. this.dataTask.context.data = data;
  20853. inner$4(this).dataBeforeProcessed = data;
  20854. autoSeriesName(this);
  20855. },
  20856. fillDataTextStyle: function (data) {
  20857. // Default data label emphasis `show`
  20858. // FIXME Tree structure data ?
  20859. // FIXME Performance ?
  20860. if (data && !isTypedArray(data)) {
  20861. var props = ['show'];
  20862. for (var i = 0; i < data.length; i++) {
  20863. if (data[i] && data[i].label) {
  20864. defaultEmphasis(data[i], 'label', props);
  20865. }
  20866. }
  20867. }
  20868. },
  20869. /**
  20870. * Init a data structure from data related option in series
  20871. * Must be overwritten
  20872. */
  20873. getInitialData: function () {},
  20874. /**
  20875. * Append data to list
  20876. * @param {Object} params
  20877. * @param {Array|TypedArray} params.data
  20878. */
  20879. appendData: function (params) {
  20880. // FIXME ???
  20881. // (1) If data from dataset, forbidden append.
  20882. // (2) support append data of dataset.
  20883. var data = this.getRawData();
  20884. data.appendData(params.data);
  20885. },
  20886. /**
  20887. * Consider some method like `filter`, `map` need make new data,
  20888. * We should make sure that `seriesModel.getData()` get correct
  20889. * data in the stream procedure. So we fetch data from upstream
  20890. * each time `task.perform` called.
  20891. * @param {string} [dataType]
  20892. * @return {module:echarts/data/List}
  20893. */
  20894. getData: function (dataType) {
  20895. var task = getCurrentTask(this);
  20896. if (task) {
  20897. var data = task.context.data;
  20898. return dataType == null ? data : data.getLinkedData(dataType);
  20899. }
  20900. else {
  20901. // When series is not alive (that may happen when click toolbox
  20902. // restore or setOption with not merge mode), series data may
  20903. // be still need to judge animation or something when graphic
  20904. // elements want to know whether fade out.
  20905. return inner$4(this).data;
  20906. }
  20907. },
  20908. /**
  20909. * @param {module:echarts/data/List} data
  20910. */
  20911. setData: function (data) {
  20912. var task = getCurrentTask(this);
  20913. if (task) {
  20914. var context = task.context;
  20915. // Consider case: filter, data sample.
  20916. if (context.data !== data && task.modifyOutputEnd) {
  20917. task.setOutputEnd(data.count());
  20918. }
  20919. context.outputData = data;
  20920. // Caution: setData should update context.data,
  20921. // Because getData may be called multiply in a
  20922. // single stage and expect to get the data just
  20923. // set. (For example, AxisProxy, x y both call
  20924. // getData and setDate sequentially).
  20925. // So the context.data should be fetched from
  20926. // upstream each time when a stage starts to be
  20927. // performed.
  20928. if (task !== this.dataTask) {
  20929. context.data = data;
  20930. }
  20931. }
  20932. inner$4(this).data = data;
  20933. },
  20934. /**
  20935. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20936. * @return {module:echarts/data/Source} source
  20937. */
  20938. getSource: function () {
  20939. return getSource(this);
  20940. },
  20941. /**
  20942. * Get data before processed
  20943. * @return {module:echarts/data/List}
  20944. */
  20945. getRawData: function () {
  20946. return inner$4(this).dataBeforeProcessed;
  20947. },
  20948. /**
  20949. * Get base axis if has coordinate system and has axis.
  20950. * By default use coordSys.getBaseAxis();
  20951. * Can be overrided for some chart.
  20952. * @return {type} description
  20953. */
  20954. getBaseAxis: function () {
  20955. var coordSys = this.coordinateSystem;
  20956. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20957. },
  20958. // FIXME
  20959. /**
  20960. * Default tooltip formatter
  20961. *
  20962. * @param {number} dataIndex
  20963. * @param {boolean} [multipleSeries=false]
  20964. * @param {number} [dataType]
  20965. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20966. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20967. * string is used as DOM HTML content.
  20968. * 'richText' is used for rendering tooltip in rich text form, for those where
  20969. * DOM operation is not supported.
  20970. * @return {Object} formatted tooltip with `html` and `markers`
  20971. */
  20972. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20973. var series = this;
  20974. renderMode = renderMode || 'html';
  20975. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20976. var isRichText = renderMode === 'richText';
  20977. var markers = {};
  20978. var markerId = 0;
  20979. function formatArrayValue(value) {
  20980. // ??? TODO refactor these logic.
  20981. // check: category-no-encode-has-axis-data in dataset.html
  20982. var vertially = reduce(value, function (vertially, val, idx) {
  20983. var dimItem = data.getDimensionInfo(idx);
  20984. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20985. }, 0);
  20986. var result = [];
  20987. tooltipDims.length
  20988. ? each$1(tooltipDims, function (dim) {
  20989. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20990. })
  20991. // By default, all dims is used on tooltip.
  20992. : each$1(value, setEachItem);
  20993. function setEachItem(val, dim) {
  20994. var dimInfo = data.getDimensionInfo(dim);
  20995. // If `dimInfo.tooltip` is not set, show tooltip.
  20996. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20997. return;
  20998. }
  20999. var dimType = dimInfo.type;
  21000. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  21001. var dimHead = getTooltipMarker({
  21002. color: color,
  21003. type: 'subItem',
  21004. renderMode: renderMode,
  21005. markerId: markName
  21006. });
  21007. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  21008. var valStr = (vertially
  21009. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  21010. : ''
  21011. )
  21012. // FIXME should not format time for raw data?
  21013. + encodeHTML(dimType === 'ordinal'
  21014. ? val + ''
  21015. : dimType === 'time'
  21016. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  21017. : addCommas(val)
  21018. );
  21019. valStr && result.push(valStr);
  21020. if (isRichText) {
  21021. markers[markName] = color;
  21022. ++markerId;
  21023. }
  21024. }
  21025. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  21026. var content = newLine + result.join(newLine || ', ');
  21027. return {
  21028. renderMode: renderMode,
  21029. content: content,
  21030. style: markers
  21031. };
  21032. }
  21033. function formatSingleValue(val) {
  21034. // return encodeHTML(addCommas(val));
  21035. return {
  21036. renderMode: renderMode,
  21037. content: encodeHTML(addCommas(val)),
  21038. style: markers
  21039. };
  21040. }
  21041. var data = this.getData();
  21042. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  21043. var tooltipDimLen = tooltipDims.length;
  21044. var value = this.getRawValue(dataIndex);
  21045. var isValueArr = isArray(value);
  21046. var color = data.getItemVisual(dataIndex, 'color');
  21047. if (isObject$1(color) && color.colorStops) {
  21048. color = (color.colorStops[0] || {}).color;
  21049. }
  21050. color = color || 'transparent';
  21051. // Complicated rule for pretty tooltip.
  21052. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  21053. ? formatArrayValue(value)
  21054. : tooltipDimLen
  21055. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  21056. : formatSingleValue(isValueArr ? value[0] : value);
  21057. var content = formattedValue.content;
  21058. var markName = series.seriesIndex + 'at' + markerId;
  21059. var colorEl = getTooltipMarker({
  21060. color: color,
  21061. type: 'item',
  21062. renderMode: renderMode,
  21063. markerId: markName
  21064. });
  21065. markers[markName] = color;
  21066. ++markerId;
  21067. var name = data.getName(dataIndex);
  21068. var seriesName = this.name;
  21069. if (!isNameSpecified(this)) {
  21070. seriesName = '';
  21071. }
  21072. seriesName = seriesName
  21073. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  21074. : '';
  21075. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  21076. var html = !multipleSeries
  21077. ? seriesName + colorStr
  21078. + (name
  21079. ? encodeHTML(name) + ': ' + content
  21080. : content
  21081. )
  21082. : colorStr + seriesName + content;
  21083. return {
  21084. html: html,
  21085. markers: markers
  21086. };
  21087. },
  21088. /**
  21089. * @return {boolean}
  21090. */
  21091. isAnimationEnabled: function () {
  21092. if (env$1.node) {
  21093. return false;
  21094. }
  21095. var animationEnabled = this.getShallow('animation');
  21096. if (animationEnabled) {
  21097. if (this.getData().count() > this.getShallow('animationThreshold')) {
  21098. animationEnabled = false;
  21099. }
  21100. }
  21101. return animationEnabled;
  21102. },
  21103. restoreData: function () {
  21104. this.dataTask.dirty();
  21105. },
  21106. getColorFromPalette: function (name, scope, requestColorNum) {
  21107. var ecModel = this.ecModel;
  21108. // PENDING
  21109. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  21110. if (!color) {
  21111. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  21112. }
  21113. return color;
  21114. },
  21115. /**
  21116. * Use `data.mapDimension(coordDim, true)` instead.
  21117. * @deprecated
  21118. */
  21119. coordDimToDataDim: function (coordDim) {
  21120. return this.getRawData().mapDimension(coordDim, true);
  21121. },
  21122. /**
  21123. * Get progressive rendering count each step
  21124. * @return {number}
  21125. */
  21126. getProgressive: function () {
  21127. return this.get('progressive');
  21128. },
  21129. /**
  21130. * Get progressive rendering count each step
  21131. * @return {number}
  21132. */
  21133. getProgressiveThreshold: function () {
  21134. return this.get('progressiveThreshold');
  21135. },
  21136. /**
  21137. * Get data indices for show tooltip content. See tooltip.
  21138. * @abstract
  21139. * @param {Array.<string>|string} dim
  21140. * @param {Array.<number>} value
  21141. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  21142. * @return {Object} {dataIndices, nestestValue}.
  21143. */
  21144. getAxisTooltipData: null,
  21145. /**
  21146. * See tooltip.
  21147. * @abstract
  21148. * @param {number} dataIndex
  21149. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  21150. */
  21151. getTooltipPosition: null,
  21152. /**
  21153. * @see {module:echarts/stream/Scheduler}
  21154. */
  21155. pipeTask: null,
  21156. /**
  21157. * Convinient for override in extended class.
  21158. * @protected
  21159. * @type {Function}
  21160. */
  21161. preventIncremental: null,
  21162. /**
  21163. * @public
  21164. * @readOnly
  21165. * @type {Object}
  21166. */
  21167. pipelineContext: null
  21168. });
  21169. mixin(SeriesModel, dataFormatMixin);
  21170. mixin(SeriesModel, colorPaletteMixin);
  21171. /**
  21172. * MUST be called after `prepareSource` called
  21173. * Here we need to make auto series, especially for auto legend. But we
  21174. * do not modify series.name in option to avoid side effects.
  21175. */
  21176. function autoSeriesName(seriesModel) {
  21177. // User specified name has higher priority, otherwise it may cause
  21178. // series can not be queried unexpectedly.
  21179. var name = seriesModel.name;
  21180. if (!isNameSpecified(seriesModel)) {
  21181. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  21182. }
  21183. }
  21184. function getSeriesAutoName(seriesModel) {
  21185. var data = seriesModel.getRawData();
  21186. var dataDims = data.mapDimension('seriesName', true);
  21187. var nameArr = [];
  21188. each$1(dataDims, function (dataDim) {
  21189. var dimInfo = data.getDimensionInfo(dataDim);
  21190. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  21191. });
  21192. return nameArr.join(' ');
  21193. }
  21194. function dataTaskCount(context) {
  21195. return context.model.getRawData().count();
  21196. }
  21197. function dataTaskReset(context) {
  21198. var seriesModel = context.model;
  21199. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  21200. return dataTaskProgress;
  21201. }
  21202. function dataTaskProgress(param, context) {
  21203. // Avoid repead cloneShallow when data just created in reset.
  21204. if (param.end > context.outputData.count()) {
  21205. context.model.getRawData().cloneShallow(context.outputData);
  21206. }
  21207. }
  21208. // TODO refactor
  21209. function wrapData(data, seriesModel) {
  21210. each$1(data.CHANGABLE_METHODS, function (methodName) {
  21211. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  21212. });
  21213. }
  21214. function onDataSelfChange(seriesModel) {
  21215. var task = getCurrentTask(seriesModel);
  21216. if (task) {
  21217. // Consider case: filter, selectRange
  21218. task.setOutputEnd(this.count());
  21219. }
  21220. }
  21221. function getCurrentTask(seriesModel) {
  21222. var scheduler = (seriesModel.ecModel || {}).scheduler;
  21223. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  21224. if (pipeline) {
  21225. // When pipline finished, the currrentTask keep the last
  21226. // task (renderTask).
  21227. var task = pipeline.currentTask;
  21228. if (task) {
  21229. var agentStubMap = task.agentStubMap;
  21230. if (agentStubMap) {
  21231. task = agentStubMap.get(seriesModel.uid);
  21232. }
  21233. }
  21234. return task;
  21235. }
  21236. }
  21237. /*
  21238. * Licensed to the Apache Software Foundation (ASF) under one
  21239. * or more contributor license agreements. See the NOTICE file
  21240. * distributed with this work for additional information
  21241. * regarding copyright ownership. The ASF licenses this file
  21242. * to you under the Apache License, Version 2.0 (the
  21243. * "License"); you may not use this file except in compliance
  21244. * with the License. You may obtain a copy of the License at
  21245. *
  21246. * http://www.apache.org/licenses/LICENSE-2.0
  21247. *
  21248. * Unless required by applicable law or agreed to in writing,
  21249. * software distributed under the License is distributed on an
  21250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21251. * KIND, either express or implied. See the License for the
  21252. * specific language governing permissions and limitations
  21253. * under the License.
  21254. */
  21255. var Component = function () {
  21256. /**
  21257. * @type {module:zrender/container/Group}
  21258. * @readOnly
  21259. */
  21260. this.group = new Group();
  21261. /**
  21262. * @type {string}
  21263. * @readOnly
  21264. */
  21265. this.uid = getUID('viewComponent');
  21266. };
  21267. Component.prototype = {
  21268. constructor: Component,
  21269. init: function (ecModel, api) {},
  21270. render: function (componentModel, ecModel, api, payload) {},
  21271. dispose: function () {},
  21272. /**
  21273. * @param {string} eventType
  21274. * @param {Object} query
  21275. * @param {module:zrender/Element} targetEl
  21276. * @param {Object} packedEvent
  21277. * @return {boolen} Pass only when return `true`.
  21278. */
  21279. filterForExposedEvent: null
  21280. };
  21281. var componentProto = Component.prototype;
  21282. componentProto.updateView =
  21283. componentProto.updateLayout =
  21284. componentProto.updateVisual =
  21285. function (seriesModel, ecModel, api, payload) {
  21286. // Do nothing;
  21287. };
  21288. // Enable Component.extend.
  21289. enableClassExtend(Component);
  21290. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21291. enableClassManagement(Component, {registerWhenExtend: true});
  21292. /*
  21293. * Licensed to the Apache Software Foundation (ASF) under one
  21294. * or more contributor license agreements. See the NOTICE file
  21295. * distributed with this work for additional information
  21296. * regarding copyright ownership. The ASF licenses this file
  21297. * to you under the Apache License, Version 2.0 (the
  21298. * "License"); you may not use this file except in compliance
  21299. * with the License. You may obtain a copy of the License at
  21300. *
  21301. * http://www.apache.org/licenses/LICENSE-2.0
  21302. *
  21303. * Unless required by applicable law or agreed to in writing,
  21304. * software distributed under the License is distributed on an
  21305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21306. * KIND, either express or implied. See the License for the
  21307. * specific language governing permissions and limitations
  21308. * under the License.
  21309. */
  21310. /**
  21311. * @return {string} If large mode changed, return string 'reset';
  21312. */
  21313. var createRenderPlanner = function () {
  21314. var inner = makeInner();
  21315. return function (seriesModel) {
  21316. var fields = inner(seriesModel);
  21317. var pipelineContext = seriesModel.pipelineContext;
  21318. var originalLarge = fields.large;
  21319. var originalProgressive = fields.progressiveRender;
  21320. var large = fields.large = pipelineContext.large;
  21321. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  21322. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  21323. };
  21324. };
  21325. /*
  21326. * Licensed to the Apache Software Foundation (ASF) under one
  21327. * or more contributor license agreements. See the NOTICE file
  21328. * distributed with this work for additional information
  21329. * regarding copyright ownership. The ASF licenses this file
  21330. * to you under the Apache License, Version 2.0 (the
  21331. * "License"); you may not use this file except in compliance
  21332. * with the License. You may obtain a copy of the License at
  21333. *
  21334. * http://www.apache.org/licenses/LICENSE-2.0
  21335. *
  21336. * Unless required by applicable law or agreed to in writing,
  21337. * software distributed under the License is distributed on an
  21338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21339. * KIND, either express or implied. See the License for the
  21340. * specific language governing permissions and limitations
  21341. * under the License.
  21342. */
  21343. var inner$5 = makeInner();
  21344. var renderPlanner = createRenderPlanner();
  21345. function Chart() {
  21346. /**
  21347. * @type {module:zrender/container/Group}
  21348. * @readOnly
  21349. */
  21350. this.group = new Group();
  21351. /**
  21352. * @type {string}
  21353. * @readOnly
  21354. */
  21355. this.uid = getUID('viewChart');
  21356. this.renderTask = createTask({
  21357. plan: renderTaskPlan,
  21358. reset: renderTaskReset
  21359. });
  21360. this.renderTask.context = {view: this};
  21361. }
  21362. Chart.prototype = {
  21363. type: 'chart',
  21364. /**
  21365. * Init the chart.
  21366. * @param {module:echarts/model/Global} ecModel
  21367. * @param {module:echarts/ExtensionAPI} api
  21368. */
  21369. init: function (ecModel, api) {},
  21370. /**
  21371. * Render the chart.
  21372. * @param {module:echarts/model/Series} seriesModel
  21373. * @param {module:echarts/model/Global} ecModel
  21374. * @param {module:echarts/ExtensionAPI} api
  21375. * @param {Object} payload
  21376. */
  21377. render: function (seriesModel, ecModel, api, payload) {},
  21378. /**
  21379. * Highlight series or specified data item.
  21380. * @param {module:echarts/model/Series} seriesModel
  21381. * @param {module:echarts/model/Global} ecModel
  21382. * @param {module:echarts/ExtensionAPI} api
  21383. * @param {Object} payload
  21384. */
  21385. highlight: function (seriesModel, ecModel, api, payload) {
  21386. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  21387. },
  21388. /**
  21389. * Downplay series or specified data item.
  21390. * @param {module:echarts/model/Series} seriesModel
  21391. * @param {module:echarts/model/Global} ecModel
  21392. * @param {module:echarts/ExtensionAPI} api
  21393. * @param {Object} payload
  21394. */
  21395. downplay: function (seriesModel, ecModel, api, payload) {
  21396. toggleHighlight(seriesModel.getData(), payload, 'normal');
  21397. },
  21398. /**
  21399. * Remove self.
  21400. * @param {module:echarts/model/Global} ecModel
  21401. * @param {module:echarts/ExtensionAPI} api
  21402. */
  21403. remove: function (ecModel, api) {
  21404. this.group.removeAll();
  21405. },
  21406. /**
  21407. * Dispose self.
  21408. * @param {module:echarts/model/Global} ecModel
  21409. * @param {module:echarts/ExtensionAPI} api
  21410. */
  21411. dispose: function () {},
  21412. /**
  21413. * Rendering preparation in progressive mode.
  21414. * @param {module:echarts/model/Series} seriesModel
  21415. * @param {module:echarts/model/Global} ecModel
  21416. * @param {module:echarts/ExtensionAPI} api
  21417. * @param {Object} payload
  21418. */
  21419. incrementalPrepareRender: null,
  21420. /**
  21421. * Render in progressive mode.
  21422. * @param {Object} params See taskParams in `stream/task.js`
  21423. * @param {module:echarts/model/Series} seriesModel
  21424. * @param {module:echarts/model/Global} ecModel
  21425. * @param {module:echarts/ExtensionAPI} api
  21426. * @param {Object} payload
  21427. */
  21428. incrementalRender: null,
  21429. /**
  21430. * Update transform directly.
  21431. * @param {module:echarts/model/Series} seriesModel
  21432. * @param {module:echarts/model/Global} ecModel
  21433. * @param {module:echarts/ExtensionAPI} api
  21434. * @param {Object} payload
  21435. * @return {Object} {update: true}
  21436. */
  21437. updateTransform: null,
  21438. /**
  21439. * The view contains the given point.
  21440. * @interface
  21441. * @param {Array.<number>} point
  21442. * @return {boolean}
  21443. */
  21444. // containPoint: function () {}
  21445. /**
  21446. * @param {string} eventType
  21447. * @param {Object} query
  21448. * @param {module:zrender/Element} targetEl
  21449. * @param {Object} packedEvent
  21450. * @return {boolen} Pass only when return `true`.
  21451. */
  21452. filterForExposedEvent: null
  21453. };
  21454. var chartProto = Chart.prototype;
  21455. chartProto.updateView =
  21456. chartProto.updateLayout =
  21457. chartProto.updateVisual =
  21458. function (seriesModel, ecModel, api, payload) {
  21459. this.render(seriesModel, ecModel, api, payload);
  21460. };
  21461. /**
  21462. * Set state of single element
  21463. * @param {module:zrender/Element} el
  21464. * @param {string} state 'normal'|'emphasis'
  21465. * @param {number} highlightDigit
  21466. */
  21467. function elSetState(el, state, highlightDigit) {
  21468. if (el) {
  21469. el.trigger(state, highlightDigit);
  21470. if (el.isGroup
  21471. // Simple optimize.
  21472. && !isHighDownDispatcher(el)
  21473. ) {
  21474. for (var i = 0, len = el.childCount(); i < len; i++) {
  21475. elSetState(el.childAt(i), state, highlightDigit);
  21476. }
  21477. }
  21478. }
  21479. }
  21480. /**
  21481. * @param {module:echarts/data/List} data
  21482. * @param {Object} payload
  21483. * @param {string} state 'normal'|'emphasis'
  21484. */
  21485. function toggleHighlight(data, payload, state) {
  21486. var dataIndex = queryDataIndex(data, payload);
  21487. var highlightDigit = (payload && payload.highlightKey != null)
  21488. ? getHighlightDigit(payload.highlightKey)
  21489. : null;
  21490. if (dataIndex != null) {
  21491. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  21492. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  21493. });
  21494. }
  21495. else {
  21496. data.eachItemGraphicEl(function (el) {
  21497. elSetState(el, state, highlightDigit);
  21498. });
  21499. }
  21500. }
  21501. // Enable Chart.extend.
  21502. enableClassExtend(Chart, ['dispose']);
  21503. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  21504. enableClassManagement(Chart, {registerWhenExtend: true});
  21505. Chart.markUpdateMethod = function (payload, methodName) {
  21506. inner$5(payload).updateMethod = methodName;
  21507. };
  21508. function renderTaskPlan(context) {
  21509. return renderPlanner(context.model);
  21510. }
  21511. function renderTaskReset(context) {
  21512. var seriesModel = context.model;
  21513. var ecModel = context.ecModel;
  21514. var api = context.api;
  21515. var payload = context.payload;
  21516. // ???! remove updateView updateVisual
  21517. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  21518. var view = context.view;
  21519. var updateMethod = payload && inner$5(payload).updateMethod;
  21520. var methodName = progressiveRender
  21521. ? 'incrementalPrepareRender'
  21522. : (updateMethod && view[updateMethod])
  21523. ? updateMethod
  21524. // `appendData` is also supported when data amount
  21525. // is less than progressive threshold.
  21526. : 'render';
  21527. if (methodName !== 'render') {
  21528. view[methodName](seriesModel, ecModel, api, payload);
  21529. }
  21530. return progressMethodMap[methodName];
  21531. }
  21532. var progressMethodMap = {
  21533. incrementalPrepareRender: {
  21534. progress: function (params, context) {
  21535. context.view.incrementalRender(
  21536. params, context.model, context.ecModel, context.api, context.payload
  21537. );
  21538. }
  21539. },
  21540. render: {
  21541. // Put view.render in `progress` to support appendData. But in this case
  21542. // view.render should not be called in reset, otherwise it will be called
  21543. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21544. // in any cases.
  21545. forceFirstProgress: true,
  21546. progress: function (params, context) {
  21547. context.view.render(
  21548. context.model, context.ecModel, context.api, context.payload
  21549. );
  21550. }
  21551. }
  21552. };
  21553. /*
  21554. * Licensed to the Apache Software Foundation (ASF) under one
  21555. * or more contributor license agreements. See the NOTICE file
  21556. * distributed with this work for additional information
  21557. * regarding copyright ownership. The ASF licenses this file
  21558. * to you under the Apache License, Version 2.0 (the
  21559. * "License"); you may not use this file except in compliance
  21560. * with the License. You may obtain a copy of the License at
  21561. *
  21562. * http://www.apache.org/licenses/LICENSE-2.0
  21563. *
  21564. * Unless required by applicable law or agreed to in writing,
  21565. * software distributed under the License is distributed on an
  21566. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21567. * KIND, either express or implied. See the License for the
  21568. * specific language governing permissions and limitations
  21569. * under the License.
  21570. */
  21571. /**
  21572. * @public
  21573. * @param {(Function)} fn
  21574. * @param {number} [delay=0] Unit: ms.
  21575. * @param {boolean} [debounce=false]
  21576. * true: If call interval less than `delay`, only the last call works.
  21577. * false: If call interval less than `delay, call works on fixed rate.
  21578. * @return {(Function)} throttled fn.
  21579. */
  21580. function throttle(fn, delay, debounce) {
  21581. var currCall;
  21582. var lastCall = 0;
  21583. var lastExec = 0;
  21584. var timer = null;
  21585. var diff;
  21586. var scope;
  21587. var args;
  21588. var debounceNextCall;
  21589. delay = delay || 0;
  21590. function exec() {
  21591. lastExec = (new Date()).getTime();
  21592. timer = null;
  21593. fn.apply(scope, args || []);
  21594. }
  21595. var cb = function () {
  21596. currCall = (new Date()).getTime();
  21597. scope = this;
  21598. args = arguments;
  21599. var thisDelay = debounceNextCall || delay;
  21600. var thisDebounce = debounceNextCall || debounce;
  21601. debounceNextCall = null;
  21602. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21603. clearTimeout(timer);
  21604. // Here we should make sure that: the `exec` SHOULD NOT be called later
  21605. // than a new call of `cb`, that is, preserving the command order. Consider
  21606. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21607. // happens, either the `exec` is called dierectly, or the call is delayed.
  21608. // But the delayed call should never be later than next call of `cb`. Under
  21609. // this assurance, we can simply update view state each time `dispatchAction`
  21610. // triggered by user roaming, but not need to add extra code to avoid the
  21611. // state being "rolled-back".
  21612. if (thisDebounce) {
  21613. timer = setTimeout(exec, thisDelay);
  21614. }
  21615. else {
  21616. if (diff >= 0) {
  21617. exec();
  21618. }
  21619. else {
  21620. timer = setTimeout(exec, -diff);
  21621. }
  21622. }
  21623. lastCall = currCall;
  21624. };
  21625. /**
  21626. * Clear throttle.
  21627. * @public
  21628. */
  21629. cb.clear = function () {
  21630. if (timer) {
  21631. clearTimeout(timer);
  21632. timer = null;
  21633. }
  21634. };
  21635. /**
  21636. * Enable debounce once.
  21637. */
  21638. cb.debounceNextCall = function (debounceDelay) {
  21639. debounceNextCall = debounceDelay;
  21640. };
  21641. return cb;
  21642. }
  21643. /**
  21644. * Create throttle method or update throttle rate.
  21645. *
  21646. * @example
  21647. * ComponentView.prototype.render = function () {
  21648. * ...
  21649. * throttle.createOrUpdate(
  21650. * this,
  21651. * '_dispatchAction',
  21652. * this.model.get('throttle'),
  21653. * 'fixRate'
  21654. * );
  21655. * };
  21656. * ComponentView.prototype.remove = function () {
  21657. * throttle.clear(this, '_dispatchAction');
  21658. * };
  21659. * ComponentView.prototype.dispose = function () {
  21660. * throttle.clear(this, '_dispatchAction');
  21661. * };
  21662. *
  21663. * @public
  21664. * @param {Object} obj
  21665. * @param {string} fnAttr
  21666. * @param {number} [rate]
  21667. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  21668. * @return {Function} throttled function.
  21669. */
  21670. /**
  21671. * Clear throttle. Example see throttle.createOrUpdate.
  21672. *
  21673. * @public
  21674. * @param {Object} obj
  21675. * @param {string} fnAttr
  21676. */
  21677. /*
  21678. * Licensed to the Apache Software Foundation (ASF) under one
  21679. * or more contributor license agreements. See the NOTICE file
  21680. * distributed with this work for additional information
  21681. * regarding copyright ownership. The ASF licenses this file
  21682. * to you under the Apache License, Version 2.0 (the
  21683. * "License"); you may not use this file except in compliance
  21684. * with the License. You may obtain a copy of the License at
  21685. *
  21686. * http://www.apache.org/licenses/LICENSE-2.0
  21687. *
  21688. * Unless required by applicable law or agreed to in writing,
  21689. * software distributed under the License is distributed on an
  21690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21691. * KIND, either express or implied. See the License for the
  21692. * specific language governing permissions and limitations
  21693. * under the License.
  21694. */
  21695. var seriesColor = {
  21696. createOnAllSeries: true,
  21697. performRawSeries: true,
  21698. reset: function (seriesModel, ecModel) {
  21699. var data = seriesModel.getData();
  21700. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  21701. // Set in itemStyle
  21702. var color = seriesModel.get(colorAccessPath);
  21703. var colorCallback = (isFunction$1(color) && !(color instanceof Gradient))
  21704. ? color : null;
  21705. // Default color
  21706. if (!color || colorCallback) {
  21707. color = seriesModel.getColorFromPalette(
  21708. // TODO series count changed.
  21709. seriesModel.name, null, ecModel.getSeriesCount()
  21710. );
  21711. }
  21712. data.setVisual('color', color);
  21713. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  21714. var borderColor = seriesModel.get(borderColorAccessPath);
  21715. data.setVisual('borderColor', borderColor);
  21716. // Only visible series has each data be visual encoded
  21717. if (!ecModel.isSeriesFiltered(seriesModel)) {
  21718. if (colorCallback) {
  21719. data.each(function (idx) {
  21720. data.setItemVisual(
  21721. idx, 'color', colorCallback(seriesModel.getDataParams(idx))
  21722. );
  21723. });
  21724. }
  21725. // itemStyle in each data item
  21726. var dataEach = function (data, idx) {
  21727. var itemModel = data.getItemModel(idx);
  21728. var color = itemModel.get(colorAccessPath, true);
  21729. var borderColor = itemModel.get(borderColorAccessPath, true);
  21730. if (color != null) {
  21731. data.setItemVisual(idx, 'color', color);
  21732. }
  21733. if (borderColor != null) {
  21734. data.setItemVisual(idx, 'borderColor', borderColor);
  21735. }
  21736. };
  21737. return { dataEach: data.hasItemOption ? dataEach : null };
  21738. }
  21739. }
  21740. };
  21741. /*
  21742. * Licensed to the Apache Software Foundation (ASF) under one
  21743. * or more contributor license agreements. See the NOTICE file
  21744. * distributed with this work for additional information
  21745. * regarding copyright ownership. The ASF licenses this file
  21746. * to you under the Apache License, Version 2.0 (the
  21747. * "License"); you may not use this file except in compliance
  21748. * with the License. You may obtain a copy of the License at
  21749. *
  21750. * http://www.apache.org/licenses/LICENSE-2.0
  21751. *
  21752. * Unless required by applicable law or agreed to in writing,
  21753. * software distributed under the License is distributed on an
  21754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21755. * KIND, either express or implied. See the License for the
  21756. * specific language governing permissions and limitations
  21757. * under the License.
  21758. */
  21759. /**
  21760. * Language: English.
  21761. */
  21762. var lang = {
  21763. legend: {
  21764. selector: {
  21765. all: 'All',
  21766. inverse: 'Inv'
  21767. }
  21768. },
  21769. toolbox: {
  21770. brush: {
  21771. title: {
  21772. rect: 'Box Select',
  21773. polygon: 'Lasso Select',
  21774. lineX: 'Horizontally Select',
  21775. lineY: 'Vertically Select',
  21776. keep: 'Keep Selections',
  21777. clear: 'Clear Selections'
  21778. }
  21779. },
  21780. dataView: {
  21781. title: 'Data View',
  21782. lang: ['Data View', 'Close', 'Refresh']
  21783. },
  21784. dataZoom: {
  21785. title: {
  21786. zoom: 'Zoom',
  21787. back: 'Zoom Reset'
  21788. }
  21789. },
  21790. magicType: {
  21791. title: {
  21792. line: 'Switch to Line Chart',
  21793. bar: 'Switch to Bar Chart',
  21794. stack: 'Stack',
  21795. tiled: 'Tile'
  21796. }
  21797. },
  21798. restore: {
  21799. title: 'Restore'
  21800. },
  21801. saveAsImage: {
  21802. title: 'Save as Image',
  21803. lang: ['Right Click to Save Image']
  21804. }
  21805. },
  21806. aria: {
  21807. general: {
  21808. withTitle: 'This is a chart about "{title}"',
  21809. withoutTitle: 'This is a chart'
  21810. },
  21811. series: {
  21812. single: {
  21813. prefix: '',
  21814. withName: ' with type {seriesType} named {seriesName}.',
  21815. withoutName: ' with type {seriesType}.'
  21816. },
  21817. multiple: {
  21818. prefix: '. It consists of {seriesCount} series count.',
  21819. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  21820. withoutName: ' The {seriesId} series is a {seriesType}.',
  21821. separator: {
  21822. middle: '',
  21823. end: ''
  21824. }
  21825. }
  21826. },
  21827. data: {
  21828. allData: 'The data is as follows: ',
  21829. partialData: 'The first {displayCnt} items are: ',
  21830. withName: 'the data for {name} is {value}',
  21831. withoutName: '{value}',
  21832. separator: {
  21833. middle: ',',
  21834. end: '.'
  21835. }
  21836. }
  21837. }
  21838. };
  21839. /*
  21840. * Licensed to the Apache Software Foundation (ASF) under one
  21841. * or more contributor license agreements. See the NOTICE file
  21842. * distributed with this work for additional information
  21843. * regarding copyright ownership. The ASF licenses this file
  21844. * to you under the Apache License, Version 2.0 (the
  21845. * "License"); you may not use this file except in compliance
  21846. * with the License. You may obtain a copy of the License at
  21847. *
  21848. * http://www.apache.org/licenses/LICENSE-2.0
  21849. *
  21850. * Unless required by applicable law or agreed to in writing,
  21851. * software distributed under the License is distributed on an
  21852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21853. * KIND, either express or implied. See the License for the
  21854. * specific language governing permissions and limitations
  21855. * under the License.
  21856. */
  21857. var aria = function (dom, ecModel) {
  21858. var ariaModel = ecModel.getModel('aria');
  21859. if (!ariaModel.get('show')) {
  21860. return;
  21861. }
  21862. else if (ariaModel.get('description')) {
  21863. dom.setAttribute('aria-label', ariaModel.get('description'));
  21864. return;
  21865. }
  21866. var seriesCnt = 0;
  21867. ecModel.eachSeries(function (seriesModel, idx) {
  21868. ++seriesCnt;
  21869. }, this);
  21870. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21871. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21872. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21873. var ariaLabel;
  21874. if (seriesCnt < 1) {
  21875. // No series, no aria label
  21876. return;
  21877. }
  21878. else {
  21879. var title = getTitle();
  21880. if (title) {
  21881. ariaLabel = replace(getConfig('general.withTitle'), {
  21882. title: title
  21883. });
  21884. }
  21885. else {
  21886. ariaLabel = getConfig('general.withoutTitle');
  21887. }
  21888. var seriesLabels = [];
  21889. var prefix = seriesCnt > 1
  21890. ? 'series.multiple.prefix'
  21891. : 'series.single.prefix';
  21892. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21893. ecModel.eachSeries(function (seriesModel, idx) {
  21894. if (idx < displaySeriesCnt) {
  21895. var seriesLabel;
  21896. var seriesName = seriesModel.get('name');
  21897. var seriesTpl = 'series.'
  21898. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21899. seriesLabel = getConfig(seriesName
  21900. ? seriesTpl + 'withName'
  21901. : seriesTpl + 'withoutName');
  21902. seriesLabel = replace(seriesLabel, {
  21903. seriesId: seriesModel.seriesIndex,
  21904. seriesName: seriesModel.get('name'),
  21905. seriesType: getSeriesTypeName(seriesModel.subType)
  21906. });
  21907. var data = seriesModel.getData();
  21908. window.data = data;
  21909. if (data.count() > maxDataCnt) {
  21910. // Show part of data
  21911. seriesLabel += replace(getConfig('data.partialData'), {
  21912. displayCnt: maxDataCnt
  21913. });
  21914. }
  21915. else {
  21916. seriesLabel += getConfig('data.allData');
  21917. }
  21918. var dataLabels = [];
  21919. for (var i = 0; i < data.count(); i++) {
  21920. if (i < maxDataCnt) {
  21921. var name = data.getName(i);
  21922. var value = retrieveRawValue(data, i);
  21923. dataLabels.push(
  21924. replace(
  21925. name
  21926. ? getConfig('data.withName')
  21927. : getConfig('data.withoutName'),
  21928. {
  21929. name: name,
  21930. value: value
  21931. }
  21932. )
  21933. );
  21934. }
  21935. }
  21936. seriesLabel += dataLabels
  21937. .join(getConfig('data.separator.middle'))
  21938. + getConfig('data.separator.end');
  21939. seriesLabels.push(seriesLabel);
  21940. }
  21941. });
  21942. ariaLabel += seriesLabels
  21943. .join(getConfig('series.multiple.separator.middle'))
  21944. + getConfig('series.multiple.separator.end');
  21945. dom.setAttribute('aria-label', ariaLabel);
  21946. }
  21947. function replace(str, keyValues) {
  21948. if (typeof str !== 'string') {
  21949. return str;
  21950. }
  21951. var result = str;
  21952. each$1(keyValues, function (value, key) {
  21953. result = result.replace(
  21954. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21955. value
  21956. );
  21957. });
  21958. return result;
  21959. }
  21960. function getConfig(path) {
  21961. var userConfig = ariaModel.get(path);
  21962. if (userConfig == null) {
  21963. var pathArr = path.split('.');
  21964. var result = lang.aria;
  21965. for (var i = 0; i < pathArr.length; ++i) {
  21966. result = result[pathArr[i]];
  21967. }
  21968. return result;
  21969. }
  21970. else {
  21971. return userConfig;
  21972. }
  21973. }
  21974. function getTitle() {
  21975. var title = ecModel.getModel('title').option;
  21976. if (title && title.length) {
  21977. title = title[0];
  21978. }
  21979. return title && title.text;
  21980. }
  21981. function getSeriesTypeName(type) {
  21982. return lang.series.typeNames[type] || '自定义图';
  21983. }
  21984. };
  21985. /*
  21986. * Licensed to the Apache Software Foundation (ASF) under one
  21987. * or more contributor license agreements. See the NOTICE file
  21988. * distributed with this work for additional information
  21989. * regarding copyright ownership. The ASF licenses this file
  21990. * to you under the Apache License, Version 2.0 (the
  21991. * "License"); you may not use this file except in compliance
  21992. * with the License. You may obtain a copy of the License at
  21993. *
  21994. * http://www.apache.org/licenses/LICENSE-2.0
  21995. *
  21996. * Unless required by applicable law or agreed to in writing,
  21997. * software distributed under the License is distributed on an
  21998. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21999. * KIND, either express or implied. See the License for the
  22000. * specific language governing permissions and limitations
  22001. * under the License.
  22002. */
  22003. var PI$1 = Math.PI;
  22004. /**
  22005. * @param {module:echarts/ExtensionAPI} api
  22006. * @param {Object} [opts]
  22007. * @param {string} [opts.text]
  22008. * @param {string} [opts.color]
  22009. * @param {string} [opts.textColor]
  22010. * @return {module:zrender/Element}
  22011. */
  22012. var loadingDefault = function (api, opts) {
  22013. opts = opts || {};
  22014. defaults(opts, {
  22015. text: 'loading',
  22016. color: '#c23531',
  22017. textColor: '#000',
  22018. maskColor: 'rgba(255, 255, 255, 0.8)',
  22019. zlevel: 0
  22020. });
  22021. var mask = new Rect({
  22022. style: {
  22023. fill: opts.maskColor
  22024. },
  22025. zlevel: opts.zlevel,
  22026. z: 10000
  22027. });
  22028. var arc = new Arc({
  22029. shape: {
  22030. startAngle: -PI$1 / 2,
  22031. endAngle: -PI$1 / 2 + 0.1,
  22032. r: 10
  22033. },
  22034. style: {
  22035. stroke: opts.color,
  22036. lineCap: 'round',
  22037. lineWidth: 5
  22038. },
  22039. zlevel: opts.zlevel,
  22040. z: 10001
  22041. });
  22042. var labelRect = new Rect({
  22043. style: {
  22044. fill: 'none',
  22045. text: opts.text,
  22046. textPosition: 'right',
  22047. textDistance: 10,
  22048. textFill: opts.textColor
  22049. },
  22050. zlevel: opts.zlevel,
  22051. z: 10001
  22052. });
  22053. arc.animateShape(true)
  22054. .when(1000, {
  22055. endAngle: PI$1 * 3 / 2
  22056. })
  22057. .start('circularInOut');
  22058. arc.animateShape(true)
  22059. .when(1000, {
  22060. startAngle: PI$1 * 3 / 2
  22061. })
  22062. .delay(300)
  22063. .start('circularInOut');
  22064. var group = new Group();
  22065. group.add(arc);
  22066. group.add(labelRect);
  22067. group.add(mask);
  22068. // Inject resize
  22069. group.resize = function () {
  22070. var cx = api.getWidth() / 2;
  22071. var cy = api.getHeight() / 2;
  22072. arc.setShape({
  22073. cx: cx,
  22074. cy: cy
  22075. });
  22076. var r = arc.shape.r;
  22077. labelRect.setShape({
  22078. x: cx - r,
  22079. y: cy - r,
  22080. width: r * 2,
  22081. height: r * 2
  22082. });
  22083. mask.setShape({
  22084. x: 0,
  22085. y: 0,
  22086. width: api.getWidth(),
  22087. height: api.getHeight()
  22088. });
  22089. };
  22090. group.resize();
  22091. return group;
  22092. };
  22093. /*
  22094. * Licensed to the Apache Software Foundation (ASF) under one
  22095. * or more contributor license agreements. See the NOTICE file
  22096. * distributed with this work for additional information
  22097. * regarding copyright ownership. The ASF licenses this file
  22098. * to you under the Apache License, Version 2.0 (the
  22099. * "License"); you may not use this file except in compliance
  22100. * with the License. You may obtain a copy of the License at
  22101. *
  22102. * http://www.apache.org/licenses/LICENSE-2.0
  22103. *
  22104. * Unless required by applicable law or agreed to in writing,
  22105. * software distributed under the License is distributed on an
  22106. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22107. * KIND, either express or implied. See the License for the
  22108. * specific language governing permissions and limitations
  22109. * under the License.
  22110. */
  22111. /**
  22112. * @module echarts/stream/Scheduler
  22113. */
  22114. /**
  22115. * @constructor
  22116. */
  22117. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  22118. this.ecInstance = ecInstance;
  22119. this.api = api;
  22120. this.unfinished;
  22121. // Fix current processors in case that in some rear cases that
  22122. // processors might be registered after echarts instance created.
  22123. // Register processors incrementally for a echarts instance is
  22124. // not supported by this stream architecture.
  22125. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  22126. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  22127. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  22128. /**
  22129. * @private
  22130. * @type {
  22131. * [handlerUID: string]: {
  22132. * seriesTaskMap?: {
  22133. * [seriesUID: string]: Task
  22134. * },
  22135. * overallTask?: Task
  22136. * }
  22137. * }
  22138. */
  22139. this._stageTaskMap = createHashMap();
  22140. }
  22141. var proto = Scheduler.prototype;
  22142. /**
  22143. * @param {module:echarts/model/Global} ecModel
  22144. * @param {Object} payload
  22145. */
  22146. proto.restoreData = function (ecModel, payload) {
  22147. // TODO: Only restroe needed series and components, but not all components.
  22148. // Currently `restoreData` of all of the series and component will be called.
  22149. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  22150. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  22151. // and some components like coordinate system, axes, dataZoom, visualMap only
  22152. // need their target series refresh.
  22153. // (1) If we are implementing this feature some day, we should consider these cases:
  22154. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  22155. // on the settings of `dataZoom`), it should be re-performed if the component
  22156. // is modified by `setOption`.
  22157. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  22158. // it should be re-performed when the result array of `getTargetSeries` changed.
  22159. // We use `dependencies` to cover these issues.
  22160. // (3) How to update target series when coordinate system related components modified.
  22161. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  22162. // and this case all of the tasks will be set as dirty.
  22163. ecModel.restoreData(payload);
  22164. // Theoretically an overall task not only depends on each of its target series, but also
  22165. // depends on all of the series.
  22166. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  22167. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  22168. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  22169. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  22170. // probably cause state chaos (consider `dataZoomProcessor`).
  22171. this._stageTaskMap.each(function (taskRecord) {
  22172. var overallTask = taskRecord.overallTask;
  22173. overallTask && overallTask.dirty();
  22174. });
  22175. };
  22176. // If seriesModel provided, incremental threshold is check by series data.
  22177. proto.getPerformArgs = function (task, isBlock) {
  22178. // For overall task
  22179. if (!task.__pipeline) {
  22180. return;
  22181. }
  22182. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  22183. var pCtx = pipeline.context;
  22184. var incremental = !isBlock
  22185. && pipeline.progressiveEnabled
  22186. && (!pCtx || pCtx.progressiveRender)
  22187. && task.__idxInPipeline > pipeline.blockIndex;
  22188. var step = incremental ? pipeline.step : null;
  22189. var modDataCount = pCtx && pCtx.modDataCount;
  22190. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  22191. return {step: step, modBy: modBy, modDataCount: modDataCount};
  22192. };
  22193. proto.getPipeline = function (pipelineId) {
  22194. return this._pipelineMap.get(pipelineId);
  22195. };
  22196. /**
  22197. * Current, progressive rendering starts from visual and layout.
  22198. * Always detect render mode in the same stage, avoiding that incorrect
  22199. * detection caused by data filtering.
  22200. * Caution:
  22201. * `updateStreamModes` use `seriesModel.getData()`.
  22202. */
  22203. proto.updateStreamModes = function (seriesModel, view) {
  22204. var pipeline = this._pipelineMap.get(seriesModel.uid);
  22205. var data = seriesModel.getData();
  22206. var dataLen = data.count();
  22207. // `progressiveRender` means that can render progressively in each
  22208. // animation frame. Note that some types of series do not provide
  22209. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  22210. // use the term `incremental` but not `progressive` to describe the
  22211. // case that `chart.appendData`.
  22212. var progressiveRender = pipeline.progressiveEnabled
  22213. && view.incrementalPrepareRender
  22214. && dataLen >= pipeline.threshold;
  22215. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  22216. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  22217. // see `test/candlestick-large3.html`
  22218. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  22219. seriesModel.pipelineContext = pipeline.context = {
  22220. progressiveRender: progressiveRender,
  22221. modDataCount: modDataCount,
  22222. large: large
  22223. };
  22224. };
  22225. proto.restorePipelines = function (ecModel) {
  22226. var scheduler = this;
  22227. var pipelineMap = scheduler._pipelineMap = createHashMap();
  22228. ecModel.eachSeries(function (seriesModel) {
  22229. var progressive = seriesModel.getProgressive();
  22230. var pipelineId = seriesModel.uid;
  22231. pipelineMap.set(pipelineId, {
  22232. id: pipelineId,
  22233. head: null,
  22234. tail: null,
  22235. threshold: seriesModel.getProgressiveThreshold(),
  22236. progressiveEnabled: progressive
  22237. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  22238. blockIndex: -1,
  22239. step: Math.round(progressive || 700),
  22240. count: 0
  22241. });
  22242. pipe(scheduler, seriesModel, seriesModel.dataTask);
  22243. });
  22244. };
  22245. proto.prepareStageTasks = function () {
  22246. var stageTaskMap = this._stageTaskMap;
  22247. var ecModel = this.ecInstance.getModel();
  22248. var api = this.api;
  22249. each$1(this._allHandlers, function (handler) {
  22250. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  22251. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  22252. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  22253. }, this);
  22254. };
  22255. proto.prepareView = function (view, model, ecModel, api) {
  22256. var renderTask = view.renderTask;
  22257. var context = renderTask.context;
  22258. context.model = model;
  22259. context.ecModel = ecModel;
  22260. context.api = api;
  22261. renderTask.__block = !view.incrementalPrepareRender;
  22262. pipe(this, model, renderTask);
  22263. };
  22264. proto.performDataProcessorTasks = function (ecModel, payload) {
  22265. // If we do not use `block` here, it should be considered when to update modes.
  22266. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  22267. };
  22268. // opt
  22269. // opt.visualType: 'visual' or 'layout'
  22270. // opt.setDirty
  22271. proto.performVisualTasks = function (ecModel, payload, opt) {
  22272. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  22273. };
  22274. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  22275. opt = opt || {};
  22276. var unfinished;
  22277. each$1(stageHandlers, function (stageHandler, idx) {
  22278. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  22279. return;
  22280. }
  22281. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  22282. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  22283. var overallTask = stageHandlerRecord.overallTask;
  22284. if (overallTask) {
  22285. var overallNeedDirty;
  22286. var agentStubMap = overallTask.agentStubMap;
  22287. agentStubMap.each(function (stub) {
  22288. if (needSetDirty(opt, stub)) {
  22289. stub.dirty();
  22290. overallNeedDirty = true;
  22291. }
  22292. });
  22293. overallNeedDirty && overallTask.dirty();
  22294. updatePayload(overallTask, payload);
  22295. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  22296. // Execute stubs firstly, which may set the overall task dirty,
  22297. // then execute the overall task. And stub will call seriesModel.setData,
  22298. // which ensures that in the overallTask seriesModel.getData() will not
  22299. // return incorrect data.
  22300. agentStubMap.each(function (stub) {
  22301. stub.perform(performArgs);
  22302. });
  22303. unfinished |= overallTask.perform(performArgs);
  22304. }
  22305. else if (seriesTaskMap) {
  22306. seriesTaskMap.each(function (task, pipelineId) {
  22307. if (needSetDirty(opt, task)) {
  22308. task.dirty();
  22309. }
  22310. var performArgs = scheduler.getPerformArgs(task, opt.block);
  22311. performArgs.skip = !stageHandler.performRawSeries
  22312. && ecModel.isSeriesFiltered(task.context.model);
  22313. updatePayload(task, payload);
  22314. unfinished |= task.perform(performArgs);
  22315. });
  22316. }
  22317. });
  22318. function needSetDirty(opt, task) {
  22319. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  22320. }
  22321. scheduler.unfinished |= unfinished;
  22322. }
  22323. proto.performSeriesTasks = function (ecModel) {
  22324. var unfinished;
  22325. ecModel.eachSeries(function (seriesModel) {
  22326. // Progress to the end for dataInit and dataRestore.
  22327. unfinished |= seriesModel.dataTask.perform();
  22328. });
  22329. this.unfinished |= unfinished;
  22330. };
  22331. proto.plan = function () {
  22332. // Travel pipelines, check block.
  22333. this._pipelineMap.each(function (pipeline) {
  22334. var task = pipeline.tail;
  22335. do {
  22336. if (task.__block) {
  22337. pipeline.blockIndex = task.__idxInPipeline;
  22338. break;
  22339. }
  22340. task = task.getUpstream();
  22341. }
  22342. while (task);
  22343. });
  22344. };
  22345. var updatePayload = proto.updatePayload = function (task, payload) {
  22346. payload !== 'remain' && (task.context.payload = payload);
  22347. };
  22348. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22349. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  22350. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  22351. var seriesType = stageHandler.seriesType;
  22352. var getTargetSeries = stageHandler.getTargetSeries;
  22353. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  22354. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  22355. // it works but it may cause other irrelevant charts blocked.
  22356. if (stageHandler.createOnAllSeries) {
  22357. ecModel.eachRawSeries(create);
  22358. }
  22359. else if (seriesType) {
  22360. ecModel.eachRawSeriesByType(seriesType, create);
  22361. }
  22362. else if (getTargetSeries) {
  22363. getTargetSeries(ecModel, api).each(create);
  22364. }
  22365. function create(seriesModel) {
  22366. var pipelineId = seriesModel.uid;
  22367. // Init tasks for each seriesModel only once.
  22368. // Reuse original task instance.
  22369. var task = seriesTaskMap.get(pipelineId)
  22370. || seriesTaskMap.set(pipelineId, createTask({
  22371. plan: seriesTaskPlan,
  22372. reset: seriesTaskReset,
  22373. count: seriesTaskCount
  22374. }));
  22375. task.context = {
  22376. model: seriesModel,
  22377. ecModel: ecModel,
  22378. api: api,
  22379. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  22380. plan: stageHandler.plan,
  22381. reset: stageHandler.reset,
  22382. scheduler: scheduler
  22383. };
  22384. pipe(scheduler, seriesModel, task);
  22385. }
  22386. // Clear unused series tasks.
  22387. var pipelineMap = scheduler._pipelineMap;
  22388. seriesTaskMap.each(function (task, pipelineId) {
  22389. if (!pipelineMap.get(pipelineId)) {
  22390. task.dispose();
  22391. seriesTaskMap.removeKey(pipelineId);
  22392. }
  22393. });
  22394. }
  22395. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  22396. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  22397. // For overall task, the function only be called on reset stage.
  22398. || createTask({reset: overallTaskReset});
  22399. overallTask.context = {
  22400. ecModel: ecModel,
  22401. api: api,
  22402. overallReset: stageHandler.overallReset,
  22403. scheduler: scheduler
  22404. };
  22405. // Reuse orignal stubs.
  22406. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  22407. var seriesType = stageHandler.seriesType;
  22408. var getTargetSeries = stageHandler.getTargetSeries;
  22409. var overallProgress = true;
  22410. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  22411. // An overall task with seriesType detected or has `getTargetSeries`, we add
  22412. // stub in each pipelines, it will set the overall task dirty when the pipeline
  22413. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  22414. // we set the pipeline block.
  22415. if (seriesType) {
  22416. ecModel.eachRawSeriesByType(seriesType, createStub);
  22417. }
  22418. else if (getTargetSeries) {
  22419. getTargetSeries(ecModel, api).each(createStub);
  22420. }
  22421. // Otherwise, (usually it is legancy case), the overall task will only be
  22422. // executed when upstream dirty. Otherwise the progressive rendering of all
  22423. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  22424. // dirty info from upsteam.
  22425. else {
  22426. overallProgress = false;
  22427. each$1(ecModel.getSeries(), createStub);
  22428. }
  22429. function createStub(seriesModel) {
  22430. var pipelineId = seriesModel.uid;
  22431. var stub = agentStubMap.get(pipelineId);
  22432. if (!stub) {
  22433. stub = agentStubMap.set(pipelineId, createTask(
  22434. {reset: stubReset, onDirty: stubOnDirty}
  22435. ));
  22436. // When the result of `getTargetSeries` changed, the overallTask
  22437. // should be set as dirty and re-performed.
  22438. overallTask.dirty();
  22439. }
  22440. stub.context = {
  22441. model: seriesModel,
  22442. overallProgress: overallProgress,
  22443. modifyOutputEnd: modifyOutputEnd
  22444. };
  22445. stub.agent = overallTask;
  22446. stub.__block = overallProgress;
  22447. pipe(scheduler, seriesModel, stub);
  22448. }
  22449. // Clear unused stubs.
  22450. var pipelineMap = scheduler._pipelineMap;
  22451. agentStubMap.each(function (stub, pipelineId) {
  22452. if (!pipelineMap.get(pipelineId)) {
  22453. stub.dispose();
  22454. // When the result of `getTargetSeries` changed, the overallTask
  22455. // should be set as dirty and re-performed.
  22456. overallTask.dirty();
  22457. agentStubMap.removeKey(pipelineId);
  22458. }
  22459. });
  22460. }
  22461. function overallTaskReset(context) {
  22462. context.overallReset(
  22463. context.ecModel, context.api, context.payload
  22464. );
  22465. }
  22466. function stubReset(context, upstreamContext) {
  22467. return context.overallProgress && stubProgress;
  22468. }
  22469. function stubProgress() {
  22470. this.agent.dirty();
  22471. this.getDownstream().dirty();
  22472. }
  22473. function stubOnDirty() {
  22474. this.agent && this.agent.dirty();
  22475. }
  22476. function seriesTaskPlan(context) {
  22477. return context.plan && context.plan(
  22478. context.model, context.ecModel, context.api, context.payload
  22479. );
  22480. }
  22481. function seriesTaskReset(context) {
  22482. if (context.useClearVisual) {
  22483. context.data.clearAllVisual();
  22484. }
  22485. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  22486. context.model, context.ecModel, context.api, context.payload
  22487. ));
  22488. return resetDefines.length > 1
  22489. ? map(resetDefines, function (v, idx) {
  22490. return makeSeriesTaskProgress(idx);
  22491. })
  22492. : singleSeriesTaskProgress;
  22493. }
  22494. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  22495. function makeSeriesTaskProgress(resetDefineIdx) {
  22496. return function (params, context) {
  22497. var data = context.data;
  22498. var resetDefine = context.resetDefines[resetDefineIdx];
  22499. if (resetDefine && resetDefine.dataEach) {
  22500. for (var i = params.start; i < params.end; i++) {
  22501. resetDefine.dataEach(data, i);
  22502. }
  22503. }
  22504. else if (resetDefine && resetDefine.progress) {
  22505. resetDefine.progress(params, data);
  22506. }
  22507. };
  22508. }
  22509. function seriesTaskCount(context) {
  22510. return context.data.count();
  22511. }
  22512. function pipe(scheduler, seriesModel, task) {
  22513. var pipelineId = seriesModel.uid;
  22514. var pipeline = scheduler._pipelineMap.get(pipelineId);
  22515. !pipeline.head && (pipeline.head = task);
  22516. pipeline.tail && pipeline.tail.pipe(task);
  22517. pipeline.tail = task;
  22518. task.__idxInPipeline = pipeline.count++;
  22519. task.__pipeline = pipeline;
  22520. }
  22521. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  22522. if (isFunction$1(stageHandler)) {
  22523. stageHandler = {
  22524. overallReset: stageHandler,
  22525. seriesType: detectSeriseType(stageHandler)
  22526. };
  22527. }
  22528. stageHandler.uid = getUID('stageHandler');
  22529. visualType && (stageHandler.visualType = visualType);
  22530. return stageHandler;
  22531. };
  22532. /**
  22533. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  22534. * To ensure that they can work normally, they should work in block mode, that is,
  22535. * they should not be started util the previous tasks finished. So they cause the
  22536. * progressive rendering disabled. We try to detect the series type, to narrow down
  22537. * the block range to only the series type they concern, but not all series.
  22538. */
  22539. function detectSeriseType(legacyFunc) {
  22540. seriesType = null;
  22541. try {
  22542. // Assume there is no async when calling `eachSeriesByType`.
  22543. legacyFunc(ecModelMock, apiMock);
  22544. }
  22545. catch (e) {
  22546. }
  22547. return seriesType;
  22548. }
  22549. var ecModelMock = {};
  22550. var apiMock = {};
  22551. var seriesType;
  22552. mockMethods(ecModelMock, GlobalModel);
  22553. mockMethods(apiMock, ExtensionAPI);
  22554. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  22555. seriesType = type;
  22556. };
  22557. ecModelMock.eachComponent = function (cond) {
  22558. if (cond.mainType === 'series' && cond.subType) {
  22559. seriesType = cond.subType;
  22560. }
  22561. };
  22562. function mockMethods(target, Clz) {
  22563. /* eslint-disable */
  22564. for (var name in Clz.prototype) {
  22565. // Do not use hasOwnProperty
  22566. target[name] = noop;
  22567. }
  22568. /* eslint-enable */
  22569. }
  22570. /*
  22571. * Licensed to the Apache Software Foundation (ASF) under one
  22572. * or more contributor license agreements. See the NOTICE file
  22573. * distributed with this work for additional information
  22574. * regarding copyright ownership. The ASF licenses this file
  22575. * to you under the Apache License, Version 2.0 (the
  22576. * "License"); you may not use this file except in compliance
  22577. * with the License. You may obtain a copy of the License at
  22578. *
  22579. * http://www.apache.org/licenses/LICENSE-2.0
  22580. *
  22581. * Unless required by applicable law or agreed to in writing,
  22582. * software distributed under the License is distributed on an
  22583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22584. * KIND, either express or implied. See the License for the
  22585. * specific language governing permissions and limitations
  22586. * under the License.
  22587. */
  22588. var colorAll = [
  22589. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  22590. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  22591. ];
  22592. var lightTheme = {
  22593. color: colorAll,
  22594. colorLayer: [
  22595. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  22596. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  22597. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  22598. colorAll
  22599. ]
  22600. };
  22601. /*
  22602. * Licensed to the Apache Software Foundation (ASF) under one
  22603. * or more contributor license agreements. See the NOTICE file
  22604. * distributed with this work for additional information
  22605. * regarding copyright ownership. The ASF licenses this file
  22606. * to you under the Apache License, Version 2.0 (the
  22607. * "License"); you may not use this file except in compliance
  22608. * with the License. You may obtain a copy of the License at
  22609. *
  22610. * http://www.apache.org/licenses/LICENSE-2.0
  22611. *
  22612. * Unless required by applicable law or agreed to in writing,
  22613. * software distributed under the License is distributed on an
  22614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22615. * KIND, either express or implied. See the License for the
  22616. * specific language governing permissions and limitations
  22617. * under the License.
  22618. */
  22619. var contrastColor = '#eee';
  22620. var axisCommon = function () {
  22621. return {
  22622. axisLine: {
  22623. lineStyle: {
  22624. color: contrastColor
  22625. }
  22626. },
  22627. axisTick: {
  22628. lineStyle: {
  22629. color: contrastColor
  22630. }
  22631. },
  22632. axisLabel: {
  22633. textStyle: {
  22634. color: contrastColor
  22635. }
  22636. },
  22637. splitLine: {
  22638. lineStyle: {
  22639. type: 'dashed',
  22640. color: '#aaa'
  22641. }
  22642. },
  22643. splitArea: {
  22644. areaStyle: {
  22645. color: contrastColor
  22646. }
  22647. }
  22648. };
  22649. };
  22650. var colorPalette = [
  22651. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  22652. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  22653. ];
  22654. var theme = {
  22655. color: colorPalette,
  22656. backgroundColor: '#333',
  22657. tooltip: {
  22658. axisPointer: {
  22659. lineStyle: {
  22660. color: contrastColor
  22661. },
  22662. crossStyle: {
  22663. color: contrastColor
  22664. },
  22665. label: {
  22666. color: '#000'
  22667. }
  22668. }
  22669. },
  22670. legend: {
  22671. textStyle: {
  22672. color: contrastColor
  22673. }
  22674. },
  22675. textStyle: {
  22676. color: contrastColor
  22677. },
  22678. title: {
  22679. textStyle: {
  22680. color: contrastColor
  22681. }
  22682. },
  22683. toolbox: {
  22684. iconStyle: {
  22685. normal: {
  22686. borderColor: contrastColor
  22687. }
  22688. }
  22689. },
  22690. dataZoom: {
  22691. textStyle: {
  22692. color: contrastColor
  22693. }
  22694. },
  22695. visualMap: {
  22696. textStyle: {
  22697. color: contrastColor
  22698. }
  22699. },
  22700. timeline: {
  22701. lineStyle: {
  22702. color: contrastColor
  22703. },
  22704. itemStyle: {
  22705. normal: {
  22706. color: colorPalette[1]
  22707. }
  22708. },
  22709. label: {
  22710. normal: {
  22711. textStyle: {
  22712. color: contrastColor
  22713. }
  22714. }
  22715. },
  22716. controlStyle: {
  22717. normal: {
  22718. color: contrastColor,
  22719. borderColor: contrastColor
  22720. }
  22721. }
  22722. },
  22723. timeAxis: axisCommon(),
  22724. logAxis: axisCommon(),
  22725. valueAxis: axisCommon(),
  22726. categoryAxis: axisCommon(),
  22727. line: {
  22728. symbol: 'circle'
  22729. },
  22730. graph: {
  22731. color: colorPalette
  22732. },
  22733. gauge: {
  22734. title: {
  22735. textStyle: {
  22736. color: contrastColor
  22737. }
  22738. }
  22739. },
  22740. candlestick: {
  22741. itemStyle: {
  22742. normal: {
  22743. color: '#FD1050',
  22744. color0: '#0CF49B',
  22745. borderColor: '#FD1050',
  22746. borderColor0: '#0CF49B'
  22747. }
  22748. }
  22749. }
  22750. };
  22751. theme.categoryAxis.splitLine.show = false;
  22752. /*
  22753. * Licensed to the Apache Software Foundation (ASF) under one
  22754. * or more contributor license agreements. See the NOTICE file
  22755. * distributed with this work for additional information
  22756. * regarding copyright ownership. The ASF licenses this file
  22757. * to you under the Apache License, Version 2.0 (the
  22758. * "License"); you may not use this file except in compliance
  22759. * with the License. You may obtain a copy of the License at
  22760. *
  22761. * http://www.apache.org/licenses/LICENSE-2.0
  22762. *
  22763. * Unless required by applicable law or agreed to in writing,
  22764. * software distributed under the License is distributed on an
  22765. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22766. * KIND, either express or implied. See the License for the
  22767. * specific language governing permissions and limitations
  22768. * under the License.
  22769. */
  22770. /**
  22771. * This module is imported by echarts directly.
  22772. *
  22773. * Notice:
  22774. * Always keep this file exists for backward compatibility.
  22775. * Because before 4.1.0, dataset is an optional component,
  22776. * some users may import this module manually.
  22777. */
  22778. ComponentModel.extend({
  22779. type: 'dataset',
  22780. /**
  22781. * @protected
  22782. */
  22783. defaultOption: {
  22784. // 'row', 'column'
  22785. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22786. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22787. sourceHeader: null,
  22788. dimensions: null,
  22789. source: null
  22790. },
  22791. optionUpdated: function () {
  22792. detectSourceFormat(this);
  22793. }
  22794. });
  22795. Component.extend({
  22796. type: 'dataset'
  22797. });
  22798. /**
  22799. * 椭圆形状
  22800. * @module zrender/graphic/shape/Ellipse
  22801. */
  22802. var Ellipse = Path.extend({
  22803. type: 'ellipse',
  22804. shape: {
  22805. cx: 0, cy: 0,
  22806. rx: 0, ry: 0
  22807. },
  22808. buildPath: function (ctx, shape) {
  22809. var k = 0.5522848;
  22810. var x = shape.cx;
  22811. var y = shape.cy;
  22812. var a = shape.rx;
  22813. var b = shape.ry;
  22814. var ox = a * k; // 水平控制点偏移量
  22815. var oy = b * k; // 垂直控制点偏移量
  22816. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22817. ctx.moveTo(x - a, y);
  22818. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22819. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22820. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22821. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22822. ctx.closePath();
  22823. }
  22824. });
  22825. // import RadialGradient from '../graphic/RadialGradient';
  22826. // import Pattern from '../graphic/Pattern';
  22827. // import * as vector from '../core/vector';
  22828. // Most of the values can be separated by comma and/or white space.
  22829. var DILIMITER_REG = /[\s,]+/;
  22830. /**
  22831. * For big svg string, this method might be time consuming.
  22832. *
  22833. * @param {string} svg xml string
  22834. * @return {Object} xml root.
  22835. */
  22836. function parseXML(svg) {
  22837. if (isString(svg)) {
  22838. var parser = new DOMParser();
  22839. svg = parser.parseFromString(svg, 'text/xml');
  22840. }
  22841. // Document node. If using $.get, doc node may be input.
  22842. if (svg.nodeType === 9) {
  22843. svg = svg.firstChild;
  22844. }
  22845. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22846. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22847. svg = svg.nextSibling;
  22848. }
  22849. return svg;
  22850. }
  22851. function SVGParser() {
  22852. this._defs = {};
  22853. this._root = null;
  22854. this._isDefine = false;
  22855. this._isText = false;
  22856. }
  22857. SVGParser.prototype.parse = function (xml, opt) {
  22858. opt = opt || {};
  22859. var svg = parseXML(xml);
  22860. if (!svg) {
  22861. throw new Error('Illegal svg');
  22862. }
  22863. var root = new Group();
  22864. this._root = root;
  22865. // parse view port
  22866. var viewBox = svg.getAttribute('viewBox') || '';
  22867. // If width/height not specified, means "100%" of `opt.width/height`.
  22868. // TODO: Other percent value not supported yet.
  22869. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22870. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22871. // If width/height not specified, set as null for output.
  22872. isNaN(width) && (width = null);
  22873. isNaN(height) && (height = null);
  22874. // Apply inline style on svg element.
  22875. parseAttributes(svg, root, null, true);
  22876. var child = svg.firstChild;
  22877. while (child) {
  22878. this._parseNode(child, root);
  22879. child = child.nextSibling;
  22880. }
  22881. var viewBoxRect;
  22882. var viewBoxTransform;
  22883. if (viewBox) {
  22884. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22885. // Some invalid case like viewBox: 'none'.
  22886. if (viewBoxArr.length >= 4) {
  22887. viewBoxRect = {
  22888. x: parseFloat(viewBoxArr[0] || 0),
  22889. y: parseFloat(viewBoxArr[1] || 0),
  22890. width: parseFloat(viewBoxArr[2]),
  22891. height: parseFloat(viewBoxArr[3])
  22892. };
  22893. }
  22894. }
  22895. if (viewBoxRect && width != null && height != null) {
  22896. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22897. if (!opt.ignoreViewBox) {
  22898. // If set transform on the output group, it probably bring trouble when
  22899. // some users only intend to show the clipped content inside the viewBox,
  22900. // but not intend to transform the output group. So we keep the output
  22901. // group no transform. If the user intend to use the viewBox as a
  22902. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22903. // manually according to the viewBox info in the output of this method.
  22904. var elRoot = root;
  22905. root = new Group();
  22906. root.add(elRoot);
  22907. elRoot.scale = viewBoxTransform.scale.slice();
  22908. elRoot.position = viewBoxTransform.position.slice();
  22909. }
  22910. }
  22911. // Some shapes might be overflow the viewport, which should be
  22912. // clipped despite whether the viewBox is used, as the SVG does.
  22913. if (!opt.ignoreRootClip && width != null && height != null) {
  22914. root.setClipPath(new Rect({
  22915. shape: {x: 0, y: 0, width: width, height: height}
  22916. }));
  22917. }
  22918. // Set width/height on group just for output the viewport size.
  22919. return {
  22920. root: root,
  22921. width: width,
  22922. height: height,
  22923. viewBoxRect: viewBoxRect,
  22924. viewBoxTransform: viewBoxTransform
  22925. };
  22926. };
  22927. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22928. var nodeName = xmlNode.nodeName.toLowerCase();
  22929. // TODO
  22930. // support <style>...</style> in svg, where nodeName is 'style',
  22931. // CSS classes is defined globally wherever the style tags are declared.
  22932. if (nodeName === 'defs') {
  22933. // define flag
  22934. this._isDefine = true;
  22935. }
  22936. else if (nodeName === 'text') {
  22937. this._isText = true;
  22938. }
  22939. var el;
  22940. if (this._isDefine) {
  22941. var parser = defineParsers[nodeName];
  22942. if (parser) {
  22943. var def = parser.call(this, xmlNode);
  22944. var id = xmlNode.getAttribute('id');
  22945. if (id) {
  22946. this._defs[id] = def;
  22947. }
  22948. }
  22949. }
  22950. else {
  22951. var parser = nodeParsers[nodeName];
  22952. if (parser) {
  22953. el = parser.call(this, xmlNode, parentGroup);
  22954. parentGroup.add(el);
  22955. }
  22956. }
  22957. var child = xmlNode.firstChild;
  22958. while (child) {
  22959. if (child.nodeType === 1) {
  22960. this._parseNode(child, el);
  22961. }
  22962. // Is text
  22963. if (child.nodeType === 3 && this._isText) {
  22964. this._parseText(child, el);
  22965. }
  22966. child = child.nextSibling;
  22967. }
  22968. // Quit define
  22969. if (nodeName === 'defs') {
  22970. this._isDefine = false;
  22971. }
  22972. else if (nodeName === 'text') {
  22973. this._isText = false;
  22974. }
  22975. };
  22976. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22977. if (xmlNode.nodeType === 1) {
  22978. var dx = xmlNode.getAttribute('dx') || 0;
  22979. var dy = xmlNode.getAttribute('dy') || 0;
  22980. this._textX += parseFloat(dx);
  22981. this._textY += parseFloat(dy);
  22982. }
  22983. var text = new Text({
  22984. style: {
  22985. text: xmlNode.textContent,
  22986. transformText: true
  22987. },
  22988. position: [this._textX || 0, this._textY || 0]
  22989. });
  22990. inheritStyle(parentGroup, text);
  22991. parseAttributes(xmlNode, text, this._defs);
  22992. var fontSize = text.style.fontSize;
  22993. if (fontSize && fontSize < 9) {
  22994. // PENDING
  22995. text.style.fontSize = 9;
  22996. text.scale = text.scale || [1, 1];
  22997. text.scale[0] *= fontSize / 9;
  22998. text.scale[1] *= fontSize / 9;
  22999. }
  23000. var rect = text.getBoundingRect();
  23001. this._textX += rect.width;
  23002. parentGroup.add(text);
  23003. return text;
  23004. };
  23005. var nodeParsers = {
  23006. 'g': function (xmlNode, parentGroup) {
  23007. var g = new Group();
  23008. inheritStyle(parentGroup, g);
  23009. parseAttributes(xmlNode, g, this._defs);
  23010. return g;
  23011. },
  23012. 'rect': function (xmlNode, parentGroup) {
  23013. var rect = new Rect();
  23014. inheritStyle(parentGroup, rect);
  23015. parseAttributes(xmlNode, rect, this._defs);
  23016. rect.setShape({
  23017. x: parseFloat(xmlNode.getAttribute('x') || 0),
  23018. y: parseFloat(xmlNode.getAttribute('y') || 0),
  23019. width: parseFloat(xmlNode.getAttribute('width') || 0),
  23020. height: parseFloat(xmlNode.getAttribute('height') || 0)
  23021. });
  23022. // console.log(xmlNode.getAttribute('transform'));
  23023. // console.log(rect.transform);
  23024. return rect;
  23025. },
  23026. 'circle': function (xmlNode, parentGroup) {
  23027. var circle = new Circle();
  23028. inheritStyle(parentGroup, circle);
  23029. parseAttributes(xmlNode, circle, this._defs);
  23030. circle.setShape({
  23031. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23032. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23033. r: parseFloat(xmlNode.getAttribute('r') || 0)
  23034. });
  23035. return circle;
  23036. },
  23037. 'line': function (xmlNode, parentGroup) {
  23038. var line = new Line();
  23039. inheritStyle(parentGroup, line);
  23040. parseAttributes(xmlNode, line, this._defs);
  23041. line.setShape({
  23042. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  23043. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  23044. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  23045. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  23046. });
  23047. return line;
  23048. },
  23049. 'ellipse': function (xmlNode, parentGroup) {
  23050. var ellipse = new Ellipse();
  23051. inheritStyle(parentGroup, ellipse);
  23052. parseAttributes(xmlNode, ellipse, this._defs);
  23053. ellipse.setShape({
  23054. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  23055. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  23056. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  23057. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  23058. });
  23059. return ellipse;
  23060. },
  23061. 'polygon': function (xmlNode, parentGroup) {
  23062. var points = xmlNode.getAttribute('points');
  23063. if (points) {
  23064. points = parsePoints(points);
  23065. }
  23066. var polygon = new Polygon({
  23067. shape: {
  23068. points: points || []
  23069. }
  23070. });
  23071. inheritStyle(parentGroup, polygon);
  23072. parseAttributes(xmlNode, polygon, this._defs);
  23073. return polygon;
  23074. },
  23075. 'polyline': function (xmlNode, parentGroup) {
  23076. var path = new Path();
  23077. inheritStyle(parentGroup, path);
  23078. parseAttributes(xmlNode, path, this._defs);
  23079. var points = xmlNode.getAttribute('points');
  23080. if (points) {
  23081. points = parsePoints(points);
  23082. }
  23083. var polyline = new Polyline({
  23084. shape: {
  23085. points: points || []
  23086. }
  23087. });
  23088. return polyline;
  23089. },
  23090. 'image': function (xmlNode, parentGroup) {
  23091. var img = new ZImage();
  23092. inheritStyle(parentGroup, img);
  23093. parseAttributes(xmlNode, img, this._defs);
  23094. img.setStyle({
  23095. image: xmlNode.getAttribute('xlink:href'),
  23096. x: xmlNode.getAttribute('x'),
  23097. y: xmlNode.getAttribute('y'),
  23098. width: xmlNode.getAttribute('width'),
  23099. height: xmlNode.getAttribute('height')
  23100. });
  23101. return img;
  23102. },
  23103. 'text': function (xmlNode, parentGroup) {
  23104. var x = xmlNode.getAttribute('x') || 0;
  23105. var y = xmlNode.getAttribute('y') || 0;
  23106. var dx = xmlNode.getAttribute('dx') || 0;
  23107. var dy = xmlNode.getAttribute('dy') || 0;
  23108. this._textX = parseFloat(x) + parseFloat(dx);
  23109. this._textY = parseFloat(y) + parseFloat(dy);
  23110. var g = new Group();
  23111. inheritStyle(parentGroup, g);
  23112. parseAttributes(xmlNode, g, this._defs);
  23113. return g;
  23114. },
  23115. 'tspan': function (xmlNode, parentGroup) {
  23116. var x = xmlNode.getAttribute('x');
  23117. var y = xmlNode.getAttribute('y');
  23118. if (x != null) {
  23119. // new offset x
  23120. this._textX = parseFloat(x);
  23121. }
  23122. if (y != null) {
  23123. // new offset y
  23124. this._textY = parseFloat(y);
  23125. }
  23126. var dx = xmlNode.getAttribute('dx') || 0;
  23127. var dy = xmlNode.getAttribute('dy') || 0;
  23128. var g = new Group();
  23129. inheritStyle(parentGroup, g);
  23130. parseAttributes(xmlNode, g, this._defs);
  23131. this._textX += dx;
  23132. this._textY += dy;
  23133. return g;
  23134. },
  23135. 'path': function (xmlNode, parentGroup) {
  23136. // TODO svg fill rule
  23137. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  23138. // path.style.globalCompositeOperation = 'xor';
  23139. var d = xmlNode.getAttribute('d') || '';
  23140. // Performance sensitive.
  23141. var path = createFromString(d);
  23142. inheritStyle(parentGroup, path);
  23143. parseAttributes(xmlNode, path, this._defs);
  23144. return path;
  23145. }
  23146. };
  23147. var defineParsers = {
  23148. 'lineargradient': function (xmlNode) {
  23149. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  23150. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  23151. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  23152. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  23153. var gradient = new LinearGradient(x1, y1, x2, y2);
  23154. _parseGradientColorStops(xmlNode, gradient);
  23155. return gradient;
  23156. },
  23157. 'radialgradient': function (xmlNode) {
  23158. }
  23159. };
  23160. function _parseGradientColorStops(xmlNode, gradient) {
  23161. var stop = xmlNode.firstChild;
  23162. while (stop) {
  23163. if (stop.nodeType === 1) {
  23164. var offset = stop.getAttribute('offset');
  23165. if (offset.indexOf('%') > 0) { // percentage
  23166. offset = parseInt(offset, 10) / 100;
  23167. }
  23168. else if (offset) { // number from 0 to 1
  23169. offset = parseFloat(offset);
  23170. }
  23171. else {
  23172. offset = 0;
  23173. }
  23174. var stopColor = stop.getAttribute('stop-color') || '#000000';
  23175. gradient.addColorStop(offset, stopColor);
  23176. }
  23177. stop = stop.nextSibling;
  23178. }
  23179. }
  23180. function inheritStyle(parent, child) {
  23181. if (parent && parent.__inheritedStyle) {
  23182. if (!child.__inheritedStyle) {
  23183. child.__inheritedStyle = {};
  23184. }
  23185. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  23186. }
  23187. }
  23188. function parsePoints(pointsString) {
  23189. var list = trim(pointsString).split(DILIMITER_REG);
  23190. var points = [];
  23191. for (var i = 0; i < list.length; i += 2) {
  23192. var x = parseFloat(list[i]);
  23193. var y = parseFloat(list[i + 1]);
  23194. points.push([x, y]);
  23195. }
  23196. return points;
  23197. }
  23198. var attributesMap = {
  23199. 'fill': 'fill',
  23200. 'stroke': 'stroke',
  23201. 'stroke-width': 'lineWidth',
  23202. 'opacity': 'opacity',
  23203. 'fill-opacity': 'fillOpacity',
  23204. 'stroke-opacity': 'strokeOpacity',
  23205. 'stroke-dasharray': 'lineDash',
  23206. 'stroke-dashoffset': 'lineDashOffset',
  23207. 'stroke-linecap': 'lineCap',
  23208. 'stroke-linejoin': 'lineJoin',
  23209. 'stroke-miterlimit': 'miterLimit',
  23210. 'font-family': 'fontFamily',
  23211. 'font-size': 'fontSize',
  23212. 'font-style': 'fontStyle',
  23213. 'font-weight': 'fontWeight',
  23214. 'text-align': 'textAlign',
  23215. 'alignment-baseline': 'textBaseline'
  23216. };
  23217. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  23218. var zrStyle = el.__inheritedStyle || {};
  23219. var isTextEl = el.type === 'text';
  23220. // TODO Shadow
  23221. if (xmlNode.nodeType === 1) {
  23222. parseTransformAttribute(xmlNode, el);
  23223. extend(zrStyle, parseStyleAttribute(xmlNode));
  23224. if (!onlyInlineStyle) {
  23225. for (var svgAttrName in attributesMap) {
  23226. if (attributesMap.hasOwnProperty(svgAttrName)) {
  23227. var attrValue = xmlNode.getAttribute(svgAttrName);
  23228. if (attrValue != null) {
  23229. zrStyle[attributesMap[svgAttrName]] = attrValue;
  23230. }
  23231. }
  23232. }
  23233. }
  23234. }
  23235. var elFillProp = isTextEl ? 'textFill' : 'fill';
  23236. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  23237. el.style = el.style || new Style();
  23238. var elStyle = el.style;
  23239. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  23240. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  23241. each$1([
  23242. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  23243. ], function (propName) {
  23244. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  23245. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  23246. });
  23247. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  23248. zrStyle.textBaseline = 'alphabetic';
  23249. }
  23250. if (zrStyle.textBaseline === 'alphabetic') {
  23251. zrStyle.textBaseline = 'bottom';
  23252. }
  23253. if (zrStyle.textAlign === 'start') {
  23254. zrStyle.textAlign = 'left';
  23255. }
  23256. if (zrStyle.textAlign === 'end') {
  23257. zrStyle.textAlign = 'right';
  23258. }
  23259. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  23260. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  23261. ], function (propName) {
  23262. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  23263. });
  23264. if (zrStyle.lineDash) {
  23265. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  23266. }
  23267. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  23268. // enable stroke
  23269. el[elStrokeProp] = true;
  23270. }
  23271. el.__inheritedStyle = zrStyle;
  23272. }
  23273. var urlRegex = /url\(\s*#(.*?)\)/;
  23274. function getPaint(str, defs) {
  23275. // if (str === 'none') {
  23276. // return;
  23277. // }
  23278. var urlMatch = defs && str && str.match(urlRegex);
  23279. if (urlMatch) {
  23280. var url = trim(urlMatch[1]);
  23281. var def = defs[url];
  23282. return def;
  23283. }
  23284. return str;
  23285. }
  23286. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  23287. function parseTransformAttribute(xmlNode, node) {
  23288. var transform = xmlNode.getAttribute('transform');
  23289. if (transform) {
  23290. transform = transform.replace(/,/g, ' ');
  23291. var m = null;
  23292. var transformOps = [];
  23293. transform.replace(transformRegex, function (str, type, value) {
  23294. transformOps.push(type, value);
  23295. });
  23296. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  23297. var value = transformOps[i];
  23298. var type = transformOps[i - 1];
  23299. m = m || create$1();
  23300. switch (type) {
  23301. case 'translate':
  23302. value = trim(value).split(DILIMITER_REG);
  23303. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  23304. break;
  23305. case 'scale':
  23306. value = trim(value).split(DILIMITER_REG);
  23307. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  23308. break;
  23309. case 'rotate':
  23310. value = trim(value).split(DILIMITER_REG);
  23311. rotate(m, m, parseFloat(value[0]));
  23312. break;
  23313. case 'skew':
  23314. value = trim(value).split(DILIMITER_REG);
  23315. console.warn('Skew transform is not supported yet');
  23316. break;
  23317. case 'matrix':
  23318. var value = trim(value).split(DILIMITER_REG);
  23319. m[0] = parseFloat(value[0]);
  23320. m[1] = parseFloat(value[1]);
  23321. m[2] = parseFloat(value[2]);
  23322. m[3] = parseFloat(value[3]);
  23323. m[4] = parseFloat(value[4]);
  23324. m[5] = parseFloat(value[5]);
  23325. break;
  23326. }
  23327. }
  23328. node.setLocalTransform(m);
  23329. }
  23330. }
  23331. // Value may contain space.
  23332. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  23333. function parseStyleAttribute(xmlNode) {
  23334. var style = xmlNode.getAttribute('style');
  23335. var result = {};
  23336. if (!style) {
  23337. return result;
  23338. }
  23339. var styleList = {};
  23340. styleRegex.lastIndex = 0;
  23341. var styleRegResult;
  23342. while ((styleRegResult = styleRegex.exec(style)) != null) {
  23343. styleList[styleRegResult[1]] = styleRegResult[2];
  23344. }
  23345. for (var svgAttrName in attributesMap) {
  23346. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  23347. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  23348. }
  23349. }
  23350. return result;
  23351. }
  23352. /**
  23353. * @param {Array.<number>} viewBoxRect
  23354. * @param {number} width
  23355. * @param {number} height
  23356. * @return {Object} {scale, position}
  23357. */
  23358. function makeViewBoxTransform(viewBoxRect, width, height) {
  23359. var scaleX = width / viewBoxRect.width;
  23360. var scaleY = height / viewBoxRect.height;
  23361. var scale = Math.min(scaleX, scaleY);
  23362. // preserveAspectRatio 'xMidYMid'
  23363. var viewBoxScale = [scale, scale];
  23364. var viewBoxPosition = [
  23365. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  23366. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  23367. ];
  23368. return {
  23369. scale: viewBoxScale,
  23370. position: viewBoxPosition
  23371. };
  23372. }
  23373. /**
  23374. * @param {string|XMLElement} xml
  23375. * @param {Object} [opt]
  23376. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  23377. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  23378. * @param {boolean} [opt.ignoreViewBox]
  23379. * @param {boolean} [opt.ignoreRootClip]
  23380. * @return {Object} result:
  23381. * {
  23382. * root: Group, The root of the the result tree of zrender shapes,
  23383. * width: number, the viewport width of the SVG,
  23384. * height: number, the viewport height of the SVG,
  23385. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  23386. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  23387. * }
  23388. */
  23389. /*
  23390. * Licensed to the Apache Software Foundation (ASF) under one
  23391. * or more contributor license agreements. See the NOTICE file
  23392. * distributed with this work for additional information
  23393. * regarding copyright ownership. The ASF licenses this file
  23394. * to you under the Apache License, Version 2.0 (the
  23395. * "License"); you may not use this file except in compliance
  23396. * with the License. You may obtain a copy of the License at
  23397. *
  23398. * http://www.apache.org/licenses/LICENSE-2.0
  23399. *
  23400. * Unless required by applicable law or agreed to in writing,
  23401. * software distributed under the License is distributed on an
  23402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23403. * KIND, either express or implied. See the License for the
  23404. * specific language governing permissions and limitations
  23405. * under the License.
  23406. */
  23407. var storage = createHashMap();
  23408. // For minimize the code size of common echarts package,
  23409. // do not put too much logic in this module.
  23410. var mapDataStorage = {
  23411. // The format of record: see `echarts.registerMap`.
  23412. // Compatible with previous `echarts.registerMap`.
  23413. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  23414. var records;
  23415. if (isArray(rawGeoJson)) {
  23416. records = rawGeoJson;
  23417. }
  23418. else if (rawGeoJson.svg) {
  23419. records = [{
  23420. type: 'svg',
  23421. source: rawGeoJson.svg,
  23422. specialAreas: rawGeoJson.specialAreas
  23423. }];
  23424. }
  23425. else {
  23426. // Backward compatibility.
  23427. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  23428. rawSpecialAreas = rawGeoJson.specialAreas;
  23429. rawGeoJson = rawGeoJson.geoJson;
  23430. }
  23431. records = [{
  23432. type: 'geoJSON',
  23433. source: rawGeoJson,
  23434. specialAreas: rawSpecialAreas
  23435. }];
  23436. }
  23437. each$1(records, function (record) {
  23438. var type = record.type;
  23439. type === 'geoJson' && (type = record.type = 'geoJSON');
  23440. var parse = parsers[type];
  23441. if (__DEV__) {
  23442. assert$1(parse, 'Illegal map type: ' + type);
  23443. }
  23444. parse(record);
  23445. });
  23446. return storage.set(mapName, records);
  23447. },
  23448. retrieveMap: function (mapName) {
  23449. return storage.get(mapName);
  23450. }
  23451. };
  23452. var parsers = {
  23453. geoJSON: function (record) {
  23454. var source = record.source;
  23455. record.geoJSON = !isString(source)
  23456. ? source
  23457. : (typeof JSON !== 'undefined' && JSON.parse)
  23458. ? JSON.parse(source)
  23459. : (new Function('return (' + source + ');'))();
  23460. },
  23461. // Only perform parse to XML object here, which might be time
  23462. // consiming for large SVG.
  23463. // Although convert XML to zrender element is also time consiming,
  23464. // if we do it here, the clone of zrender elements has to be
  23465. // required. So we do it once for each geo instance, util real
  23466. // performance issues call for optimizing it.
  23467. svg: function (record) {
  23468. record.svgXML = parseXML(record.source);
  23469. }
  23470. };
  23471. /*
  23472. * Licensed to the Apache Software Foundation (ASF) under one
  23473. * or more contributor license agreements. See the NOTICE file
  23474. * distributed with this work for additional information
  23475. * regarding copyright ownership. The ASF licenses this file
  23476. * to you under the Apache License, Version 2.0 (the
  23477. * "License"); you may not use this file except in compliance
  23478. * with the License. You may obtain a copy of the License at
  23479. *
  23480. * http://www.apache.org/licenses/LICENSE-2.0
  23481. *
  23482. * Unless required by applicable law or agreed to in writing,
  23483. * software distributed under the License is distributed on an
  23484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23485. * KIND, either express or implied. See the License for the
  23486. * specific language governing permissions and limitations
  23487. * under the License.
  23488. */
  23489. var assert = assert$1;
  23490. var each = each$1;
  23491. var isFunction = isFunction$1;
  23492. var isObject = isObject$1;
  23493. var parseClassType = ComponentModel.parseClassType;
  23494. var version = '4.6.0';
  23495. var dependencies = {
  23496. zrender: '4.2.0'
  23497. };
  23498. var TEST_FRAME_REMAIN_TIME = 1;
  23499. var PRIORITY_PROCESSOR_FILTER = 1000;
  23500. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  23501. var PRIORITY_PROCESSOR_DATASTACK = 900;
  23502. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  23503. var PRIORITY_VISUAL_LAYOUT = 1000;
  23504. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  23505. var PRIORITY_VISUAL_GLOBAL = 2000;
  23506. var PRIORITY_VISUAL_CHART = 3000;
  23507. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  23508. var PRIORITY_VISUAL_COMPONENT = 4000;
  23509. // FIXME
  23510. // necessary?
  23511. var PRIORITY_VISUAL_BRUSH = 5000;
  23512. var PRIORITY = {
  23513. PROCESSOR: {
  23514. FILTER: PRIORITY_PROCESSOR_FILTER,
  23515. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  23516. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  23517. },
  23518. VISUAL: {
  23519. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  23520. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  23521. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  23522. CHART: PRIORITY_VISUAL_CHART,
  23523. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  23524. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  23525. BRUSH: PRIORITY_VISUAL_BRUSH
  23526. }
  23527. };
  23528. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  23529. // where they must not be invoked nestedly, except the only case: invoke
  23530. // dispatchAction with updateMethod "none" in main process.
  23531. // This flag is used to carry out this rule.
  23532. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  23533. var IN_MAIN_PROCESS = '__flagInMainProcess';
  23534. var OPTION_UPDATED = '__optionUpdated';
  23535. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  23536. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  23537. return function (eventName, handler, context) {
  23538. if (!ignoreDisposed && this._disposed) {
  23539. disposedWarning(this.id);
  23540. return;
  23541. }
  23542. // Event name is all lowercase
  23543. eventName = eventName && eventName.toLowerCase();
  23544. Eventful.prototype[method].call(this, eventName, handler, context);
  23545. };
  23546. }
  23547. /**
  23548. * @module echarts~MessageCenter
  23549. */
  23550. function MessageCenter() {
  23551. Eventful.call(this);
  23552. }
  23553. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  23554. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  23555. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  23556. mixin(MessageCenter, Eventful);
  23557. /**
  23558. * @module echarts~ECharts
  23559. */
  23560. function ECharts(dom, theme$$1, opts) {
  23561. opts = opts || {};
  23562. // Get theme by name
  23563. if (typeof theme$$1 === 'string') {
  23564. theme$$1 = themeStorage[theme$$1];
  23565. }
  23566. /**
  23567. * @type {string}
  23568. */
  23569. this.id;
  23570. /**
  23571. * Group id
  23572. * @type {string}
  23573. */
  23574. this.group;
  23575. /**
  23576. * @type {HTMLElement}
  23577. * @private
  23578. */
  23579. this._dom = dom;
  23580. var defaultRenderer = 'canvas';
  23581. if (__DEV__) {
  23582. defaultRenderer = (
  23583. typeof window === 'undefined' ? global : window
  23584. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  23585. }
  23586. /**
  23587. * @type {module:zrender/ZRender}
  23588. * @private
  23589. */
  23590. var zr = this._zr = init$1(dom, {
  23591. renderer: opts.renderer || defaultRenderer,
  23592. devicePixelRatio: opts.devicePixelRatio,
  23593. width: opts.width,
  23594. height: opts.height
  23595. });
  23596. /**
  23597. * Expect 60 fps.
  23598. * @type {Function}
  23599. * @private
  23600. */
  23601. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  23602. var theme$$1 = clone(theme$$1);
  23603. theme$$1 && backwardCompat(theme$$1, true);
  23604. /**
  23605. * @type {Object}
  23606. * @private
  23607. */
  23608. this._theme = theme$$1;
  23609. /**
  23610. * @type {Array.<module:echarts/view/Chart>}
  23611. * @private
  23612. */
  23613. this._chartsViews = [];
  23614. /**
  23615. * @type {Object.<string, module:echarts/view/Chart>}
  23616. * @private
  23617. */
  23618. this._chartsMap = {};
  23619. /**
  23620. * @type {Array.<module:echarts/view/Component>}
  23621. * @private
  23622. */
  23623. this._componentsViews = [];
  23624. /**
  23625. * @type {Object.<string, module:echarts/view/Component>}
  23626. * @private
  23627. */
  23628. this._componentsMap = {};
  23629. /**
  23630. * @type {module:echarts/CoordinateSystem}
  23631. * @private
  23632. */
  23633. this._coordSysMgr = new CoordinateSystemManager();
  23634. /**
  23635. * @type {module:echarts/ExtensionAPI}
  23636. * @private
  23637. */
  23638. var api = this._api = createExtensionAPI(this);
  23639. // Sort on demand
  23640. function prioritySortFunc(a, b) {
  23641. return a.__prio - b.__prio;
  23642. }
  23643. sort(visualFuncs, prioritySortFunc);
  23644. sort(dataProcessorFuncs, prioritySortFunc);
  23645. /**
  23646. * @type {module:echarts/stream/Scheduler}
  23647. */
  23648. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  23649. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  23650. /**
  23651. * @type {module:echarts~MessageCenter}
  23652. * @private
  23653. */
  23654. this._messageCenter = new MessageCenter();
  23655. // Init mouse events
  23656. this._initEvents();
  23657. // In case some people write `window.onresize = chart.resize`
  23658. this.resize = bind(this.resize, this);
  23659. // Can't dispatch action during rendering procedure
  23660. this._pendingActions = [];
  23661. zr.animation.on('frame', this._onframe, this);
  23662. bindRenderedEvent(zr, this);
  23663. // ECharts instance can be used as value.
  23664. setAsPrimitive(this);
  23665. }
  23666. var echartsProto = ECharts.prototype;
  23667. echartsProto._onframe = function () {
  23668. if (this._disposed) {
  23669. return;
  23670. }
  23671. var scheduler = this._scheduler;
  23672. // Lazy update
  23673. if (this[OPTION_UPDATED]) {
  23674. var silent = this[OPTION_UPDATED].silent;
  23675. this[IN_MAIN_PROCESS] = true;
  23676. prepare(this);
  23677. updateMethods.update.call(this);
  23678. this[IN_MAIN_PROCESS] = false;
  23679. this[OPTION_UPDATED] = false;
  23680. flushPendingActions.call(this, silent);
  23681. triggerUpdatedEvent.call(this, silent);
  23682. }
  23683. // Avoid do both lazy update and progress in one frame.
  23684. else if (scheduler.unfinished) {
  23685. // Stream progress.
  23686. var remainTime = TEST_FRAME_REMAIN_TIME;
  23687. var ecModel = this._model;
  23688. var api = this._api;
  23689. scheduler.unfinished = false;
  23690. do {
  23691. var startTime = +new Date();
  23692. scheduler.performSeriesTasks(ecModel);
  23693. // Currently dataProcessorFuncs do not check threshold.
  23694. scheduler.performDataProcessorTasks(ecModel);
  23695. updateStreamModes(this, ecModel);
  23696. // Do not update coordinate system here. Because that coord system update in
  23697. // each frame is not a good user experience. So we follow the rule that
  23698. // the extent of the coordinate system is determin in the first frame (the
  23699. // frame is executed immedietely after task reset.
  23700. // this._coordSysMgr.update(ecModel, api);
  23701. // console.log('--- ec frame visual ---', remainTime);
  23702. scheduler.performVisualTasks(ecModel);
  23703. renderSeries(this, this._model, api, 'remain');
  23704. remainTime -= (+new Date() - startTime);
  23705. }
  23706. while (remainTime > 0 && scheduler.unfinished);
  23707. // Call flush explicitly for trigger finished event.
  23708. if (!scheduler.unfinished) {
  23709. this._zr.flush();
  23710. }
  23711. // Else, zr flushing be ensue within the same frame,
  23712. // because zr flushing is after onframe event.
  23713. }
  23714. };
  23715. /**
  23716. * @return {HTMLElement}
  23717. */
  23718. echartsProto.getDom = function () {
  23719. return this._dom;
  23720. };
  23721. /**
  23722. * @return {module:zrender~ZRender}
  23723. */
  23724. echartsProto.getZr = function () {
  23725. return this._zr;
  23726. };
  23727. /**
  23728. * Usage:
  23729. * chart.setOption(option, notMerge, lazyUpdate);
  23730. * chart.setOption(option, {
  23731. * notMerge: ...,
  23732. * lazyUpdate: ...,
  23733. * silent: ...
  23734. * });
  23735. *
  23736. * @param {Object} option
  23737. * @param {Object|boolean} [opts] opts or notMerge.
  23738. * @param {boolean} [opts.notMerge=false]
  23739. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23740. */
  23741. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23742. if (__DEV__) {
  23743. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23744. }
  23745. if (this._disposed) {
  23746. disposedWarning(this.id);
  23747. return;
  23748. }
  23749. var silent;
  23750. if (isObject(notMerge)) {
  23751. lazyUpdate = notMerge.lazyUpdate;
  23752. silent = notMerge.silent;
  23753. notMerge = notMerge.notMerge;
  23754. }
  23755. this[IN_MAIN_PROCESS] = true;
  23756. if (!this._model || notMerge) {
  23757. var optionManager = new OptionManager(this._api);
  23758. var theme$$1 = this._theme;
  23759. var ecModel = this._model = new GlobalModel();
  23760. ecModel.scheduler = this._scheduler;
  23761. ecModel.init(null, null, theme$$1, optionManager);
  23762. }
  23763. this._model.setOption(option, optionPreprocessorFuncs);
  23764. if (lazyUpdate) {
  23765. this[OPTION_UPDATED] = {silent: silent};
  23766. this[IN_MAIN_PROCESS] = false;
  23767. }
  23768. else {
  23769. prepare(this);
  23770. updateMethods.update.call(this);
  23771. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23772. // fetched after `setOption`.
  23773. this._zr.flush();
  23774. this[OPTION_UPDATED] = false;
  23775. this[IN_MAIN_PROCESS] = false;
  23776. flushPendingActions.call(this, silent);
  23777. triggerUpdatedEvent.call(this, silent);
  23778. }
  23779. };
  23780. /**
  23781. * @DEPRECATED
  23782. */
  23783. echartsProto.setTheme = function () {
  23784. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23785. };
  23786. /**
  23787. * @return {module:echarts/model/Global}
  23788. */
  23789. echartsProto.getModel = function () {
  23790. return this._model;
  23791. };
  23792. /**
  23793. * @return {Object}
  23794. */
  23795. echartsProto.getOption = function () {
  23796. return this._model && this._model.getOption();
  23797. };
  23798. /**
  23799. * @return {number}
  23800. */
  23801. echartsProto.getWidth = function () {
  23802. return this._zr.getWidth();
  23803. };
  23804. /**
  23805. * @return {number}
  23806. */
  23807. echartsProto.getHeight = function () {
  23808. return this._zr.getHeight();
  23809. };
  23810. /**
  23811. * @return {number}
  23812. */
  23813. echartsProto.getDevicePixelRatio = function () {
  23814. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23815. };
  23816. /**
  23817. * Get canvas which has all thing rendered
  23818. * @param {Object} opts
  23819. * @param {string} [opts.backgroundColor]
  23820. * @return {string}
  23821. */
  23822. echartsProto.getRenderedCanvas = function (opts) {
  23823. if (!env$1.canvasSupported) {
  23824. return;
  23825. }
  23826. opts = opts || {};
  23827. opts.pixelRatio = opts.pixelRatio || 1;
  23828. opts.backgroundColor = opts.backgroundColor
  23829. || this._model.get('backgroundColor');
  23830. var zr = this._zr;
  23831. // var list = zr.storage.getDisplayList();
  23832. // Stop animations
  23833. // Never works before in init animation, so remove it.
  23834. // zrUtil.each(list, function (el) {
  23835. // el.stopAnimation(true);
  23836. // });
  23837. return zr.painter.getRenderedCanvas(opts);
  23838. };
  23839. /**
  23840. * Get svg data url
  23841. * @return {string}
  23842. */
  23843. echartsProto.getSvgDataUrl = function () {
  23844. if (!env$1.svgSupported) {
  23845. return;
  23846. }
  23847. var zr = this._zr;
  23848. var list = zr.storage.getDisplayList();
  23849. // Stop animations
  23850. each$1(list, function (el) {
  23851. el.stopAnimation(true);
  23852. });
  23853. return zr.painter.pathToDataUrl();
  23854. };
  23855. /**
  23856. * @return {string}
  23857. * @param {Object} opts
  23858. * @param {string} [opts.type='png']
  23859. * @param {string} [opts.pixelRatio=1]
  23860. * @param {string} [opts.backgroundColor]
  23861. * @param {string} [opts.excludeComponents]
  23862. */
  23863. echartsProto.getDataURL = function (opts) {
  23864. if (this._disposed) {
  23865. disposedWarning(this.id);
  23866. return;
  23867. }
  23868. opts = opts || {};
  23869. var excludeComponents = opts.excludeComponents;
  23870. var ecModel = this._model;
  23871. var excludesComponentViews = [];
  23872. var self = this;
  23873. each(excludeComponents, function (componentType) {
  23874. ecModel.eachComponent({
  23875. mainType: componentType
  23876. }, function (component) {
  23877. var view = self._componentsMap[component.__viewId];
  23878. if (!view.group.ignore) {
  23879. excludesComponentViews.push(view);
  23880. view.group.ignore = true;
  23881. }
  23882. });
  23883. });
  23884. var url = this._zr.painter.getType() === 'svg'
  23885. ? this.getSvgDataUrl()
  23886. : this.getRenderedCanvas(opts).toDataURL(
  23887. 'image/' + (opts && opts.type || 'png')
  23888. );
  23889. each(excludesComponentViews, function (view) {
  23890. view.group.ignore = false;
  23891. });
  23892. return url;
  23893. };
  23894. /**
  23895. * @return {string}
  23896. * @param {Object} opts
  23897. * @param {string} [opts.type='png']
  23898. * @param {string} [opts.pixelRatio=1]
  23899. * @param {string} [opts.backgroundColor]
  23900. */
  23901. echartsProto.getConnectedDataURL = function (opts) {
  23902. if (this._disposed) {
  23903. disposedWarning(this.id);
  23904. return;
  23905. }
  23906. if (!env$1.canvasSupported) {
  23907. return;
  23908. }
  23909. var groupId = this.group;
  23910. var mathMin = Math.min;
  23911. var mathMax = Math.max;
  23912. var MAX_NUMBER = Infinity;
  23913. if (connectedGroups[groupId]) {
  23914. var left = MAX_NUMBER;
  23915. var top = MAX_NUMBER;
  23916. var right = -MAX_NUMBER;
  23917. var bottom = -MAX_NUMBER;
  23918. var canvasList = [];
  23919. var dpr = (opts && opts.pixelRatio) || 1;
  23920. each$1(instances, function (chart, id) {
  23921. if (chart.group === groupId) {
  23922. var canvas = chart.getRenderedCanvas(
  23923. clone(opts)
  23924. );
  23925. var boundingRect = chart.getDom().getBoundingClientRect();
  23926. left = mathMin(boundingRect.left, left);
  23927. top = mathMin(boundingRect.top, top);
  23928. right = mathMax(boundingRect.right, right);
  23929. bottom = mathMax(boundingRect.bottom, bottom);
  23930. canvasList.push({
  23931. dom: canvas,
  23932. left: boundingRect.left,
  23933. top: boundingRect.top
  23934. });
  23935. }
  23936. });
  23937. left *= dpr;
  23938. top *= dpr;
  23939. right *= dpr;
  23940. bottom *= dpr;
  23941. var width = right - left;
  23942. var height = bottom - top;
  23943. var targetCanvas = createCanvas();
  23944. targetCanvas.width = width;
  23945. targetCanvas.height = height;
  23946. var zr = init$1(targetCanvas);
  23947. // Background between the charts
  23948. if (opts.connectedBackgroundColor) {
  23949. zr.add(new Rect({
  23950. shape: {
  23951. x: 0,
  23952. y: 0,
  23953. width: width,
  23954. height: height
  23955. },
  23956. style: {
  23957. fill: opts.connectedBackgroundColor
  23958. }
  23959. }));
  23960. }
  23961. each(canvasList, function (item) {
  23962. var img = new ZImage({
  23963. style: {
  23964. x: item.left * dpr - left,
  23965. y: item.top * dpr - top,
  23966. image: item.dom
  23967. }
  23968. });
  23969. zr.add(img);
  23970. });
  23971. zr.refreshImmediately();
  23972. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23973. }
  23974. else {
  23975. return this.getDataURL(opts);
  23976. }
  23977. };
  23978. /**
  23979. * Convert from logical coordinate system to pixel coordinate system.
  23980. * See CoordinateSystem#convertToPixel.
  23981. * @param {string|Object} finder
  23982. * If string, e.g., 'geo', means {geoIndex: 0}.
  23983. * If Object, could contain some of these properties below:
  23984. * {
  23985. * seriesIndex / seriesId / seriesName,
  23986. * geoIndex / geoId, geoName,
  23987. * bmapIndex / bmapId / bmapName,
  23988. * xAxisIndex / xAxisId / xAxisName,
  23989. * yAxisIndex / yAxisId / yAxisName,
  23990. * gridIndex / gridId / gridName,
  23991. * ... (can be extended)
  23992. * }
  23993. * @param {Array|number} value
  23994. * @return {Array|number} result
  23995. */
  23996. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23997. /**
  23998. * Convert from pixel coordinate system to logical coordinate system.
  23999. * See CoordinateSystem#convertFromPixel.
  24000. * @param {string|Object} finder
  24001. * If string, e.g., 'geo', means {geoIndex: 0}.
  24002. * If Object, could contain some of these properties below:
  24003. * {
  24004. * seriesIndex / seriesId / seriesName,
  24005. * geoIndex / geoId / geoName,
  24006. * bmapIndex / bmapId / bmapName,
  24007. * xAxisIndex / xAxisId / xAxisName,
  24008. * yAxisIndex / yAxisId / yAxisName
  24009. * gridIndex / gridId / gridName,
  24010. * ... (can be extended)
  24011. * }
  24012. * @param {Array|number} value
  24013. * @return {Array|number} result
  24014. */
  24015. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  24016. function doConvertPixel(methodName, finder, value) {
  24017. if (this._disposed) {
  24018. disposedWarning(this.id);
  24019. return;
  24020. }
  24021. var ecModel = this._model;
  24022. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  24023. var result;
  24024. finder = parseFinder(ecModel, finder);
  24025. for (var i = 0; i < coordSysList.length; i++) {
  24026. var coordSys = coordSysList[i];
  24027. if (coordSys[methodName]
  24028. && (result = coordSys[methodName](ecModel, finder, value)) != null
  24029. ) {
  24030. return result;
  24031. }
  24032. }
  24033. if (__DEV__) {
  24034. console.warn(
  24035. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  24036. );
  24037. }
  24038. }
  24039. /**
  24040. * Is the specified coordinate systems or components contain the given pixel point.
  24041. * @param {string|Object} finder
  24042. * If string, e.g., 'geo', means {geoIndex: 0}.
  24043. * If Object, could contain some of these properties below:
  24044. * {
  24045. * seriesIndex / seriesId / seriesName,
  24046. * geoIndex / geoId / geoName,
  24047. * bmapIndex / bmapId / bmapName,
  24048. * xAxisIndex / xAxisId / xAxisName,
  24049. * yAxisIndex / yAxisId / yAxisName,
  24050. * gridIndex / gridId / gridName,
  24051. * ... (can be extended)
  24052. * }
  24053. * @param {Array|number} value
  24054. * @return {boolean} result
  24055. */
  24056. echartsProto.containPixel = function (finder, value) {
  24057. if (this._disposed) {
  24058. disposedWarning(this.id);
  24059. return;
  24060. }
  24061. var ecModel = this._model;
  24062. var result;
  24063. finder = parseFinder(ecModel, finder);
  24064. each$1(finder, function (models, key) {
  24065. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  24066. var coordSys = model.coordinateSystem;
  24067. if (coordSys && coordSys.containPoint) {
  24068. result |= !!coordSys.containPoint(value);
  24069. }
  24070. else if (key === 'seriesModels') {
  24071. var view = this._chartsMap[model.__viewId];
  24072. if (view && view.containPoint) {
  24073. result |= view.containPoint(value, model);
  24074. }
  24075. else {
  24076. if (__DEV__) {
  24077. console.warn(key + ': ' + (view
  24078. ? 'The found component do not support containPoint.'
  24079. : 'No view mapping to the found component.'
  24080. ));
  24081. }
  24082. }
  24083. }
  24084. else {
  24085. if (__DEV__) {
  24086. console.warn(key + ': containPoint is not supported');
  24087. }
  24088. }
  24089. }, this);
  24090. }, this);
  24091. return !!result;
  24092. };
  24093. /**
  24094. * Get visual from series or data.
  24095. * @param {string|Object} finder
  24096. * If string, e.g., 'series', means {seriesIndex: 0}.
  24097. * If Object, could contain some of these properties below:
  24098. * {
  24099. * seriesIndex / seriesId / seriesName,
  24100. * dataIndex / dataIndexInside
  24101. * }
  24102. * If dataIndex is not specified, series visual will be fetched,
  24103. * but not data item visual.
  24104. * If all of seriesIndex, seriesId, seriesName are not specified,
  24105. * visual will be fetched from first series.
  24106. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  24107. */
  24108. echartsProto.getVisual = function (finder, visualType) {
  24109. var ecModel = this._model;
  24110. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  24111. var seriesModel = finder.seriesModel;
  24112. if (__DEV__) {
  24113. if (!seriesModel) {
  24114. console.warn('There is no specified seires model');
  24115. }
  24116. }
  24117. var data = seriesModel.getData();
  24118. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  24119. ? finder.dataIndexInside
  24120. : finder.hasOwnProperty('dataIndex')
  24121. ? data.indexOfRawIndex(finder.dataIndex)
  24122. : null;
  24123. return dataIndexInside != null
  24124. ? data.getItemVisual(dataIndexInside, visualType)
  24125. : data.getVisual(visualType);
  24126. };
  24127. /**
  24128. * Get view of corresponding component model
  24129. * @param {module:echarts/model/Component} componentModel
  24130. * @return {module:echarts/view/Component}
  24131. */
  24132. echartsProto.getViewOfComponentModel = function (componentModel) {
  24133. return this._componentsMap[componentModel.__viewId];
  24134. };
  24135. /**
  24136. * Get view of corresponding series model
  24137. * @param {module:echarts/model/Series} seriesModel
  24138. * @return {module:echarts/view/Chart}
  24139. */
  24140. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  24141. return this._chartsMap[seriesModel.__viewId];
  24142. };
  24143. var updateMethods = {
  24144. prepareAndUpdate: function (payload) {
  24145. prepare(this);
  24146. updateMethods.update.call(this, payload);
  24147. },
  24148. /**
  24149. * @param {Object} payload
  24150. * @private
  24151. */
  24152. update: function (payload) {
  24153. // console.profile && console.profile('update');
  24154. var ecModel = this._model;
  24155. var api = this._api;
  24156. var zr = this._zr;
  24157. var coordSysMgr = this._coordSysMgr;
  24158. var scheduler = this._scheduler;
  24159. // update before setOption
  24160. if (!ecModel) {
  24161. return;
  24162. }
  24163. scheduler.restoreData(ecModel, payload);
  24164. scheduler.performSeriesTasks(ecModel);
  24165. // TODO
  24166. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  24167. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  24168. // Create new coordinate system each update
  24169. // In LineView may save the old coordinate system and use it to get the orignal point
  24170. coordSysMgr.create(ecModel, api);
  24171. scheduler.performDataProcessorTasks(ecModel, payload);
  24172. // Current stream render is not supported in data process. So we can update
  24173. // stream modes after data processing, where the filtered data is used to
  24174. // deteming whether use progressive rendering.
  24175. updateStreamModes(this, ecModel);
  24176. // We update stream modes before coordinate system updated, then the modes info
  24177. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  24178. // the drawback is the full coord info can not be fetched. Fortunately this full
  24179. // coord is not requied in stream mode updater currently.
  24180. coordSysMgr.update(ecModel, api);
  24181. clearColorPalette(ecModel);
  24182. scheduler.performVisualTasks(ecModel, payload);
  24183. render(this, ecModel, api, payload);
  24184. // Set background
  24185. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  24186. // In IE8
  24187. if (!env$1.canvasSupported) {
  24188. var colorArr = parse(backgroundColor);
  24189. backgroundColor = stringify(colorArr, 'rgb');
  24190. if (colorArr[3] === 0) {
  24191. backgroundColor = 'transparent';
  24192. }
  24193. }
  24194. else {
  24195. zr.setBackgroundColor(backgroundColor);
  24196. }
  24197. performPostUpdateFuncs(ecModel, api);
  24198. // console.profile && console.profileEnd('update');
  24199. },
  24200. /**
  24201. * @param {Object} payload
  24202. * @private
  24203. */
  24204. updateTransform: function (payload) {
  24205. var ecModel = this._model;
  24206. var ecIns = this;
  24207. var api = this._api;
  24208. // update before setOption
  24209. if (!ecModel) {
  24210. return;
  24211. }
  24212. // ChartView.markUpdateMethod(payload, 'updateTransform');
  24213. var componentDirtyList = [];
  24214. ecModel.eachComponent(function (componentType, componentModel) {
  24215. var componentView = ecIns.getViewOfComponentModel(componentModel);
  24216. if (componentView && componentView.__alive) {
  24217. if (componentView.updateTransform) {
  24218. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  24219. result && result.update && componentDirtyList.push(componentView);
  24220. }
  24221. else {
  24222. componentDirtyList.push(componentView);
  24223. }
  24224. }
  24225. });
  24226. var seriesDirtyMap = createHashMap();
  24227. ecModel.eachSeries(function (seriesModel) {
  24228. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24229. if (chartView.updateTransform) {
  24230. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  24231. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  24232. }
  24233. else {
  24234. seriesDirtyMap.set(seriesModel.uid, 1);
  24235. }
  24236. });
  24237. clearColorPalette(ecModel);
  24238. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24239. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24240. this._scheduler.performVisualTasks(
  24241. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  24242. );
  24243. // Currently, not call render of components. Geo render cost a lot.
  24244. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  24245. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  24246. performPostUpdateFuncs(ecModel, this._api);
  24247. },
  24248. /**
  24249. * @param {Object} payload
  24250. * @private
  24251. */
  24252. updateView: function (payload) {
  24253. var ecModel = this._model;
  24254. // update before setOption
  24255. if (!ecModel) {
  24256. return;
  24257. }
  24258. Chart.markUpdateMethod(payload, 'updateView');
  24259. clearColorPalette(ecModel);
  24260. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24261. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24262. render(this, this._model, this._api, payload);
  24263. performPostUpdateFuncs(ecModel, this._api);
  24264. },
  24265. /**
  24266. * @param {Object} payload
  24267. * @private
  24268. */
  24269. updateVisual: function (payload) {
  24270. updateMethods.update.call(this, payload);
  24271. // var ecModel = this._model;
  24272. // // update before setOption
  24273. // if (!ecModel) {
  24274. // return;
  24275. // }
  24276. // ChartView.markUpdateMethod(payload, 'updateVisual');
  24277. // clearColorPalette(ecModel);
  24278. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24279. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  24280. // render(this, this._model, this._api, payload);
  24281. // performPostUpdateFuncs(ecModel, this._api);
  24282. },
  24283. /**
  24284. * @param {Object} payload
  24285. * @private
  24286. */
  24287. updateLayout: function (payload) {
  24288. updateMethods.update.call(this, payload);
  24289. // var ecModel = this._model;
  24290. // // update before setOption
  24291. // if (!ecModel) {
  24292. // return;
  24293. // }
  24294. // ChartView.markUpdateMethod(payload, 'updateLayout');
  24295. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  24296. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  24297. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  24298. // render(this, this._model, this._api, payload);
  24299. // performPostUpdateFuncs(ecModel, this._api);
  24300. }
  24301. };
  24302. function prepare(ecIns) {
  24303. var ecModel = ecIns._model;
  24304. var scheduler = ecIns._scheduler;
  24305. scheduler.restorePipelines(ecModel);
  24306. scheduler.prepareStageTasks();
  24307. prepareView(ecIns, 'component', ecModel, scheduler);
  24308. prepareView(ecIns, 'chart', ecModel, scheduler);
  24309. scheduler.plan();
  24310. }
  24311. /**
  24312. * @private
  24313. */
  24314. function updateDirectly(ecIns, method, payload, mainType, subType) {
  24315. var ecModel = ecIns._model;
  24316. // broadcast
  24317. if (!mainType) {
  24318. // FIXME
  24319. // Chart will not be update directly here, except set dirty.
  24320. // But there is no such scenario now.
  24321. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  24322. return;
  24323. }
  24324. var query = {};
  24325. query[mainType + 'Id'] = payload[mainType + 'Id'];
  24326. query[mainType + 'Index'] = payload[mainType + 'Index'];
  24327. query[mainType + 'Name'] = payload[mainType + 'Name'];
  24328. var condition = {mainType: mainType, query: query};
  24329. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  24330. var excludeSeriesId = payload.excludeSeriesId;
  24331. if (excludeSeriesId != null) {
  24332. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  24333. }
  24334. // If dispatchAction before setOption, do nothing.
  24335. ecModel && ecModel.eachComponent(condition, function (model) {
  24336. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  24337. callView(ecIns[
  24338. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24339. ][model.__viewId]);
  24340. }
  24341. }, ecIns);
  24342. function callView(view) {
  24343. view && view.__alive && view[method] && view[method](
  24344. view.__model, ecModel, ecIns._api, payload
  24345. );
  24346. }
  24347. }
  24348. /**
  24349. * Resize the chart
  24350. * @param {Object} opts
  24351. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  24352. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  24353. * @param {boolean} [opts.silent=false]
  24354. */
  24355. echartsProto.resize = function (opts) {
  24356. if (__DEV__) {
  24357. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  24358. }
  24359. if (this._disposed) {
  24360. disposedWarning(this.id);
  24361. return;
  24362. }
  24363. this._zr.resize(opts);
  24364. var ecModel = this._model;
  24365. // Resize loading effect
  24366. this._loadingFX && this._loadingFX.resize();
  24367. if (!ecModel) {
  24368. return;
  24369. }
  24370. var optionChanged = ecModel.resetOption('media');
  24371. var silent = opts && opts.silent;
  24372. this[IN_MAIN_PROCESS] = true;
  24373. optionChanged && prepare(this);
  24374. updateMethods.update.call(this);
  24375. this[IN_MAIN_PROCESS] = false;
  24376. flushPendingActions.call(this, silent);
  24377. triggerUpdatedEvent.call(this, silent);
  24378. };
  24379. function updateStreamModes(ecIns, ecModel) {
  24380. var chartsMap = ecIns._chartsMap;
  24381. var scheduler = ecIns._scheduler;
  24382. ecModel.eachSeries(function (seriesModel) {
  24383. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  24384. });
  24385. }
  24386. /**
  24387. * Show loading effect
  24388. * @param {string} [name='default']
  24389. * @param {Object} [cfg]
  24390. */
  24391. echartsProto.showLoading = function (name, cfg) {
  24392. if (this._disposed) {
  24393. disposedWarning(this.id);
  24394. return;
  24395. }
  24396. if (isObject(name)) {
  24397. cfg = name;
  24398. name = '';
  24399. }
  24400. name = name || 'default';
  24401. this.hideLoading();
  24402. if (!loadingEffects[name]) {
  24403. if (__DEV__) {
  24404. console.warn('Loading effects ' + name + ' not exists.');
  24405. }
  24406. return;
  24407. }
  24408. var el = loadingEffects[name](this._api, cfg);
  24409. var zr = this._zr;
  24410. this._loadingFX = el;
  24411. zr.add(el);
  24412. };
  24413. /**
  24414. * Hide loading effect
  24415. */
  24416. echartsProto.hideLoading = function () {
  24417. if (this._disposed) {
  24418. disposedWarning(this.id);
  24419. return;
  24420. }
  24421. this._loadingFX && this._zr.remove(this._loadingFX);
  24422. this._loadingFX = null;
  24423. };
  24424. /**
  24425. * @param {Object} eventObj
  24426. * @return {Object}
  24427. */
  24428. echartsProto.makeActionFromEvent = function (eventObj) {
  24429. var payload = extend({}, eventObj);
  24430. payload.type = eventActionMap[eventObj.type];
  24431. return payload;
  24432. };
  24433. /**
  24434. * @pubilc
  24435. * @param {Object} payload
  24436. * @param {string} [payload.type] Action type
  24437. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  24438. * @param {boolean} [opt.silent=false] Whether trigger events.
  24439. * @param {boolean} [opt.flush=undefined]
  24440. * true: Flush immediately, and then pixel in canvas can be fetched
  24441. * immediately. Caution: it might affect performance.
  24442. * false: Not flush.
  24443. * undefined: Auto decide whether perform flush.
  24444. */
  24445. echartsProto.dispatchAction = function (payload, opt) {
  24446. if (this._disposed) {
  24447. disposedWarning(this.id);
  24448. return;
  24449. }
  24450. if (!isObject(opt)) {
  24451. opt = {silent: !!opt};
  24452. }
  24453. if (!actions[payload.type]) {
  24454. return;
  24455. }
  24456. // Avoid dispatch action before setOption. Especially in `connect`.
  24457. if (!this._model) {
  24458. return;
  24459. }
  24460. // May dispatchAction in rendering procedure
  24461. if (this[IN_MAIN_PROCESS]) {
  24462. this._pendingActions.push(payload);
  24463. return;
  24464. }
  24465. doDispatchAction.call(this, payload, opt.silent);
  24466. if (opt.flush) {
  24467. this._zr.flush(true);
  24468. }
  24469. else if (opt.flush !== false && env$1.browser.weChat) {
  24470. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  24471. // hang when sliding page (on touch event), which cause that zr does not
  24472. // refresh util user interaction finished, which is not expected.
  24473. // But `dispatchAction` may be called too frequently when pan on touch
  24474. // screen, which impacts performance if do not throttle them.
  24475. this._throttledZrFlush();
  24476. }
  24477. flushPendingActions.call(this, opt.silent);
  24478. triggerUpdatedEvent.call(this, opt.silent);
  24479. };
  24480. function doDispatchAction(payload, silent) {
  24481. var payloadType = payload.type;
  24482. var escapeConnect = payload.escapeConnect;
  24483. var actionWrap = actions[payloadType];
  24484. var actionInfo = actionWrap.actionInfo;
  24485. var cptType = (actionInfo.update || 'update').split(':');
  24486. var updateMethod = cptType.pop();
  24487. cptType = cptType[0] != null && parseClassType(cptType[0]);
  24488. this[IN_MAIN_PROCESS] = true;
  24489. var payloads = [payload];
  24490. var batched = false;
  24491. // Batch action
  24492. if (payload.batch) {
  24493. batched = true;
  24494. payloads = map(payload.batch, function (item) {
  24495. item = defaults(extend({}, item), payload);
  24496. item.batch = null;
  24497. return item;
  24498. });
  24499. }
  24500. var eventObjBatch = [];
  24501. var eventObj;
  24502. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  24503. each(payloads, function (batchItem) {
  24504. // Action can specify the event by return it.
  24505. eventObj = actionWrap.action(batchItem, this._model, this._api);
  24506. // Emit event outside
  24507. eventObj = eventObj || extend({}, batchItem);
  24508. // Convert type to eventType
  24509. eventObj.type = actionInfo.event || eventObj.type;
  24510. eventObjBatch.push(eventObj);
  24511. // light update does not perform data process, layout and visual.
  24512. if (isHighDown) {
  24513. // method, payload, mainType, subType
  24514. updateDirectly(this, updateMethod, batchItem, 'series');
  24515. }
  24516. else if (cptType) {
  24517. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  24518. }
  24519. }, this);
  24520. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  24521. // Still dirty
  24522. if (this[OPTION_UPDATED]) {
  24523. // FIXME Pass payload ?
  24524. prepare(this);
  24525. updateMethods.update.call(this, payload);
  24526. this[OPTION_UPDATED] = false;
  24527. }
  24528. else {
  24529. updateMethods[updateMethod].call(this, payload);
  24530. }
  24531. }
  24532. // Follow the rule of action batch
  24533. if (batched) {
  24534. eventObj = {
  24535. type: actionInfo.event || payloadType,
  24536. escapeConnect: escapeConnect,
  24537. batch: eventObjBatch
  24538. };
  24539. }
  24540. else {
  24541. eventObj = eventObjBatch[0];
  24542. }
  24543. this[IN_MAIN_PROCESS] = false;
  24544. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  24545. }
  24546. function flushPendingActions(silent) {
  24547. var pendingActions = this._pendingActions;
  24548. while (pendingActions.length) {
  24549. var payload = pendingActions.shift();
  24550. doDispatchAction.call(this, payload, silent);
  24551. }
  24552. }
  24553. function triggerUpdatedEvent(silent) {
  24554. !silent && this.trigger('updated');
  24555. }
  24556. /**
  24557. * Event `rendered` is triggered when zr
  24558. * rendered. It is useful for realtime
  24559. * snapshot (reflect animation).
  24560. *
  24561. * Event `finished` is triggered when:
  24562. * (1) zrender rendering finished.
  24563. * (2) initial animation finished.
  24564. * (3) progressive rendering finished.
  24565. * (4) no pending action.
  24566. * (5) no delayed setOption needs to be processed.
  24567. */
  24568. function bindRenderedEvent(zr, ecIns) {
  24569. zr.on('rendered', function () {
  24570. ecIns.trigger('rendered');
  24571. // The `finished` event should not be triggered repeatly,
  24572. // so it should only be triggered when rendering indeed happend
  24573. // in zrender. (Consider the case that dipatchAction is keep
  24574. // triggering when mouse move).
  24575. if (
  24576. // Although zr is dirty if initial animation is not finished
  24577. // and this checking is called on frame, we also check
  24578. // animation finished for robustness.
  24579. zr.animation.isFinished()
  24580. && !ecIns[OPTION_UPDATED]
  24581. && !ecIns._scheduler.unfinished
  24582. && !ecIns._pendingActions.length
  24583. ) {
  24584. ecIns.trigger('finished');
  24585. }
  24586. });
  24587. }
  24588. /**
  24589. * @param {Object} params
  24590. * @param {number} params.seriesIndex
  24591. * @param {Array|TypedArray} params.data
  24592. */
  24593. echartsProto.appendData = function (params) {
  24594. if (this._disposed) {
  24595. disposedWarning(this.id);
  24596. return;
  24597. }
  24598. var seriesIndex = params.seriesIndex;
  24599. var ecModel = this.getModel();
  24600. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  24601. if (__DEV__) {
  24602. assert(params.data && seriesModel);
  24603. }
  24604. seriesModel.appendData(params);
  24605. // Note: `appendData` does not support that update extent of coordinate
  24606. // system, util some scenario require that. In the expected usage of
  24607. // `appendData`, the initial extent of coordinate system should better
  24608. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  24609. // the extent changed while `appendData`, the location of the painted
  24610. // graphic elements have to be changed, which make the usage of
  24611. // `appendData` meaningless.
  24612. this._scheduler.unfinished = true;
  24613. };
  24614. /**
  24615. * Register event
  24616. * @method
  24617. */
  24618. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  24619. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  24620. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  24621. /**
  24622. * Prepare view instances of charts and components
  24623. * @param {module:echarts/model/Global} ecModel
  24624. * @private
  24625. */
  24626. function prepareView(ecIns, type, ecModel, scheduler) {
  24627. var isComponent = type === 'component';
  24628. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  24629. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  24630. var zr = ecIns._zr;
  24631. var api = ecIns._api;
  24632. for (var i = 0; i < viewList.length; i++) {
  24633. viewList[i].__alive = false;
  24634. }
  24635. isComponent
  24636. ? ecModel.eachComponent(function (componentType, model) {
  24637. componentType !== 'series' && doPrepare(model);
  24638. })
  24639. : ecModel.eachSeries(doPrepare);
  24640. function doPrepare(model) {
  24641. // Consider: id same and type changed.
  24642. var viewId = '_ec_' + model.id + '_' + model.type;
  24643. var view = viewMap[viewId];
  24644. if (!view) {
  24645. var classType = parseClassType(model.type);
  24646. var Clazz = isComponent
  24647. ? Component.getClass(classType.main, classType.sub)
  24648. : Chart.getClass(classType.sub);
  24649. if (__DEV__) {
  24650. assert(Clazz, classType.sub + ' does not exist.');
  24651. }
  24652. view = new Clazz();
  24653. view.init(ecModel, api);
  24654. viewMap[viewId] = view;
  24655. viewList.push(view);
  24656. zr.add(view.group);
  24657. }
  24658. model.__viewId = view.__id = viewId;
  24659. view.__alive = true;
  24660. view.__model = model;
  24661. view.group.__ecComponentInfo = {
  24662. mainType: model.mainType,
  24663. index: model.componentIndex
  24664. };
  24665. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  24666. }
  24667. for (var i = 0; i < viewList.length;) {
  24668. var view = viewList[i];
  24669. if (!view.__alive) {
  24670. !isComponent && view.renderTask.dispose();
  24671. zr.remove(view.group);
  24672. view.dispose(ecModel, api);
  24673. viewList.splice(i, 1);
  24674. delete viewMap[view.__id];
  24675. view.__id = view.group.__ecComponentInfo = null;
  24676. }
  24677. else {
  24678. i++;
  24679. }
  24680. }
  24681. }
  24682. // /**
  24683. // * Encode visual infomation from data after data processing
  24684. // *
  24685. // * @param {module:echarts/model/Global} ecModel
  24686. // * @param {object} layout
  24687. // * @param {boolean} [layoutFilter] `true`: only layout,
  24688. // * `false`: only not layout,
  24689. // * `null`/`undefined`: all.
  24690. // * @param {string} taskBaseTag
  24691. // * @private
  24692. // */
  24693. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  24694. // each(visualFuncs, function (visual, index) {
  24695. // var isLayout = visual.isLayout;
  24696. // if (layoutFilter == null
  24697. // || (layoutFilter === false && !isLayout)
  24698. // || (layoutFilter === true && isLayout)
  24699. // ) {
  24700. // visual.func(ecModel, api, payload);
  24701. // }
  24702. // });
  24703. // }
  24704. function clearColorPalette(ecModel) {
  24705. ecModel.clearColorPalette();
  24706. ecModel.eachSeries(function (seriesModel) {
  24707. seriesModel.clearColorPalette();
  24708. });
  24709. }
  24710. function render(ecIns, ecModel, api, payload) {
  24711. renderComponents(ecIns, ecModel, api, payload);
  24712. each(ecIns._chartsViews, function (chart) {
  24713. chart.__alive = false;
  24714. });
  24715. renderSeries(ecIns, ecModel, api, payload);
  24716. // Remove groups of unrendered charts
  24717. each(ecIns._chartsViews, function (chart) {
  24718. if (!chart.__alive) {
  24719. chart.remove(ecModel, api);
  24720. }
  24721. });
  24722. }
  24723. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  24724. each(dirtyList || ecIns._componentsViews, function (componentView) {
  24725. var componentModel = componentView.__model;
  24726. componentView.render(componentModel, ecModel, api, payload);
  24727. updateZ(componentModel, componentView);
  24728. });
  24729. }
  24730. /**
  24731. * Render each chart and component
  24732. * @private
  24733. */
  24734. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  24735. // Render all charts
  24736. var scheduler = ecIns._scheduler;
  24737. var unfinished;
  24738. ecModel.eachSeries(function (seriesModel) {
  24739. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24740. chartView.__alive = true;
  24741. var renderTask = chartView.renderTask;
  24742. scheduler.updatePayload(renderTask, payload);
  24743. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  24744. renderTask.dirty();
  24745. }
  24746. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  24747. chartView.group.silent = !!seriesModel.get('silent');
  24748. updateZ(seriesModel, chartView);
  24749. updateBlend(seriesModel, chartView);
  24750. });
  24751. scheduler.unfinished |= unfinished;
  24752. // If use hover layer
  24753. updateHoverLayerStatus(ecIns, ecModel);
  24754. // Add aria
  24755. aria(ecIns._zr.dom, ecModel);
  24756. }
  24757. function performPostUpdateFuncs(ecModel, api) {
  24758. each(postUpdateFuncs, function (func) {
  24759. func(ecModel, api);
  24760. });
  24761. }
  24762. var MOUSE_EVENT_NAMES = [
  24763. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  24764. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  24765. ];
  24766. /**
  24767. * @private
  24768. */
  24769. echartsProto._initEvents = function () {
  24770. each(MOUSE_EVENT_NAMES, function (eveName) {
  24771. var handler = function (e) {
  24772. var ecModel = this.getModel();
  24773. var el = e.target;
  24774. var params;
  24775. var isGlobalOut = eveName === 'globalout';
  24776. // no e.target when 'globalout'.
  24777. if (isGlobalOut) {
  24778. params = {};
  24779. }
  24780. else if (el && el.dataIndex != null) {
  24781. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  24782. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  24783. }
  24784. // If element has custom eventData of components
  24785. else if (el && el.eventData) {
  24786. params = extend({}, el.eventData);
  24787. }
  24788. // Contract: if params prepared in mouse event,
  24789. // these properties must be specified:
  24790. // {
  24791. // componentType: string (component main type)
  24792. // componentIndex: number
  24793. // }
  24794. // Otherwise event query can not work.
  24795. if (params) {
  24796. var componentType = params.componentType;
  24797. var componentIndex = params.componentIndex;
  24798. // Special handling for historic reason: when trigger by
  24799. // markLine/markPoint/markArea, the componentType is
  24800. // 'markLine'/'markPoint'/'markArea', but we should better
  24801. // enable them to be queried by seriesIndex, since their
  24802. // option is set in each series.
  24803. if (componentType === 'markLine'
  24804. || componentType === 'markPoint'
  24805. || componentType === 'markArea'
  24806. ) {
  24807. componentType = 'series';
  24808. componentIndex = params.seriesIndex;
  24809. }
  24810. var model = componentType && componentIndex != null
  24811. && ecModel.getComponent(componentType, componentIndex);
  24812. var view = model && this[
  24813. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24814. ][model.__viewId];
  24815. if (__DEV__) {
  24816. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24817. // be missed, otherwise there is no way to distinguish source component.
  24818. // See `dataFormat.getDataParams`.
  24819. if (!isGlobalOut && !(model && view)) {
  24820. console.warn('model or view can not be found by params');
  24821. }
  24822. }
  24823. params.event = e;
  24824. params.type = eveName;
  24825. this._ecEventProcessor.eventInfo = {
  24826. targetEl: el,
  24827. packedEvent: params,
  24828. model: model,
  24829. view: view
  24830. };
  24831. this.trigger(eveName, params);
  24832. }
  24833. };
  24834. // Consider that some component (like tooltip, brush, ...)
  24835. // register zr event handler, but user event handler might
  24836. // do anything, such as call `setOption` or `dispatchAction`,
  24837. // which probably update any of the content and probably
  24838. // cause problem if it is called previous other inner handlers.
  24839. handler.zrEventfulCallAtLast = true;
  24840. this._zr.on(eveName, handler, this);
  24841. }, this);
  24842. each(eventActionMap, function (actionType, eventType) {
  24843. this._messageCenter.on(eventType, function (event) {
  24844. this.trigger(eventType, event);
  24845. }, this);
  24846. }, this);
  24847. };
  24848. /**
  24849. * @return {boolean}
  24850. */
  24851. echartsProto.isDisposed = function () {
  24852. return this._disposed;
  24853. };
  24854. /**
  24855. * Clear
  24856. */
  24857. echartsProto.clear = function () {
  24858. if (this._disposed) {
  24859. disposedWarning(this.id);
  24860. return;
  24861. }
  24862. this.setOption({ series: [] }, true);
  24863. };
  24864. /**
  24865. * Dispose instance
  24866. */
  24867. echartsProto.dispose = function () {
  24868. if (this._disposed) {
  24869. disposedWarning(this.id);
  24870. return;
  24871. }
  24872. this._disposed = true;
  24873. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24874. var api = this._api;
  24875. var ecModel = this._model;
  24876. each(this._componentsViews, function (component) {
  24877. component.dispose(ecModel, api);
  24878. });
  24879. each(this._chartsViews, function (chart) {
  24880. chart.dispose(ecModel, api);
  24881. });
  24882. // Dispose after all views disposed
  24883. this._zr.dispose();
  24884. delete instances[this.id];
  24885. };
  24886. mixin(ECharts, Eventful);
  24887. function disposedWarning(id) {
  24888. if (__DEV__) {
  24889. console.warn('Instance ' + id + ' has been disposed');
  24890. }
  24891. }
  24892. function updateHoverLayerStatus(ecIns, ecModel) {
  24893. var zr = ecIns._zr;
  24894. var storage = zr.storage;
  24895. var elCount = 0;
  24896. storage.traverse(function (el) {
  24897. elCount++;
  24898. });
  24899. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24900. ecModel.eachSeries(function (seriesModel) {
  24901. if (seriesModel.preventUsingHoverLayer) {
  24902. return;
  24903. }
  24904. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  24905. if (chartView.__alive) {
  24906. chartView.group.traverse(function (el) {
  24907. // Don't switch back.
  24908. el.useHoverLayer = true;
  24909. });
  24910. }
  24911. });
  24912. }
  24913. }
  24914. /**
  24915. * Update chart progressive and blend.
  24916. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24917. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24918. */
  24919. function updateBlend(seriesModel, chartView) {
  24920. var blendMode = seriesModel.get('blendMode') || null;
  24921. if (__DEV__) {
  24922. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24923. console.warn('Only canvas support blendMode');
  24924. }
  24925. }
  24926. chartView.group.traverse(function (el) {
  24927. // FIXME marker and other components
  24928. if (!el.isGroup) {
  24929. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24930. if (el.style.blend !== blendMode) {
  24931. el.setStyle('blend', blendMode);
  24932. }
  24933. }
  24934. if (el.eachPendingDisplayable) {
  24935. el.eachPendingDisplayable(function (displayable) {
  24936. displayable.setStyle('blend', blendMode);
  24937. });
  24938. }
  24939. });
  24940. }
  24941. /**
  24942. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24943. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24944. */
  24945. function updateZ(model, view) {
  24946. var z = model.get('z');
  24947. var zlevel = model.get('zlevel');
  24948. // Set z and zlevel
  24949. view.group.traverse(function (el) {
  24950. if (el.type !== 'group') {
  24951. z != null && (el.z = z);
  24952. zlevel != null && (el.zlevel = zlevel);
  24953. }
  24954. });
  24955. }
  24956. function createExtensionAPI(ecInstance) {
  24957. var coordSysMgr = ecInstance._coordSysMgr;
  24958. return extend(new ExtensionAPI(ecInstance), {
  24959. // Inject methods
  24960. getCoordinateSystems: bind(
  24961. coordSysMgr.getCoordinateSystems, coordSysMgr
  24962. ),
  24963. getComponentByElement: function (el) {
  24964. while (el) {
  24965. var modelInfo = el.__ecComponentInfo;
  24966. if (modelInfo != null) {
  24967. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24968. }
  24969. el = el.parent;
  24970. }
  24971. }
  24972. });
  24973. }
  24974. /**
  24975. * @class
  24976. * Usage of query:
  24977. * `chart.on('click', query, handler);`
  24978. * The `query` can be:
  24979. * + The component type query string, only `mainType` or `mainType.subType`,
  24980. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24981. * + The component query object, like:
  24982. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24983. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24984. * + The data query object, like:
  24985. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24986. * + The other query object (cmponent customized query), like:
  24987. * `{element: 'some'}` (only available in custom series).
  24988. *
  24989. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24990. * same as there is no such prop in the `query` object.
  24991. */
  24992. function EventProcessor() {
  24993. // These info required: targetEl, packedEvent, model, view
  24994. this.eventInfo;
  24995. }
  24996. EventProcessor.prototype = {
  24997. constructor: EventProcessor,
  24998. normalizeQuery: function (query) {
  24999. var cptQuery = {};
  25000. var dataQuery = {};
  25001. var otherQuery = {};
  25002. // `query` is `mainType` or `mainType.subType` of component.
  25003. if (isString(query)) {
  25004. var condCptType = parseClassType(query);
  25005. // `.main` and `.sub` may be ''.
  25006. cptQuery.mainType = condCptType.main || null;
  25007. cptQuery.subType = condCptType.sub || null;
  25008. }
  25009. // `query` is an object, convert to {mainType, index, name, id}.
  25010. else {
  25011. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  25012. // can not be used in `compomentModel.filterForExposedEvent`.
  25013. var suffixes = ['Index', 'Name', 'Id'];
  25014. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  25015. each$1(query, function (val, key) {
  25016. var reserved = false;
  25017. for (var i = 0; i < suffixes.length; i++) {
  25018. var propSuffix = suffixes[i];
  25019. var suffixPos = key.lastIndexOf(propSuffix);
  25020. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  25021. var mainType = key.slice(0, suffixPos);
  25022. // Consider `dataIndex`.
  25023. if (mainType !== 'data') {
  25024. cptQuery.mainType = mainType;
  25025. cptQuery[propSuffix.toLowerCase()] = val;
  25026. reserved = true;
  25027. }
  25028. }
  25029. }
  25030. if (dataKeys.hasOwnProperty(key)) {
  25031. dataQuery[key] = val;
  25032. reserved = true;
  25033. }
  25034. if (!reserved) {
  25035. otherQuery[key] = val;
  25036. }
  25037. });
  25038. }
  25039. return {
  25040. cptQuery: cptQuery,
  25041. dataQuery: dataQuery,
  25042. otherQuery: otherQuery
  25043. };
  25044. },
  25045. filter: function (eventType, query, args) {
  25046. // They should be assigned before each trigger call.
  25047. var eventInfo = this.eventInfo;
  25048. if (!eventInfo) {
  25049. return true;
  25050. }
  25051. var targetEl = eventInfo.targetEl;
  25052. var packedEvent = eventInfo.packedEvent;
  25053. var model = eventInfo.model;
  25054. var view = eventInfo.view;
  25055. // For event like 'globalout'.
  25056. if (!model || !view) {
  25057. return true;
  25058. }
  25059. var cptQuery = query.cptQuery;
  25060. var dataQuery = query.dataQuery;
  25061. return check(cptQuery, model, 'mainType')
  25062. && check(cptQuery, model, 'subType')
  25063. && check(cptQuery, model, 'index', 'componentIndex')
  25064. && check(cptQuery, model, 'name')
  25065. && check(cptQuery, model, 'id')
  25066. && check(dataQuery, packedEvent, 'name')
  25067. && check(dataQuery, packedEvent, 'dataIndex')
  25068. && check(dataQuery, packedEvent, 'dataType')
  25069. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  25070. eventType, query.otherQuery, targetEl, packedEvent
  25071. ));
  25072. function check(query, host, prop, propOnHost) {
  25073. return query[prop] == null || host[propOnHost || prop] === query[prop];
  25074. }
  25075. },
  25076. afterTrigger: function () {
  25077. // Make sure the eventInfo wont be used in next trigger.
  25078. this.eventInfo = null;
  25079. }
  25080. };
  25081. /**
  25082. * @type {Object} key: actionType.
  25083. * @inner
  25084. */
  25085. var actions = {};
  25086. /**
  25087. * Map eventType to actionType
  25088. * @type {Object}
  25089. */
  25090. var eventActionMap = {};
  25091. /**
  25092. * Data processor functions of each stage
  25093. * @type {Array.<Object.<string, Function>>}
  25094. * @inner
  25095. */
  25096. var dataProcessorFuncs = [];
  25097. /**
  25098. * @type {Array.<Function>}
  25099. * @inner
  25100. */
  25101. var optionPreprocessorFuncs = [];
  25102. /**
  25103. * @type {Array.<Function>}
  25104. * @inner
  25105. */
  25106. var postUpdateFuncs = [];
  25107. /**
  25108. * Visual encoding functions of each stage
  25109. * @type {Array.<Object.<string, Function>>}
  25110. */
  25111. var visualFuncs = [];
  25112. /**
  25113. * Theme storage
  25114. * @type {Object.<key, Object>}
  25115. */
  25116. var themeStorage = {};
  25117. /**
  25118. * Loading effects
  25119. */
  25120. var loadingEffects = {};
  25121. var instances = {};
  25122. var connectedGroups = {};
  25123. var idBase = new Date() - 0;
  25124. var groupIdBase = new Date() - 0;
  25125. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  25126. function enableConnect(chart) {
  25127. var STATUS_PENDING = 0;
  25128. var STATUS_UPDATING = 1;
  25129. var STATUS_UPDATED = 2;
  25130. var STATUS_KEY = '__connectUpdateStatus';
  25131. function updateConnectedChartsStatus(charts, status) {
  25132. for (var i = 0; i < charts.length; i++) {
  25133. var otherChart = charts[i];
  25134. otherChart[STATUS_KEY] = status;
  25135. }
  25136. }
  25137. each(eventActionMap, function (actionType, eventType) {
  25138. chart._messageCenter.on(eventType, function (event) {
  25139. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  25140. if (event && event.escapeConnect) {
  25141. return;
  25142. }
  25143. var action = chart.makeActionFromEvent(event);
  25144. var otherCharts = [];
  25145. each(instances, function (otherChart) {
  25146. if (otherChart !== chart && otherChart.group === chart.group) {
  25147. otherCharts.push(otherChart);
  25148. }
  25149. });
  25150. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  25151. each(otherCharts, function (otherChart) {
  25152. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  25153. otherChart.dispatchAction(action);
  25154. }
  25155. });
  25156. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  25157. }
  25158. });
  25159. });
  25160. }
  25161. /**
  25162. * @param {HTMLElement} dom
  25163. * @param {Object} [theme]
  25164. * @param {Object} opts
  25165. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  25166. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  25167. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  25168. * Can be 'auto' (the same as null/undefined)
  25169. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  25170. * Can be 'auto' (the same as null/undefined)
  25171. */
  25172. function init(dom, theme$$1, opts) {
  25173. if (__DEV__) {
  25174. // Check version
  25175. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  25176. throw new Error(
  25177. 'zrender/src ' + version$1
  25178. + ' is too old for ECharts ' + version
  25179. + '. Current version need ZRender '
  25180. + dependencies.zrender + '+'
  25181. );
  25182. }
  25183. if (!dom) {
  25184. throw new Error('Initialize failed: invalid dom.');
  25185. }
  25186. }
  25187. var existInstance = getInstanceByDom(dom);
  25188. if (existInstance) {
  25189. if (__DEV__) {
  25190. console.warn('There is a chart instance already initialized on the dom.');
  25191. }
  25192. return existInstance;
  25193. }
  25194. if (__DEV__) {
  25195. if (isDom(dom)
  25196. && dom.nodeName.toUpperCase() !== 'CANVAS'
  25197. && (
  25198. (!dom.clientWidth && (!opts || opts.width == null))
  25199. || (!dom.clientHeight && (!opts || opts.height == null))
  25200. )
  25201. ) {
  25202. console.warn('Can\'t get DOM width or height. Please check '
  25203. + 'dom.clientWidth and dom.clientHeight. They should not be 0.'
  25204. + 'For example, you may need to call this in the callback '
  25205. + 'of window.onload.');
  25206. }
  25207. }
  25208. var chart = new ECharts(dom, theme$$1, opts);
  25209. chart.id = 'ec_' + idBase++;
  25210. instances[chart.id] = chart;
  25211. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  25212. enableConnect(chart);
  25213. return chart;
  25214. }
  25215. /**
  25216. * @return {string|Array.<module:echarts~ECharts>} groupId
  25217. */
  25218. function connect(groupId) {
  25219. // Is array of charts
  25220. if (isArray(groupId)) {
  25221. var charts = groupId;
  25222. groupId = null;
  25223. // If any chart has group
  25224. each(charts, function (chart) {
  25225. if (chart.group != null) {
  25226. groupId = chart.group;
  25227. }
  25228. });
  25229. groupId = groupId || ('g_' + groupIdBase++);
  25230. each(charts, function (chart) {
  25231. chart.group = groupId;
  25232. });
  25233. }
  25234. connectedGroups[groupId] = true;
  25235. return groupId;
  25236. }
  25237. /**
  25238. * @DEPRECATED
  25239. * @return {string} groupId
  25240. */
  25241. function disConnect(groupId) {
  25242. connectedGroups[groupId] = false;
  25243. }
  25244. /**
  25245. * @return {string} groupId
  25246. */
  25247. var disconnect = disConnect;
  25248. /**
  25249. * Dispose a chart instance
  25250. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  25251. */
  25252. function dispose(chart) {
  25253. if (typeof chart === 'string') {
  25254. chart = instances[chart];
  25255. }
  25256. else if (!(chart instanceof ECharts)) {
  25257. // Try to treat as dom
  25258. chart = getInstanceByDom(chart);
  25259. }
  25260. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  25261. chart.dispose();
  25262. }
  25263. }
  25264. /**
  25265. * @param {HTMLElement} dom
  25266. * @return {echarts~ECharts}
  25267. */
  25268. function getInstanceByDom(dom) {
  25269. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  25270. }
  25271. /**
  25272. * @param {string} key
  25273. * @return {echarts~ECharts}
  25274. */
  25275. function getInstanceById(key) {
  25276. return instances[key];
  25277. }
  25278. /**
  25279. * Register theme
  25280. */
  25281. function registerTheme(name, theme$$1) {
  25282. themeStorage[name] = theme$$1;
  25283. }
  25284. /**
  25285. * Register option preprocessor
  25286. * @param {Function} preprocessorFunc
  25287. */
  25288. function registerPreprocessor(preprocessorFunc) {
  25289. optionPreprocessorFuncs.push(preprocessorFunc);
  25290. }
  25291. /**
  25292. * @param {number} [priority=1000]
  25293. * @param {Object|Function} processor
  25294. */
  25295. function registerProcessor(priority, processor) {
  25296. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  25297. }
  25298. /**
  25299. * Register postUpdater
  25300. * @param {Function} postUpdateFunc
  25301. */
  25302. function registerPostUpdate(postUpdateFunc) {
  25303. postUpdateFuncs.push(postUpdateFunc);
  25304. }
  25305. /**
  25306. * Usage:
  25307. * registerAction('someAction', 'someEvent', function () { ... });
  25308. * registerAction('someAction', function () { ... });
  25309. * registerAction(
  25310. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  25311. * function () { ... }
  25312. * );
  25313. *
  25314. * @param {(string|Object)} actionInfo
  25315. * @param {string} actionInfo.type
  25316. * @param {string} [actionInfo.event]
  25317. * @param {string} [actionInfo.update]
  25318. * @param {string} [eventName]
  25319. * @param {Function} action
  25320. */
  25321. function registerAction(actionInfo, eventName, action) {
  25322. if (typeof eventName === 'function') {
  25323. action = eventName;
  25324. eventName = '';
  25325. }
  25326. var actionType = isObject(actionInfo)
  25327. ? actionInfo.type
  25328. : ([actionInfo, actionInfo = {
  25329. event: eventName
  25330. }][0]);
  25331. // Event name is all lowercase
  25332. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  25333. eventName = actionInfo.event;
  25334. // Validate action type and event name.
  25335. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  25336. if (!actions[actionType]) {
  25337. actions[actionType] = {action: action, actionInfo: actionInfo};
  25338. }
  25339. eventActionMap[eventName] = actionType;
  25340. }
  25341. /**
  25342. * @param {string} type
  25343. * @param {*} CoordinateSystem
  25344. */
  25345. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  25346. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  25347. }
  25348. /**
  25349. * Get dimensions of specified coordinate system.
  25350. * @param {string} type
  25351. * @return {Array.<string|Object>}
  25352. */
  25353. function getCoordinateSystemDimensions(type) {
  25354. var coordSysCreator = CoordinateSystemManager.get(type);
  25355. if (coordSysCreator) {
  25356. return coordSysCreator.getDimensionsInfo
  25357. ? coordSysCreator.getDimensionsInfo()
  25358. : coordSysCreator.dimensions.slice();
  25359. }
  25360. }
  25361. /**
  25362. * Layout is a special stage of visual encoding
  25363. * Most visual encoding like color are common for different chart
  25364. * But each chart has it's own layout algorithm
  25365. *
  25366. * @param {number} [priority=1000]
  25367. * @param {Function} layoutTask
  25368. */
  25369. function registerLayout(priority, layoutTask) {
  25370. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  25371. }
  25372. /**
  25373. * @param {number} [priority=3000]
  25374. * @param {module:echarts/stream/Task} visualTask
  25375. */
  25376. function registerVisual(priority, visualTask) {
  25377. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  25378. }
  25379. /**
  25380. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  25381. */
  25382. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  25383. if (isFunction(priority) || isObject(priority)) {
  25384. fn = priority;
  25385. priority = defaultPriority;
  25386. }
  25387. if (__DEV__) {
  25388. if (isNaN(priority) || priority == null) {
  25389. throw new Error('Illegal priority');
  25390. }
  25391. // Check duplicate
  25392. each(targetList, function (wrap) {
  25393. assert(wrap.__raw !== fn);
  25394. });
  25395. }
  25396. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  25397. stageHandler.__prio = priority;
  25398. stageHandler.__raw = fn;
  25399. targetList.push(stageHandler);
  25400. return stageHandler;
  25401. }
  25402. /**
  25403. * @param {string} name
  25404. */
  25405. function registerLoading(name, loadingFx) {
  25406. loadingEffects[name] = loadingFx;
  25407. }
  25408. /**
  25409. * @param {Object} opts
  25410. * @param {string} [superClass]
  25411. */
  25412. function extendComponentModel(opts/*, superClass*/) {
  25413. // var Clazz = ComponentModel;
  25414. // if (superClass) {
  25415. // var classType = parseClassType(superClass);
  25416. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25417. // }
  25418. return ComponentModel.extend(opts);
  25419. }
  25420. /**
  25421. * @param {Object} opts
  25422. * @param {string} [superClass]
  25423. */
  25424. function extendComponentView(opts/*, superClass*/) {
  25425. // var Clazz = ComponentView;
  25426. // if (superClass) {
  25427. // var classType = parseClassType(superClass);
  25428. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  25429. // }
  25430. return Component.extend(opts);
  25431. }
  25432. /**
  25433. * @param {Object} opts
  25434. * @param {string} [superClass]
  25435. */
  25436. function extendSeriesModel(opts/*, superClass*/) {
  25437. // var Clazz = SeriesModel;
  25438. // if (superClass) {
  25439. // superClass = 'series.' + superClass.replace('series.', '');
  25440. // var classType = parseClassType(superClass);
  25441. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  25442. // }
  25443. return SeriesModel.extend(opts);
  25444. }
  25445. /**
  25446. * @param {Object} opts
  25447. * @param {string} [superClass]
  25448. */
  25449. function extendChartView(opts/*, superClass*/) {
  25450. // var Clazz = ChartView;
  25451. // if (superClass) {
  25452. // superClass = superClass.replace('series.', '');
  25453. // var classType = parseClassType(superClass);
  25454. // Clazz = ChartView.getClass(classType.main, true);
  25455. // }
  25456. return Chart.extend(opts);
  25457. }
  25458. /**
  25459. * ZRender need a canvas context to do measureText.
  25460. * But in node environment canvas may be created by node-canvas.
  25461. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  25462. *
  25463. * Be careful of using it in the browser.
  25464. *
  25465. * @param {Function} creator
  25466. * @example
  25467. * var Canvas = require('canvas');
  25468. * var echarts = require('echarts');
  25469. * echarts.setCanvasCreator(function () {
  25470. * // Small size is enough.
  25471. * return new Canvas(32, 32);
  25472. * });
  25473. */
  25474. function setCanvasCreator(creator) {
  25475. $override('createCanvas', creator);
  25476. }
  25477. /**
  25478. * @param {string} mapName
  25479. * @param {Array.<Object>|Object|string} geoJson
  25480. * @param {Object} [specialAreas]
  25481. *
  25482. * @example GeoJSON
  25483. * $.get('USA.json', function (geoJson) {
  25484. * echarts.registerMap('USA', geoJson);
  25485. * // Or
  25486. * echarts.registerMap('USA', {
  25487. * geoJson: geoJson,
  25488. * specialAreas: {}
  25489. * })
  25490. * });
  25491. *
  25492. * $.get('airport.svg', function (svg) {
  25493. * echarts.registerMap('airport', {
  25494. * svg: svg
  25495. * }
  25496. * });
  25497. *
  25498. * echarts.registerMap('eu', [
  25499. * {svg: eu-topographic.svg},
  25500. * {geoJSON: eu.json}
  25501. * ])
  25502. */
  25503. function registerMap(mapName, geoJson, specialAreas) {
  25504. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  25505. }
  25506. /**
  25507. * @param {string} mapName
  25508. * @return {Object}
  25509. */
  25510. function getMap(mapName) {
  25511. // For backward compatibility, only return the first one.
  25512. var records = mapDataStorage.retrieveMap(mapName);
  25513. return records && records[0] && {
  25514. geoJson: records[0].geoJSON,
  25515. specialAreas: records[0].specialAreas
  25516. };
  25517. }
  25518. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  25519. registerPreprocessor(backwardCompat);
  25520. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  25521. registerLoading('default', loadingDefault);
  25522. // Default actions
  25523. registerAction({
  25524. type: 'highlight',
  25525. event: 'highlight',
  25526. update: 'highlight'
  25527. }, noop);
  25528. registerAction({
  25529. type: 'downplay',
  25530. event: 'downplay',
  25531. update: 'downplay'
  25532. }, noop);
  25533. // Default theme
  25534. registerTheme('light', lightTheme);
  25535. registerTheme('dark', theme);
  25536. // For backward compatibility, where the namespace `dataTool` will
  25537. // be mounted on `echarts` is the extension `dataTool` is imported.
  25538. var dataTool = {};
  25539. /*
  25540. * Licensed to the Apache Software Foundation (ASF) under one
  25541. * or more contributor license agreements. See the NOTICE file
  25542. * distributed with this work for additional information
  25543. * regarding copyright ownership. The ASF licenses this file
  25544. * to you under the Apache License, Version 2.0 (the
  25545. * "License"); you may not use this file except in compliance
  25546. * with the License. You may obtain a copy of the License at
  25547. *
  25548. * http://www.apache.org/licenses/LICENSE-2.0
  25549. *
  25550. * Unless required by applicable law or agreed to in writing,
  25551. * software distributed under the License is distributed on an
  25552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25553. * KIND, either express or implied. See the License for the
  25554. * specific language governing permissions and limitations
  25555. * under the License.
  25556. */
  25557. function defaultKeyGetter(item) {
  25558. return item;
  25559. }
  25560. /**
  25561. * @param {Array} oldArr
  25562. * @param {Array} newArr
  25563. * @param {Function} oldKeyGetter
  25564. * @param {Function} newKeyGetter
  25565. * @param {Object} [context] Can be visited by this.context in callback.
  25566. */
  25567. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  25568. this._old = oldArr;
  25569. this._new = newArr;
  25570. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  25571. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  25572. this.context = context;
  25573. }
  25574. DataDiffer.prototype = {
  25575. constructor: DataDiffer,
  25576. /**
  25577. * Callback function when add a data
  25578. */
  25579. add: function (func) {
  25580. this._add = func;
  25581. return this;
  25582. },
  25583. /**
  25584. * Callback function when update a data
  25585. */
  25586. update: function (func) {
  25587. this._update = func;
  25588. return this;
  25589. },
  25590. /**
  25591. * Callback function when remove a data
  25592. */
  25593. remove: function (func) {
  25594. this._remove = func;
  25595. return this;
  25596. },
  25597. execute: function () {
  25598. var oldArr = this._old;
  25599. var newArr = this._new;
  25600. var oldDataIndexMap = {};
  25601. var newDataIndexMap = {};
  25602. var oldDataKeyArr = [];
  25603. var newDataKeyArr = [];
  25604. var i;
  25605. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  25606. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  25607. for (i = 0; i < oldArr.length; i++) {
  25608. var key = oldDataKeyArr[i];
  25609. var idx = newDataIndexMap[key];
  25610. // idx can never be empty array here. see 'set null' logic below.
  25611. if (idx != null) {
  25612. // Consider there is duplicate key (for example, use dataItem.name as key).
  25613. // We should make sure every item in newArr and oldArr can be visited.
  25614. var len = idx.length;
  25615. if (len) {
  25616. len === 1 && (newDataIndexMap[key] = null);
  25617. idx = idx.shift();
  25618. }
  25619. else {
  25620. newDataIndexMap[key] = null;
  25621. }
  25622. this._update && this._update(idx, i);
  25623. }
  25624. else {
  25625. this._remove && this._remove(i);
  25626. }
  25627. }
  25628. for (var i = 0; i < newDataKeyArr.length; i++) {
  25629. var key = newDataKeyArr[i];
  25630. if (newDataIndexMap.hasOwnProperty(key)) {
  25631. var idx = newDataIndexMap[key];
  25632. if (idx == null) {
  25633. continue;
  25634. }
  25635. // idx can never be empty array here. see 'set null' logic above.
  25636. if (!idx.length) {
  25637. this._add && this._add(idx);
  25638. }
  25639. else {
  25640. for (var j = 0, len = idx.length; j < len; j++) {
  25641. this._add && this._add(idx[j]);
  25642. }
  25643. }
  25644. }
  25645. }
  25646. }
  25647. };
  25648. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  25649. for (var i = 0; i < arr.length; i++) {
  25650. // Add prefix to avoid conflict with Object.prototype.
  25651. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  25652. var existence = map[key];
  25653. if (existence == null) {
  25654. keyArr.push(key);
  25655. map[key] = i;
  25656. }
  25657. else {
  25658. if (!existence.length) {
  25659. map[key] = existence = [existence];
  25660. }
  25661. existence.push(i);
  25662. }
  25663. }
  25664. }
  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. var OTHER_DIMENSIONS = createHashMap([
  25684. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  25685. ]);
  25686. function summarizeDimensions(data) {
  25687. var summary = {};
  25688. var encode = summary.encode = {};
  25689. var notExtraCoordDimMap = createHashMap();
  25690. var defaultedLabel = [];
  25691. var defaultedTooltip = [];
  25692. // See the comment of `List.js#userOutput`.
  25693. var userOutput = summary.userOutput = {
  25694. dimensionNames: data.dimensions.slice(),
  25695. encode: {}
  25696. };
  25697. each$1(data.dimensions, function (dimName) {
  25698. var dimItem = data.getDimensionInfo(dimName);
  25699. var coordDim = dimItem.coordDim;
  25700. if (coordDim) {
  25701. if (__DEV__) {
  25702. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  25703. }
  25704. var coordDimIndex = dimItem.coordDimIndex;
  25705. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  25706. if (!dimItem.isExtraCoord) {
  25707. notExtraCoordDimMap.set(coordDim, 1);
  25708. // Use the last coord dim (and label friendly) as default label,
  25709. // because when dataset is used, it is hard to guess which dimension
  25710. // can be value dimension. If both show x, y on label is not look good,
  25711. // and conventionally y axis is focused more.
  25712. if (mayLabelDimType(dimItem.type)) {
  25713. defaultedLabel[0] = dimName;
  25714. }
  25715. // User output encode do not contain generated coords.
  25716. // And it only has index. User can use index to retrieve value from the raw item array.
  25717. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  25718. }
  25719. if (dimItem.defaultTooltip) {
  25720. defaultedTooltip.push(dimName);
  25721. }
  25722. }
  25723. OTHER_DIMENSIONS.each(function (v, otherDim) {
  25724. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  25725. var dimIndex = dimItem.otherDims[otherDim];
  25726. if (dimIndex != null && dimIndex !== false) {
  25727. encodeArr[dimIndex] = dimItem.name;
  25728. }
  25729. });
  25730. });
  25731. var dataDimsOnCoord = [];
  25732. var encodeFirstDimNotExtra = {};
  25733. notExtraCoordDimMap.each(function (v, coordDim) {
  25734. var dimArr = encode[coordDim];
  25735. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  25736. // But should fix the case that radar axes: simplify the logic
  25737. // of `completeDimension`, remove `extraPrefix`.
  25738. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  25739. // Not necessary to remove duplicate, because a data
  25740. // dim canot on more than one coordDim.
  25741. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  25742. });
  25743. summary.dataDimsOnCoord = dataDimsOnCoord;
  25744. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  25745. var encodeLabel = encode.label;
  25746. // FIXME `encode.label` is not recommanded, because formatter can not be set
  25747. // in this way. Use label.formatter instead. May be remove this approach someday.
  25748. if (encodeLabel && encodeLabel.length) {
  25749. defaultedLabel = encodeLabel.slice();
  25750. }
  25751. var encodeTooltip = encode.tooltip;
  25752. if (encodeTooltip && encodeTooltip.length) {
  25753. defaultedTooltip = encodeTooltip.slice();
  25754. }
  25755. else if (!defaultedTooltip.length) {
  25756. defaultedTooltip = defaultedLabel.slice();
  25757. }
  25758. encode.defaultedLabel = defaultedLabel;
  25759. encode.defaultedTooltip = defaultedTooltip;
  25760. return summary;
  25761. }
  25762. function getOrCreateEncodeArr(encode, dim) {
  25763. if (!encode.hasOwnProperty(dim)) {
  25764. encode[dim] = [];
  25765. }
  25766. return encode[dim];
  25767. }
  25768. function getDimensionTypeByAxis(axisType) {
  25769. return axisType === 'category'
  25770. ? 'ordinal'
  25771. : axisType === 'time'
  25772. ? 'time'
  25773. : 'float';
  25774. }
  25775. function mayLabelDimType(dimType) {
  25776. // In most cases, ordinal and time do not suitable for label.
  25777. // Ordinal info can be displayed on axis. Time is too long.
  25778. return !(dimType === 'ordinal' || dimType === 'time');
  25779. }
  25780. // function findTheLastDimMayLabel(data) {
  25781. // // Get last value dim
  25782. // var dimensions = data.dimensions.slice();
  25783. // var valueType;
  25784. // var valueDim;
  25785. // while (dimensions.length && (
  25786. // valueDim = dimensions.pop(),
  25787. // valueType = data.getDimensionInfo(valueDim).type,
  25788. // valueType === 'ordinal' || valueType === 'time'
  25789. // )) {} // jshint ignore:line
  25790. // return valueDim;
  25791. // }
  25792. /*
  25793. * Licensed to the Apache Software Foundation (ASF) under one
  25794. * or more contributor license agreements. See the NOTICE file
  25795. * distributed with this work for additional information
  25796. * regarding copyright ownership. The ASF licenses this file
  25797. * to you under the Apache License, Version 2.0 (the
  25798. * "License"); you may not use this file except in compliance
  25799. * with the License. You may obtain a copy of the License at
  25800. *
  25801. * http://www.apache.org/licenses/LICENSE-2.0
  25802. *
  25803. * Unless required by applicable law or agreed to in writing,
  25804. * software distributed under the License is distributed on an
  25805. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25806. * KIND, either express or implied. See the License for the
  25807. * specific language governing permissions and limitations
  25808. * under the License.
  25809. */
  25810. /**
  25811. * @class
  25812. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  25813. */
  25814. function DataDimensionInfo(opt) {
  25815. if (opt != null) {
  25816. extend(this, opt);
  25817. }
  25818. /**
  25819. * Dimension name.
  25820. * Mandatory.
  25821. * @type {string}
  25822. */
  25823. // this.name;
  25824. /**
  25825. * The origin name in dimsDef, see source helper.
  25826. * If displayName given, the tooltip will displayed vertically.
  25827. * Optional.
  25828. * @type {string}
  25829. */
  25830. // this.displayName;
  25831. /**
  25832. * Which coordSys dimension this dimension mapped to.
  25833. * A `coordDim` can be a "coordSysDim" that the coordSys required
  25834. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  25835. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  25836. * (That is determined by whether `isExtraCoord` is `true`).
  25837. * Mandatory.
  25838. * @type {string}
  25839. */
  25840. // this.coordDim;
  25841. /**
  25842. * The index of this dimension in `series.encode[coordDim]`.
  25843. * Mandatory.
  25844. * @type {number}
  25845. */
  25846. // this.coordDimIndex;
  25847. /**
  25848. * Dimension type. The enumerable values are the key of
  25849. * `dataCtors` of `data/List`.
  25850. * Optional.
  25851. * @type {string}
  25852. */
  25853. // this.type;
  25854. /**
  25855. * This index of this dimension info in `data/List#_dimensionInfos`.
  25856. * Mandatory after added to `data/List`.
  25857. * @type {number}
  25858. */
  25859. // this.index;
  25860. /**
  25861. * The format of `otherDims` is:
  25862. * ```js
  25863. * {
  25864. * tooltip: number optional,
  25865. * label: number optional,
  25866. * itemName: number optional,
  25867. * seriesName: number optional,
  25868. * }
  25869. * ```
  25870. *
  25871. * A `series.encode` can specified these fields:
  25872. * ```js
  25873. * encode: {
  25874. * // "3, 1, 5" is the index of data dimension.
  25875. * tooltip: [3, 1, 5],
  25876. * label: [0, 3],
  25877. * ...
  25878. * }
  25879. * ```
  25880. * `otherDims` is the parse result of the `series.encode` above, like:
  25881. * ```js
  25882. * // Suppose the index of this data dimension is `3`.
  25883. * this.otherDims = {
  25884. * // `3` is at the index `0` of the `encode.tooltip`
  25885. * tooltip: 0,
  25886. * // `3` is at the index `1` of the `encode.tooltip`
  25887. * label: 1
  25888. * };
  25889. * ```
  25890. *
  25891. * This prop should never be `null`/`undefined` after initialized.
  25892. * @type {Object}
  25893. */
  25894. this.otherDims = {};
  25895. /**
  25896. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  25897. * "coordSys" required.
  25898. * Mandatory.
  25899. * @type {boolean}
  25900. */
  25901. // this.isExtraCoord;
  25902. /**
  25903. * @type {module:data/OrdinalMeta}
  25904. */
  25905. // this.ordinalMeta;
  25906. /**
  25907. * Whether to create inverted indices.
  25908. * @type {boolean}
  25909. */
  25910. // this.createInvertedIndices;
  25911. }
  25912. /*
  25913. * Licensed to the Apache Software Foundation (ASF) under one
  25914. * or more contributor license agreements. See the NOTICE file
  25915. * distributed with this work for additional information
  25916. * regarding copyright ownership. The ASF licenses this file
  25917. * to you under the Apache License, Version 2.0 (the
  25918. * "License"); you may not use this file except in compliance
  25919. * with the License. You may obtain a copy of the License at
  25920. *
  25921. * http://www.apache.org/licenses/LICENSE-2.0
  25922. *
  25923. * Unless required by applicable law or agreed to in writing,
  25924. * software distributed under the License is distributed on an
  25925. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25926. * KIND, either express or implied. See the License for the
  25927. * specific language governing permissions and limitations
  25928. * under the License.
  25929. */
  25930. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25931. /**
  25932. * List for data storage
  25933. * @module echarts/data/List
  25934. */
  25935. var isObject$4 = isObject$1;
  25936. var UNDEFINED = 'undefined';
  25937. var INDEX_NOT_FOUND = -1;
  25938. // Use prefix to avoid index to be the same as otherIdList[idx],
  25939. // which will cause weird udpate animation.
  25940. var ID_PREFIX = 'e\0\0';
  25941. var dataCtors = {
  25942. 'float': typeof Float64Array === UNDEFINED
  25943. ? Array : Float64Array,
  25944. 'int': typeof Int32Array === UNDEFINED
  25945. ? Array : Int32Array,
  25946. // Ordinal data type can be string or int
  25947. 'ordinal': Array,
  25948. 'number': Array,
  25949. 'time': Array
  25950. };
  25951. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25952. // different from the Ctor of typed array.
  25953. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25954. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25955. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25956. function getIndicesCtor(list) {
  25957. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25958. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25959. }
  25960. function cloneChunk(originalChunk) {
  25961. var Ctor = originalChunk.constructor;
  25962. // Only shallow clone is enough when Array.
  25963. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25964. }
  25965. var TRANSFERABLE_PROPERTIES = [
  25966. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25967. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25968. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25969. ];
  25970. var CLONE_PROPERTIES = [
  25971. '_extent', '_approximateExtent', '_rawExtent'
  25972. ];
  25973. function transferProperties(target, source) {
  25974. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25975. if (source.hasOwnProperty(propName)) {
  25976. target[propName] = source[propName];
  25977. }
  25978. });
  25979. target.__wrappedMethods = source.__wrappedMethods;
  25980. each$1(CLONE_PROPERTIES, function (propName) {
  25981. target[propName] = clone(source[propName]);
  25982. });
  25983. target._calculationInfo = extend(source._calculationInfo);
  25984. }
  25985. /**
  25986. * @constructor
  25987. * @alias module:echarts/data/List
  25988. *
  25989. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  25990. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25991. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25992. * @param {module:echarts/model/Model} hostModel
  25993. */
  25994. var List = function (dimensions, hostModel) {
  25995. dimensions = dimensions || ['x', 'y'];
  25996. var dimensionInfos = {};
  25997. var dimensionNames = [];
  25998. var invertedIndicesMap = {};
  25999. for (var i = 0; i < dimensions.length; i++) {
  26000. // Use the original dimensions[i], where other flag props may exists.
  26001. var dimensionInfo = dimensions[i];
  26002. if (isString(dimensionInfo)) {
  26003. dimensionInfo = new DataDimensionInfo({name: dimensionInfo});
  26004. }
  26005. else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  26006. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  26007. }
  26008. var dimensionName = dimensionInfo.name;
  26009. dimensionInfo.type = dimensionInfo.type || 'float';
  26010. if (!dimensionInfo.coordDim) {
  26011. dimensionInfo.coordDim = dimensionName;
  26012. dimensionInfo.coordDimIndex = 0;
  26013. }
  26014. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  26015. dimensionNames.push(dimensionName);
  26016. dimensionInfos[dimensionName] = dimensionInfo;
  26017. dimensionInfo.index = i;
  26018. if (dimensionInfo.createInvertedIndices) {
  26019. invertedIndicesMap[dimensionName] = [];
  26020. }
  26021. }
  26022. /**
  26023. * @readOnly
  26024. * @type {Array.<string>}
  26025. */
  26026. this.dimensions = dimensionNames;
  26027. /**
  26028. * Infomation of each data dimension, like data type.
  26029. * @type {Object}
  26030. */
  26031. this._dimensionInfos = dimensionInfos;
  26032. /**
  26033. * @type {module:echarts/model/Model}
  26034. */
  26035. this.hostModel = hostModel;
  26036. /**
  26037. * @type {module:echarts/model/Model}
  26038. */
  26039. this.dataType;
  26040. /**
  26041. * Indices stores the indices of data subset after filtered.
  26042. * This data subset will be used in chart.
  26043. * @type {Array.<number>}
  26044. * @readOnly
  26045. */
  26046. this._indices = null;
  26047. this._count = 0;
  26048. this._rawCount = 0;
  26049. /**
  26050. * Data storage
  26051. * @type {Object.<key, Array.<TypedArray|Array>>}
  26052. * @private
  26053. */
  26054. this._storage = {};
  26055. /**
  26056. * @type {Array.<string>}
  26057. */
  26058. this._nameList = [];
  26059. /**
  26060. * @type {Array.<string>}
  26061. */
  26062. this._idList = [];
  26063. /**
  26064. * Models of data option is stored sparse for optimizing memory cost
  26065. * @type {Array.<module:echarts/model/Model>}
  26066. * @private
  26067. */
  26068. this._optionModels = [];
  26069. /**
  26070. * Global visual properties after visual coding
  26071. * @type {Object}
  26072. * @private
  26073. */
  26074. this._visual = {};
  26075. /**
  26076. * Globel layout properties.
  26077. * @type {Object}
  26078. * @private
  26079. */
  26080. this._layout = {};
  26081. /**
  26082. * Item visual properties after visual coding
  26083. * @type {Array.<Object>}
  26084. * @private
  26085. */
  26086. this._itemVisuals = [];
  26087. /**
  26088. * Key: visual type, Value: boolean
  26089. * @type {Object}
  26090. * @readOnly
  26091. */
  26092. this.hasItemVisual = {};
  26093. /**
  26094. * Item layout properties after layout
  26095. * @type {Array.<Object>}
  26096. * @private
  26097. */
  26098. this._itemLayouts = [];
  26099. /**
  26100. * Graphic elemnents
  26101. * @type {Array.<module:zrender/Element>}
  26102. * @private
  26103. */
  26104. this._graphicEls = [];
  26105. /**
  26106. * Max size of each chunk.
  26107. * @type {number}
  26108. * @private
  26109. */
  26110. this._chunkSize = 1e5;
  26111. /**
  26112. * @type {number}
  26113. * @private
  26114. */
  26115. this._chunkCount = 0;
  26116. /**
  26117. * @type {Array.<Array|Object>}
  26118. * @private
  26119. */
  26120. this._rawData;
  26121. /**
  26122. * Raw extent will not be cloned, but only transfered.
  26123. * It will not be calculated util needed.
  26124. * key: dim,
  26125. * value: {end: number, extent: Array.<number>}
  26126. * @type {Object}
  26127. * @private
  26128. */
  26129. this._rawExtent = {};
  26130. /**
  26131. * @type {Object}
  26132. * @private
  26133. */
  26134. this._extent = {};
  26135. /**
  26136. * key: dim
  26137. * value: extent
  26138. * @type {Object}
  26139. * @private
  26140. */
  26141. this._approximateExtent = {};
  26142. /**
  26143. * Cache summary info for fast visit. See "dimensionHelper".
  26144. * @type {Object}
  26145. * @private
  26146. */
  26147. this._dimensionsSummary = summarizeDimensions(this);
  26148. /**
  26149. * @type {Object.<Array|TypedArray>}
  26150. * @private
  26151. */
  26152. this._invertedIndicesMap = invertedIndicesMap;
  26153. /**
  26154. * @type {Object}
  26155. * @private
  26156. */
  26157. this._calculationInfo = {};
  26158. /**
  26159. * User output info of this data.
  26160. * DO NOT use it in other places!
  26161. *
  26162. * When preparing user params for user callbacks, we have
  26163. * to clone these inner data structures to prevent users
  26164. * from modifying them to effect built-in logic. And for
  26165. * performance consideration we make this `userOutput` to
  26166. * avoid clone them too many times.
  26167. *
  26168. * @type {Object}
  26169. * @readOnly
  26170. */
  26171. this.userOutput = this._dimensionsSummary.userOutput;
  26172. };
  26173. var listProto = List.prototype;
  26174. listProto.type = 'list';
  26175. /**
  26176. * If each data item has it's own option
  26177. * @type {boolean}
  26178. */
  26179. listProto.hasItemOption = true;
  26180. /**
  26181. * The meanings of the input parameter `dim`:
  26182. *
  26183. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  26184. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  26185. * + If dim is a number-like string (e.g., `"1"`):
  26186. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  26187. * + If not, it will be converted to a number, which means the index of the dimension.
  26188. * (why? because of the backward compatbility. We have been tolerating number-like string in
  26189. * dimension setting, although now it seems that it is not a good idea.)
  26190. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  26191. * if no dimension name is defined as `"1"`.
  26192. * + If dim is a not-number-like string, it means the concrete dim name.
  26193. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  26194. * or customized in `dimensions` property of option like `"age"`.
  26195. *
  26196. * Get dimension name
  26197. * @param {string|number} dim See above.
  26198. * @return {string} Concrete dim name.
  26199. */
  26200. listProto.getDimension = function (dim) {
  26201. if (typeof dim === 'number'
  26202. // If being a number-like string but not being defined a dimension name.
  26203. || (!isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim))
  26204. ) {
  26205. dim = this.dimensions[dim];
  26206. }
  26207. return dim;
  26208. };
  26209. /**
  26210. * Get type and calculation info of particular dimension
  26211. * @param {string|number} dim
  26212. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  26213. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  26214. */
  26215. listProto.getDimensionInfo = function (dim) {
  26216. // Do not clone, because there may be categories in dimInfo.
  26217. return this._dimensionInfos[this.getDimension(dim)];
  26218. };
  26219. /**
  26220. * @return {Array.<string>} concrete dimension name list on coord.
  26221. */
  26222. listProto.getDimensionsOnCoord = function () {
  26223. return this._dimensionsSummary.dataDimsOnCoord.slice();
  26224. };
  26225. /**
  26226. * @param {string} coordDim
  26227. * @param {number} [idx] A coordDim may map to more than one data dim.
  26228. * If idx is `true`, return a array of all mapped dims.
  26229. * If idx is not specified, return the first dim not extra.
  26230. * @return {string|Array.<string>} concrete data dim.
  26231. * If idx is number, and not found, return null/undefined.
  26232. * If idx is `true`, and not found, return empty array (always return array).
  26233. */
  26234. listProto.mapDimension = function (coordDim, idx) {
  26235. var dimensionsSummary = this._dimensionsSummary;
  26236. if (idx == null) {
  26237. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  26238. }
  26239. var dims = dimensionsSummary.encode[coordDim];
  26240. return idx === true
  26241. // always return array if idx is `true`
  26242. ? (dims || []).slice()
  26243. : (dims && dims[idx]);
  26244. };
  26245. /**
  26246. * Initialize from data
  26247. * @param {Array.<Object|number|Array>} data source or data or data provider.
  26248. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  26249. * defualt label/tooltip.
  26250. * A name can be specified in encode.itemName,
  26251. * or dataItem.name (only for series option data),
  26252. * or provided in nameList from outside.
  26253. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  26254. */
  26255. listProto.initData = function (data, nameList, dimValueGetter) {
  26256. var notProvider = Source.isInstance(data) || isArrayLike(data);
  26257. if (notProvider) {
  26258. data = new DefaultDataProvider(data, this.dimensions.length);
  26259. }
  26260. if (__DEV__) {
  26261. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  26262. throw new Error('Inavlid data provider.');
  26263. }
  26264. }
  26265. this._rawData = data;
  26266. // Clear
  26267. this._storage = {};
  26268. this._indices = null;
  26269. this._nameList = nameList || [];
  26270. this._idList = [];
  26271. this._nameRepeatCount = {};
  26272. if (!dimValueGetter) {
  26273. this.hasItemOption = false;
  26274. }
  26275. /**
  26276. * @readOnly
  26277. */
  26278. this.defaultDimValueGetter = defaultDimValueGetters[
  26279. this._rawData.getSource().sourceFormat
  26280. ];
  26281. // Default dim value getter
  26282. this._dimValueGetter = dimValueGetter = dimValueGetter
  26283. || this.defaultDimValueGetter;
  26284. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  26285. // Reset raw extent.
  26286. this._rawExtent = {};
  26287. this._initDataFromProvider(0, data.count());
  26288. // If data has no item option.
  26289. if (data.pure) {
  26290. this.hasItemOption = false;
  26291. }
  26292. };
  26293. listProto.getProvider = function () {
  26294. return this._rawData;
  26295. };
  26296. /**
  26297. * Caution: Can be only called on raw data (before `this._indices` created).
  26298. */
  26299. listProto.appendData = function (data) {
  26300. if (__DEV__) {
  26301. assert$1(!this._indices, 'appendData can only be called on raw data.');
  26302. }
  26303. var rawData = this._rawData;
  26304. var start = this.count();
  26305. rawData.appendData(data);
  26306. var end = rawData.count();
  26307. if (!rawData.persistent) {
  26308. end += start;
  26309. }
  26310. this._initDataFromProvider(start, end);
  26311. };
  26312. /**
  26313. * Caution: Can be only called on raw data (before `this._indices` created).
  26314. * This method does not modify `rawData` (`dataProvider`), but only
  26315. * add values to storage.
  26316. *
  26317. * The final count will be increased by `Math.max(values.length, names.length)`.
  26318. *
  26319. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  26320. * [
  26321. * [12, 33, 44],
  26322. * [NaN, 43, 1],
  26323. * ['-', 'asdf', 0]
  26324. * ]
  26325. * Each item is exaclty cooresponding to a dimension.
  26326. * @param {Array.<string>} [names]
  26327. */
  26328. listProto.appendValues = function (values, names) {
  26329. var chunkSize = this._chunkSize;
  26330. var storage = this._storage;
  26331. var dimensions = this.dimensions;
  26332. var dimLen = dimensions.length;
  26333. var rawExtent = this._rawExtent;
  26334. var start = this.count();
  26335. var end = start + Math.max(values.length, names ? names.length : 0);
  26336. var originalChunkCount = this._chunkCount;
  26337. for (var i = 0; i < dimLen; i++) {
  26338. var dim = dimensions[i];
  26339. if (!rawExtent[dim]) {
  26340. rawExtent[dim] = getInitialExtent();
  26341. }
  26342. if (!storage[dim]) {
  26343. storage[dim] = [];
  26344. }
  26345. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  26346. this._chunkCount = storage[dim].length;
  26347. }
  26348. var emptyDataItem = new Array(dimLen);
  26349. for (var idx = start; idx < end; idx++) {
  26350. var sourceIdx = idx - start;
  26351. var chunkIndex = Math.floor(idx / chunkSize);
  26352. var chunkOffset = idx % chunkSize;
  26353. // Store the data by dimensions
  26354. for (var k = 0; k < dimLen; k++) {
  26355. var dim = dimensions[k];
  26356. var val = this._dimValueGetterArrayRows(
  26357. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  26358. );
  26359. storage[dim][chunkIndex][chunkOffset] = val;
  26360. var dimRawExtent = rawExtent[dim];
  26361. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26362. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26363. }
  26364. if (names) {
  26365. this._nameList[idx] = names[sourceIdx];
  26366. }
  26367. }
  26368. this._rawCount = this._count = end;
  26369. // Reset data extent
  26370. this._extent = {};
  26371. prepareInvertedIndex(this);
  26372. };
  26373. listProto._initDataFromProvider = function (start, end) {
  26374. // Optimize.
  26375. if (start >= end) {
  26376. return;
  26377. }
  26378. var chunkSize = this._chunkSize;
  26379. var rawData = this._rawData;
  26380. var storage = this._storage;
  26381. var dimensions = this.dimensions;
  26382. var dimLen = dimensions.length;
  26383. var dimensionInfoMap = this._dimensionInfos;
  26384. var nameList = this._nameList;
  26385. var idList = this._idList;
  26386. var rawExtent = this._rawExtent;
  26387. var nameRepeatCount = this._nameRepeatCount = {};
  26388. var nameDimIdx;
  26389. var originalChunkCount = this._chunkCount;
  26390. for (var i = 0; i < dimLen; i++) {
  26391. var dim = dimensions[i];
  26392. if (!rawExtent[dim]) {
  26393. rawExtent[dim] = getInitialExtent();
  26394. }
  26395. var dimInfo = dimensionInfoMap[dim];
  26396. if (dimInfo.otherDims.itemName === 0) {
  26397. nameDimIdx = this._nameDimIdx = i;
  26398. }
  26399. if (dimInfo.otherDims.itemId === 0) {
  26400. this._idDimIdx = i;
  26401. }
  26402. if (!storage[dim]) {
  26403. storage[dim] = [];
  26404. }
  26405. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  26406. this._chunkCount = storage[dim].length;
  26407. }
  26408. var dataItem = new Array(dimLen);
  26409. for (var idx = start; idx < end; idx++) {
  26410. // NOTICE: Try not to write things into dataItem
  26411. dataItem = rawData.getItem(idx, dataItem);
  26412. // Each data item is value
  26413. // [1, 2]
  26414. // 2
  26415. // Bar chart, line chart which uses category axis
  26416. // only gives the 'y' value. 'x' value is the indices of category
  26417. // Use a tempValue to normalize the value to be a (x, y) value
  26418. var chunkIndex = Math.floor(idx / chunkSize);
  26419. var chunkOffset = idx % chunkSize;
  26420. // Store the data by dimensions
  26421. for (var k = 0; k < dimLen; k++) {
  26422. var dim = dimensions[k];
  26423. var dimStorage = storage[dim][chunkIndex];
  26424. // PENDING NULL is empty or zero
  26425. var val = this._dimValueGetter(dataItem, dim, idx, k);
  26426. dimStorage[chunkOffset] = val;
  26427. var dimRawExtent = rawExtent[dim];
  26428. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  26429. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  26430. }
  26431. // ??? FIXME not check by pure but sourceFormat?
  26432. // TODO refactor these logic.
  26433. if (!rawData.pure) {
  26434. var name = nameList[idx];
  26435. if (dataItem && name == null) {
  26436. // If dataItem is {name: ...}, it has highest priority.
  26437. // That is appropriate for many common cases.
  26438. if (dataItem.name != null) {
  26439. // There is no other place to persistent dataItem.name,
  26440. // so save it to nameList.
  26441. nameList[idx] = name = dataItem.name;
  26442. }
  26443. else if (nameDimIdx != null) {
  26444. var nameDim = dimensions[nameDimIdx];
  26445. var nameDimChunk = storage[nameDim][chunkIndex];
  26446. if (nameDimChunk) {
  26447. name = nameDimChunk[chunkOffset];
  26448. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  26449. if (ordinalMeta && ordinalMeta.categories.length) {
  26450. name = ordinalMeta.categories[name];
  26451. }
  26452. }
  26453. }
  26454. }
  26455. // Try using the id in option
  26456. // id or name is used on dynamical data, mapping old and new items.
  26457. var id = dataItem == null ? null : dataItem.id;
  26458. if (id == null && name != null) {
  26459. // Use name as id and add counter to avoid same name
  26460. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  26461. id = name;
  26462. if (nameRepeatCount[name] > 0) {
  26463. id += '__ec__' + nameRepeatCount[name];
  26464. }
  26465. nameRepeatCount[name]++;
  26466. }
  26467. id != null && (idList[idx] = id);
  26468. }
  26469. }
  26470. if (!rawData.persistent && rawData.clean) {
  26471. // Clean unused data if data source is typed array.
  26472. rawData.clean();
  26473. }
  26474. this._rawCount = this._count = end;
  26475. // Reset data extent
  26476. this._extent = {};
  26477. prepareInvertedIndex(this);
  26478. };
  26479. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  26480. var DataCtor = dataCtors[dimInfo.type];
  26481. var lastChunkIndex = chunkCount - 1;
  26482. var dim = dimInfo.name;
  26483. var resizeChunkArray = storage[dim][lastChunkIndex];
  26484. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  26485. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  26486. // The cost of the copy is probably inconsiderable
  26487. // within the initial chunkSize.
  26488. for (var j = 0; j < resizeChunkArray.length; j++) {
  26489. newStore[j] = resizeChunkArray[j];
  26490. }
  26491. storage[dim][lastChunkIndex] = newStore;
  26492. }
  26493. // Create new chunks.
  26494. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  26495. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  26496. }
  26497. }
  26498. function prepareInvertedIndex(list) {
  26499. var invertedIndicesMap = list._invertedIndicesMap;
  26500. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  26501. var dimInfo = list._dimensionInfos[dim];
  26502. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  26503. var ordinalMeta = dimInfo.ordinalMeta;
  26504. if (ordinalMeta) {
  26505. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  26506. ordinalMeta.categories.length
  26507. );
  26508. // The default value of TypedArray is 0. To avoid miss
  26509. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  26510. for (var i = 0; i < invertedIndices.length; i++) {
  26511. invertedIndices[i] = INDEX_NOT_FOUND;
  26512. }
  26513. for (var i = 0; i < list._count; i++) {
  26514. // Only support the case that all values are distinct.
  26515. invertedIndices[list.get(dim, i)] = i;
  26516. }
  26517. }
  26518. });
  26519. }
  26520. function getRawValueFromStore(list, dimIndex, rawIndex) {
  26521. var val;
  26522. if (dimIndex != null) {
  26523. var chunkSize = list._chunkSize;
  26524. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26525. var chunkOffset = rawIndex % chunkSize;
  26526. var dim = list.dimensions[dimIndex];
  26527. var chunk = list._storage[dim][chunkIndex];
  26528. if (chunk) {
  26529. val = chunk[chunkOffset];
  26530. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  26531. if (ordinalMeta && ordinalMeta.categories.length) {
  26532. val = ordinalMeta.categories[val];
  26533. }
  26534. }
  26535. }
  26536. return val;
  26537. }
  26538. /**
  26539. * @return {number}
  26540. */
  26541. listProto.count = function () {
  26542. return this._count;
  26543. };
  26544. listProto.getIndices = function () {
  26545. var newIndices;
  26546. var indices = this._indices;
  26547. if (indices) {
  26548. var Ctor = indices.constructor;
  26549. var thisCount = this._count;
  26550. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  26551. if (Ctor === Array) {
  26552. newIndices = new Ctor(thisCount);
  26553. for (var i = 0; i < thisCount; i++) {
  26554. newIndices[i] = indices[i];
  26555. }
  26556. }
  26557. else {
  26558. newIndices = new Ctor(indices.buffer, 0, thisCount);
  26559. }
  26560. }
  26561. else {
  26562. var Ctor = getIndicesCtor(this);
  26563. var newIndices = new Ctor(this.count());
  26564. for (var i = 0; i < newIndices.length; i++) {
  26565. newIndices[i] = i;
  26566. }
  26567. }
  26568. return newIndices;
  26569. };
  26570. /**
  26571. * Get value. Return NaN if idx is out of range.
  26572. * @param {string} dim Dim must be concrete name.
  26573. * @param {number} idx
  26574. * @param {boolean} stack
  26575. * @return {number}
  26576. */
  26577. listProto.get = function (dim, idx /*, stack */) {
  26578. if (!(idx >= 0 && idx < this._count)) {
  26579. return NaN;
  26580. }
  26581. var storage = this._storage;
  26582. if (!storage[dim]) {
  26583. // TODO Warn ?
  26584. return NaN;
  26585. }
  26586. idx = this.getRawIndex(idx);
  26587. var chunkIndex = Math.floor(idx / this._chunkSize);
  26588. var chunkOffset = idx % this._chunkSize;
  26589. var chunkStore = storage[dim][chunkIndex];
  26590. var value = chunkStore[chunkOffset];
  26591. // FIXME ordinal data type is not stackable
  26592. // if (stack) {
  26593. // var dimensionInfo = this._dimensionInfos[dim];
  26594. // if (dimensionInfo && dimensionInfo.stackable) {
  26595. // var stackedOn = this.stackedOn;
  26596. // while (stackedOn) {
  26597. // // Get no stacked data of stacked on
  26598. // var stackedValue = stackedOn.get(dim, idx);
  26599. // // Considering positive stack, negative stack and empty data
  26600. // if ((value >= 0 && stackedValue > 0) // Positive stack
  26601. // || (value <= 0 && stackedValue < 0) // Negative stack
  26602. // ) {
  26603. // value += stackedValue;
  26604. // }
  26605. // stackedOn = stackedOn.stackedOn;
  26606. // }
  26607. // }
  26608. // }
  26609. return value;
  26610. };
  26611. /**
  26612. * @param {string} dim concrete dim
  26613. * @param {number} rawIndex
  26614. * @return {number|string}
  26615. */
  26616. listProto.getByRawIndex = function (dim, rawIdx) {
  26617. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  26618. return NaN;
  26619. }
  26620. var dimStore = this._storage[dim];
  26621. if (!dimStore) {
  26622. // TODO Warn ?
  26623. return NaN;
  26624. }
  26625. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26626. var chunkOffset = rawIdx % this._chunkSize;
  26627. var chunkStore = dimStore[chunkIndex];
  26628. return chunkStore[chunkOffset];
  26629. };
  26630. /**
  26631. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  26632. * Hack a much simpler _getFast
  26633. * @private
  26634. */
  26635. listProto._getFast = function (dim, rawIdx) {
  26636. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  26637. var chunkOffset = rawIdx % this._chunkSize;
  26638. var chunkStore = this._storage[dim][chunkIndex];
  26639. return chunkStore[chunkOffset];
  26640. };
  26641. /**
  26642. * Get value for multi dimensions.
  26643. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  26644. * @param {number} idx
  26645. * @return {number}
  26646. */
  26647. listProto.getValues = function (dimensions, idx /*, stack */) {
  26648. var values = [];
  26649. if (!isArray(dimensions)) {
  26650. // stack = idx;
  26651. idx = dimensions;
  26652. dimensions = this.dimensions;
  26653. }
  26654. for (var i = 0, len = dimensions.length; i < len; i++) {
  26655. values.push(this.get(dimensions[i], idx /*, stack */));
  26656. }
  26657. return values;
  26658. };
  26659. /**
  26660. * If value is NaN. Inlcuding '-'
  26661. * Only check the coord dimensions.
  26662. * @param {string} dim
  26663. * @param {number} idx
  26664. * @return {number}
  26665. */
  26666. listProto.hasValue = function (idx) {
  26667. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  26668. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  26669. // Ordinal type originally can be string or number.
  26670. // But when an ordinal type is used on coord, it can
  26671. // not be string but only number. So we can also use isNaN.
  26672. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  26673. return false;
  26674. }
  26675. }
  26676. return true;
  26677. };
  26678. /**
  26679. * Get extent of data in one dimension
  26680. * @param {string} dim
  26681. * @param {boolean} stack
  26682. */
  26683. listProto.getDataExtent = function (dim /*, stack */) {
  26684. // Make sure use concrete dim as cache name.
  26685. dim = this.getDimension(dim);
  26686. var dimData = this._storage[dim];
  26687. var initialExtent = getInitialExtent();
  26688. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  26689. if (!dimData) {
  26690. return initialExtent;
  26691. }
  26692. // Make more strict checkings to ensure hitting cache.
  26693. var currEnd = this.count();
  26694. // var cacheName = [dim, !!stack].join('_');
  26695. // var cacheName = dim;
  26696. // Consider the most cases when using data zoom, `getDataExtent`
  26697. // happened before filtering. We cache raw extent, which is not
  26698. // necessary to be cleared and recalculated when restore data.
  26699. var useRaw = !this._indices; // && !stack;
  26700. var dimExtent;
  26701. if (useRaw) {
  26702. return this._rawExtent[dim].slice();
  26703. }
  26704. dimExtent = this._extent[dim];
  26705. if (dimExtent) {
  26706. return dimExtent.slice();
  26707. }
  26708. dimExtent = initialExtent;
  26709. var min = dimExtent[0];
  26710. var max = dimExtent[1];
  26711. for (var i = 0; i < currEnd; i++) {
  26712. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  26713. var value = this._getFast(dim, this.getRawIndex(i));
  26714. value < min && (min = value);
  26715. value > max && (max = value);
  26716. }
  26717. dimExtent = [min, max];
  26718. this._extent[dim] = dimExtent;
  26719. return dimExtent;
  26720. };
  26721. /**
  26722. * Optimize for the scenario that data is filtered by a given extent.
  26723. * Consider that if data amount is more than hundreds of thousand,
  26724. * extent calculation will cost more than 10ms and the cache will
  26725. * be erased because of the filtering.
  26726. */
  26727. listProto.getApproximateExtent = function (dim /*, stack */) {
  26728. dim = this.getDimension(dim);
  26729. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  26730. };
  26731. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  26732. dim = this.getDimension(dim);
  26733. this._approximateExtent[dim] = extent.slice();
  26734. };
  26735. /**
  26736. * @param {string} key
  26737. * @return {*}
  26738. */
  26739. listProto.getCalculationInfo = function (key) {
  26740. return this._calculationInfo[key];
  26741. };
  26742. /**
  26743. * @param {string|Object} key or k-v object
  26744. * @param {*} [value]
  26745. */
  26746. listProto.setCalculationInfo = function (key, value) {
  26747. isObject$4(key)
  26748. ? extend(this._calculationInfo, key)
  26749. : (this._calculationInfo[key] = value);
  26750. };
  26751. /**
  26752. * Get sum of data in one dimension
  26753. * @param {string} dim
  26754. */
  26755. listProto.getSum = function (dim /*, stack */) {
  26756. var dimData = this._storage[dim];
  26757. var sum = 0;
  26758. if (dimData) {
  26759. for (var i = 0, len = this.count(); i < len; i++) {
  26760. var value = this.get(dim, i /*, stack */);
  26761. if (!isNaN(value)) {
  26762. sum += value;
  26763. }
  26764. }
  26765. }
  26766. return sum;
  26767. };
  26768. /**
  26769. * Get median of data in one dimension
  26770. * @param {string} dim
  26771. */
  26772. listProto.getMedian = function (dim /*, stack */) {
  26773. var dimDataArray = [];
  26774. // map all data of one dimension
  26775. this.each(dim, function (val, idx) {
  26776. if (!isNaN(val)) {
  26777. dimDataArray.push(val);
  26778. }
  26779. });
  26780. // TODO
  26781. // Use quick select?
  26782. // immutability & sort
  26783. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  26784. return a - b;
  26785. });
  26786. var len = this.count();
  26787. // calculate median
  26788. return len === 0
  26789. ? 0
  26790. : len % 2 === 1
  26791. ? sortedDimDataArray[(len - 1) / 2]
  26792. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  26793. };
  26794. // /**
  26795. // * Retreive the index with given value
  26796. // * @param {string} dim Concrete dimension.
  26797. // * @param {number} value
  26798. // * @return {number}
  26799. // */
  26800. // Currently incorrect: should return dataIndex but not rawIndex.
  26801. // Do not fix it until this method is to be used somewhere.
  26802. // FIXME Precision of float value
  26803. // listProto.indexOf = function (dim, value) {
  26804. // var storage = this._storage;
  26805. // var dimData = storage[dim];
  26806. // var chunkSize = this._chunkSize;
  26807. // if (dimData) {
  26808. // for (var i = 0, len = this.count(); i < len; i++) {
  26809. // var chunkIndex = Math.floor(i / chunkSize);
  26810. // var chunkOffset = i % chunkSize;
  26811. // if (dimData[chunkIndex][chunkOffset] === value) {
  26812. // return i;
  26813. // }
  26814. // }
  26815. // }
  26816. // return -1;
  26817. // };
  26818. /**
  26819. * Only support the dimension which inverted index created.
  26820. * Do not support other cases until required.
  26821. * @param {string} concrete dim
  26822. * @param {number|string} value
  26823. * @return {number} rawIndex
  26824. */
  26825. listProto.rawIndexOf = function (dim, value) {
  26826. var invertedIndices = dim && this._invertedIndicesMap[dim];
  26827. if (__DEV__) {
  26828. if (!invertedIndices) {
  26829. throw new Error('Do not supported yet');
  26830. }
  26831. }
  26832. var rawIndex = invertedIndices[value];
  26833. if (rawIndex == null || isNaN(rawIndex)) {
  26834. return INDEX_NOT_FOUND;
  26835. }
  26836. return rawIndex;
  26837. };
  26838. /**
  26839. * Retreive the index with given name
  26840. * @param {number} idx
  26841. * @param {number} name
  26842. * @return {number}
  26843. */
  26844. listProto.indexOfName = function (name) {
  26845. for (var i = 0, len = this.count(); i < len; i++) {
  26846. if (this.getName(i) === name) {
  26847. return i;
  26848. }
  26849. }
  26850. return -1;
  26851. };
  26852. /**
  26853. * Retreive the index with given raw data index
  26854. * @param {number} idx
  26855. * @param {number} name
  26856. * @return {number}
  26857. */
  26858. listProto.indexOfRawIndex = function (rawIndex) {
  26859. if (rawIndex >= this._rawCount || rawIndex < 0) {
  26860. return -1;
  26861. }
  26862. if (!this._indices) {
  26863. return rawIndex;
  26864. }
  26865. // Indices are ascending
  26866. var indices = this._indices;
  26867. // If rawIndex === dataIndex
  26868. var rawDataIndex = indices[rawIndex];
  26869. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  26870. return rawIndex;
  26871. }
  26872. var left = 0;
  26873. var right = this._count - 1;
  26874. while (left <= right) {
  26875. var mid = (left + right) / 2 | 0;
  26876. if (indices[mid] < rawIndex) {
  26877. left = mid + 1;
  26878. }
  26879. else if (indices[mid] > rawIndex) {
  26880. right = mid - 1;
  26881. }
  26882. else {
  26883. return mid;
  26884. }
  26885. }
  26886. return -1;
  26887. };
  26888. /**
  26889. * Retreive the index of nearest value
  26890. * @param {string} dim
  26891. * @param {number} value
  26892. * @param {number} [maxDistance=Infinity]
  26893. * @return {Array.<number>} If and only if multiple indices has
  26894. * the same value, they are put to the result.
  26895. */
  26896. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  26897. var storage = this._storage;
  26898. var dimData = storage[dim];
  26899. var nearestIndices = [];
  26900. if (!dimData) {
  26901. return nearestIndices;
  26902. }
  26903. if (maxDistance == null) {
  26904. maxDistance = Infinity;
  26905. }
  26906. var minDist = Infinity;
  26907. var minDiff = -1;
  26908. var nearestIndicesLen = 0;
  26909. // Check the test case of `test/ut/spec/data/List.js`.
  26910. for (var i = 0, len = this.count(); i < len; i++) {
  26911. var diff = value - this.get(dim, i);
  26912. var dist = Math.abs(diff);
  26913. if (dist <= maxDistance) {
  26914. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  26915. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  26916. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  26917. // So we chose the one that `diff >= 0` in this csae.
  26918. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  26919. // should be push to `nearestIndices`.
  26920. if (dist < minDist
  26921. || (dist === minDist && diff >= 0 && minDiff < 0)
  26922. ) {
  26923. minDist = dist;
  26924. minDiff = diff;
  26925. nearestIndicesLen = 0;
  26926. }
  26927. if (diff === minDiff) {
  26928. nearestIndices[nearestIndicesLen++] = i;
  26929. }
  26930. }
  26931. }
  26932. nearestIndices.length = nearestIndicesLen;
  26933. return nearestIndices;
  26934. };
  26935. /**
  26936. * Get raw data index
  26937. * @param {number} idx
  26938. * @return {number}
  26939. */
  26940. listProto.getRawIndex = getRawIndexWithoutIndices;
  26941. function getRawIndexWithoutIndices(idx) {
  26942. return idx;
  26943. }
  26944. function getRawIndexWithIndices(idx) {
  26945. if (idx < this._count && idx >= 0) {
  26946. return this._indices[idx];
  26947. }
  26948. return -1;
  26949. }
  26950. /**
  26951. * Get raw data item
  26952. * @param {number} idx
  26953. * @return {number}
  26954. */
  26955. listProto.getRawDataItem = function (idx) {
  26956. if (!this._rawData.persistent) {
  26957. var val = [];
  26958. for (var i = 0; i < this.dimensions.length; i++) {
  26959. var dim = this.dimensions[i];
  26960. val.push(this.get(dim, idx));
  26961. }
  26962. return val;
  26963. }
  26964. else {
  26965. return this._rawData.getItem(this.getRawIndex(idx));
  26966. }
  26967. };
  26968. /**
  26969. * @param {number} idx
  26970. * @param {boolean} [notDefaultIdx=false]
  26971. * @return {string}
  26972. */
  26973. listProto.getName = function (idx) {
  26974. var rawIndex = this.getRawIndex(idx);
  26975. return this._nameList[rawIndex]
  26976. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26977. || '';
  26978. };
  26979. /**
  26980. * @param {number} idx
  26981. * @param {boolean} [notDefaultIdx=false]
  26982. * @return {string}
  26983. */
  26984. listProto.getId = function (idx) {
  26985. return getId(this, this.getRawIndex(idx));
  26986. };
  26987. function getId(list, rawIndex) {
  26988. var id = list._idList[rawIndex];
  26989. if (id == null) {
  26990. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26991. }
  26992. if (id == null) {
  26993. // FIXME Check the usage in graph, should not use prefix.
  26994. id = ID_PREFIX + rawIndex;
  26995. }
  26996. return id;
  26997. }
  26998. function normalizeDimensions(dimensions) {
  26999. if (!isArray(dimensions)) {
  27000. dimensions = [dimensions];
  27001. }
  27002. return dimensions;
  27003. }
  27004. function validateDimensions(list, dims) {
  27005. for (var i = 0; i < dims.length; i++) {
  27006. // stroage may be empty when no data, so use
  27007. // dimensionInfos to check.
  27008. if (!list._dimensionInfos[dims[i]]) {
  27009. console.error('Unkown dimension ' + dims[i]);
  27010. }
  27011. }
  27012. }
  27013. /**
  27014. * Data iteration
  27015. * @param {string|Array.<string>}
  27016. * @param {Function} cb
  27017. * @param {*} [context=this]
  27018. *
  27019. * @example
  27020. * list.each('x', function (x, idx) {});
  27021. * list.each(['x', 'y'], function (x, y, idx) {});
  27022. * list.each(function (idx) {})
  27023. */
  27024. listProto.each = function (dims, cb, context, contextCompat) {
  27025. 'use strict';
  27026. if (!this._count) {
  27027. return;
  27028. }
  27029. if (typeof dims === 'function') {
  27030. contextCompat = context;
  27031. context = cb;
  27032. cb = dims;
  27033. dims = [];
  27034. }
  27035. // contextCompat just for compat echarts3
  27036. context = context || contextCompat || this;
  27037. dims = map(normalizeDimensions(dims), this.getDimension, this);
  27038. if (__DEV__) {
  27039. validateDimensions(this, dims);
  27040. }
  27041. var dimSize = dims.length;
  27042. for (var i = 0; i < this.count(); i++) {
  27043. // Simple optimization
  27044. switch (dimSize) {
  27045. case 0:
  27046. cb.call(context, i);
  27047. break;
  27048. case 1:
  27049. cb.call(context, this.get(dims[0], i), i);
  27050. break;
  27051. case 2:
  27052. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  27053. break;
  27054. default:
  27055. var k = 0;
  27056. var value = [];
  27057. for (; k < dimSize; k++) {
  27058. value[k] = this.get(dims[k], i);
  27059. }
  27060. // Index
  27061. value[k] = i;
  27062. cb.apply(context, value);
  27063. }
  27064. }
  27065. };
  27066. /**
  27067. * Data filter
  27068. * @param {string|Array.<string>}
  27069. * @param {Function} cb
  27070. * @param {*} [context=this]
  27071. */
  27072. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  27073. 'use strict';
  27074. if (!this._count) {
  27075. return;
  27076. }
  27077. if (typeof dimensions === 'function') {
  27078. contextCompat = context;
  27079. context = cb;
  27080. cb = dimensions;
  27081. dimensions = [];
  27082. }
  27083. // contextCompat just for compat echarts3
  27084. context = context || contextCompat || this;
  27085. dimensions = map(
  27086. normalizeDimensions(dimensions), this.getDimension, this
  27087. );
  27088. if (__DEV__) {
  27089. validateDimensions(this, dimensions);
  27090. }
  27091. var count = this.count();
  27092. var Ctor = getIndicesCtor(this);
  27093. var newIndices = new Ctor(count);
  27094. var value = [];
  27095. var dimSize = dimensions.length;
  27096. var offset = 0;
  27097. var dim0 = dimensions[0];
  27098. for (var i = 0; i < count; i++) {
  27099. var keep;
  27100. var rawIdx = this.getRawIndex(i);
  27101. // Simple optimization
  27102. if (dimSize === 0) {
  27103. keep = cb.call(context, i);
  27104. }
  27105. else if (dimSize === 1) {
  27106. var val = this._getFast(dim0, rawIdx);
  27107. keep = cb.call(context, val, i);
  27108. }
  27109. else {
  27110. for (var k = 0; k < dimSize; k++) {
  27111. value[k] = this._getFast(dim0, rawIdx);
  27112. }
  27113. value[k] = i;
  27114. keep = cb.apply(context, value);
  27115. }
  27116. if (keep) {
  27117. newIndices[offset++] = rawIdx;
  27118. }
  27119. }
  27120. // Set indices after filtered.
  27121. if (offset < count) {
  27122. this._indices = newIndices;
  27123. }
  27124. this._count = offset;
  27125. // Reset data extent
  27126. this._extent = {};
  27127. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27128. return this;
  27129. };
  27130. /**
  27131. * Select data in range. (For optimization of filter)
  27132. * (Manually inline code, support 5 million data filtering in data zoom.)
  27133. */
  27134. listProto.selectRange = function (range) {
  27135. 'use strict';
  27136. if (!this._count) {
  27137. return;
  27138. }
  27139. var dimensions = [];
  27140. for (var dim in range) {
  27141. if (range.hasOwnProperty(dim)) {
  27142. dimensions.push(dim);
  27143. }
  27144. }
  27145. if (__DEV__) {
  27146. validateDimensions(this, dimensions);
  27147. }
  27148. var dimSize = dimensions.length;
  27149. if (!dimSize) {
  27150. return;
  27151. }
  27152. var originalCount = this.count();
  27153. var Ctor = getIndicesCtor(this);
  27154. var newIndices = new Ctor(originalCount);
  27155. var offset = 0;
  27156. var dim0 = dimensions[0];
  27157. var min = range[dim0][0];
  27158. var max = range[dim0][1];
  27159. var quickFinished = false;
  27160. if (!this._indices) {
  27161. // Extreme optimization for common case. About 2x faster in chrome.
  27162. var idx = 0;
  27163. if (dimSize === 1) {
  27164. var dimStorage = this._storage[dimensions[0]];
  27165. for (var k = 0; k < this._chunkCount; k++) {
  27166. var chunkStorage = dimStorage[k];
  27167. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27168. for (var i = 0; i < len; i++) {
  27169. var val = chunkStorage[i];
  27170. // NaN will not be filtered. Consider the case, in line chart, empty
  27171. // value indicates the line should be broken. But for the case like
  27172. // scatter plot, a data item with empty value will not be rendered,
  27173. // but the axis extent may be effected if some other dim of the data
  27174. // item has value. Fortunately it is not a significant negative effect.
  27175. if (
  27176. (val >= min && val <= max) || isNaN(val)
  27177. ) {
  27178. newIndices[offset++] = idx;
  27179. }
  27180. idx++;
  27181. }
  27182. }
  27183. quickFinished = true;
  27184. }
  27185. else if (dimSize === 2) {
  27186. var dimStorage = this._storage[dim0];
  27187. var dimStorage2 = this._storage[dimensions[1]];
  27188. var min2 = range[dimensions[1]][0];
  27189. var max2 = range[dimensions[1]][1];
  27190. for (var k = 0; k < this._chunkCount; k++) {
  27191. var chunkStorage = dimStorage[k];
  27192. var chunkStorage2 = dimStorage2[k];
  27193. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  27194. for (var i = 0; i < len; i++) {
  27195. var val = chunkStorage[i];
  27196. var val2 = chunkStorage2[i];
  27197. // Do not filter NaN, see comment above.
  27198. if ((
  27199. (val >= min && val <= max) || isNaN(val)
  27200. )
  27201. && (
  27202. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  27203. )
  27204. ) {
  27205. newIndices[offset++] = idx;
  27206. }
  27207. idx++;
  27208. }
  27209. }
  27210. quickFinished = true;
  27211. }
  27212. }
  27213. if (!quickFinished) {
  27214. if (dimSize === 1) {
  27215. for (var i = 0; i < originalCount; i++) {
  27216. var rawIndex = this.getRawIndex(i);
  27217. var val = this._getFast(dim0, rawIndex);
  27218. // Do not filter NaN, see comment above.
  27219. if (
  27220. (val >= min && val <= max) || isNaN(val)
  27221. ) {
  27222. newIndices[offset++] = rawIndex;
  27223. }
  27224. }
  27225. }
  27226. else {
  27227. for (var i = 0; i < originalCount; i++) {
  27228. var keep = true;
  27229. var rawIndex = this.getRawIndex(i);
  27230. for (var k = 0; k < dimSize; k++) {
  27231. var dimk = dimensions[k];
  27232. var val = this._getFast(dim, rawIndex);
  27233. // Do not filter NaN, see comment above.
  27234. if (val < range[dimk][0] || val > range[dimk][1]) {
  27235. keep = false;
  27236. }
  27237. }
  27238. if (keep) {
  27239. newIndices[offset++] = this.getRawIndex(i);
  27240. }
  27241. }
  27242. }
  27243. }
  27244. // Set indices after filtered.
  27245. if (offset < originalCount) {
  27246. this._indices = newIndices;
  27247. }
  27248. this._count = offset;
  27249. // Reset data extent
  27250. this._extent = {};
  27251. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27252. return this;
  27253. };
  27254. /**
  27255. * Data mapping to a plain array
  27256. * @param {string|Array.<string>} [dimensions]
  27257. * @param {Function} cb
  27258. * @param {*} [context=this]
  27259. * @return {Array}
  27260. */
  27261. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  27262. 'use strict';
  27263. if (typeof dimensions === 'function') {
  27264. contextCompat = context;
  27265. context = cb;
  27266. cb = dimensions;
  27267. dimensions = [];
  27268. }
  27269. // contextCompat just for compat echarts3
  27270. context = context || contextCompat || this;
  27271. var result = [];
  27272. this.each(dimensions, function () {
  27273. result.push(cb && cb.apply(this, arguments));
  27274. }, context);
  27275. return result;
  27276. };
  27277. // Data in excludeDimensions is copied, otherwise transfered.
  27278. function cloneListForMapAndSample(original, excludeDimensions) {
  27279. var allDimensions = original.dimensions;
  27280. var list = new List(
  27281. map(allDimensions, original.getDimensionInfo, original),
  27282. original.hostModel
  27283. );
  27284. // FIXME If needs stackedOn, value may already been stacked
  27285. transferProperties(list, original);
  27286. var storage = list._storage = {};
  27287. var originalStorage = original._storage;
  27288. // Init storage
  27289. for (var i = 0; i < allDimensions.length; i++) {
  27290. var dim = allDimensions[i];
  27291. if (originalStorage[dim]) {
  27292. // Notice that we do not reset invertedIndicesMap here, becuase
  27293. // there is no scenario of mapping or sampling ordinal dimension.
  27294. if (indexOf(excludeDimensions, dim) >= 0) {
  27295. storage[dim] = cloneDimStore(originalStorage[dim]);
  27296. list._rawExtent[dim] = getInitialExtent();
  27297. list._extent[dim] = null;
  27298. }
  27299. else {
  27300. // Direct reference for other dimensions
  27301. storage[dim] = originalStorage[dim];
  27302. }
  27303. }
  27304. }
  27305. return list;
  27306. }
  27307. function cloneDimStore(originalDimStore) {
  27308. var newDimStore = new Array(originalDimStore.length);
  27309. for (var j = 0; j < originalDimStore.length; j++) {
  27310. newDimStore[j] = cloneChunk(originalDimStore[j]);
  27311. }
  27312. return newDimStore;
  27313. }
  27314. function getInitialExtent() {
  27315. return [Infinity, -Infinity];
  27316. }
  27317. /**
  27318. * Data mapping to a new List with given dimensions
  27319. * @param {string|Array.<string>} dimensions
  27320. * @param {Function} cb
  27321. * @param {*} [context=this]
  27322. * @return {Array}
  27323. */
  27324. listProto.map = function (dimensions, cb, context, contextCompat) {
  27325. 'use strict';
  27326. // contextCompat just for compat echarts3
  27327. context = context || contextCompat || this;
  27328. dimensions = map(
  27329. normalizeDimensions(dimensions), this.getDimension, this
  27330. );
  27331. if (__DEV__) {
  27332. validateDimensions(this, dimensions);
  27333. }
  27334. var list = cloneListForMapAndSample(this, dimensions);
  27335. // Following properties are all immutable.
  27336. // So we can reference to the same value
  27337. list._indices = this._indices;
  27338. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27339. var storage = list._storage;
  27340. var tmpRetValue = [];
  27341. var chunkSize = this._chunkSize;
  27342. var dimSize = dimensions.length;
  27343. var dataCount = this.count();
  27344. var values = [];
  27345. var rawExtent = list._rawExtent;
  27346. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  27347. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  27348. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  27349. }
  27350. values[dimSize] = dataIndex;
  27351. var retValue = cb && cb.apply(context, values);
  27352. if (retValue != null) {
  27353. // a number or string (in oridinal dimension)?
  27354. if (typeof retValue !== 'object') {
  27355. tmpRetValue[0] = retValue;
  27356. retValue = tmpRetValue;
  27357. }
  27358. var rawIndex = this.getRawIndex(dataIndex);
  27359. var chunkIndex = Math.floor(rawIndex / chunkSize);
  27360. var chunkOffset = rawIndex % chunkSize;
  27361. for (var i = 0; i < retValue.length; i++) {
  27362. var dim = dimensions[i];
  27363. var val = retValue[i];
  27364. var rawExtentOnDim = rawExtent[dim];
  27365. var dimStore = storage[dim];
  27366. if (dimStore) {
  27367. dimStore[chunkIndex][chunkOffset] = val;
  27368. }
  27369. if (val < rawExtentOnDim[0]) {
  27370. rawExtentOnDim[0] = val;
  27371. }
  27372. if (val > rawExtentOnDim[1]) {
  27373. rawExtentOnDim[1] = val;
  27374. }
  27375. }
  27376. }
  27377. }
  27378. return list;
  27379. };
  27380. /**
  27381. * Large data down sampling on given dimension
  27382. * @param {string} dimension
  27383. * @param {number} rate
  27384. * @param {Function} sampleValue
  27385. * @param {Function} sampleIndex Sample index for name and id
  27386. */
  27387. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  27388. var list = cloneListForMapAndSample(this, [dimension]);
  27389. var targetStorage = list._storage;
  27390. var frameValues = [];
  27391. var frameSize = Math.floor(1 / rate);
  27392. var dimStore = targetStorage[dimension];
  27393. var len = this.count();
  27394. var chunkSize = this._chunkSize;
  27395. var rawExtentOnDim = list._rawExtent[dimension];
  27396. var newIndices = new (getIndicesCtor(this))(len);
  27397. var offset = 0;
  27398. for (var i = 0; i < len; i += frameSize) {
  27399. // Last frame
  27400. if (frameSize > len - i) {
  27401. frameSize = len - i;
  27402. frameValues.length = frameSize;
  27403. }
  27404. for (var k = 0; k < frameSize; k++) {
  27405. var dataIdx = this.getRawIndex(i + k);
  27406. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  27407. var originalChunkOffset = dataIdx % chunkSize;
  27408. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  27409. }
  27410. var value = sampleValue(frameValues);
  27411. var sampleFrameIdx = this.getRawIndex(
  27412. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  27413. );
  27414. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  27415. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  27416. // Only write value on the filtered data
  27417. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  27418. if (value < rawExtentOnDim[0]) {
  27419. rawExtentOnDim[0] = value;
  27420. }
  27421. if (value > rawExtentOnDim[1]) {
  27422. rawExtentOnDim[1] = value;
  27423. }
  27424. newIndices[offset++] = sampleFrameIdx;
  27425. }
  27426. list._count = offset;
  27427. list._indices = newIndices;
  27428. list.getRawIndex = getRawIndexWithIndices;
  27429. return list;
  27430. };
  27431. /**
  27432. * Get model of one data item.
  27433. *
  27434. * @param {number} idx
  27435. */
  27436. // FIXME Model proxy ?
  27437. listProto.getItemModel = function (idx) {
  27438. var hostModel = this.hostModel;
  27439. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  27440. };
  27441. /**
  27442. * Create a data differ
  27443. * @param {module:echarts/data/List} otherList
  27444. * @return {module:echarts/data/DataDiffer}
  27445. */
  27446. listProto.diff = function (otherList) {
  27447. var thisList = this;
  27448. return new DataDiffer(
  27449. otherList ? otherList.getIndices() : [],
  27450. this.getIndices(),
  27451. function (idx) {
  27452. return getId(otherList, idx);
  27453. },
  27454. function (idx) {
  27455. return getId(thisList, idx);
  27456. }
  27457. );
  27458. };
  27459. /**
  27460. * Get visual property.
  27461. * @param {string} key
  27462. */
  27463. listProto.getVisual = function (key) {
  27464. var visual = this._visual;
  27465. return visual && visual[key];
  27466. };
  27467. /**
  27468. * Set visual property
  27469. * @param {string|Object} key
  27470. * @param {*} [value]
  27471. *
  27472. * @example
  27473. * setVisual('color', color);
  27474. * setVisual({
  27475. * 'color': color
  27476. * });
  27477. */
  27478. listProto.setVisual = function (key, val) {
  27479. if (isObject$4(key)) {
  27480. for (var name in key) {
  27481. if (key.hasOwnProperty(name)) {
  27482. this.setVisual(name, key[name]);
  27483. }
  27484. }
  27485. return;
  27486. }
  27487. this._visual = this._visual || {};
  27488. this._visual[key] = val;
  27489. };
  27490. /**
  27491. * Set layout property.
  27492. * @param {string|Object} key
  27493. * @param {*} [val]
  27494. */
  27495. listProto.setLayout = function (key, val) {
  27496. if (isObject$4(key)) {
  27497. for (var name in key) {
  27498. if (key.hasOwnProperty(name)) {
  27499. this.setLayout(name, key[name]);
  27500. }
  27501. }
  27502. return;
  27503. }
  27504. this._layout[key] = val;
  27505. };
  27506. /**
  27507. * Get layout property.
  27508. * @param {string} key.
  27509. * @return {*}
  27510. */
  27511. listProto.getLayout = function (key) {
  27512. return this._layout[key];
  27513. };
  27514. /**
  27515. * Get layout of single data item
  27516. * @param {number} idx
  27517. */
  27518. listProto.getItemLayout = function (idx) {
  27519. return this._itemLayouts[idx];
  27520. };
  27521. /**
  27522. * Set layout of single data item
  27523. * @param {number} idx
  27524. * @param {Object} layout
  27525. * @param {boolean=} [merge=false]
  27526. */
  27527. listProto.setItemLayout = function (idx, layout, merge$$1) {
  27528. this._itemLayouts[idx] = merge$$1
  27529. ? extend(this._itemLayouts[idx] || {}, layout)
  27530. : layout;
  27531. };
  27532. /**
  27533. * Clear all layout of single data item
  27534. */
  27535. listProto.clearItemLayouts = function () {
  27536. this._itemLayouts.length = 0;
  27537. };
  27538. /**
  27539. * Get visual property of single data item
  27540. * @param {number} idx
  27541. * @param {string} key
  27542. * @param {boolean} [ignoreParent=false]
  27543. */
  27544. listProto.getItemVisual = function (idx, key, ignoreParent) {
  27545. var itemVisual = this._itemVisuals[idx];
  27546. var val = itemVisual && itemVisual[key];
  27547. if (val == null && !ignoreParent) {
  27548. // Use global visual property
  27549. return this.getVisual(key);
  27550. }
  27551. return val;
  27552. };
  27553. /**
  27554. * Set visual property of single data item
  27555. *
  27556. * @param {number} idx
  27557. * @param {string|Object} key
  27558. * @param {*} [value]
  27559. *
  27560. * @example
  27561. * setItemVisual(0, 'color', color);
  27562. * setItemVisual(0, {
  27563. * 'color': color
  27564. * });
  27565. */
  27566. listProto.setItemVisual = function (idx, key, value) {
  27567. var itemVisual = this._itemVisuals[idx] || {};
  27568. var hasItemVisual = this.hasItemVisual;
  27569. this._itemVisuals[idx] = itemVisual;
  27570. if (isObject$4(key)) {
  27571. for (var name in key) {
  27572. if (key.hasOwnProperty(name)) {
  27573. itemVisual[name] = key[name];
  27574. hasItemVisual[name] = true;
  27575. }
  27576. }
  27577. return;
  27578. }
  27579. itemVisual[key] = value;
  27580. hasItemVisual[key] = true;
  27581. };
  27582. /**
  27583. * Clear itemVisuals and list visual.
  27584. */
  27585. listProto.clearAllVisual = function () {
  27586. this._visual = {};
  27587. this._itemVisuals = [];
  27588. this.hasItemVisual = {};
  27589. };
  27590. var setItemDataAndSeriesIndex = function (child) {
  27591. child.seriesIndex = this.seriesIndex;
  27592. child.dataIndex = this.dataIndex;
  27593. child.dataType = this.dataType;
  27594. };
  27595. /**
  27596. * Set graphic element relative to data. It can be set as null
  27597. * @param {number} idx
  27598. * @param {module:zrender/Element} [el]
  27599. */
  27600. listProto.setItemGraphicEl = function (idx, el) {
  27601. var hostModel = this.hostModel;
  27602. if (el) {
  27603. // Add data index and series index for indexing the data by element
  27604. // Useful in tooltip
  27605. el.dataIndex = idx;
  27606. el.dataType = this.dataType;
  27607. el.seriesIndex = hostModel && hostModel.seriesIndex;
  27608. if (el.type === 'group') {
  27609. el.traverse(setItemDataAndSeriesIndex, el);
  27610. }
  27611. }
  27612. this._graphicEls[idx] = el;
  27613. };
  27614. /**
  27615. * @param {number} idx
  27616. * @return {module:zrender/Element}
  27617. */
  27618. listProto.getItemGraphicEl = function (idx) {
  27619. return this._graphicEls[idx];
  27620. };
  27621. /**
  27622. * @param {Function} cb
  27623. * @param {*} context
  27624. */
  27625. listProto.eachItemGraphicEl = function (cb, context) {
  27626. each$1(this._graphicEls, function (el, idx) {
  27627. if (el) {
  27628. cb && cb.call(context, el, idx);
  27629. }
  27630. });
  27631. };
  27632. /**
  27633. * Shallow clone a new list except visual and layout properties, and graph elements.
  27634. * New list only change the indices.
  27635. */
  27636. listProto.cloneShallow = function (list) {
  27637. if (!list) {
  27638. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  27639. list = new List(dimensionInfoList, this.hostModel);
  27640. }
  27641. // FIXME
  27642. list._storage = this._storage;
  27643. transferProperties(list, this);
  27644. // Clone will not change the data extent and indices
  27645. if (this._indices) {
  27646. var Ctor = this._indices.constructor;
  27647. list._indices = new Ctor(this._indices);
  27648. }
  27649. else {
  27650. list._indices = null;
  27651. }
  27652. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  27653. return list;
  27654. };
  27655. /**
  27656. * Wrap some method to add more feature
  27657. * @param {string} methodName
  27658. * @param {Function} injectFunction
  27659. */
  27660. listProto.wrapMethod = function (methodName, injectFunction) {
  27661. var originalMethod = this[methodName];
  27662. if (typeof originalMethod !== 'function') {
  27663. return;
  27664. }
  27665. this.__wrappedMethods = this.__wrappedMethods || [];
  27666. this.__wrappedMethods.push(methodName);
  27667. this[methodName] = function () {
  27668. var res = originalMethod.apply(this, arguments);
  27669. return injectFunction.apply(this, [res].concat(slice(arguments)));
  27670. };
  27671. };
  27672. // Methods that create a new list based on this list should be listed here.
  27673. // Notice that those method should `RETURN` the new list.
  27674. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  27675. // Methods that change indices of this list should be listed here.
  27676. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27677. /*
  27678. * Licensed to the Apache Software Foundation (ASF) under one
  27679. * or more contributor license agreements. See the NOTICE file
  27680. * distributed with this work for additional information
  27681. * regarding copyright ownership. The ASF licenses this file
  27682. * to you under the Apache License, Version 2.0 (the
  27683. * "License"); you may not use this file except in compliance
  27684. * with the License. You may obtain a copy of the License at
  27685. *
  27686. * http://www.apache.org/licenses/LICENSE-2.0
  27687. *
  27688. * Unless required by applicable law or agreed to in writing,
  27689. * software distributed under the License is distributed on an
  27690. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27691. * KIND, either express or implied. See the License for the
  27692. * specific language governing permissions and limitations
  27693. * under the License.
  27694. */
  27695. /**
  27696. * @deprecated
  27697. * Use `echarts/data/helper/createDimensions` instead.
  27698. */
  27699. /**
  27700. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  27701. *
  27702. * This method builds the relationship between:
  27703. * + "what the coord sys or series requires (see `sysDims`)",
  27704. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  27705. * + "what the data source provids (see `source`)".
  27706. *
  27707. * Some guess strategy will be adapted if user does not define something.
  27708. * If no 'value' dimension specified, the first no-named dimension will be
  27709. * named as 'value'.
  27710. *
  27711. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  27712. * provides not only dim template, but also default order.
  27713. * properties: 'name', 'type', 'displayName'.
  27714. * `name` of each item provides default coord name.
  27715. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  27716. * provide dims count that the sysDim required.
  27717. * [{ordinalMeta}] can be specified.
  27718. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  27719. * @param {Object} [opt]
  27720. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  27721. * For example: ['asdf', {name, type}, ...].
  27722. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  27723. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  27724. * If not specified, auto find the next available data dim.
  27725. * param source {module:data/Source}
  27726. * param dimCount {number}
  27727. * return {Object} encode Never be `null/undefined`.
  27728. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  27729. * If not specified, extra dim names will be:
  27730. * 'value', 'value0', 'value1', ...
  27731. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  27732. * If `generateCoordCount` specified, the generated dim names will be:
  27733. * `generateCoord` + 0, `generateCoord` + 1, ...
  27734. * can be Infinity, indicate that use all of the remain columns.
  27735. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  27736. * @return {Array.<module:data/DataDimensionInfo>}
  27737. */
  27738. function completeDimensions(sysDims, source, opt) {
  27739. if (!Source.isInstance(source)) {
  27740. source = Source.seriesDataToSource(source);
  27741. }
  27742. opt = opt || {};
  27743. sysDims = (sysDims || []).slice();
  27744. var dimsDef = (opt.dimsDef || []).slice();
  27745. var dataDimNameMap = createHashMap();
  27746. var coordDimNameMap = createHashMap();
  27747. // var valueCandidate;
  27748. var result = [];
  27749. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  27750. // Apply user defined dims (`name` and `type`) and init result.
  27751. for (var i = 0; i < dimCount; i++) {
  27752. var dimDefItem = dimsDef[i] = extend(
  27753. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  27754. );
  27755. var userDimName = dimDefItem.name;
  27756. var resultItem = result[i] = new DataDimensionInfo();
  27757. // Name will be applied later for avoiding duplication.
  27758. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  27759. // Only if `series.dimensions` is defined in option
  27760. // displayName, will be set, and dimension will be diplayed vertically in
  27761. // tooltip by default.
  27762. resultItem.name = resultItem.displayName = userDimName;
  27763. dataDimNameMap.set(userDimName, i);
  27764. }
  27765. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  27766. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  27767. }
  27768. var encodeDef = opt.encodeDef;
  27769. if (!encodeDef && opt.encodeDefaulter) {
  27770. encodeDef = opt.encodeDefaulter(source, dimCount);
  27771. }
  27772. encodeDef = createHashMap(encodeDef);
  27773. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  27774. encodeDef.each(function (dataDims, coordDim) {
  27775. dataDims = normalizeToArray(dataDims).slice();
  27776. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  27777. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  27778. // this case.
  27779. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  27780. encodeDef.set(coordDim, false);
  27781. return;
  27782. }
  27783. var validDataDims = encodeDef.set(coordDim, []);
  27784. each$1(dataDims, function (resultDimIdx, idx) {
  27785. // The input resultDimIdx can be dim name or index.
  27786. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  27787. if (resultDimIdx != null && resultDimIdx < dimCount) {
  27788. validDataDims[idx] = resultDimIdx;
  27789. applyDim(result[resultDimIdx], coordDim, idx);
  27790. }
  27791. });
  27792. });
  27793. // Apply templetes and default order from `sysDims`.
  27794. var availDimIdx = 0;
  27795. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  27796. var coordDim;
  27797. var sysDimItem;
  27798. var sysDimItemDimsDef;
  27799. var sysDimItemOtherDims;
  27800. if (isString(sysDimItem)) {
  27801. coordDim = sysDimItem;
  27802. sysDimItem = {};
  27803. }
  27804. else {
  27805. coordDim = sysDimItem.name;
  27806. var ordinalMeta = sysDimItem.ordinalMeta;
  27807. sysDimItem.ordinalMeta = null;
  27808. sysDimItem = clone(sysDimItem);
  27809. sysDimItem.ordinalMeta = ordinalMeta;
  27810. // `coordDimIndex` should not be set directly.
  27811. sysDimItemDimsDef = sysDimItem.dimsDef;
  27812. sysDimItemOtherDims = sysDimItem.otherDims;
  27813. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex =
  27814. sysDimItem.dimsDef = sysDimItem.otherDims = null;
  27815. }
  27816. var dataDims = encodeDef.get(coordDim);
  27817. // negative resultDimIdx means no need to mapping.
  27818. if (dataDims === false) {
  27819. return;
  27820. }
  27821. var dataDims = normalizeToArray(dataDims);
  27822. // dimensions provides default dim sequences.
  27823. if (!dataDims.length) {
  27824. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  27825. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  27826. availDimIdx++;
  27827. }
  27828. availDimIdx < result.length && dataDims.push(availDimIdx++);
  27829. }
  27830. }
  27831. // Apply templates.
  27832. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  27833. var resultItem = result[resultDimIdx];
  27834. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  27835. if (resultItem.name == null && sysDimItemDimsDef) {
  27836. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  27837. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  27838. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  27839. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  27840. }
  27841. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  27842. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  27843. });
  27844. });
  27845. function applyDim(resultItem, coordDim, coordDimIndex) {
  27846. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  27847. resultItem.otherDims[coordDim] = coordDimIndex;
  27848. }
  27849. else {
  27850. resultItem.coordDim = coordDim;
  27851. resultItem.coordDimIndex = coordDimIndex;
  27852. coordDimNameMap.set(coordDim, true);
  27853. }
  27854. }
  27855. // Make sure the first extra dim is 'value'.
  27856. var generateCoord = opt.generateCoord;
  27857. var generateCoordCount = opt.generateCoordCount;
  27858. var fromZero = generateCoordCount != null;
  27859. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  27860. var extra = generateCoord || 'value';
  27861. // Set dim `name` and other `coordDim` and other props.
  27862. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  27863. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  27864. var coordDim = resultItem.coordDim;
  27865. if (coordDim == null) {
  27866. resultItem.coordDim = genName(
  27867. extra, coordDimNameMap, fromZero
  27868. );
  27869. resultItem.coordDimIndex = 0;
  27870. if (!generateCoord || generateCoordCount <= 0) {
  27871. resultItem.isExtraCoord = true;
  27872. }
  27873. generateCoordCount--;
  27874. }
  27875. resultItem.name == null && (resultItem.name = genName(
  27876. resultItem.coordDim,
  27877. dataDimNameMap
  27878. ));
  27879. if (resultItem.type == null
  27880. && (
  27881. guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must
  27882. // Consider the case:
  27883. // {
  27884. // dataset: {source: [
  27885. // ['2001', 123],
  27886. // ['2002', 456],
  27887. // ...
  27888. // ['The others', 987],
  27889. // ]},
  27890. // series: {type: 'pie'}
  27891. // }
  27892. // The first colum should better be treated as a "ordinal" although it
  27893. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  27894. || (resultItem.isExtraCoord
  27895. && (resultItem.otherDims.itemName != null
  27896. || resultItem.otherDims.seriesName != null
  27897. )
  27898. )
  27899. )
  27900. ) {
  27901. resultItem.type = 'ordinal';
  27902. }
  27903. }
  27904. return result;
  27905. }
  27906. // ??? TODO
  27907. // Originally detect dimCount by data[0]. Should we
  27908. // optimize it to only by sysDims and dimensions and encode.
  27909. // So only necessary dims will be initialized.
  27910. // But
  27911. // (1) custom series should be considered. where other dims
  27912. // may be visited.
  27913. // (2) sometimes user need to calcualte bubble size or use visualMap
  27914. // on other dimensions besides coordSys needed.
  27915. // So, dims that is not used by system, should be shared in storage?
  27916. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  27917. // Note that the result dimCount should not small than columns count
  27918. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  27919. var dimCount = Math.max(
  27920. source.dimensionsDetectCount || 1,
  27921. sysDims.length,
  27922. dimsDef.length,
  27923. optDimCount || 0
  27924. );
  27925. each$1(sysDims, function (sysDimItem) {
  27926. var sysDimItemDimsDef = sysDimItem.dimsDef;
  27927. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  27928. });
  27929. return dimCount;
  27930. }
  27931. function genName(name, map$$1, fromZero) {
  27932. if (fromZero || map$$1.get(name) != null) {
  27933. var i = 0;
  27934. while (map$$1.get(name + i) != null) {
  27935. i++;
  27936. }
  27937. name += i;
  27938. }
  27939. map$$1.set(name, true);
  27940. return name;
  27941. }
  27942. /*
  27943. * Licensed to the Apache Software Foundation (ASF) under one
  27944. * or more contributor license agreements. See the NOTICE file
  27945. * distributed with this work for additional information
  27946. * regarding copyright ownership. The ASF licenses this file
  27947. * to you under the Apache License, Version 2.0 (the
  27948. * "License"); you may not use this file except in compliance
  27949. * with the License. You may obtain a copy of the License at
  27950. *
  27951. * http://www.apache.org/licenses/LICENSE-2.0
  27952. *
  27953. * Unless required by applicable law or agreed to in writing,
  27954. * software distributed under the License is distributed on an
  27955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27956. * KIND, either express or implied. See the License for the
  27957. * specific language governing permissions and limitations
  27958. * under the License.
  27959. */
  27960. /**
  27961. * Substitute `completeDimensions`.
  27962. * `completeDimensions` is to be deprecated.
  27963. */
  27964. /**
  27965. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  27966. * @param {Object|Array} [opt]
  27967. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  27968. * @param {number} [opt.dimensionsCount]
  27969. * @param {string} [opt.generateCoord]
  27970. * @param {string} [opt.generateCoordCount]
  27971. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  27972. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  27973. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  27974. * @return {Array.<Object>} dimensionsInfo
  27975. */
  27976. var createDimensions = function (source, opt) {
  27977. opt = opt || {};
  27978. return completeDimensions(opt.coordDimensions || [], source, {
  27979. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  27980. encodeDef: opt.encodeDefine || source.encodeDefine,
  27981. dimCount: opt.dimensionsCount,
  27982. encodeDefaulter: opt.encodeDefaulter,
  27983. generateCoord: opt.generateCoord,
  27984. generateCoordCount: opt.generateCoordCount
  27985. });
  27986. };
  27987. /*
  27988. * Licensed to the Apache Software Foundation (ASF) under one
  27989. * or more contributor license agreements. See the NOTICE file
  27990. * distributed with this work for additional information
  27991. * regarding copyright ownership. The ASF licenses this file
  27992. * to you under the Apache License, Version 2.0 (the
  27993. * "License"); you may not use this file except in compliance
  27994. * with the License. You may obtain a copy of the License at
  27995. *
  27996. * http://www.apache.org/licenses/LICENSE-2.0
  27997. *
  27998. * Unless required by applicable law or agreed to in writing,
  27999. * software distributed under the License is distributed on an
  28000. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28001. * KIND, either express or implied. See the License for the
  28002. * specific language governing permissions and limitations
  28003. * under the License.
  28004. */
  28005. /**
  28006. * Helper for model references.
  28007. * There are many manners to refer axis/coordSys.
  28008. */
  28009. // TODO
  28010. // merge relevant logic to this file?
  28011. // check: "modelHelper" of tooltip and "BrushTargetManager".
  28012. /**
  28013. * @class
  28014. * For example:
  28015. * {
  28016. * coordSysName: 'cartesian2d',
  28017. * coordSysDims: ['x', 'y', ...],
  28018. * axisMap: HashMap({
  28019. * x: xAxisModel,
  28020. * y: yAxisModel
  28021. * }),
  28022. * categoryAxisMap: HashMap({
  28023. * x: xAxisModel,
  28024. * y: undefined
  28025. * }),
  28026. * // The index of the first category axis in `coordSysDims`.
  28027. * // `null/undefined` means no category axis exists.
  28028. * firstCategoryDimIndex: 1,
  28029. * // To replace user specified encode.
  28030. * }
  28031. */
  28032. function CoordSysInfo(coordSysName) {
  28033. /**
  28034. * @type {string}
  28035. */
  28036. this.coordSysName = coordSysName;
  28037. /**
  28038. * @type {Array.<string>}
  28039. */
  28040. this.coordSysDims = [];
  28041. /**
  28042. * @type {module:zrender/core/util#HashMap}
  28043. */
  28044. this.axisMap = createHashMap();
  28045. /**
  28046. * @type {module:zrender/core/util#HashMap}
  28047. */
  28048. this.categoryAxisMap = createHashMap();
  28049. /**
  28050. * @type {number}
  28051. */
  28052. this.firstCategoryDimIndex = null;
  28053. }
  28054. /**
  28055. * @return {module:model/referHelper#CoordSysInfo}
  28056. */
  28057. function getCoordSysInfoBySeries(seriesModel) {
  28058. var coordSysName = seriesModel.get('coordinateSystem');
  28059. var result = new CoordSysInfo(coordSysName);
  28060. var fetch = fetchers[coordSysName];
  28061. if (fetch) {
  28062. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  28063. return result;
  28064. }
  28065. }
  28066. var fetchers = {
  28067. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  28068. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  28069. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  28070. if (__DEV__) {
  28071. if (!xAxisModel) {
  28072. throw new Error('xAxis "' + retrieve(
  28073. seriesModel.get('xAxisIndex'),
  28074. seriesModel.get('xAxisId'),
  28075. 0
  28076. ) + '" not found');
  28077. }
  28078. if (!yAxisModel) {
  28079. throw new Error('yAxis "' + retrieve(
  28080. seriesModel.get('xAxisIndex'),
  28081. seriesModel.get('yAxisId'),
  28082. 0
  28083. ) + '" not found');
  28084. }
  28085. }
  28086. result.coordSysDims = ['x', 'y'];
  28087. axisMap.set('x', xAxisModel);
  28088. axisMap.set('y', yAxisModel);
  28089. if (isCategory(xAxisModel)) {
  28090. categoryAxisMap.set('x', xAxisModel);
  28091. result.firstCategoryDimIndex = 0;
  28092. }
  28093. if (isCategory(yAxisModel)) {
  28094. categoryAxisMap.set('y', yAxisModel);
  28095. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  28096. }
  28097. },
  28098. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  28099. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  28100. if (__DEV__) {
  28101. if (!singleAxisModel) {
  28102. throw new Error('singleAxis should be specified.');
  28103. }
  28104. }
  28105. result.coordSysDims = ['single'];
  28106. axisMap.set('single', singleAxisModel);
  28107. if (isCategory(singleAxisModel)) {
  28108. categoryAxisMap.set('single', singleAxisModel);
  28109. result.firstCategoryDimIndex = 0;
  28110. }
  28111. },
  28112. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  28113. var polarModel = seriesModel.getReferringComponents('polar')[0];
  28114. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  28115. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  28116. if (__DEV__) {
  28117. if (!angleAxisModel) {
  28118. throw new Error('angleAxis option not found');
  28119. }
  28120. if (!radiusAxisModel) {
  28121. throw new Error('radiusAxis option not found');
  28122. }
  28123. }
  28124. result.coordSysDims = ['radius', 'angle'];
  28125. axisMap.set('radius', radiusAxisModel);
  28126. axisMap.set('angle', angleAxisModel);
  28127. if (isCategory(radiusAxisModel)) {
  28128. categoryAxisMap.set('radius', radiusAxisModel);
  28129. result.firstCategoryDimIndex = 0;
  28130. }
  28131. if (isCategory(angleAxisModel)) {
  28132. categoryAxisMap.set('angle', angleAxisModel);
  28133. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  28134. }
  28135. },
  28136. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  28137. result.coordSysDims = ['lng', 'lat'];
  28138. },
  28139. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  28140. var ecModel = seriesModel.ecModel;
  28141. var parallelModel = ecModel.getComponent(
  28142. 'parallel', seriesModel.get('parallelIndex')
  28143. );
  28144. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  28145. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  28146. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  28147. var axisDim = coordSysDims[index];
  28148. axisMap.set(axisDim, axisModel);
  28149. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  28150. categoryAxisMap.set(axisDim, axisModel);
  28151. result.firstCategoryDimIndex = index;
  28152. }
  28153. });
  28154. }
  28155. };
  28156. function isCategory(axisModel) {
  28157. return axisModel.get('type') === 'category';
  28158. }
  28159. /*
  28160. * Licensed to the Apache Software Foundation (ASF) under one
  28161. * or more contributor license agreements. See the NOTICE file
  28162. * distributed with this work for additional information
  28163. * regarding copyright ownership. The ASF licenses this file
  28164. * to you under the Apache License, Version 2.0 (the
  28165. * "License"); you may not use this file except in compliance
  28166. * with the License. You may obtain a copy of the License at
  28167. *
  28168. * http://www.apache.org/licenses/LICENSE-2.0
  28169. *
  28170. * Unless required by applicable law or agreed to in writing,
  28171. * software distributed under the License is distributed on an
  28172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28173. * KIND, either express or implied. See the License for the
  28174. * specific language governing permissions and limitations
  28175. * under the License.
  28176. */
  28177. /**
  28178. * Note that it is too complicated to support 3d stack by value
  28179. * (have to create two-dimension inverted index), so in 3d case
  28180. * we just support that stacked by index.
  28181. *
  28182. * @param {module:echarts/model/Series} seriesModel
  28183. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  28184. * The input dimensionInfoList will be modified.
  28185. * @param {Object} [opt]
  28186. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  28187. * @param {boolean} [opt.byIndex=false]
  28188. * @return {Object} calculationInfo
  28189. * {
  28190. * stackedDimension: string
  28191. * stackedByDimension: string
  28192. * isStackedByIndex: boolean
  28193. * stackedOverDimension: string
  28194. * stackResultDimension: string
  28195. * }
  28196. */
  28197. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  28198. opt = opt || {};
  28199. var byIndex = opt.byIndex;
  28200. var stackedCoordDimension = opt.stackedCoordDimension;
  28201. // Compatibal: when `stack` is set as '', do not stack.
  28202. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  28203. var stackedByDimInfo;
  28204. var stackedDimInfo;
  28205. var stackResultDimension;
  28206. var stackedOverDimension;
  28207. each$1(dimensionInfoList, function (dimensionInfo, index) {
  28208. if (isString(dimensionInfo)) {
  28209. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  28210. }
  28211. if (mayStack && !dimensionInfo.isExtraCoord) {
  28212. // Find the first ordinal dimension as the stackedByDimInfo.
  28213. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  28214. stackedByDimInfo = dimensionInfo;
  28215. }
  28216. // Find the first stackable dimension as the stackedDimInfo.
  28217. if (!stackedDimInfo
  28218. && dimensionInfo.type !== 'ordinal'
  28219. && dimensionInfo.type !== 'time'
  28220. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  28221. ) {
  28222. stackedDimInfo = dimensionInfo;
  28223. }
  28224. }
  28225. });
  28226. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  28227. // Compatible with previous design, value axis (time axis) only stack by index.
  28228. // It may make sense if the user provides elaborately constructed data.
  28229. byIndex = true;
  28230. }
  28231. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  28232. // That put stack logic in List is for using conveniently in echarts extensions, but it
  28233. // might not be a good way.
  28234. if (stackedDimInfo) {
  28235. // Use a weird name that not duplicated with other names.
  28236. stackResultDimension = '__\0ecstackresult';
  28237. stackedOverDimension = '__\0ecstackedover';
  28238. // Create inverted index to fast query index by value.
  28239. if (stackedByDimInfo) {
  28240. stackedByDimInfo.createInvertedIndices = true;
  28241. }
  28242. var stackedDimCoordDim = stackedDimInfo.coordDim;
  28243. var stackedDimType = stackedDimInfo.type;
  28244. var stackedDimCoordIndex = 0;
  28245. each$1(dimensionInfoList, function (dimensionInfo) {
  28246. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  28247. stackedDimCoordIndex++;
  28248. }
  28249. });
  28250. dimensionInfoList.push({
  28251. name: stackResultDimension,
  28252. coordDim: stackedDimCoordDim,
  28253. coordDimIndex: stackedDimCoordIndex,
  28254. type: stackedDimType,
  28255. isExtraCoord: true,
  28256. isCalculationCoord: true
  28257. });
  28258. stackedDimCoordIndex++;
  28259. dimensionInfoList.push({
  28260. name: stackedOverDimension,
  28261. // This dimension contains stack base (generally, 0), so do not set it as
  28262. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  28263. coordDim: stackedOverDimension,
  28264. coordDimIndex: stackedDimCoordIndex,
  28265. type: stackedDimType,
  28266. isExtraCoord: true,
  28267. isCalculationCoord: true
  28268. });
  28269. }
  28270. return {
  28271. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  28272. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  28273. isStackedByIndex: byIndex,
  28274. stackedOverDimension: stackedOverDimension,
  28275. stackResultDimension: stackResultDimension
  28276. };
  28277. }
  28278. /**
  28279. * @param {module:echarts/data/List} data
  28280. * @param {string} stackedDim
  28281. */
  28282. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  28283. // Each single series only maps to one pair of axis. So we do not need to
  28284. // check stackByDim, whatever stacked by a dimension or stacked by index.
  28285. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  28286. // && (
  28287. // stackedByDim != null
  28288. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  28289. // : data.getCalculationInfo('isStackedByIndex')
  28290. // );
  28291. }
  28292. /**
  28293. * @param {module:echarts/data/List} data
  28294. * @param {string} targetDim
  28295. * @param {string} [stackedByDim] If not input this parameter, check whether
  28296. * stacked by index.
  28297. * @return {string} dimension
  28298. */
  28299. function getStackedDimension(data, targetDim) {
  28300. return isDimensionStacked(data, targetDim)
  28301. ? data.getCalculationInfo('stackResultDimension')
  28302. : targetDim;
  28303. }
  28304. /*
  28305. * Licensed to the Apache Software Foundation (ASF) under one
  28306. * or more contributor license agreements. See the NOTICE file
  28307. * distributed with this work for additional information
  28308. * regarding copyright ownership. The ASF licenses this file
  28309. * to you under the Apache License, Version 2.0 (the
  28310. * "License"); you may not use this file except in compliance
  28311. * with the License. You may obtain a copy of the License at
  28312. *
  28313. * http://www.apache.org/licenses/LICENSE-2.0
  28314. *
  28315. * Unless required by applicable law or agreed to in writing,
  28316. * software distributed under the License is distributed on an
  28317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28318. * KIND, either express or implied. See the License for the
  28319. * specific language governing permissions and limitations
  28320. * under the License.
  28321. */
  28322. /**
  28323. * @param {module:echarts/data/Source|Array} source Or raw data.
  28324. * @param {module:echarts/model/Series} seriesModel
  28325. * @param {Object} [opt]
  28326. * @param {string} [opt.generateCoord]
  28327. * @param {boolean} [opt.useEncodeDefaulter]
  28328. */
  28329. function createListFromArray(source, seriesModel, opt) {
  28330. opt = opt || {};
  28331. if (!Source.isInstance(source)) {
  28332. source = Source.seriesDataToSource(source);
  28333. }
  28334. var coordSysName = seriesModel.get('coordinateSystem');
  28335. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  28336. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  28337. var coordSysDimDefs;
  28338. if (coordSysInfo) {
  28339. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  28340. var dimInfo = {name: dim};
  28341. var axisModel = coordSysInfo.axisMap.get(dim);
  28342. if (axisModel) {
  28343. var axisType = axisModel.get('type');
  28344. dimInfo.type = getDimensionTypeByAxis(axisType);
  28345. // dimInfo.stackable = isStackable(axisType);
  28346. }
  28347. return dimInfo;
  28348. });
  28349. }
  28350. if (!coordSysDimDefs) {
  28351. // Get dimensions from registered coordinate system
  28352. coordSysDimDefs = (registeredCoordSys && (
  28353. registeredCoordSys.getDimensionsInfo
  28354. ? registeredCoordSys.getDimensionsInfo()
  28355. : registeredCoordSys.dimensions.slice()
  28356. )) || ['x', 'y'];
  28357. }
  28358. var dimInfoList = createDimensions(source, {
  28359. coordDimensions: coordSysDimDefs,
  28360. generateCoord: opt.generateCoord,
  28361. encodeDefaulter: opt.useEncodeDefaulter
  28362. ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel)
  28363. : null
  28364. });
  28365. var firstCategoryDimIndex;
  28366. var hasNameEncode;
  28367. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  28368. var coordDim = dimInfo.coordDim;
  28369. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  28370. if (categoryAxisModel) {
  28371. if (firstCategoryDimIndex == null) {
  28372. firstCategoryDimIndex = dimIndex;
  28373. }
  28374. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  28375. }
  28376. if (dimInfo.otherDims.itemName != null) {
  28377. hasNameEncode = true;
  28378. }
  28379. });
  28380. if (!hasNameEncode && firstCategoryDimIndex != null) {
  28381. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  28382. }
  28383. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  28384. var list = new List(dimInfoList, seriesModel);
  28385. list.setCalculationInfo(stackCalculationInfo);
  28386. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  28387. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  28388. // Use dataIndex as ordinal value in categoryAxis
  28389. return dimIndex === firstCategoryDimIndex
  28390. ? dataIndex
  28391. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  28392. }
  28393. : null;
  28394. list.hasItemOption = false;
  28395. list.initData(source, null, dimValueGetter);
  28396. return list;
  28397. }
  28398. function isNeedCompleteOrdinalData(source) {
  28399. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  28400. var sampleItem = firstDataNotNull(source.data || []);
  28401. return sampleItem != null
  28402. && !isArray(getDataItemValue(sampleItem));
  28403. }
  28404. }
  28405. function firstDataNotNull(data) {
  28406. var i = 0;
  28407. while (i < data.length && data[i] == null) {
  28408. i++;
  28409. }
  28410. return data[i];
  28411. }
  28412. /*
  28413. * Licensed to the Apache Software Foundation (ASF) under one
  28414. * or more contributor license agreements. See the NOTICE file
  28415. * distributed with this work for additional information
  28416. * regarding copyright ownership. The ASF licenses this file
  28417. * to you under the Apache License, Version 2.0 (the
  28418. * "License"); you may not use this file except in compliance
  28419. * with the License. You may obtain a copy of the License at
  28420. *
  28421. * http://www.apache.org/licenses/LICENSE-2.0
  28422. *
  28423. * Unless required by applicable law or agreed to in writing,
  28424. * software distributed under the License is distributed on an
  28425. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28426. * KIND, either express or implied. See the License for the
  28427. * specific language governing permissions and limitations
  28428. * under the License.
  28429. */
  28430. SeriesModel.extend({
  28431. type: 'series.line',
  28432. dependencies: ['grid', 'polar'],
  28433. getInitialData: function (option, ecModel) {
  28434. if (__DEV__) {
  28435. var coordSys = option.coordinateSystem;
  28436. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  28437. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  28438. }
  28439. }
  28440. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  28441. },
  28442. defaultOption: {
  28443. zlevel: 0,
  28444. z: 2,
  28445. coordinateSystem: 'cartesian2d',
  28446. legendHoverLink: true,
  28447. hoverAnimation: true,
  28448. // stack: null
  28449. // xAxisIndex: 0,
  28450. // yAxisIndex: 0,
  28451. // polarIndex: 0,
  28452. // If clip the overflow value
  28453. clip: true,
  28454. // cursor: null,
  28455. label: {
  28456. position: 'top'
  28457. },
  28458. // itemStyle: {
  28459. // },
  28460. lineStyle: {
  28461. width: 2,
  28462. type: 'solid'
  28463. },
  28464. // areaStyle: {
  28465. // origin of areaStyle. Valid values:
  28466. // `'auto'/null/undefined`: from axisLine to data
  28467. // `'start'`: from min to data
  28468. // `'end'`: from data to max
  28469. // origin: 'auto'
  28470. // },
  28471. // false, 'start', 'end', 'middle'
  28472. step: false,
  28473. // Disabled if step is true
  28474. smooth: false,
  28475. smoothMonotone: null,
  28476. symbol: 'emptyCircle',
  28477. symbolSize: 4,
  28478. symbolRotate: null,
  28479. showSymbol: true,
  28480. // `false`: follow the label interval strategy.
  28481. // `true`: show all symbols.
  28482. // `'auto'`: If possible, show all symbols, otherwise
  28483. // follow the label interval strategy.
  28484. showAllSymbol: 'auto',
  28485. // Whether to connect break point.
  28486. connectNulls: false,
  28487. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  28488. sampling: 'none',
  28489. animationEasing: 'linear',
  28490. // Disable progressive
  28491. progressive: 0,
  28492. hoverLayerThreshold: Infinity
  28493. }
  28494. });
  28495. /*
  28496. * Licensed to the Apache Software Foundation (ASF) under one
  28497. * or more contributor license agreements. See the NOTICE file
  28498. * distributed with this work for additional information
  28499. * regarding copyright ownership. The ASF licenses this file
  28500. * to you under the Apache License, Version 2.0 (the
  28501. * "License"); you may not use this file except in compliance
  28502. * with the License. You may obtain a copy of the License at
  28503. *
  28504. * http://www.apache.org/licenses/LICENSE-2.0
  28505. *
  28506. * Unless required by applicable law or agreed to in writing,
  28507. * software distributed under the License is distributed on an
  28508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28509. * KIND, either express or implied. See the License for the
  28510. * specific language governing permissions and limitations
  28511. * under the License.
  28512. */
  28513. // Symbol factory
  28514. /**
  28515. * Triangle shape
  28516. * @inner
  28517. */
  28518. var Triangle = extendShape({
  28519. type: 'triangle',
  28520. shape: {
  28521. cx: 0,
  28522. cy: 0,
  28523. width: 0,
  28524. height: 0
  28525. },
  28526. buildPath: function (path, shape) {
  28527. var cx = shape.cx;
  28528. var cy = shape.cy;
  28529. var width = shape.width / 2;
  28530. var height = shape.height / 2;
  28531. path.moveTo(cx, cy - height);
  28532. path.lineTo(cx + width, cy + height);
  28533. path.lineTo(cx - width, cy + height);
  28534. path.closePath();
  28535. }
  28536. });
  28537. /**
  28538. * Diamond shape
  28539. * @inner
  28540. */
  28541. var Diamond = extendShape({
  28542. type: 'diamond',
  28543. shape: {
  28544. cx: 0,
  28545. cy: 0,
  28546. width: 0,
  28547. height: 0
  28548. },
  28549. buildPath: function (path, shape) {
  28550. var cx = shape.cx;
  28551. var cy = shape.cy;
  28552. var width = shape.width / 2;
  28553. var height = shape.height / 2;
  28554. path.moveTo(cx, cy - height);
  28555. path.lineTo(cx + width, cy);
  28556. path.lineTo(cx, cy + height);
  28557. path.lineTo(cx - width, cy);
  28558. path.closePath();
  28559. }
  28560. });
  28561. /**
  28562. * Pin shape
  28563. * @inner
  28564. */
  28565. var Pin = extendShape({
  28566. type: 'pin',
  28567. shape: {
  28568. // x, y on the cusp
  28569. x: 0,
  28570. y: 0,
  28571. width: 0,
  28572. height: 0
  28573. },
  28574. buildPath: function (path, shape) {
  28575. var x = shape.x;
  28576. var y = shape.y;
  28577. var w = shape.width / 5 * 3;
  28578. // Height must be larger than width
  28579. var h = Math.max(w, shape.height);
  28580. var r = w / 2;
  28581. // Dist on y with tangent point and circle center
  28582. var dy = r * r / (h - r);
  28583. var cy = y - h + r + dy;
  28584. var angle = Math.asin(dy / r);
  28585. // Dist on x with tangent point and circle center
  28586. var dx = Math.cos(angle) * r;
  28587. var tanX = Math.sin(angle);
  28588. var tanY = Math.cos(angle);
  28589. var cpLen = r * 0.6;
  28590. var cpLen2 = r * 0.7;
  28591. path.moveTo(x - dx, cy + dy);
  28592. path.arc(
  28593. x, cy, r,
  28594. Math.PI - angle,
  28595. Math.PI * 2 + angle
  28596. );
  28597. path.bezierCurveTo(
  28598. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28599. x, y - cpLen2,
  28600. x, y
  28601. );
  28602. path.bezierCurveTo(
  28603. x, y - cpLen2,
  28604. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28605. x - dx, cy + dy
  28606. );
  28607. path.closePath();
  28608. }
  28609. });
  28610. /**
  28611. * Arrow shape
  28612. * @inner
  28613. */
  28614. var Arrow = extendShape({
  28615. type: 'arrow',
  28616. shape: {
  28617. x: 0,
  28618. y: 0,
  28619. width: 0,
  28620. height: 0
  28621. },
  28622. buildPath: function (ctx, shape) {
  28623. var height = shape.height;
  28624. var width = shape.width;
  28625. var x = shape.x;
  28626. var y = shape.y;
  28627. var dx = width / 3 * 2;
  28628. ctx.moveTo(x, y);
  28629. ctx.lineTo(x + dx, y + height);
  28630. ctx.lineTo(x, y + height / 4 * 3);
  28631. ctx.lineTo(x - dx, y + height);
  28632. ctx.lineTo(x, y);
  28633. ctx.closePath();
  28634. }
  28635. });
  28636. /**
  28637. * Map of path contructors
  28638. * @type {Object.<string, module:zrender/graphic/Path>}
  28639. */
  28640. var symbolCtors = {
  28641. line: Line,
  28642. rect: Rect,
  28643. roundRect: Rect,
  28644. square: Rect,
  28645. circle: Circle,
  28646. diamond: Diamond,
  28647. pin: Pin,
  28648. arrow: Arrow,
  28649. triangle: Triangle
  28650. };
  28651. var symbolShapeMakers = {
  28652. line: function (x, y, w, h, shape) {
  28653. // FIXME
  28654. shape.x1 = x;
  28655. shape.y1 = y + h / 2;
  28656. shape.x2 = x + w;
  28657. shape.y2 = y + h / 2;
  28658. },
  28659. rect: function (x, y, w, h, shape) {
  28660. shape.x = x;
  28661. shape.y = y;
  28662. shape.width = w;
  28663. shape.height = h;
  28664. },
  28665. roundRect: function (x, y, w, h, shape) {
  28666. shape.x = x;
  28667. shape.y = y;
  28668. shape.width = w;
  28669. shape.height = h;
  28670. shape.r = Math.min(w, h) / 4;
  28671. },
  28672. square: function (x, y, w, h, shape) {
  28673. var size = Math.min(w, h);
  28674. shape.x = x;
  28675. shape.y = y;
  28676. shape.width = size;
  28677. shape.height = size;
  28678. },
  28679. circle: function (x, y, w, h, shape) {
  28680. // Put circle in the center of square
  28681. shape.cx = x + w / 2;
  28682. shape.cy = y + h / 2;
  28683. shape.r = Math.min(w, h) / 2;
  28684. },
  28685. diamond: function (x, y, w, h, shape) {
  28686. shape.cx = x + w / 2;
  28687. shape.cy = y + h / 2;
  28688. shape.width = w;
  28689. shape.height = h;
  28690. },
  28691. pin: function (x, y, w, h, shape) {
  28692. shape.x = x + w / 2;
  28693. shape.y = y + h / 2;
  28694. shape.width = w;
  28695. shape.height = h;
  28696. },
  28697. arrow: function (x, y, w, h, shape) {
  28698. shape.x = x + w / 2;
  28699. shape.y = y + h / 2;
  28700. shape.width = w;
  28701. shape.height = h;
  28702. },
  28703. triangle: function (x, y, w, h, shape) {
  28704. shape.cx = x + w / 2;
  28705. shape.cy = y + h / 2;
  28706. shape.width = w;
  28707. shape.height = h;
  28708. }
  28709. };
  28710. var symbolBuildProxies = {};
  28711. each$1(symbolCtors, function (Ctor, name) {
  28712. symbolBuildProxies[name] = new Ctor();
  28713. });
  28714. var SymbolClz$2 = extendShape({
  28715. type: 'symbol',
  28716. shape: {
  28717. symbolType: '',
  28718. x: 0,
  28719. y: 0,
  28720. width: 0,
  28721. height: 0
  28722. },
  28723. calculateTextPosition: function (out, style, rect) {
  28724. var res = calculateTextPosition(out, style, rect);
  28725. var shape = this.shape;
  28726. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28727. res.y = rect.y + rect.height * 0.4;
  28728. }
  28729. return res;
  28730. },
  28731. buildPath: function (ctx, shape, inBundle) {
  28732. var symbolType = shape.symbolType;
  28733. if (symbolType !== 'none') {
  28734. var proxySymbol = symbolBuildProxies[symbolType];
  28735. if (!proxySymbol) {
  28736. // Default rect
  28737. symbolType = 'rect';
  28738. proxySymbol = symbolBuildProxies[symbolType];
  28739. }
  28740. symbolShapeMakers[symbolType](
  28741. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28742. );
  28743. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28744. }
  28745. }
  28746. });
  28747. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28748. function symbolPathSetColor(color, innerColor) {
  28749. if (this.type !== 'image') {
  28750. var symbolStyle = this.style;
  28751. var symbolShape = this.shape;
  28752. if (symbolShape && symbolShape.symbolType === 'line') {
  28753. symbolStyle.stroke = color;
  28754. }
  28755. else if (this.__isEmptyBrush) {
  28756. symbolStyle.stroke = color;
  28757. symbolStyle.fill = innerColor || '#fff';
  28758. }
  28759. else {
  28760. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28761. symbolStyle.fill && (symbolStyle.fill = color);
  28762. symbolStyle.stroke && (symbolStyle.stroke = color);
  28763. }
  28764. this.dirty(false);
  28765. }
  28766. }
  28767. /**
  28768. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28769. * @param {string} symbolType
  28770. * @param {number} x
  28771. * @param {number} y
  28772. * @param {number} w
  28773. * @param {number} h
  28774. * @param {string} color
  28775. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28776. * for path and image only.
  28777. */
  28778. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28779. // TODO Support image object, DynamicImage.
  28780. var isEmpty = symbolType.indexOf('empty') === 0;
  28781. if (isEmpty) {
  28782. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28783. }
  28784. var symbolPath;
  28785. if (symbolType.indexOf('image://') === 0) {
  28786. symbolPath = makeImage(
  28787. symbolType.slice(8),
  28788. new BoundingRect(x, y, w, h),
  28789. keepAspect ? 'center' : 'cover'
  28790. );
  28791. }
  28792. else if (symbolType.indexOf('path://') === 0) {
  28793. symbolPath = makePath(
  28794. symbolType.slice(7),
  28795. {},
  28796. new BoundingRect(x, y, w, h),
  28797. keepAspect ? 'center' : 'cover'
  28798. );
  28799. }
  28800. else {
  28801. symbolPath = new SymbolClz$2({
  28802. shape: {
  28803. symbolType: symbolType,
  28804. x: x,
  28805. y: y,
  28806. width: w,
  28807. height: h
  28808. }
  28809. });
  28810. }
  28811. symbolPath.__isEmptyBrush = isEmpty;
  28812. symbolPath.setColor = symbolPathSetColor;
  28813. symbolPath.setColor(color);
  28814. return symbolPath;
  28815. }
  28816. /*
  28817. * Licensed to the Apache Software Foundation (ASF) under one
  28818. * or more contributor license agreements. See the NOTICE file
  28819. * distributed with this work for additional information
  28820. * regarding copyright ownership. The ASF licenses this file
  28821. * to you under the Apache License, Version 2.0 (the
  28822. * "License"); you may not use this file except in compliance
  28823. * with the License. You may obtain a copy of the License at
  28824. *
  28825. * http://www.apache.org/licenses/LICENSE-2.0
  28826. *
  28827. * Unless required by applicable law or agreed to in writing,
  28828. * software distributed under the License is distributed on an
  28829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28830. * KIND, either express or implied. See the License for the
  28831. * specific language governing permissions and limitations
  28832. * under the License.
  28833. */
  28834. /**
  28835. * @param {module:echarts/data/List} data
  28836. * @param {number} dataIndex
  28837. * @return {string} label string. Not null/undefined
  28838. */
  28839. function getDefaultLabel(data, dataIndex) {
  28840. var labelDims = data.mapDimension('defaultedLabel', true);
  28841. var len = labelDims.length;
  28842. // Simple optimization (in lots of cases, label dims length is 1)
  28843. if (len === 1) {
  28844. return retrieveRawValue(data, dataIndex, labelDims[0]);
  28845. }
  28846. else if (len) {
  28847. var vals = [];
  28848. for (var i = 0; i < labelDims.length; i++) {
  28849. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  28850. vals.push(val);
  28851. }
  28852. return vals.join(' ');
  28853. }
  28854. }
  28855. /*
  28856. * Licensed to the Apache Software Foundation (ASF) under one
  28857. * or more contributor license agreements. See the NOTICE file
  28858. * distributed with this work for additional information
  28859. * regarding copyright ownership. The ASF licenses this file
  28860. * to you under the Apache License, Version 2.0 (the
  28861. * "License"); you may not use this file except in compliance
  28862. * with the License. You may obtain a copy of the License at
  28863. *
  28864. * http://www.apache.org/licenses/LICENSE-2.0
  28865. *
  28866. * Unless required by applicable law or agreed to in writing,
  28867. * software distributed under the License is distributed on an
  28868. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28869. * KIND, either express or implied. See the License for the
  28870. * specific language governing permissions and limitations
  28871. * under the License.
  28872. */
  28873. /**
  28874. * @module echarts/chart/helper/Symbol
  28875. */
  28876. /**
  28877. * @constructor
  28878. * @alias {module:echarts/chart/helper/Symbol}
  28879. * @param {module:echarts/data/List} data
  28880. * @param {number} idx
  28881. * @extends {module:zrender/graphic/Group}
  28882. */
  28883. function SymbolClz(data, idx, seriesScope) {
  28884. Group.call(this);
  28885. this.updateData(data, idx, seriesScope);
  28886. }
  28887. var symbolProto = SymbolClz.prototype;
  28888. /**
  28889. * @public
  28890. * @static
  28891. * @param {module:echarts/data/List} data
  28892. * @param {number} dataIndex
  28893. * @return {Array.<number>} [width, height]
  28894. */
  28895. var getSymbolSize = SymbolClz.getSymbolSize = function (data, idx) {
  28896. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  28897. return symbolSize instanceof Array
  28898. ? symbolSize.slice()
  28899. : [+symbolSize, +symbolSize];
  28900. };
  28901. function getScale(symbolSize) {
  28902. return [symbolSize[0] / 2, symbolSize[1] / 2];
  28903. }
  28904. function driftSymbol(dx, dy) {
  28905. this.parent.drift(dx, dy);
  28906. }
  28907. symbolProto._createSymbol = function (
  28908. symbolType,
  28909. data,
  28910. idx,
  28911. symbolSize,
  28912. keepAspect
  28913. ) {
  28914. // Remove paths created before
  28915. this.removeAll();
  28916. var color = data.getItemVisual(idx, 'color');
  28917. // var symbolPath = createSymbol(
  28918. // symbolType, -0.5, -0.5, 1, 1, color
  28919. // );
  28920. // If width/height are set too small (e.g., set to 1) on ios10
  28921. // and macOS Sierra, a circle stroke become a rect, no matter what
  28922. // the scale is set. So we set width/height as 2. See #4150.
  28923. var symbolPath = createSymbol(
  28924. symbolType, -1, -1, 2, 2, color, keepAspect
  28925. );
  28926. symbolPath.attr({
  28927. z2: 100,
  28928. culling: true,
  28929. scale: getScale(symbolSize)
  28930. });
  28931. // Rewrite drift method
  28932. symbolPath.drift = driftSymbol;
  28933. this._symbolType = symbolType;
  28934. this.add(symbolPath);
  28935. };
  28936. /**
  28937. * Stop animation
  28938. * @param {boolean} toLastFrame
  28939. */
  28940. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  28941. this.childAt(0).stopAnimation(toLastFrame);
  28942. };
  28943. /**
  28944. * FIXME:
  28945. * Caution: This method breaks the encapsulation of this module,
  28946. * but it indeed brings convenience. So do not use the method
  28947. * unless you detailedly know all the implements of `Symbol`,
  28948. * especially animation.
  28949. *
  28950. * Get symbol path element.
  28951. */
  28952. symbolProto.getSymbolPath = function () {
  28953. return this.childAt(0);
  28954. };
  28955. /**
  28956. * Get scale(aka, current symbol size).
  28957. * Including the change caused by animation
  28958. */
  28959. symbolProto.getScale = function () {
  28960. return this.childAt(0).scale;
  28961. };
  28962. /**
  28963. * Highlight symbol
  28964. */
  28965. symbolProto.highlight = function () {
  28966. this.childAt(0).trigger('emphasis');
  28967. };
  28968. /**
  28969. * Downplay symbol
  28970. */
  28971. symbolProto.downplay = function () {
  28972. this.childAt(0).trigger('normal');
  28973. };
  28974. /**
  28975. * @param {number} zlevel
  28976. * @param {number} z
  28977. */
  28978. symbolProto.setZ = function (zlevel, z) {
  28979. var symbolPath = this.childAt(0);
  28980. symbolPath.zlevel = zlevel;
  28981. symbolPath.z = z;
  28982. };
  28983. symbolProto.setDraggable = function (draggable) {
  28984. var symbolPath = this.childAt(0);
  28985. symbolPath.draggable = draggable;
  28986. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  28987. };
  28988. /**
  28989. * Update symbol properties
  28990. * @param {module:echarts/data/List} data
  28991. * @param {number} idx
  28992. * @param {Object} [seriesScope]
  28993. * @param {Object} [seriesScope.itemStyle]
  28994. * @param {Object} [seriesScope.hoverItemStyle]
  28995. * @param {Object} [seriesScope.symbolRotate]
  28996. * @param {Object} [seriesScope.symbolOffset]
  28997. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  28998. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  28999. * @param {boolean} [seriesScope.hoverAnimation]
  29000. * @param {Object} [seriesScope.cursorStyle]
  29001. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29002. * @param {string} [seriesScope.symbolInnerColor]
  29003. * @param {Object} [seriesScope.fadeIn=false]
  29004. */
  29005. symbolProto.updateData = function (data, idx, seriesScope) {
  29006. this.silent = false;
  29007. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29008. var seriesModel = data.hostModel;
  29009. var symbolSize = getSymbolSize(data, idx);
  29010. var isInit = symbolType !== this._symbolType;
  29011. if (isInit) {
  29012. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29013. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29014. }
  29015. else {
  29016. var symbolPath = this.childAt(0);
  29017. symbolPath.silent = false;
  29018. updateProps(symbolPath, {
  29019. scale: getScale(symbolSize)
  29020. }, seriesModel, idx);
  29021. }
  29022. this._updateCommon(data, idx, symbolSize, seriesScope);
  29023. if (isInit) {
  29024. var symbolPath = this.childAt(0);
  29025. var fadeIn = seriesScope && seriesScope.fadeIn;
  29026. var target = {scale: symbolPath.scale.slice()};
  29027. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29028. symbolPath.scale = [0, 0];
  29029. fadeIn && (symbolPath.style.opacity = 0);
  29030. initProps(symbolPath, target, seriesModel, idx);
  29031. }
  29032. this._seriesModel = seriesModel;
  29033. };
  29034. // Update common properties
  29035. var normalStyleAccessPath = ['itemStyle'];
  29036. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29037. var normalLabelAccessPath = ['label'];
  29038. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29039. /**
  29040. * @param {module:echarts/data/List} data
  29041. * @param {number} idx
  29042. * @param {Array.<number>} symbolSize
  29043. * @param {Object} [seriesScope]
  29044. */
  29045. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29046. var symbolPath = this.childAt(0);
  29047. var seriesModel = data.hostModel;
  29048. var color = data.getItemVisual(idx, 'color');
  29049. // Reset style
  29050. if (symbolPath.type !== 'image') {
  29051. symbolPath.useStyle({
  29052. strokeNoScale: true
  29053. });
  29054. }
  29055. else {
  29056. symbolPath.setStyle({
  29057. opacity: null,
  29058. shadowBlur: null,
  29059. shadowOffsetX: null,
  29060. shadowOffsetY: null,
  29061. shadowColor: null
  29062. });
  29063. }
  29064. var itemStyle = seriesScope && seriesScope.itemStyle;
  29065. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29066. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29067. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29068. var labelModel = seriesScope && seriesScope.labelModel;
  29069. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29070. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29071. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29072. if (!seriesScope || data.hasItemOption) {
  29073. var itemModel = (seriesScope && seriesScope.itemModel)
  29074. ? seriesScope.itemModel : data.getItemModel(idx);
  29075. // Color must be excluded.
  29076. // Because symbol provide setColor individually to set fill and stroke
  29077. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29078. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29079. symbolRotate = itemModel.getShallow('symbolRotate');
  29080. symbolOffset = itemModel.getShallow('symbolOffset');
  29081. labelModel = itemModel.getModel(normalLabelAccessPath);
  29082. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29083. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29084. cursorStyle = itemModel.getShallow('cursor');
  29085. }
  29086. else {
  29087. hoverItemStyle = extend({}, hoverItemStyle);
  29088. }
  29089. var elStyle = symbolPath.style;
  29090. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29091. if (symbolOffset) {
  29092. symbolPath.attr('position', [
  29093. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29094. parsePercent$1(symbolOffset[1], symbolSize[1])
  29095. ]);
  29096. }
  29097. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29098. // PENDING setColor before setStyle!!!
  29099. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29100. symbolPath.setStyle(itemStyle);
  29101. var opacity = data.getItemVisual(idx, 'opacity');
  29102. if (opacity != null) {
  29103. elStyle.opacity = opacity;
  29104. }
  29105. var liftZ = data.getItemVisual(idx, 'liftZ');
  29106. var z2Origin = symbolPath.__z2Origin;
  29107. if (liftZ != null) {
  29108. if (z2Origin == null) {
  29109. symbolPath.__z2Origin = symbolPath.z2;
  29110. symbolPath.z2 += liftZ;
  29111. }
  29112. }
  29113. else if (z2Origin != null) {
  29114. symbolPath.z2 = z2Origin;
  29115. symbolPath.__z2Origin = null;
  29116. }
  29117. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29118. setLabelStyle(
  29119. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29120. {
  29121. labelFetcher: seriesModel,
  29122. labelDataIndex: idx,
  29123. defaultText: getLabelDefaultText,
  29124. isRectText: true,
  29125. autoColor: color
  29126. }
  29127. );
  29128. // Do not execute util needed.
  29129. function getLabelDefaultText(idx, opt) {
  29130. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29131. }
  29132. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  29133. symbolPath.hoverStyle = hoverItemStyle;
  29134. symbolPath.highDownOnUpdate = (
  29135. hoverAnimation && seriesModel.isAnimationEnabled()
  29136. ) ? highDownOnUpdate : null;
  29137. setHoverStyle(symbolPath);
  29138. };
  29139. function highDownOnUpdate(fromState, toState) {
  29140. // Do not support this hover animation util some scenario required.
  29141. // Animation can only be supported in hover layer when using `el.incremetal`.
  29142. if (this.incremental || this.useHoverLayer) {
  29143. return;
  29144. }
  29145. if (toState === 'emphasis') {
  29146. var scale = this.__symbolOriginalScale;
  29147. var ratio = scale[1] / scale[0];
  29148. var emphasisOpt = {
  29149. scale: [
  29150. Math.max(scale[0] * 1.1, scale[0] + 3),
  29151. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29152. ]
  29153. };
  29154. // FIXME
  29155. // modify it after support stop specified animation.
  29156. // toState === fromState
  29157. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  29158. this.animateTo(emphasisOpt, 400, 'elasticOut');
  29159. }
  29160. else if (toState === 'normal') {
  29161. this.animateTo({
  29162. scale: this.__symbolOriginalScale
  29163. }, 400, 'elasticOut');
  29164. }
  29165. }
  29166. /**
  29167. * @param {Function} cb
  29168. * @param {Object} [opt]
  29169. * @param {Object} [opt.keepLabel=true]
  29170. */
  29171. symbolProto.fadeOut = function (cb, opt) {
  29172. var symbolPath = this.childAt(0);
  29173. // Avoid mistaken hover when fading out
  29174. this.silent = symbolPath.silent = true;
  29175. // Not show text when animating
  29176. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29177. updateProps(
  29178. symbolPath,
  29179. {
  29180. style: {opacity: 0},
  29181. scale: [0, 0]
  29182. },
  29183. this._seriesModel,
  29184. this.dataIndex,
  29185. cb
  29186. );
  29187. };
  29188. inherits(SymbolClz, Group);
  29189. /*
  29190. * Licensed to the Apache Software Foundation (ASF) under one
  29191. * or more contributor license agreements. See the NOTICE file
  29192. * distributed with this work for additional information
  29193. * regarding copyright ownership. The ASF licenses this file
  29194. * to you under the Apache License, Version 2.0 (the
  29195. * "License"); you may not use this file except in compliance
  29196. * with the License. You may obtain a copy of the License at
  29197. *
  29198. * http://www.apache.org/licenses/LICENSE-2.0
  29199. *
  29200. * Unless required by applicable law or agreed to in writing,
  29201. * software distributed under the License is distributed on an
  29202. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29203. * KIND, either express or implied. See the License for the
  29204. * specific language governing permissions and limitations
  29205. * under the License.
  29206. */
  29207. /**
  29208. * @module echarts/chart/helper/SymbolDraw
  29209. */
  29210. /**
  29211. * @constructor
  29212. * @alias module:echarts/chart/helper/SymbolDraw
  29213. * @param {module:zrender/graphic/Group} [symbolCtor]
  29214. */
  29215. function SymbolDraw(symbolCtor) {
  29216. this.group = new Group();
  29217. this._symbolCtor = symbolCtor || SymbolClz;
  29218. }
  29219. var symbolDrawProto = SymbolDraw.prototype;
  29220. function symbolNeedsDraw(data, point, idx, opt) {
  29221. return point && !isNaN(point[0]) && !isNaN(point[1])
  29222. && !(opt.isIgnore && opt.isIgnore(idx))
  29223. // We do not set clipShape on group, because it will cut part of
  29224. // the symbol element shape. We use the same clip shape here as
  29225. // the line clip.
  29226. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29227. && data.getItemVisual(idx, 'symbol') !== 'none';
  29228. }
  29229. /**
  29230. * Update symbols draw by new data
  29231. * @param {module:echarts/data/List} data
  29232. * @param {Object} [opt] Or isIgnore
  29233. * @param {Function} [opt.isIgnore]
  29234. * @param {Object} [opt.clipShape]
  29235. */
  29236. symbolDrawProto.updateData = function (data, opt) {
  29237. opt = normalizeUpdateOpt(opt);
  29238. var group = this.group;
  29239. var seriesModel = data.hostModel;
  29240. var oldData = this._data;
  29241. var SymbolCtor = this._symbolCtor;
  29242. var seriesScope = makeSeriesScope(data);
  29243. // There is no oldLineData only when first rendering or switching from
  29244. // stream mode to normal mode, where previous elements should be removed.
  29245. if (!oldData) {
  29246. group.removeAll();
  29247. }
  29248. data.diff(oldData)
  29249. .add(function (newIdx) {
  29250. var point = data.getItemLayout(newIdx);
  29251. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29252. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29253. symbolEl.attr('position', point);
  29254. data.setItemGraphicEl(newIdx, symbolEl);
  29255. group.add(symbolEl);
  29256. }
  29257. })
  29258. .update(function (newIdx, oldIdx) {
  29259. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29260. var point = data.getItemLayout(newIdx);
  29261. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29262. group.remove(symbolEl);
  29263. return;
  29264. }
  29265. if (!symbolEl) {
  29266. symbolEl = new SymbolCtor(data, newIdx);
  29267. symbolEl.attr('position', point);
  29268. }
  29269. else {
  29270. symbolEl.updateData(data, newIdx, seriesScope);
  29271. updateProps(symbolEl, {
  29272. position: point
  29273. }, seriesModel);
  29274. }
  29275. // Add back
  29276. group.add(symbolEl);
  29277. data.setItemGraphicEl(newIdx, symbolEl);
  29278. })
  29279. .remove(function (oldIdx) {
  29280. var el = oldData.getItemGraphicEl(oldIdx);
  29281. el && el.fadeOut(function () {
  29282. group.remove(el);
  29283. });
  29284. })
  29285. .execute();
  29286. this._data = data;
  29287. };
  29288. symbolDrawProto.isPersistent = function () {
  29289. return true;
  29290. };
  29291. symbolDrawProto.updateLayout = function () {
  29292. var data = this._data;
  29293. if (data) {
  29294. // Not use animation
  29295. data.eachItemGraphicEl(function (el, idx) {
  29296. var point = data.getItemLayout(idx);
  29297. el.attr('position', point);
  29298. });
  29299. }
  29300. };
  29301. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29302. this._seriesScope = makeSeriesScope(data);
  29303. this._data = null;
  29304. this.group.removeAll();
  29305. };
  29306. /**
  29307. * Update symbols draw by new data
  29308. * @param {module:echarts/data/List} data
  29309. * @param {Object} [opt] Or isIgnore
  29310. * @param {Function} [opt.isIgnore]
  29311. * @param {Object} [opt.clipShape]
  29312. */
  29313. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29314. opt = normalizeUpdateOpt(opt);
  29315. function updateIncrementalAndHover(el) {
  29316. if (!el.isGroup) {
  29317. el.incremental = el.useHoverLayer = true;
  29318. }
  29319. }
  29320. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29321. var point = data.getItemLayout(idx);
  29322. if (symbolNeedsDraw(data, point, idx, opt)) {
  29323. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29324. el.traverse(updateIncrementalAndHover);
  29325. el.attr('position', point);
  29326. this.group.add(el);
  29327. data.setItemGraphicEl(idx, el);
  29328. }
  29329. }
  29330. };
  29331. function normalizeUpdateOpt(opt) {
  29332. if (opt != null && !isObject$1(opt)) {
  29333. opt = {isIgnore: opt};
  29334. }
  29335. return opt || {};
  29336. }
  29337. symbolDrawProto.remove = function (enableAnimation) {
  29338. var group = this.group;
  29339. var data = this._data;
  29340. // Incremental model do not have this._data.
  29341. if (data && enableAnimation) {
  29342. data.eachItemGraphicEl(function (el) {
  29343. el.fadeOut(function () {
  29344. group.remove(el);
  29345. });
  29346. });
  29347. }
  29348. else {
  29349. group.removeAll();
  29350. }
  29351. };
  29352. function makeSeriesScope(data) {
  29353. var seriesModel = data.hostModel;
  29354. return {
  29355. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29356. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29357. symbolRotate: seriesModel.get('symbolRotate'),
  29358. symbolOffset: seriesModel.get('symbolOffset'),
  29359. hoverAnimation: seriesModel.get('hoverAnimation'),
  29360. labelModel: seriesModel.getModel('label'),
  29361. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29362. cursorStyle: seriesModel.get('cursor')
  29363. };
  29364. }
  29365. /*
  29366. * Licensed to the Apache Software Foundation (ASF) under one
  29367. * or more contributor license agreements. See the NOTICE file
  29368. * distributed with this work for additional information
  29369. * regarding copyright ownership. The ASF licenses this file
  29370. * to you under the Apache License, Version 2.0 (the
  29371. * "License"); you may not use this file except in compliance
  29372. * with the License. You may obtain a copy of the License at
  29373. *
  29374. * http://www.apache.org/licenses/LICENSE-2.0
  29375. *
  29376. * Unless required by applicable law or agreed to in writing,
  29377. * software distributed under the License is distributed on an
  29378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29379. * KIND, either express or implied. See the License for the
  29380. * specific language governing permissions and limitations
  29381. * under the License.
  29382. */
  29383. /**
  29384. * @param {Object} coordSys
  29385. * @param {module:echarts/data/List} data
  29386. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29387. */
  29388. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29389. var baseAxis = coordSys.getBaseAxis();
  29390. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29391. var valueStart = getValueStart(valueAxis, valueOrigin);
  29392. var baseAxisDim = baseAxis.dim;
  29393. var valueAxisDim = valueAxis.dim;
  29394. var valueDim = data.mapDimension(valueAxisDim);
  29395. var baseDim = data.mapDimension(baseAxisDim);
  29396. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29397. var dims = map(coordSys.dimensions, function (coordDim) {
  29398. return data.mapDimension(coordDim);
  29399. });
  29400. var stacked;
  29401. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29402. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  29403. dims[0] = stackResultDim;
  29404. }
  29405. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  29406. dims[1] = stackResultDim;
  29407. }
  29408. return {
  29409. dataDimsForPoint: dims,
  29410. valueStart: valueStart,
  29411. valueAxisDim: valueAxisDim,
  29412. baseAxisDim: baseAxisDim,
  29413. stacked: !!stacked,
  29414. valueDim: valueDim,
  29415. baseDim: baseDim,
  29416. baseDataOffset: baseDataOffset,
  29417. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29418. };
  29419. }
  29420. function getValueStart(valueAxis, valueOrigin) {
  29421. var valueStart = 0;
  29422. var extent = valueAxis.scale.getExtent();
  29423. if (valueOrigin === 'start') {
  29424. valueStart = extent[0];
  29425. }
  29426. else if (valueOrigin === 'end') {
  29427. valueStart = extent[1];
  29428. }
  29429. // auto
  29430. else {
  29431. // Both positive
  29432. if (extent[0] > 0) {
  29433. valueStart = extent[0];
  29434. }
  29435. // Both negative
  29436. else if (extent[1] < 0) {
  29437. valueStart = extent[1];
  29438. }
  29439. // If is one positive, and one negative, onZero shall be true
  29440. }
  29441. return valueStart;
  29442. }
  29443. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  29444. var value = NaN;
  29445. if (dataCoordInfo.stacked) {
  29446. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  29447. }
  29448. if (isNaN(value)) {
  29449. value = dataCoordInfo.valueStart;
  29450. }
  29451. var baseDataOffset = dataCoordInfo.baseDataOffset;
  29452. var stackedData = [];
  29453. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  29454. stackedData[1 - baseDataOffset] = value;
  29455. return coordSys.dataToPoint(stackedData);
  29456. }
  29457. /*
  29458. * Licensed to the Apache Software Foundation (ASF) under one
  29459. * or more contributor license agreements. See the NOTICE file
  29460. * distributed with this work for additional information
  29461. * regarding copyright ownership. The ASF licenses this file
  29462. * to you under the Apache License, Version 2.0 (the
  29463. * "License"); you may not use this file except in compliance
  29464. * with the License. You may obtain a copy of the License at
  29465. *
  29466. * http://www.apache.org/licenses/LICENSE-2.0
  29467. *
  29468. * Unless required by applicable law or agreed to in writing,
  29469. * software distributed under the License is distributed on an
  29470. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29471. * KIND, either express or implied. See the License for the
  29472. * specific language governing permissions and limitations
  29473. * under the License.
  29474. */
  29475. // var arrayDiff = require('zrender/src/core/arrayDiff');
  29476. // 'zrender/src/core/arrayDiff' has been used before, but it did
  29477. // not do well in performance when roam with fixed dataZoom window.
  29478. // function convertToIntId(newIdList, oldIdList) {
  29479. // // Generate int id instead of string id.
  29480. // // Compare string maybe slow in score function of arrDiff
  29481. // // Assume id in idList are all unique
  29482. // var idIndicesMap = {};
  29483. // var idx = 0;
  29484. // for (var i = 0; i < newIdList.length; i++) {
  29485. // idIndicesMap[newIdList[i]] = idx;
  29486. // newIdList[i] = idx++;
  29487. // }
  29488. // for (var i = 0; i < oldIdList.length; i++) {
  29489. // var oldId = oldIdList[i];
  29490. // // Same with newIdList
  29491. // if (idIndicesMap[oldId]) {
  29492. // oldIdList[i] = idIndicesMap[oldId];
  29493. // }
  29494. // else {
  29495. // oldIdList[i] = idx++;
  29496. // }
  29497. // }
  29498. // }
  29499. function diffData(oldData, newData) {
  29500. var diffResult = [];
  29501. newData.diff(oldData)
  29502. .add(function (idx) {
  29503. diffResult.push({cmd: '+', idx: idx});
  29504. })
  29505. .update(function (newIdx, oldIdx) {
  29506. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  29507. })
  29508. .remove(function (idx) {
  29509. diffResult.push({cmd: '-', idx: idx});
  29510. })
  29511. .execute();
  29512. return diffResult;
  29513. }
  29514. var lineAnimationDiff = function (
  29515. oldData, newData,
  29516. oldStackedOnPoints, newStackedOnPoints,
  29517. oldCoordSys, newCoordSys,
  29518. oldValueOrigin, newValueOrigin
  29519. ) {
  29520. var diff = diffData(oldData, newData);
  29521. // var newIdList = newData.mapArray(newData.getId);
  29522. // var oldIdList = oldData.mapArray(oldData.getId);
  29523. // convertToIntId(newIdList, oldIdList);
  29524. // // FIXME One data ?
  29525. // diff = arrayDiff(oldIdList, newIdList);
  29526. var currPoints = [];
  29527. var nextPoints = [];
  29528. // Points for stacking base line
  29529. var currStackedPoints = [];
  29530. var nextStackedPoints = [];
  29531. var status = [];
  29532. var sortedIndices = [];
  29533. var rawIndices = [];
  29534. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  29535. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  29536. for (var i = 0; i < diff.length; i++) {
  29537. var diffItem = diff[i];
  29538. var pointAdded = true;
  29539. // FIXME, animation is not so perfect when dataZoom window moves fast
  29540. // Which is in case remvoing or add more than one data in the tail or head
  29541. switch (diffItem.cmd) {
  29542. case '=':
  29543. var currentPt = oldData.getItemLayout(diffItem.idx);
  29544. var nextPt = newData.getItemLayout(diffItem.idx1);
  29545. // If previous data is NaN, use next point directly
  29546. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  29547. currentPt = nextPt.slice();
  29548. }
  29549. currPoints.push(currentPt);
  29550. nextPoints.push(nextPt);
  29551. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  29552. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  29553. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  29554. break;
  29555. case '+':
  29556. var idx = diffItem.idx;
  29557. currPoints.push(
  29558. oldCoordSys.dataToPoint([
  29559. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  29560. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  29561. ])
  29562. );
  29563. nextPoints.push(newData.getItemLayout(idx).slice());
  29564. currStackedPoints.push(
  29565. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  29566. );
  29567. nextStackedPoints.push(newStackedOnPoints[idx]);
  29568. rawIndices.push(newData.getRawIndex(idx));
  29569. break;
  29570. case '-':
  29571. var idx = diffItem.idx;
  29572. var rawIndex = oldData.getRawIndex(idx);
  29573. // Data is replaced. In the case of dynamic data queue
  29574. // FIXME FIXME FIXME
  29575. if (rawIndex !== idx) {
  29576. currPoints.push(oldData.getItemLayout(idx));
  29577. nextPoints.push(newCoordSys.dataToPoint([
  29578. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  29579. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  29580. ]));
  29581. currStackedPoints.push(oldStackedOnPoints[idx]);
  29582. nextStackedPoints.push(
  29583. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  29584. );
  29585. rawIndices.push(rawIndex);
  29586. }
  29587. else {
  29588. pointAdded = false;
  29589. }
  29590. }
  29591. // Original indices
  29592. if (pointAdded) {
  29593. status.push(diffItem);
  29594. sortedIndices.push(sortedIndices.length);
  29595. }
  29596. }
  29597. // Diff result may be crossed if all items are changed
  29598. // Sort by data index
  29599. sortedIndices.sort(function (a, b) {
  29600. return rawIndices[a] - rawIndices[b];
  29601. });
  29602. var sortedCurrPoints = [];
  29603. var sortedNextPoints = [];
  29604. var sortedCurrStackedPoints = [];
  29605. var sortedNextStackedPoints = [];
  29606. var sortedStatus = [];
  29607. for (var i = 0; i < sortedIndices.length; i++) {
  29608. var idx = sortedIndices[i];
  29609. sortedCurrPoints[i] = currPoints[idx];
  29610. sortedNextPoints[i] = nextPoints[idx];
  29611. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  29612. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  29613. sortedStatus[i] = status[idx];
  29614. }
  29615. return {
  29616. current: sortedCurrPoints,
  29617. next: sortedNextPoints,
  29618. stackedOnCurrent: sortedCurrStackedPoints,
  29619. stackedOnNext: sortedNextStackedPoints,
  29620. status: sortedStatus
  29621. };
  29622. };
  29623. /*
  29624. * Licensed to the Apache Software Foundation (ASF) under one
  29625. * or more contributor license agreements. See the NOTICE file
  29626. * distributed with this work for additional information
  29627. * regarding copyright ownership. The ASF licenses this file
  29628. * to you under the Apache License, Version 2.0 (the
  29629. * "License"); you may not use this file except in compliance
  29630. * with the License. You may obtain a copy of the License at
  29631. *
  29632. * http://www.apache.org/licenses/LICENSE-2.0
  29633. *
  29634. * Unless required by applicable law or agreed to in writing,
  29635. * software distributed under the License is distributed on an
  29636. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29637. * KIND, either express or implied. See the License for the
  29638. * specific language governing permissions and limitations
  29639. * under the License.
  29640. */
  29641. // Poly path support NaN point
  29642. var vec2Min = min;
  29643. var vec2Max = max;
  29644. var scaleAndAdd$1 = scaleAndAdd;
  29645. var v2Copy = copy;
  29646. // Temporary variable
  29647. var v = [];
  29648. var cp0 = [];
  29649. var cp1 = [];
  29650. function isPointNull(p) {
  29651. return isNaN(p[0]) || isNaN(p[1]);
  29652. }
  29653. function drawSegment(
  29654. ctx, points, start, segLen, allLen,
  29655. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29656. ) {
  29657. // if (smoothMonotone == null) {
  29658. // if (isMono(points, 'x')) {
  29659. // return drawMono(ctx, points, start, segLen, allLen,
  29660. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  29661. // }
  29662. // else if (isMono(points, 'y')) {
  29663. // return drawMono(ctx, points, start, segLen, allLen,
  29664. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  29665. // }
  29666. // else {
  29667. // return drawNonMono.apply(this, arguments);
  29668. // }
  29669. // }
  29670. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  29671. // return drawMono.apply(this, arguments);
  29672. // }
  29673. // else {
  29674. // return drawNonMono.apply(this, arguments);
  29675. // }
  29676. if (smoothMonotone === 'none' || !smoothMonotone) {
  29677. return drawNonMono.apply(this, arguments);
  29678. }
  29679. else {
  29680. return drawMono.apply(this, arguments);
  29681. }
  29682. }
  29683. /**
  29684. * Check if points is in monotone.
  29685. *
  29686. * @param {number[][]} points Array of points which is in [x, y] form
  29687. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  29688. * dimension that is checking.
  29689. * If is 'none', `drawNonMono` should be
  29690. * called.
  29691. * If is undefined, either being monotone
  29692. * in 'x' or 'y' will call `drawMono`.
  29693. */
  29694. // function isMono(points, smoothMonotone) {
  29695. // if (points.length <= 1) {
  29696. // return true;
  29697. // }
  29698. // var dim = smoothMonotone === 'x' ? 0 : 1;
  29699. // var last = points[0][dim];
  29700. // var lastDiff = 0;
  29701. // for (var i = 1; i < points.length; ++i) {
  29702. // var diff = points[i][dim] - last;
  29703. // if (!isNaN(diff) && !isNaN(lastDiff)
  29704. // && diff !== 0 && lastDiff !== 0
  29705. // && ((diff >= 0) !== (lastDiff >= 0))
  29706. // ) {
  29707. // return false;
  29708. // }
  29709. // if (!isNaN(diff) && diff !== 0) {
  29710. // lastDiff = diff;
  29711. // last = points[i][dim];
  29712. // }
  29713. // }
  29714. // return true;
  29715. // }
  29716. /**
  29717. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  29718. * control points will be used. This should be used when points are monotone
  29719. * either in x or y dimension.
  29720. */
  29721. function drawMono(
  29722. ctx, points, start, segLen, allLen,
  29723. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29724. ) {
  29725. var prevIdx = 0;
  29726. var idx = start;
  29727. for (var k = 0; k < segLen; k++) {
  29728. var p = points[idx];
  29729. if (idx >= allLen || idx < 0) {
  29730. break;
  29731. }
  29732. if (isPointNull(p)) {
  29733. if (connectNulls) {
  29734. idx += dir;
  29735. continue;
  29736. }
  29737. break;
  29738. }
  29739. if (idx === start) {
  29740. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29741. }
  29742. else {
  29743. if (smooth > 0) {
  29744. var prevP = points[prevIdx];
  29745. var dim = smoothMonotone === 'y' ? 1 : 0;
  29746. // Length of control point to p, either in x or y, but not both
  29747. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  29748. v2Copy(cp0, prevP);
  29749. cp0[dim] = prevP[dim] + ctrlLen;
  29750. v2Copy(cp1, p);
  29751. cp1[dim] = p[dim] - ctrlLen;
  29752. ctx.bezierCurveTo(
  29753. cp0[0], cp0[1],
  29754. cp1[0], cp1[1],
  29755. p[0], p[1]
  29756. );
  29757. }
  29758. else {
  29759. ctx.lineTo(p[0], p[1]);
  29760. }
  29761. }
  29762. prevIdx = idx;
  29763. idx += dir;
  29764. }
  29765. return k;
  29766. }
  29767. /**
  29768. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  29769. * situations. This should be used when points are non-monotone neither in x or
  29770. * y dimension.
  29771. */
  29772. function drawNonMono(
  29773. ctx, points, start, segLen, allLen,
  29774. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  29775. ) {
  29776. var prevIdx = 0;
  29777. var idx = start;
  29778. for (var k = 0; k < segLen; k++) {
  29779. var p = points[idx];
  29780. if (idx >= allLen || idx < 0) {
  29781. break;
  29782. }
  29783. if (isPointNull(p)) {
  29784. if (connectNulls) {
  29785. idx += dir;
  29786. continue;
  29787. }
  29788. break;
  29789. }
  29790. if (idx === start) {
  29791. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  29792. v2Copy(cp0, p);
  29793. }
  29794. else {
  29795. if (smooth > 0) {
  29796. var nextIdx = idx + dir;
  29797. var nextP = points[nextIdx];
  29798. if (connectNulls) {
  29799. // Find next point not null
  29800. while (nextP && isPointNull(points[nextIdx])) {
  29801. nextIdx += dir;
  29802. nextP = points[nextIdx];
  29803. }
  29804. }
  29805. var ratioNextSeg = 0.5;
  29806. var prevP = points[prevIdx];
  29807. var nextP = points[nextIdx];
  29808. // Last point
  29809. if (!nextP || isPointNull(nextP)) {
  29810. v2Copy(cp1, p);
  29811. }
  29812. else {
  29813. // If next data is null in not connect case
  29814. if (isPointNull(nextP) && !connectNulls) {
  29815. nextP = p;
  29816. }
  29817. sub(v, nextP, prevP);
  29818. var lenPrevSeg;
  29819. var lenNextSeg;
  29820. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  29821. var dim = smoothMonotone === 'x' ? 0 : 1;
  29822. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  29823. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  29824. }
  29825. else {
  29826. lenPrevSeg = dist(p, prevP);
  29827. lenNextSeg = dist(p, nextP);
  29828. }
  29829. // Use ratio of seg length
  29830. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  29831. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  29832. }
  29833. // Smooth constraint
  29834. vec2Min(cp0, cp0, smoothMax);
  29835. vec2Max(cp0, cp0, smoothMin);
  29836. vec2Min(cp1, cp1, smoothMax);
  29837. vec2Max(cp1, cp1, smoothMin);
  29838. ctx.bezierCurveTo(
  29839. cp0[0], cp0[1],
  29840. cp1[0], cp1[1],
  29841. p[0], p[1]
  29842. );
  29843. // cp0 of next segment
  29844. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  29845. }
  29846. else {
  29847. ctx.lineTo(p[0], p[1]);
  29848. }
  29849. }
  29850. prevIdx = idx;
  29851. idx += dir;
  29852. }
  29853. return k;
  29854. }
  29855. function getBoundingBox(points, smoothConstraint) {
  29856. var ptMin = [Infinity, Infinity];
  29857. var ptMax = [-Infinity, -Infinity];
  29858. if (smoothConstraint) {
  29859. for (var i = 0; i < points.length; i++) {
  29860. var pt = points[i];
  29861. if (pt[0] < ptMin[0]) {
  29862. ptMin[0] = pt[0];
  29863. }
  29864. if (pt[1] < ptMin[1]) {
  29865. ptMin[1] = pt[1];
  29866. }
  29867. if (pt[0] > ptMax[0]) {
  29868. ptMax[0] = pt[0];
  29869. }
  29870. if (pt[1] > ptMax[1]) {
  29871. ptMax[1] = pt[1];
  29872. }
  29873. }
  29874. }
  29875. return {
  29876. min: smoothConstraint ? ptMin : ptMax,
  29877. max: smoothConstraint ? ptMax : ptMin
  29878. };
  29879. }
  29880. var Polyline$1 = Path.extend({
  29881. type: 'ec-polyline',
  29882. shape: {
  29883. points: [],
  29884. smooth: 0,
  29885. smoothConstraint: true,
  29886. smoothMonotone: null,
  29887. connectNulls: false
  29888. },
  29889. style: {
  29890. fill: null,
  29891. stroke: '#000'
  29892. },
  29893. brush: fixClipWithShadow(Path.prototype.brush),
  29894. buildPath: function (ctx, shape) {
  29895. var points = shape.points;
  29896. var i = 0;
  29897. var len$$1 = points.length;
  29898. var result = getBoundingBox(points, shape.smoothConstraint);
  29899. if (shape.connectNulls) {
  29900. // Must remove first and last null values avoid draw error in polygon
  29901. for (; len$$1 > 0; len$$1--) {
  29902. if (!isPointNull(points[len$$1 - 1])) {
  29903. break;
  29904. }
  29905. }
  29906. for (; i < len$$1; i++) {
  29907. if (!isPointNull(points[i])) {
  29908. break;
  29909. }
  29910. }
  29911. }
  29912. while (i < len$$1) {
  29913. i += drawSegment(
  29914. ctx, points, i, len$$1, len$$1,
  29915. 1, result.min, result.max, shape.smooth,
  29916. shape.smoothMonotone, shape.connectNulls
  29917. ) + 1;
  29918. }
  29919. }
  29920. });
  29921. var Polygon$1 = Path.extend({
  29922. type: 'ec-polygon',
  29923. shape: {
  29924. points: [],
  29925. // Offset between stacked base points and points
  29926. stackedOnPoints: [],
  29927. smooth: 0,
  29928. stackedOnSmooth: 0,
  29929. smoothConstraint: true,
  29930. smoothMonotone: null,
  29931. connectNulls: false
  29932. },
  29933. brush: fixClipWithShadow(Path.prototype.brush),
  29934. buildPath: function (ctx, shape) {
  29935. var points = shape.points;
  29936. var stackedOnPoints = shape.stackedOnPoints;
  29937. var i = 0;
  29938. var len$$1 = points.length;
  29939. var smoothMonotone = shape.smoothMonotone;
  29940. var bbox = getBoundingBox(points, shape.smoothConstraint);
  29941. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  29942. if (shape.connectNulls) {
  29943. // Must remove first and last null values avoid draw error in polygon
  29944. for (; len$$1 > 0; len$$1--) {
  29945. if (!isPointNull(points[len$$1 - 1])) {
  29946. break;
  29947. }
  29948. }
  29949. for (; i < len$$1; i++) {
  29950. if (!isPointNull(points[i])) {
  29951. break;
  29952. }
  29953. }
  29954. }
  29955. while (i < len$$1) {
  29956. var k = drawSegment(
  29957. ctx, points, i, len$$1, len$$1,
  29958. 1, bbox.min, bbox.max, shape.smooth,
  29959. smoothMonotone, shape.connectNulls
  29960. );
  29961. drawSegment(
  29962. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  29963. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  29964. smoothMonotone, shape.connectNulls
  29965. );
  29966. i += k + 1;
  29967. ctx.closePath();
  29968. }
  29969. }
  29970. });
  29971. /*
  29972. * Licensed to the Apache Software Foundation (ASF) under one
  29973. * or more contributor license agreements. See the NOTICE file
  29974. * distributed with this work for additional information
  29975. * regarding copyright ownership. The ASF licenses this file
  29976. * to you under the Apache License, Version 2.0 (the
  29977. * "License"); you may not use this file except in compliance
  29978. * with the License. You may obtain a copy of the License at
  29979. *
  29980. * http://www.apache.org/licenses/LICENSE-2.0
  29981. *
  29982. * Unless required by applicable law or agreed to in writing,
  29983. * software distributed under the License is distributed on an
  29984. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29985. * KIND, either express or implied. See the License for the
  29986. * specific language governing permissions and limitations
  29987. * under the License.
  29988. */
  29989. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  29990. var rect = cartesian.getArea();
  29991. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  29992. var x = rect.x;
  29993. var y = rect.y;
  29994. var width = rect.width;
  29995. var height = rect.height;
  29996. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  29997. // Expand the clip path a bit to avoid the border is clipped and looks thinner
  29998. x -= lineWidth / 2;
  29999. y -= lineWidth / 2;
  30000. width += lineWidth;
  30001. height += lineWidth;
  30002. var clipPath = new Rect({
  30003. shape: {
  30004. x: x,
  30005. y: y,
  30006. width: width,
  30007. height: height
  30008. }
  30009. });
  30010. if (hasAnimation) {
  30011. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30012. initProps(clipPath, {
  30013. shape: {
  30014. width: width,
  30015. height: height
  30016. }
  30017. }, seriesModel);
  30018. }
  30019. return clipPath;
  30020. }
  30021. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  30022. var sectorArea = polar.getArea();
  30023. // Avoid float number rounding error for symbol on the edge of axis extent.
  30024. var clipPath = new Sector({
  30025. shape: {
  30026. cx: round$1(polar.cx, 1),
  30027. cy: round$1(polar.cy, 1),
  30028. r0: round$1(sectorArea.r0, 1),
  30029. r: round$1(sectorArea.r, 1),
  30030. startAngle: sectorArea.startAngle,
  30031. endAngle: sectorArea.endAngle,
  30032. clockwise: sectorArea.clockwise
  30033. }
  30034. });
  30035. if (hasAnimation) {
  30036. clipPath.shape.endAngle = sectorArea.startAngle;
  30037. initProps(clipPath, {
  30038. shape: {
  30039. endAngle: sectorArea.endAngle
  30040. }
  30041. }, seriesModel);
  30042. }
  30043. return clipPath;
  30044. }
  30045. function createClipPath(coordSys, hasAnimation, seriesModel) {
  30046. if (!coordSys) {
  30047. return null;
  30048. }
  30049. else if (coordSys.type === 'polar') {
  30050. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30051. }
  30052. else if (coordSys.type === 'cartesian2d') {
  30053. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  30054. }
  30055. return null;
  30056. }
  30057. /*
  30058. * Licensed to the Apache Software Foundation (ASF) under one
  30059. * or more contributor license agreements. See the NOTICE file
  30060. * distributed with this work for additional information
  30061. * regarding copyright ownership. The ASF licenses this file
  30062. * to you under the Apache License, Version 2.0 (the
  30063. * "License"); you may not use this file except in compliance
  30064. * with the License. You may obtain a copy of the License at
  30065. *
  30066. * http://www.apache.org/licenses/LICENSE-2.0
  30067. *
  30068. * Unless required by applicable law or agreed to in writing,
  30069. * software distributed under the License is distributed on an
  30070. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30071. * KIND, either express or implied. See the License for the
  30072. * specific language governing permissions and limitations
  30073. * under the License.
  30074. */
  30075. // FIXME step not support polar
  30076. function isPointsSame(points1, points2) {
  30077. if (points1.length !== points2.length) {
  30078. return;
  30079. }
  30080. for (var i = 0; i < points1.length; i++) {
  30081. var p1 = points1[i];
  30082. var p2 = points2[i];
  30083. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30084. return;
  30085. }
  30086. }
  30087. return true;
  30088. }
  30089. function getSmooth(smooth) {
  30090. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30091. }
  30092. /**
  30093. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30094. * @param {module:echarts/data/List} data
  30095. * @param {Object} dataCoordInfo
  30096. * @param {Array.<Array.<number>>} points
  30097. */
  30098. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30099. if (!dataCoordInfo.valueDim) {
  30100. return [];
  30101. }
  30102. var points = [];
  30103. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30104. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30105. }
  30106. return points;
  30107. }
  30108. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30109. var baseAxis = coordSys.getBaseAxis();
  30110. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30111. var stepPoints = [];
  30112. for (var i = 0; i < points.length - 1; i++) {
  30113. var nextPt = points[i + 1];
  30114. var pt = points[i];
  30115. stepPoints.push(pt);
  30116. var stepPt = [];
  30117. switch (stepTurnAt) {
  30118. case 'end':
  30119. stepPt[baseIndex] = nextPt[baseIndex];
  30120. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30121. // default is start
  30122. stepPoints.push(stepPt);
  30123. break;
  30124. case 'middle':
  30125. // default is start
  30126. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30127. var stepPt2 = [];
  30128. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30129. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30130. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30131. stepPoints.push(stepPt);
  30132. stepPoints.push(stepPt2);
  30133. break;
  30134. default:
  30135. stepPt[baseIndex] = pt[baseIndex];
  30136. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30137. // default is start
  30138. stepPoints.push(stepPt);
  30139. }
  30140. }
  30141. // Last points
  30142. points[i] && stepPoints.push(points[i]);
  30143. return stepPoints;
  30144. }
  30145. function getVisualGradient(data, coordSys) {
  30146. var visualMetaList = data.getVisual('visualMeta');
  30147. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30148. // When data.count() is 0, gradient range can not be calculated.
  30149. return;
  30150. }
  30151. if (coordSys.type !== 'cartesian2d') {
  30152. if (__DEV__) {
  30153. console.warn('Visual map on line style is only supported on cartesian2d.');
  30154. }
  30155. return;
  30156. }
  30157. var coordDim;
  30158. var visualMeta;
  30159. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30160. var dimIndex = visualMetaList[i].dimension;
  30161. var dimName = data.dimensions[dimIndex];
  30162. var dimInfo = data.getDimensionInfo(dimName);
  30163. coordDim = dimInfo && dimInfo.coordDim;
  30164. // Can only be x or y
  30165. if (coordDim === 'x' || coordDim === 'y') {
  30166. visualMeta = visualMetaList[i];
  30167. break;
  30168. }
  30169. }
  30170. if (!visualMeta) {
  30171. if (__DEV__) {
  30172. console.warn('Visual map on line style only support x or y dimension.');
  30173. }
  30174. return;
  30175. }
  30176. // If the area to be rendered is bigger than area defined by LinearGradient,
  30177. // the canvas spec prescribes that the color of the first stop and the last
  30178. // stop should be used. But if two stops are added at offset 0, in effect
  30179. // browsers use the color of the second stop to render area outside
  30180. // LinearGradient. So we can only infinitesimally extend area defined in
  30181. // LinearGradient to render `outerColors`.
  30182. var axis = coordSys.getAxis(coordDim);
  30183. // dataToCoor mapping may not be linear, but must be monotonic.
  30184. var colorStops = map(visualMeta.stops, function (stop) {
  30185. return {
  30186. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30187. color: stop.color
  30188. };
  30189. });
  30190. var stopLen = colorStops.length;
  30191. var outerColors = visualMeta.outerColors.slice();
  30192. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30193. colorStops.reverse();
  30194. outerColors.reverse();
  30195. }
  30196. var tinyExtent = 10; // Arbitrary value: 10px
  30197. var minCoord = colorStops[0].coord - tinyExtent;
  30198. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30199. var coordSpan = maxCoord - minCoord;
  30200. if (coordSpan < 1e-3) {
  30201. return 'transparent';
  30202. }
  30203. each$1(colorStops, function (stop) {
  30204. stop.offset = (stop.coord - minCoord) / coordSpan;
  30205. });
  30206. colorStops.push({
  30207. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30208. color: outerColors[1] || 'transparent'
  30209. });
  30210. colorStops.unshift({ // notice colorStops.length have been changed.
  30211. offset: stopLen ? colorStops[0].offset : 0.5,
  30212. color: outerColors[0] || 'transparent'
  30213. });
  30214. // zrUtil.each(colorStops, function (colorStop) {
  30215. // // Make sure each offset has rounded px to avoid not sharp edge
  30216. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30217. // });
  30218. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30219. gradient[coordDim] = minCoord;
  30220. gradient[coordDim + '2'] = maxCoord;
  30221. return gradient;
  30222. }
  30223. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30224. var showAllSymbol = seriesModel.get('showAllSymbol');
  30225. var isAuto = showAllSymbol === 'auto';
  30226. if (showAllSymbol && !isAuto) {
  30227. return;
  30228. }
  30229. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30230. if (!categoryAxis) {
  30231. return;
  30232. }
  30233. // Note that category label interval strategy might bring some weird effect
  30234. // in some scenario: users may wonder why some of the symbols are not
  30235. // displayed. So we show all symbols as possible as we can.
  30236. if (isAuto
  30237. // Simplify the logic, do not determine label overlap here.
  30238. && canShowAllSymbolForCategory(categoryAxis, data)
  30239. ) {
  30240. return;
  30241. }
  30242. // Otherwise follow the label interval strategy on category axis.
  30243. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30244. var labelMap = {};
  30245. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30246. labelMap[labelItem.tickValue] = 1;
  30247. });
  30248. return function (dataIndex) {
  30249. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30250. };
  30251. }
  30252. function canShowAllSymbolForCategory(categoryAxis, data) {
  30253. // In mose cases, line is monotonous on category axis, and the label size
  30254. // is close with each other. So we check the symbol size and some of the
  30255. // label size alone with the category axis to estimate whether all symbol
  30256. // can be shown without overlap.
  30257. var axisExtent = categoryAxis.getExtent();
  30258. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30259. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30260. // Sampling some points, max 5.
  30261. var dataLen = data.count();
  30262. var step = Math.max(1, Math.round(dataLen / 5));
  30263. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30264. if (SymbolClz.getSymbolSize(
  30265. data, dataIndex
  30266. // Only for cartesian, where `isHorizontal` exists.
  30267. )[categoryAxis.isHorizontal() ? 1 : 0]
  30268. // Empirical number
  30269. * 1.5 > availSize
  30270. ) {
  30271. return false;
  30272. }
  30273. }
  30274. return true;
  30275. }
  30276. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  30277. if (coordSys.type === 'cartesian2d') {
  30278. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  30279. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel);
  30280. // Expand clip shape to avoid clipping when line value exceeds axis
  30281. if (!seriesModel.get('clip', true)) {
  30282. var rectShape = clipPath.shape;
  30283. var expandSize = Math.max(rectShape.width, rectShape.height);
  30284. if (isHorizontal) {
  30285. rectShape.y -= expandSize;
  30286. rectShape.height += expandSize * 2;
  30287. }
  30288. else {
  30289. rectShape.x -= expandSize;
  30290. rectShape.width += expandSize * 2;
  30291. }
  30292. }
  30293. return clipPath;
  30294. }
  30295. else {
  30296. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  30297. }
  30298. }
  30299. Chart.extend({
  30300. type: 'line',
  30301. init: function () {
  30302. var lineGroup = new Group();
  30303. var symbolDraw = new SymbolDraw();
  30304. this.group.add(symbolDraw.group);
  30305. this._symbolDraw = symbolDraw;
  30306. this._lineGroup = lineGroup;
  30307. },
  30308. render: function (seriesModel, ecModel, api) {
  30309. var coordSys = seriesModel.coordinateSystem;
  30310. var group = this.group;
  30311. var data = seriesModel.getData();
  30312. var lineStyleModel = seriesModel.getModel('lineStyle');
  30313. var areaStyleModel = seriesModel.getModel('areaStyle');
  30314. var points = data.mapArray(data.getItemLayout);
  30315. var isCoordSysPolar = coordSys.type === 'polar';
  30316. var prevCoordSys = this._coordSys;
  30317. var symbolDraw = this._symbolDraw;
  30318. var polyline = this._polyline;
  30319. var polygon = this._polygon;
  30320. var lineGroup = this._lineGroup;
  30321. var hasAnimation = seriesModel.get('animation');
  30322. var isAreaChart = !areaStyleModel.isEmpty();
  30323. var valueOrigin = areaStyleModel.get('origin');
  30324. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30325. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30326. var showSymbol = seriesModel.get('showSymbol');
  30327. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30328. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30329. // Remove temporary symbols
  30330. var oldData = this._data;
  30331. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30332. if (el.__temp) {
  30333. group.remove(el);
  30334. oldData.setItemGraphicEl(idx, null);
  30335. }
  30336. });
  30337. // Remove previous created symbols if showSymbol changed to false
  30338. if (!showSymbol) {
  30339. symbolDraw.remove();
  30340. }
  30341. group.add(lineGroup);
  30342. // FIXME step not support polar
  30343. var step = !isCoordSysPolar && seriesModel.get('step');
  30344. var clipShapeForSymbol;
  30345. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  30346. clipShapeForSymbol = coordSys.getArea();
  30347. // Avoid float number rounding error for symbol on the edge of axis extent.
  30348. // See #7913 and `test/dataZoom-clip.html`.
  30349. if (clipShapeForSymbol.width != null) {
  30350. clipShapeForSymbol.x -= 0.1;
  30351. clipShapeForSymbol.y -= 0.1;
  30352. clipShapeForSymbol.width += 0.2;
  30353. clipShapeForSymbol.height += 0.2;
  30354. }
  30355. else if (clipShapeForSymbol.r0) {
  30356. clipShapeForSymbol.r0 -= 0.5;
  30357. clipShapeForSymbol.r1 += 0.5;
  30358. }
  30359. }
  30360. this._clipShapeForSymbol = clipShapeForSymbol;
  30361. // Initialization animation or coordinate system changed
  30362. if (
  30363. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30364. ) {
  30365. showSymbol && symbolDraw.updateData(data, {
  30366. isIgnore: isIgnoreFunc,
  30367. clipShape: clipShapeForSymbol
  30368. });
  30369. if (step) {
  30370. // TODO If stacked series is not step
  30371. points = turnPointsIntoStep(points, coordSys, step);
  30372. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30373. }
  30374. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30375. if (isAreaChart) {
  30376. polygon = this._newPolygon(
  30377. points, stackedOnPoints,
  30378. coordSys, hasAnimation
  30379. );
  30380. }
  30381. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  30382. }
  30383. else {
  30384. if (isAreaChart && !polygon) {
  30385. // If areaStyle is added
  30386. polygon = this._newPolygon(
  30387. points, stackedOnPoints,
  30388. coordSys, hasAnimation
  30389. );
  30390. }
  30391. else if (polygon && !isAreaChart) {
  30392. // If areaStyle is removed
  30393. lineGroup.remove(polygon);
  30394. polygon = this._polygon = null;
  30395. }
  30396. // Update clipPath
  30397. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel));
  30398. // Always update, or it is wrong in the case turning on legend
  30399. // because points are not changed
  30400. showSymbol && symbolDraw.updateData(data, {
  30401. isIgnore: isIgnoreFunc,
  30402. clipShape: clipShapeForSymbol
  30403. });
  30404. // Stop symbol animation and sync with line points
  30405. // FIXME performance?
  30406. data.eachItemGraphicEl(function (el) {
  30407. el.stopAnimation(true);
  30408. });
  30409. // In the case data zoom triggerred refreshing frequently
  30410. // Data may not change if line has a category axis. So it should animate nothing
  30411. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30412. || !isPointsSame(this._points, points)
  30413. ) {
  30414. if (hasAnimation) {
  30415. this._updateAnimation(
  30416. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30417. );
  30418. }
  30419. else {
  30420. // Not do it in update with animation
  30421. if (step) {
  30422. // TODO If stacked series is not step
  30423. points = turnPointsIntoStep(points, coordSys, step);
  30424. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30425. }
  30426. polyline.setShape({
  30427. points: points
  30428. });
  30429. polygon && polygon.setShape({
  30430. points: points,
  30431. stackedOnPoints: stackedOnPoints
  30432. });
  30433. }
  30434. }
  30435. }
  30436. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30437. polyline.useStyle(defaults(
  30438. // Use color in lineStyle first
  30439. lineStyleModel.getLineStyle(),
  30440. {
  30441. fill: 'none',
  30442. stroke: visualColor,
  30443. lineJoin: 'bevel'
  30444. }
  30445. ));
  30446. var smooth = seriesModel.get('smooth');
  30447. smooth = getSmooth(seriesModel.get('smooth'));
  30448. polyline.setShape({
  30449. smooth: smooth,
  30450. smoothMonotone: seriesModel.get('smoothMonotone'),
  30451. connectNulls: seriesModel.get('connectNulls')
  30452. });
  30453. if (polygon) {
  30454. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30455. var stackedOnSmooth = 0;
  30456. polygon.useStyle(defaults(
  30457. areaStyleModel.getAreaStyle(),
  30458. {
  30459. fill: visualColor,
  30460. opacity: 0.7,
  30461. lineJoin: 'bevel'
  30462. }
  30463. ));
  30464. if (stackedOnSeries) {
  30465. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30466. }
  30467. polygon.setShape({
  30468. smooth: smooth,
  30469. stackedOnSmooth: stackedOnSmooth,
  30470. smoothMonotone: seriesModel.get('smoothMonotone'),
  30471. connectNulls: seriesModel.get('connectNulls')
  30472. });
  30473. }
  30474. this._data = data;
  30475. // Save the coordinate system for transition animation when data changed
  30476. this._coordSys = coordSys;
  30477. this._stackedOnPoints = stackedOnPoints;
  30478. this._points = points;
  30479. this._step = step;
  30480. this._valueOrigin = valueOrigin;
  30481. },
  30482. dispose: function () {},
  30483. highlight: function (seriesModel, ecModel, api, payload) {
  30484. var data = seriesModel.getData();
  30485. var dataIndex = queryDataIndex(data, payload);
  30486. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  30487. var symbol = data.getItemGraphicEl(dataIndex);
  30488. if (!symbol) {
  30489. // Create a temporary symbol if it is not exists
  30490. var pt = data.getItemLayout(dataIndex);
  30491. if (!pt) {
  30492. // Null data
  30493. return;
  30494. }
  30495. // fix #11360: should't draw symbol outside clipShapeForSymbol
  30496. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  30497. return;
  30498. }
  30499. symbol = new SymbolClz(data, dataIndex);
  30500. symbol.position = pt;
  30501. symbol.setZ(
  30502. seriesModel.get('zlevel'),
  30503. seriesModel.get('z')
  30504. );
  30505. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  30506. symbol.__temp = true;
  30507. data.setItemGraphicEl(dataIndex, symbol);
  30508. // Stop scale animation
  30509. symbol.stopSymbolAnimation(true);
  30510. this.group.add(symbol);
  30511. }
  30512. symbol.highlight();
  30513. }
  30514. else {
  30515. // Highlight whole series
  30516. Chart.prototype.highlight.call(
  30517. this, seriesModel, ecModel, api, payload
  30518. );
  30519. }
  30520. },
  30521. downplay: function (seriesModel, ecModel, api, payload) {
  30522. var data = seriesModel.getData();
  30523. var dataIndex = queryDataIndex(data, payload);
  30524. if (dataIndex != null && dataIndex >= 0) {
  30525. var symbol = data.getItemGraphicEl(dataIndex);
  30526. if (symbol) {
  30527. if (symbol.__temp) {
  30528. data.setItemGraphicEl(dataIndex, null);
  30529. this.group.remove(symbol);
  30530. }
  30531. else {
  30532. symbol.downplay();
  30533. }
  30534. }
  30535. }
  30536. else {
  30537. // FIXME
  30538. // can not downplay completely.
  30539. // Downplay whole series
  30540. Chart.prototype.downplay.call(
  30541. this, seriesModel, ecModel, api, payload
  30542. );
  30543. }
  30544. },
  30545. /**
  30546. * @param {module:zrender/container/Group} group
  30547. * @param {Array.<Array.<number>>} points
  30548. * @private
  30549. */
  30550. _newPolyline: function (points) {
  30551. var polyline = this._polyline;
  30552. // Remove previous created polyline
  30553. if (polyline) {
  30554. this._lineGroup.remove(polyline);
  30555. }
  30556. polyline = new Polyline$1({
  30557. shape: {
  30558. points: points
  30559. },
  30560. silent: true,
  30561. z2: 10
  30562. });
  30563. this._lineGroup.add(polyline);
  30564. this._polyline = polyline;
  30565. return polyline;
  30566. },
  30567. /**
  30568. * @param {module:zrender/container/Group} group
  30569. * @param {Array.<Array.<number>>} stackedOnPoints
  30570. * @param {Array.<Array.<number>>} points
  30571. * @private
  30572. */
  30573. _newPolygon: function (points, stackedOnPoints) {
  30574. var polygon = this._polygon;
  30575. // Remove previous created polygon
  30576. if (polygon) {
  30577. this._lineGroup.remove(polygon);
  30578. }
  30579. polygon = new Polygon$1({
  30580. shape: {
  30581. points: points,
  30582. stackedOnPoints: stackedOnPoints
  30583. },
  30584. silent: true
  30585. });
  30586. this._lineGroup.add(polygon);
  30587. this._polygon = polygon;
  30588. return polygon;
  30589. },
  30590. /**
  30591. * @private
  30592. */
  30593. // FIXME Two value axis
  30594. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  30595. var polyline = this._polyline;
  30596. var polygon = this._polygon;
  30597. var seriesModel = data.hostModel;
  30598. var diff = lineAnimationDiff(
  30599. this._data, data,
  30600. this._stackedOnPoints, stackedOnPoints,
  30601. this._coordSys, coordSys,
  30602. this._valueOrigin, valueOrigin
  30603. );
  30604. var current = diff.current;
  30605. var stackedOnCurrent = diff.stackedOnCurrent;
  30606. var next = diff.next;
  30607. var stackedOnNext = diff.stackedOnNext;
  30608. if (step) {
  30609. // TODO If stacked series is not step
  30610. current = turnPointsIntoStep(diff.current, coordSys, step);
  30611. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  30612. next = turnPointsIntoStep(diff.next, coordSys, step);
  30613. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  30614. }
  30615. // `diff.current` is subset of `current` (which should be ensured by
  30616. // turnPointsIntoStep), so points in `__points` can be updated when
  30617. // points in `current` are update during animation.
  30618. polyline.shape.__points = diff.current;
  30619. polyline.shape.points = current;
  30620. updateProps(polyline, {
  30621. shape: {
  30622. points: next
  30623. }
  30624. }, seriesModel);
  30625. if (polygon) {
  30626. polygon.setShape({
  30627. points: current,
  30628. stackedOnPoints: stackedOnCurrent
  30629. });
  30630. updateProps(polygon, {
  30631. shape: {
  30632. points: next,
  30633. stackedOnPoints: stackedOnNext
  30634. }
  30635. }, seriesModel);
  30636. }
  30637. var updatedDataInfo = [];
  30638. var diffStatus = diff.status;
  30639. for (var i = 0; i < diffStatus.length; i++) {
  30640. var cmd = diffStatus[i].cmd;
  30641. if (cmd === '=') {
  30642. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  30643. if (el) {
  30644. updatedDataInfo.push({
  30645. el: el,
  30646. ptIdx: i // Index of points
  30647. });
  30648. }
  30649. }
  30650. }
  30651. if (polyline.animators && polyline.animators.length) {
  30652. polyline.animators[0].during(function () {
  30653. for (var i = 0; i < updatedDataInfo.length; i++) {
  30654. var el = updatedDataInfo[i].el;
  30655. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  30656. }
  30657. });
  30658. }
  30659. },
  30660. remove: function (ecModel) {
  30661. var group = this.group;
  30662. var oldData = this._data;
  30663. this._lineGroup.removeAll();
  30664. this._symbolDraw.remove(true);
  30665. // Remove temporary created elements when highlighting
  30666. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30667. if (el.__temp) {
  30668. group.remove(el);
  30669. oldData.setItemGraphicEl(idx, null);
  30670. }
  30671. });
  30672. this._polyline =
  30673. this._polygon =
  30674. this._coordSys =
  30675. this._points =
  30676. this._stackedOnPoints =
  30677. this._data = null;
  30678. }
  30679. });
  30680. /*
  30681. * Licensed to the Apache Software Foundation (ASF) under one
  30682. * or more contributor license agreements. See the NOTICE file
  30683. * distributed with this work for additional information
  30684. * regarding copyright ownership. The ASF licenses this file
  30685. * to you under the Apache License, Version 2.0 (the
  30686. * "License"); you may not use this file except in compliance
  30687. * with the License. You may obtain a copy of the License at
  30688. *
  30689. * http://www.apache.org/licenses/LICENSE-2.0
  30690. *
  30691. * Unless required by applicable law or agreed to in writing,
  30692. * software distributed under the License is distributed on an
  30693. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30694. * KIND, either express or implied. See the License for the
  30695. * specific language governing permissions and limitations
  30696. * under the License.
  30697. */
  30698. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  30699. // Encoding visual for all series include which is filtered for legend drawing
  30700. return {
  30701. seriesType: seriesType,
  30702. // For legend.
  30703. performRawSeries: true,
  30704. reset: function (seriesModel, ecModel, api) {
  30705. var data = seriesModel.getData();
  30706. var symbolType = seriesModel.get('symbol');
  30707. var symbolSize = seriesModel.get('symbolSize');
  30708. var keepAspect = seriesModel.get('symbolKeepAspect');
  30709. var hasSymbolTypeCallback = isFunction$1(symbolType);
  30710. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  30711. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback;
  30712. var seriesSymbol = (!hasSymbolTypeCallback && symbolType) ? symbolType : defaultSymbolType;
  30713. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  30714. data.setVisual({
  30715. legendSymbol: legendSymbol || seriesSymbol,
  30716. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  30717. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  30718. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  30719. // some cases but generally it is not recommanded.
  30720. symbol: seriesSymbol,
  30721. symbolSize: seriesSymbolSize,
  30722. symbolKeepAspect: keepAspect
  30723. });
  30724. // Only visible series has each data be visual encoded
  30725. if (ecModel.isSeriesFiltered(seriesModel)) {
  30726. return;
  30727. }
  30728. function dataEach(data, idx) {
  30729. if (hasCallback) {
  30730. var rawValue = seriesModel.getRawValue(idx);
  30731. var params = seriesModel.getDataParams(idx);
  30732. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  30733. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  30734. }
  30735. if (data.hasItemOption) {
  30736. var itemModel = data.getItemModel(idx);
  30737. var itemSymbolType = itemModel.getShallow('symbol', true);
  30738. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  30739. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true);
  30740. // If has item symbol
  30741. if (itemSymbolType != null) {
  30742. data.setItemVisual(idx, 'symbol', itemSymbolType);
  30743. }
  30744. if (itemSymbolSize != null) {
  30745. // PENDING Transform symbolSize ?
  30746. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  30747. }
  30748. if (itemSymbolKeepAspect != null) {
  30749. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  30750. }
  30751. }
  30752. }
  30753. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  30754. }
  30755. };
  30756. };
  30757. /*
  30758. * Licensed to the Apache Software Foundation (ASF) under one
  30759. * or more contributor license agreements. See the NOTICE file
  30760. * distributed with this work for additional information
  30761. * regarding copyright ownership. The ASF licenses this file
  30762. * to you under the Apache License, Version 2.0 (the
  30763. * "License"); you may not use this file except in compliance
  30764. * with the License. You may obtain a copy of the License at
  30765. *
  30766. * http://www.apache.org/licenses/LICENSE-2.0
  30767. *
  30768. * Unless required by applicable law or agreed to in writing,
  30769. * software distributed under the License is distributed on an
  30770. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30771. * KIND, either express or implied. See the License for the
  30772. * specific language governing permissions and limitations
  30773. * under the License.
  30774. */
  30775. /* global Float32Array */
  30776. var layoutPoints = function (seriesType) {
  30777. return {
  30778. seriesType: seriesType,
  30779. plan: createRenderPlanner(),
  30780. reset: function (seriesModel) {
  30781. var data = seriesModel.getData();
  30782. var coordSys = seriesModel.coordinateSystem;
  30783. var pipelineContext = seriesModel.pipelineContext;
  30784. var isLargeRender = pipelineContext.large;
  30785. if (!coordSys) {
  30786. return;
  30787. }
  30788. var dims = map(coordSys.dimensions, function (dim) {
  30789. return data.mapDimension(dim);
  30790. }).slice(0, 2);
  30791. var dimLen = dims.length;
  30792. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30793. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  30794. dims[0] = stackResultDim;
  30795. }
  30796. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  30797. dims[1] = stackResultDim;
  30798. }
  30799. function progress(params, data) {
  30800. var segCount = params.end - params.start;
  30801. var points = isLargeRender && new Float32Array(segCount * dimLen);
  30802. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  30803. var point;
  30804. if (dimLen === 1) {
  30805. var x = data.get(dims[0], i);
  30806. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  30807. }
  30808. else {
  30809. var x = tmpIn[0] = data.get(dims[0], i);
  30810. var y = tmpIn[1] = data.get(dims[1], i);
  30811. // Also {Array.<number>}, not undefined to avoid if...else... statement
  30812. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  30813. }
  30814. if (isLargeRender) {
  30815. points[offset++] = point ? point[0] : NaN;
  30816. points[offset++] = point ? point[1] : NaN;
  30817. }
  30818. else {
  30819. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  30820. }
  30821. }
  30822. isLargeRender && data.setLayout('symbolPoints', points);
  30823. }
  30824. return dimLen && {progress: progress};
  30825. }
  30826. };
  30827. };
  30828. /*
  30829. * Licensed to the Apache Software Foundation (ASF) under one
  30830. * or more contributor license agreements. See the NOTICE file
  30831. * distributed with this work for additional information
  30832. * regarding copyright ownership. The ASF licenses this file
  30833. * to you under the Apache License, Version 2.0 (the
  30834. * "License"); you may not use this file except in compliance
  30835. * with the License. You may obtain a copy of the License at
  30836. *
  30837. * http://www.apache.org/licenses/LICENSE-2.0
  30838. *
  30839. * Unless required by applicable law or agreed to in writing,
  30840. * software distributed under the License is distributed on an
  30841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30842. * KIND, either express or implied. See the License for the
  30843. * specific language governing permissions and limitations
  30844. * under the License.
  30845. */
  30846. var samplers = {
  30847. average: function (frame) {
  30848. var sum = 0;
  30849. var count = 0;
  30850. for (var i = 0; i < frame.length; i++) {
  30851. if (!isNaN(frame[i])) {
  30852. sum += frame[i];
  30853. count++;
  30854. }
  30855. }
  30856. // Return NaN if count is 0
  30857. return count === 0 ? NaN : sum / count;
  30858. },
  30859. sum: function (frame) {
  30860. var sum = 0;
  30861. for (var i = 0; i < frame.length; i++) {
  30862. // Ignore NaN
  30863. sum += frame[i] || 0;
  30864. }
  30865. return sum;
  30866. },
  30867. max: function (frame) {
  30868. var max = -Infinity;
  30869. for (var i = 0; i < frame.length; i++) {
  30870. frame[i] > max && (max = frame[i]);
  30871. }
  30872. // NaN will cause illegal axis extent.
  30873. return isFinite(max) ? max : NaN;
  30874. },
  30875. min: function (frame) {
  30876. var min = Infinity;
  30877. for (var i = 0; i < frame.length; i++) {
  30878. frame[i] < min && (min = frame[i]);
  30879. }
  30880. // NaN will cause illegal axis extent.
  30881. return isFinite(min) ? min : NaN;
  30882. },
  30883. // TODO
  30884. // Median
  30885. nearest: function (frame) {
  30886. return frame[0];
  30887. }
  30888. };
  30889. var indexSampler = function (frame, value) {
  30890. return Math.round(frame.length / 2);
  30891. };
  30892. var dataSample = function (seriesType) {
  30893. return {
  30894. seriesType: seriesType,
  30895. modifyOutputEnd: true,
  30896. reset: function (seriesModel, ecModel, api) {
  30897. var data = seriesModel.getData();
  30898. var sampling = seriesModel.get('sampling');
  30899. var coordSys = seriesModel.coordinateSystem;
  30900. // Only cartesian2d support down sampling
  30901. if (coordSys.type === 'cartesian2d' && sampling) {
  30902. var baseAxis = coordSys.getBaseAxis();
  30903. var valueAxis = coordSys.getOtherAxis(baseAxis);
  30904. var extent = baseAxis.getExtent();
  30905. // Coordinste system has been resized
  30906. var size = extent[1] - extent[0];
  30907. var rate = Math.round(data.count() / size);
  30908. if (rate > 1) {
  30909. var sampler;
  30910. if (typeof sampling === 'string') {
  30911. sampler = samplers[sampling];
  30912. }
  30913. else if (typeof sampling === 'function') {
  30914. sampler = sampling;
  30915. }
  30916. if (sampler) {
  30917. // Only support sample the first dim mapped from value axis.
  30918. seriesModel.setData(data.downSample(
  30919. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  30920. ));
  30921. }
  30922. }
  30923. }
  30924. }
  30925. };
  30926. };
  30927. /*
  30928. * Licensed to the Apache Software Foundation (ASF) under one
  30929. * or more contributor license agreements. See the NOTICE file
  30930. * distributed with this work for additional information
  30931. * regarding copyright ownership. The ASF licenses this file
  30932. * to you under the Apache License, Version 2.0 (the
  30933. * "License"); you may not use this file except in compliance
  30934. * with the License. You may obtain a copy of the License at
  30935. *
  30936. * http://www.apache.org/licenses/LICENSE-2.0
  30937. *
  30938. * Unless required by applicable law or agreed to in writing,
  30939. * software distributed under the License is distributed on an
  30940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30941. * KIND, either express or implied. See the License for the
  30942. * specific language governing permissions and limitations
  30943. * under the License.
  30944. */
  30945. /**
  30946. * // Scale class management
  30947. * @module echarts/scale/Scale
  30948. */
  30949. /**
  30950. * @param {Object} [setting]
  30951. */
  30952. function Scale(setting) {
  30953. this._setting = setting || {};
  30954. /**
  30955. * Extent
  30956. * @type {Array.<number>}
  30957. * @protected
  30958. */
  30959. this._extent = [Infinity, -Infinity];
  30960. /**
  30961. * Step is calculated in adjustExtent
  30962. * @type {Array.<number>}
  30963. * @protected
  30964. */
  30965. this._interval = 0;
  30966. this.init && this.init.apply(this, arguments);
  30967. }
  30968. /**
  30969. * Parse input val to valid inner number.
  30970. * @param {*} val
  30971. * @return {number}
  30972. */
  30973. Scale.prototype.parse = function (val) {
  30974. // Notice: This would be a trap here, If the implementation
  30975. // of this method depends on extent, and this method is used
  30976. // before extent set (like in dataZoom), it would be wrong.
  30977. // Nevertheless, parse does not depend on extent generally.
  30978. return val;
  30979. };
  30980. Scale.prototype.getSetting = function (name) {
  30981. return this._setting[name];
  30982. };
  30983. Scale.prototype.contain = function (val) {
  30984. var extent = this._extent;
  30985. return val >= extent[0] && val <= extent[1];
  30986. };
  30987. /**
  30988. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  30989. * @param {number} val
  30990. * @return {number}
  30991. */
  30992. Scale.prototype.normalize = function (val) {
  30993. var extent = this._extent;
  30994. if (extent[1] === extent[0]) {
  30995. return 0.5;
  30996. }
  30997. return (val - extent[0]) / (extent[1] - extent[0]);
  30998. };
  30999. /**
  31000. * Scale normalized value
  31001. * @param {number} val
  31002. * @return {number}
  31003. */
  31004. Scale.prototype.scale = function (val) {
  31005. var extent = this._extent;
  31006. return val * (extent[1] - extent[0]) + extent[0];
  31007. };
  31008. /**
  31009. * Set extent from data
  31010. * @param {Array.<number>} other
  31011. */
  31012. Scale.prototype.unionExtent = function (other) {
  31013. var extent = this._extent;
  31014. other[0] < extent[0] && (extent[0] = other[0]);
  31015. other[1] > extent[1] && (extent[1] = other[1]);
  31016. // not setExtent because in log axis it may transformed to power
  31017. // this.setExtent(extent[0], extent[1]);
  31018. };
  31019. /**
  31020. * Set extent from data
  31021. * @param {module:echarts/data/List} data
  31022. * @param {string} dim
  31023. */
  31024. Scale.prototype.unionExtentFromData = function (data, dim) {
  31025. this.unionExtent(data.getApproximateExtent(dim));
  31026. };
  31027. /**
  31028. * Get extent
  31029. * @return {Array.<number>}
  31030. */
  31031. Scale.prototype.getExtent = function () {
  31032. return this._extent.slice();
  31033. };
  31034. /**
  31035. * Set extent
  31036. * @param {number} start
  31037. * @param {number} end
  31038. */
  31039. Scale.prototype.setExtent = function (start, end) {
  31040. var thisExtent = this._extent;
  31041. if (!isNaN(start)) {
  31042. thisExtent[0] = start;
  31043. }
  31044. if (!isNaN(end)) {
  31045. thisExtent[1] = end;
  31046. }
  31047. };
  31048. /**
  31049. * When axis extent depends on data and no data exists,
  31050. * axis ticks should not be drawn, which is named 'blank'.
  31051. */
  31052. Scale.prototype.isBlank = function () {
  31053. return this._isBlank;
  31054. },
  31055. /**
  31056. * When axis extent depends on data and no data exists,
  31057. * axis ticks should not be drawn, which is named 'blank'.
  31058. */
  31059. Scale.prototype.setBlank = function (isBlank) {
  31060. this._isBlank = isBlank;
  31061. };
  31062. /**
  31063. * @abstract
  31064. * @param {*} tick
  31065. * @return {string} label of the tick.
  31066. */
  31067. Scale.prototype.getLabel = null;
  31068. enableClassExtend(Scale);
  31069. enableClassManagement(Scale, {
  31070. registerWhenExtend: true
  31071. });
  31072. /*
  31073. * Licensed to the Apache Software Foundation (ASF) under one
  31074. * or more contributor license agreements. See the NOTICE file
  31075. * distributed with this work for additional information
  31076. * regarding copyright ownership. The ASF licenses this file
  31077. * to you under the Apache License, Version 2.0 (the
  31078. * "License"); you may not use this file except in compliance
  31079. * with the License. You may obtain a copy of the License at
  31080. *
  31081. * http://www.apache.org/licenses/LICENSE-2.0
  31082. *
  31083. * Unless required by applicable law or agreed to in writing,
  31084. * software distributed under the License is distributed on an
  31085. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31086. * KIND, either express or implied. See the License for the
  31087. * specific language governing permissions and limitations
  31088. * under the License.
  31089. */
  31090. /**
  31091. * @constructor
  31092. * @param {Object} [opt]
  31093. * @param {Object} [opt.categories=[]]
  31094. * @param {Object} [opt.needCollect=false]
  31095. * @param {Object} [opt.deduplication=false]
  31096. */
  31097. function OrdinalMeta(opt) {
  31098. /**
  31099. * @readOnly
  31100. * @type {Array.<string>}
  31101. */
  31102. this.categories = opt.categories || [];
  31103. /**
  31104. * @private
  31105. * @type {boolean}
  31106. */
  31107. this._needCollect = opt.needCollect;
  31108. /**
  31109. * @private
  31110. * @type {boolean}
  31111. */
  31112. this._deduplication = opt.deduplication;
  31113. /**
  31114. * @private
  31115. * @type {boolean}
  31116. */
  31117. this._map;
  31118. }
  31119. /**
  31120. * @param {module:echarts/model/Model} axisModel
  31121. * @return {module:echarts/data/OrdinalMeta}
  31122. */
  31123. OrdinalMeta.createByAxisModel = function (axisModel) {
  31124. var option = axisModel.option;
  31125. var data = option.data;
  31126. var categories = data && map(data, getName);
  31127. return new OrdinalMeta({
  31128. categories: categories,
  31129. needCollect: !categories,
  31130. // deduplication is default in axis.
  31131. deduplication: option.dedplication !== false
  31132. });
  31133. };
  31134. var proto$1 = OrdinalMeta.prototype;
  31135. /**
  31136. * @param {string} category
  31137. * @return {number} ordinal
  31138. */
  31139. proto$1.getOrdinal = function (category) {
  31140. return getOrCreateMap(this).get(category);
  31141. };
  31142. /**
  31143. * @param {*} category
  31144. * @return {number} The ordinal. If not found, return NaN.
  31145. */
  31146. proto$1.parseAndCollect = function (category) {
  31147. var index;
  31148. var needCollect = this._needCollect;
  31149. // The value of category dim can be the index of the given category set.
  31150. // This feature is only supported when !needCollect, because we should
  31151. // consider a common case: a value is 2017, which is a number but is
  31152. // expected to be tread as a category. This case usually happen in dataset,
  31153. // where it happent to be no need of the index feature.
  31154. if (typeof category !== 'string' && !needCollect) {
  31155. return category;
  31156. }
  31157. // Optimize for the scenario:
  31158. // category is ['2012-01-01', '2012-01-02', ...], where the input
  31159. // data has been ensured not duplicate and is large data.
  31160. // Notice, if a dataset dimension provide categroies, usually echarts
  31161. // should remove duplication except user tell echarts dont do that
  31162. // (set axis.deduplication = false), because echarts do not know whether
  31163. // the values in the category dimension has duplication (consider the
  31164. // parallel-aqi example)
  31165. if (needCollect && !this._deduplication) {
  31166. index = this.categories.length;
  31167. this.categories[index] = category;
  31168. return index;
  31169. }
  31170. var map$$1 = getOrCreateMap(this);
  31171. index = map$$1.get(category);
  31172. if (index == null) {
  31173. if (needCollect) {
  31174. index = this.categories.length;
  31175. this.categories[index] = category;
  31176. map$$1.set(category, index);
  31177. }
  31178. else {
  31179. index = NaN;
  31180. }
  31181. }
  31182. return index;
  31183. };
  31184. // Consider big data, do not create map until needed.
  31185. function getOrCreateMap(ordinalMeta) {
  31186. return ordinalMeta._map || (
  31187. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  31188. );
  31189. }
  31190. function getName(obj) {
  31191. if (isObject$1(obj) && obj.value != null) {
  31192. return obj.value;
  31193. }
  31194. else {
  31195. return obj + '';
  31196. }
  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. * Linear continuous scale
  31218. * @module echarts/coord/scale/Ordinal
  31219. *
  31220. * http://en.wikipedia.org/wiki/Level_of_measurement
  31221. */
  31222. // FIXME only one data
  31223. var scaleProto = Scale.prototype;
  31224. var OrdinalScale = Scale.extend({
  31225. type: 'ordinal',
  31226. /**
  31227. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  31228. */
  31229. init: function (ordinalMeta, extent) {
  31230. // Caution: Should not use instanceof, consider ec-extensions using
  31231. // import approach to get OrdinalMeta class.
  31232. if (!ordinalMeta || isArray(ordinalMeta)) {
  31233. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  31234. }
  31235. this._ordinalMeta = ordinalMeta;
  31236. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  31237. },
  31238. parse: function (val) {
  31239. return typeof val === 'string'
  31240. ? this._ordinalMeta.getOrdinal(val)
  31241. // val might be float.
  31242. : Math.round(val);
  31243. },
  31244. contain: function (rank) {
  31245. rank = this.parse(rank);
  31246. return scaleProto.contain.call(this, rank)
  31247. && this._ordinalMeta.categories[rank] != null;
  31248. },
  31249. /**
  31250. * Normalize given rank or name to linear [0, 1]
  31251. * @param {number|string} [val]
  31252. * @return {number}
  31253. */
  31254. normalize: function (val) {
  31255. return scaleProto.normalize.call(this, this.parse(val));
  31256. },
  31257. scale: function (val) {
  31258. return Math.round(scaleProto.scale.call(this, val));
  31259. },
  31260. /**
  31261. * @return {Array}
  31262. */
  31263. getTicks: function () {
  31264. var ticks = [];
  31265. var extent = this._extent;
  31266. var rank = extent[0];
  31267. while (rank <= extent[1]) {
  31268. ticks.push(rank);
  31269. rank++;
  31270. }
  31271. return ticks;
  31272. },
  31273. /**
  31274. * Get item on rank n
  31275. * @param {number} n
  31276. * @return {string}
  31277. */
  31278. getLabel: function (n) {
  31279. if (!this.isBlank()) {
  31280. // Note that if no data, ordinalMeta.categories is an empty array.
  31281. return this._ordinalMeta.categories[n];
  31282. }
  31283. },
  31284. /**
  31285. * @return {number}
  31286. */
  31287. count: function () {
  31288. return this._extent[1] - this._extent[0] + 1;
  31289. },
  31290. /**
  31291. * @override
  31292. */
  31293. unionExtentFromData: function (data, dim) {
  31294. this.unionExtent(data.getApproximateExtent(dim));
  31295. },
  31296. getOrdinalMeta: function () {
  31297. return this._ordinalMeta;
  31298. },
  31299. niceTicks: noop,
  31300. niceExtent: noop
  31301. });
  31302. /**
  31303. * @return {module:echarts/scale/Time}
  31304. */
  31305. OrdinalScale.create = function () {
  31306. return new OrdinalScale();
  31307. };
  31308. /*
  31309. * Licensed to the Apache Software Foundation (ASF) under one
  31310. * or more contributor license agreements. See the NOTICE file
  31311. * distributed with this work for additional information
  31312. * regarding copyright ownership. The ASF licenses this file
  31313. * to you under the Apache License, Version 2.0 (the
  31314. * "License"); you may not use this file except in compliance
  31315. * with the License. You may obtain a copy of the License at
  31316. *
  31317. * http://www.apache.org/licenses/LICENSE-2.0
  31318. *
  31319. * Unless required by applicable law or agreed to in writing,
  31320. * software distributed under the License is distributed on an
  31321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31322. * KIND, either express or implied. See the License for the
  31323. * specific language governing permissions and limitations
  31324. * under the License.
  31325. */
  31326. /**
  31327. * For testable.
  31328. */
  31329. var roundNumber$1 = round$1;
  31330. /**
  31331. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  31332. * Should be extent[0] < extent[1].
  31333. * @param {number} splitNumber splitNumber should be >= 1.
  31334. * @param {number} [minInterval]
  31335. * @param {number} [maxInterval]
  31336. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  31337. */
  31338. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  31339. var result = {};
  31340. var span = extent[1] - extent[0];
  31341. var interval = result.interval = nice(span / splitNumber, true);
  31342. if (minInterval != null && interval < minInterval) {
  31343. interval = result.interval = minInterval;
  31344. }
  31345. if (maxInterval != null && interval > maxInterval) {
  31346. interval = result.interval = maxInterval;
  31347. }
  31348. // Tow more digital for tick.
  31349. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  31350. // Niced extent inside original extent
  31351. var niceTickExtent = result.niceTickExtent = [
  31352. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  31353. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  31354. ];
  31355. fixExtent(niceTickExtent, extent);
  31356. return result;
  31357. }
  31358. /**
  31359. * @param {number} interval
  31360. * @return {number} interval precision
  31361. */
  31362. function getIntervalPrecision(interval) {
  31363. // Tow more digital for tick.
  31364. return getPrecisionSafe(interval) + 2;
  31365. }
  31366. function clamp(niceTickExtent, idx, extent) {
  31367. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  31368. }
  31369. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  31370. function fixExtent(niceTickExtent, extent) {
  31371. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  31372. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  31373. clamp(niceTickExtent, 0, extent);
  31374. clamp(niceTickExtent, 1, extent);
  31375. if (niceTickExtent[0] > niceTickExtent[1]) {
  31376. niceTickExtent[0] = niceTickExtent[1];
  31377. }
  31378. }
  31379. /*
  31380. * Licensed to the Apache Software Foundation (ASF) under one
  31381. * or more contributor license agreements. See the NOTICE file
  31382. * distributed with this work for additional information
  31383. * regarding copyright ownership. The ASF licenses this file
  31384. * to you under the Apache License, Version 2.0 (the
  31385. * "License"); you may not use this file except in compliance
  31386. * with the License. You may obtain a copy of the License at
  31387. *
  31388. * http://www.apache.org/licenses/LICENSE-2.0
  31389. *
  31390. * Unless required by applicable law or agreed to in writing,
  31391. * software distributed under the License is distributed on an
  31392. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31393. * KIND, either express or implied. See the License for the
  31394. * specific language governing permissions and limitations
  31395. * under the License.
  31396. */
  31397. /**
  31398. * Interval scale
  31399. * @module echarts/scale/Interval
  31400. */
  31401. var roundNumber = round$1;
  31402. /**
  31403. * @alias module:echarts/coord/scale/Interval
  31404. * @constructor
  31405. */
  31406. var IntervalScale = Scale.extend({
  31407. type: 'interval',
  31408. _interval: 0,
  31409. _intervalPrecision: 2,
  31410. setExtent: function (start, end) {
  31411. var thisExtent = this._extent;
  31412. //start,end may be a Number like '25',so...
  31413. if (!isNaN(start)) {
  31414. thisExtent[0] = parseFloat(start);
  31415. }
  31416. if (!isNaN(end)) {
  31417. thisExtent[1] = parseFloat(end);
  31418. }
  31419. },
  31420. unionExtent: function (other) {
  31421. var extent = this._extent;
  31422. other[0] < extent[0] && (extent[0] = other[0]);
  31423. other[1] > extent[1] && (extent[1] = other[1]);
  31424. // unionExtent may called by it's sub classes
  31425. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  31426. },
  31427. /**
  31428. * Get interval
  31429. */
  31430. getInterval: function () {
  31431. return this._interval;
  31432. },
  31433. /**
  31434. * Set interval
  31435. */
  31436. setInterval: function (interval) {
  31437. this._interval = interval;
  31438. // Dropped auto calculated niceExtent and use user setted extent
  31439. // We assume user wan't to set both interval, min, max to get a better result
  31440. this._niceExtent = this._extent.slice();
  31441. this._intervalPrecision = getIntervalPrecision(interval);
  31442. },
  31443. /**
  31444. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  31445. * @return {Array.<number>}
  31446. */
  31447. getTicks: function (expandToNicedExtent) {
  31448. var interval = this._interval;
  31449. var extent = this._extent;
  31450. var niceTickExtent = this._niceExtent;
  31451. var intervalPrecision = this._intervalPrecision;
  31452. var ticks = [];
  31453. // If interval is 0, return [];
  31454. if (!interval) {
  31455. return ticks;
  31456. }
  31457. // Consider this case: using dataZoom toolbox, zoom and zoom.
  31458. var safeLimit = 10000;
  31459. if (extent[0] < niceTickExtent[0]) {
  31460. if (expandToNicedExtent) {
  31461. ticks.push(roundNumber(niceTickExtent[0] - interval));
  31462. }
  31463. else {
  31464. ticks.push(extent[0]);
  31465. }
  31466. }
  31467. var tick = niceTickExtent[0];
  31468. while (tick <= niceTickExtent[1]) {
  31469. ticks.push(tick);
  31470. // Avoid rounding error
  31471. tick = roundNumber(tick + interval, intervalPrecision);
  31472. if (tick === ticks[ticks.length - 1]) {
  31473. // Consider out of safe float point, e.g.,
  31474. // -3711126.9907707 + 2e-10 === -3711126.9907707
  31475. break;
  31476. }
  31477. if (ticks.length > safeLimit) {
  31478. return [];
  31479. }
  31480. }
  31481. // Consider this case: the last item of ticks is smaller
  31482. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  31483. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  31484. if (extent[1] > lastNiceTick) {
  31485. if (expandToNicedExtent) {
  31486. ticks.push(lastNiceTick + interval);
  31487. }
  31488. else {
  31489. ticks.push(extent[1]);
  31490. }
  31491. }
  31492. return ticks;
  31493. },
  31494. /**
  31495. * @param {number} [splitNumber=5]
  31496. * @return {Array.<Array.<number>>}
  31497. */
  31498. getMinorTicks: function (splitNumber) {
  31499. var ticks = this.getTicks(true);
  31500. var minorTicks = [];
  31501. var extent = this.getExtent();
  31502. for (var i = 1; i < ticks.length; i++) {
  31503. var nextTick = ticks[i];
  31504. var prevTick = ticks[i - 1];
  31505. var count = 0;
  31506. var minorTicksGroup = [];
  31507. var interval = nextTick - prevTick;
  31508. var minorInterval = interval / splitNumber;
  31509. while (count < splitNumber - 1) {
  31510. var minorTick = round$1(prevTick + (count + 1) * minorInterval);
  31511. // For the first and last interval. The count may be less than splitNumber.
  31512. if (minorTick > extent[0] && minorTick < extent[1]) {
  31513. minorTicksGroup.push(minorTick);
  31514. }
  31515. count++;
  31516. }
  31517. minorTicks.push(minorTicksGroup);
  31518. }
  31519. return minorTicks;
  31520. },
  31521. /**
  31522. * @param {number} data
  31523. * @param {Object} [opt]
  31524. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  31525. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  31526. * @return {string}
  31527. */
  31528. getLabel: function (data, opt) {
  31529. if (data == null) {
  31530. return '';
  31531. }
  31532. var precision = opt && opt.precision;
  31533. if (precision == null) {
  31534. precision = getPrecisionSafe(data) || 0;
  31535. }
  31536. else if (precision === 'auto') {
  31537. // Should be more precise then tick.
  31538. precision = this._intervalPrecision;
  31539. }
  31540. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  31541. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  31542. data = roundNumber(data, precision, true);
  31543. return addCommas(data);
  31544. },
  31545. /**
  31546. * Update interval and extent of intervals for nice ticks
  31547. *
  31548. * @param {number} [splitNumber = 5] Desired number of ticks
  31549. * @param {number} [minInterval]
  31550. * @param {number} [maxInterval]
  31551. */
  31552. niceTicks: function (splitNumber, minInterval, maxInterval) {
  31553. splitNumber = splitNumber || 5;
  31554. var extent = this._extent;
  31555. var span = extent[1] - extent[0];
  31556. if (!isFinite(span)) {
  31557. return;
  31558. }
  31559. // User may set axis min 0 and data are all negative
  31560. // FIXME If it needs to reverse ?
  31561. if (span < 0) {
  31562. span = -span;
  31563. extent.reverse();
  31564. }
  31565. var result = intervalScaleNiceTicks(
  31566. extent, splitNumber, minInterval, maxInterval
  31567. );
  31568. this._intervalPrecision = result.intervalPrecision;
  31569. this._interval = result.interval;
  31570. this._niceExtent = result.niceTickExtent;
  31571. },
  31572. /**
  31573. * Nice extent.
  31574. * @param {Object} opt
  31575. * @param {number} [opt.splitNumber = 5] Given approx tick number
  31576. * @param {boolean} [opt.fixMin=false]
  31577. * @param {boolean} [opt.fixMax=false]
  31578. * @param {boolean} [opt.minInterval]
  31579. * @param {boolean} [opt.maxInterval]
  31580. */
  31581. niceExtent: function (opt) {
  31582. var extent = this._extent;
  31583. // If extent start and end are same, expand them
  31584. if (extent[0] === extent[1]) {
  31585. if (extent[0] !== 0) {
  31586. // Expand extent
  31587. var expandSize = extent[0];
  31588. // In the fowllowing case
  31589. // Axis has been fixed max 100
  31590. // Plus data are all 100 and axis extent are [100, 100].
  31591. // Extend to the both side will cause expanded max is larger than fixed max.
  31592. // So only expand to the smaller side.
  31593. if (!opt.fixMax) {
  31594. extent[1] += expandSize / 2;
  31595. extent[0] -= expandSize / 2;
  31596. }
  31597. else {
  31598. extent[0] -= expandSize / 2;
  31599. }
  31600. }
  31601. else {
  31602. extent[1] = 1;
  31603. }
  31604. }
  31605. var span = extent[1] - extent[0];
  31606. // If there are no data and extent are [Infinity, -Infinity]
  31607. if (!isFinite(span)) {
  31608. extent[0] = 0;
  31609. extent[1] = 1;
  31610. }
  31611. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  31612. // var extent = this._extent;
  31613. var interval = this._interval;
  31614. if (!opt.fixMin) {
  31615. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  31616. }
  31617. if (!opt.fixMax) {
  31618. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  31619. }
  31620. }
  31621. });
  31622. /**
  31623. * @return {module:echarts/scale/Time}
  31624. */
  31625. IntervalScale.create = function () {
  31626. return new IntervalScale();
  31627. };
  31628. /*
  31629. * Licensed to the Apache Software Foundation (ASF) under one
  31630. * or more contributor license agreements. See the NOTICE file
  31631. * distributed with this work for additional information
  31632. * regarding copyright ownership. The ASF licenses this file
  31633. * to you under the Apache License, Version 2.0 (the
  31634. * "License"); you may not use this file except in compliance
  31635. * with the License. You may obtain a copy of the License at
  31636. *
  31637. * http://www.apache.org/licenses/LICENSE-2.0
  31638. *
  31639. * Unless required by applicable law or agreed to in writing,
  31640. * software distributed under the License is distributed on an
  31641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31642. * KIND, either express or implied. See the License for the
  31643. * specific language governing permissions and limitations
  31644. * under the License.
  31645. */
  31646. /* global Float32Array */
  31647. var STACK_PREFIX = '__ec_stack_';
  31648. var LARGE_BAR_MIN_WIDTH = 0.5;
  31649. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  31650. function getSeriesStackId(seriesModel) {
  31651. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  31652. }
  31653. function getAxisKey(axis) {
  31654. return axis.dim + axis.index;
  31655. }
  31656. /**
  31657. * @param {Object} opt
  31658. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  31659. * @param {number} opt.count Positive interger.
  31660. * @param {number} [opt.barWidth]
  31661. * @param {number} [opt.barMaxWidth]
  31662. * @param {number} [opt.barMinWidth]
  31663. * @param {number} [opt.barGap]
  31664. * @param {number} [opt.barCategoryGap]
  31665. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  31666. */
  31667. function prepareLayoutBarSeries(seriesType, ecModel) {
  31668. var seriesModels = [];
  31669. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  31670. // Check series coordinate, do layout for cartesian2d only
  31671. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  31672. seriesModels.push(seriesModel);
  31673. }
  31674. });
  31675. return seriesModels;
  31676. }
  31677. /**
  31678. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  31679. * values.
  31680. * This works for time axes, value axes, and log axes.
  31681. * For a single time axis, return value is in the form like
  31682. * {'x_0': [1000000]}.
  31683. * The value of 1000000 is in milliseconds.
  31684. */
  31685. function getValueAxesMinGaps(barSeries) {
  31686. /**
  31687. * Map from axis.index to values.
  31688. * For a single time axis, axisValues is in the form like
  31689. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  31690. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  31691. * series.
  31692. */
  31693. var axisValues = {};
  31694. each$1(barSeries, function (seriesModel) {
  31695. var cartesian = seriesModel.coordinateSystem;
  31696. var baseAxis = cartesian.getBaseAxis();
  31697. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  31698. return;
  31699. }
  31700. var data = seriesModel.getData();
  31701. var key = baseAxis.dim + '_' + baseAxis.index;
  31702. var dim = data.mapDimension(baseAxis.dim);
  31703. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  31704. var value = data.get(dim, i);
  31705. if (!axisValues[key]) {
  31706. // No previous data for the axis
  31707. axisValues[key] = [value];
  31708. }
  31709. else {
  31710. // No value in previous series
  31711. axisValues[key].push(value);
  31712. }
  31713. // Ignore duplicated time values in the same axis
  31714. }
  31715. });
  31716. var axisMinGaps = [];
  31717. for (var key in axisValues) {
  31718. if (axisValues.hasOwnProperty(key)) {
  31719. var valuesInAxis = axisValues[key];
  31720. if (valuesInAxis) {
  31721. // Sort axis values into ascending order to calculate gaps
  31722. valuesInAxis.sort(function (a, b) {
  31723. return a - b;
  31724. });
  31725. var min = null;
  31726. for (var j = 1; j < valuesInAxis.length; ++j) {
  31727. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  31728. if (delta > 0) {
  31729. // Ignore 0 delta because they are of the same axis value
  31730. min = min === null ? delta : Math.min(min, delta);
  31731. }
  31732. }
  31733. // Set to null if only have one data
  31734. axisMinGaps[key] = min;
  31735. }
  31736. }
  31737. }
  31738. return axisMinGaps;
  31739. }
  31740. function makeColumnLayout(barSeries) {
  31741. var axisMinGaps = getValueAxesMinGaps(barSeries);
  31742. var seriesInfoList = [];
  31743. each$1(barSeries, function (seriesModel) {
  31744. var cartesian = seriesModel.coordinateSystem;
  31745. var baseAxis = cartesian.getBaseAxis();
  31746. var axisExtent = baseAxis.getExtent();
  31747. var bandWidth;
  31748. if (baseAxis.type === 'category') {
  31749. bandWidth = baseAxis.getBandWidth();
  31750. }
  31751. else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  31752. var key = baseAxis.dim + '_' + baseAxis.index;
  31753. var minGap = axisMinGaps[key];
  31754. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  31755. var scale = baseAxis.scale.getExtent();
  31756. var scaleSpan = Math.abs(scale[1] - scale[0]);
  31757. bandWidth = minGap
  31758. ? extentSpan / scaleSpan * minGap
  31759. : extentSpan; // When there is only one data value
  31760. }
  31761. else {
  31762. var data = seriesModel.getData();
  31763. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  31764. }
  31765. var barWidth = parsePercent$1(
  31766. seriesModel.get('barWidth'), bandWidth
  31767. );
  31768. var barMaxWidth = parsePercent$1(
  31769. seriesModel.get('barMaxWidth'), bandWidth
  31770. );
  31771. var barMinWidth = parsePercent$1(
  31772. // barMinWidth by default is 1 in cartesian. Because in value axis,
  31773. // the auto-calculated bar width might be less than 1.
  31774. seriesModel.get('barMinWidth') || 1, bandWidth
  31775. );
  31776. var barGap = seriesModel.get('barGap');
  31777. var barCategoryGap = seriesModel.get('barCategoryGap');
  31778. seriesInfoList.push({
  31779. bandWidth: bandWidth,
  31780. barWidth: barWidth,
  31781. barMaxWidth: barMaxWidth,
  31782. barMinWidth: barMinWidth,
  31783. barGap: barGap,
  31784. barCategoryGap: barCategoryGap,
  31785. axisKey: getAxisKey(baseAxis),
  31786. stackId: getSeriesStackId(seriesModel)
  31787. });
  31788. });
  31789. return doCalBarWidthAndOffset(seriesInfoList);
  31790. }
  31791. function doCalBarWidthAndOffset(seriesInfoList) {
  31792. // Columns info on each category axis. Key is cartesian name
  31793. var columnsMap = {};
  31794. each$1(seriesInfoList, function (seriesInfo, idx) {
  31795. var axisKey = seriesInfo.axisKey;
  31796. var bandWidth = seriesInfo.bandWidth;
  31797. var columnsOnAxis = columnsMap[axisKey] || {
  31798. bandWidth: bandWidth,
  31799. remainedWidth: bandWidth,
  31800. autoWidthCount: 0,
  31801. categoryGap: '20%',
  31802. gap: '30%',
  31803. stacks: {}
  31804. };
  31805. var stacks = columnsOnAxis.stacks;
  31806. columnsMap[axisKey] = columnsOnAxis;
  31807. var stackId = seriesInfo.stackId;
  31808. if (!stacks[stackId]) {
  31809. columnsOnAxis.autoWidthCount++;
  31810. }
  31811. stacks[stackId] = stacks[stackId] || {
  31812. width: 0,
  31813. maxWidth: 0
  31814. };
  31815. // Caution: In a single coordinate system, these barGrid attributes
  31816. // will be shared by series. Consider that they have default values,
  31817. // only the attributes set on the last series will work.
  31818. // Do not change this fact unless there will be a break change.
  31819. var barWidth = seriesInfo.barWidth;
  31820. if (barWidth && !stacks[stackId].width) {
  31821. // See #6312, do not restrict width.
  31822. stacks[stackId].width = barWidth;
  31823. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  31824. columnsOnAxis.remainedWidth -= barWidth;
  31825. }
  31826. var barMaxWidth = seriesInfo.barMaxWidth;
  31827. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  31828. var barMinWidth = seriesInfo.barMinWidth;
  31829. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  31830. var barGap = seriesInfo.barGap;
  31831. (barGap != null) && (columnsOnAxis.gap = barGap);
  31832. var barCategoryGap = seriesInfo.barCategoryGap;
  31833. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  31834. });
  31835. var result = {};
  31836. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  31837. result[coordSysName] = {};
  31838. var stacks = columnsOnAxis.stacks;
  31839. var bandWidth = columnsOnAxis.bandWidth;
  31840. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  31841. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  31842. var remainedWidth = columnsOnAxis.remainedWidth;
  31843. var autoWidthCount = columnsOnAxis.autoWidthCount;
  31844. var autoWidth = (remainedWidth - categoryGap)
  31845. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31846. autoWidth = Math.max(autoWidth, 0);
  31847. // Find if any auto calculated bar exceeded maxBarWidth
  31848. each$1(stacks, function (column) {
  31849. var maxWidth = column.maxWidth;
  31850. var minWidth = column.minWidth;
  31851. if (!column.width) {
  31852. var finalWidth = autoWidth;
  31853. if (maxWidth && maxWidth < finalWidth) {
  31854. finalWidth = Math.min(maxWidth, remainedWidth);
  31855. }
  31856. // `minWidth` has higher priority. `minWidth` decide that wheter the
  31857. // bar is able to be visible. So `minWidth` should not be restricted
  31858. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  31859. // the extreme cases for `value` axis, bars are allowed to overlap
  31860. // with each other if `minWidth` specified.
  31861. if (minWidth && minWidth > finalWidth) {
  31862. finalWidth = minWidth;
  31863. }
  31864. if (finalWidth !== autoWidth) {
  31865. column.width = finalWidth;
  31866. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31867. autoWidthCount--;
  31868. }
  31869. }
  31870. else {
  31871. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  31872. // CSS does. Becuase barWidth can be a percent value, where
  31873. // `barMaxWidth` can be used to restrict the final width.
  31874. var finalWidth = column.width;
  31875. if (maxWidth) {
  31876. finalWidth = Math.min(finalWidth, maxWidth);
  31877. }
  31878. // `minWidth` has higher priority, as described above
  31879. if (minWidth) {
  31880. finalWidth = Math.max(finalWidth, minWidth);
  31881. }
  31882. column.width = finalWidth;
  31883. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  31884. autoWidthCount--;
  31885. }
  31886. });
  31887. // Recalculate width again
  31888. autoWidth = (remainedWidth - categoryGap)
  31889. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  31890. autoWidth = Math.max(autoWidth, 0);
  31891. var widthSum = 0;
  31892. var lastColumn;
  31893. each$1(stacks, function (column, idx) {
  31894. if (!column.width) {
  31895. column.width = autoWidth;
  31896. }
  31897. lastColumn = column;
  31898. widthSum += column.width * (1 + barGapPercent);
  31899. });
  31900. if (lastColumn) {
  31901. widthSum -= lastColumn.width * barGapPercent;
  31902. }
  31903. var offset = -widthSum / 2;
  31904. each$1(stacks, function (column, stackId) {
  31905. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  31906. bandWidth: bandWidth,
  31907. offset: offset,
  31908. width: column.width
  31909. };
  31910. offset += column.width * (1 + barGapPercent);
  31911. });
  31912. });
  31913. return result;
  31914. }
  31915. /**
  31916. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  31917. * @param {module:echarts/coord/Axis} axis
  31918. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  31919. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  31920. */
  31921. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  31922. if (barWidthAndOffset && axis) {
  31923. var result = barWidthAndOffset[getAxisKey(axis)];
  31924. if (result != null && seriesModel != null) {
  31925. result = result[getSeriesStackId(seriesModel)];
  31926. }
  31927. return result;
  31928. }
  31929. }
  31930. /**
  31931. * @param {string} seriesType
  31932. * @param {module:echarts/model/Global} ecModel
  31933. */
  31934. function layout(seriesType, ecModel) {
  31935. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  31936. var barWidthAndOffset = makeColumnLayout(seriesModels);
  31937. var lastStackCoords = {};
  31938. each$1(seriesModels, function (seriesModel) {
  31939. var data = seriesModel.getData();
  31940. var cartesian = seriesModel.coordinateSystem;
  31941. var baseAxis = cartesian.getBaseAxis();
  31942. var stackId = getSeriesStackId(seriesModel);
  31943. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  31944. var columnOffset = columnLayoutInfo.offset;
  31945. var columnWidth = columnLayoutInfo.width;
  31946. var valueAxis = cartesian.getOtherAxis(baseAxis);
  31947. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  31948. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  31949. data.setLayout({
  31950. bandWidth: columnLayoutInfo.bandWidth,
  31951. offset: columnOffset,
  31952. size: columnWidth
  31953. });
  31954. var valueDim = data.mapDimension(valueAxis.dim);
  31955. var baseDim = data.mapDimension(baseAxis.dim);
  31956. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  31957. var isValueAxisH = valueAxis.isHorizontal();
  31958. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  31959. for (var idx = 0, len = data.count(); idx < len; idx++) {
  31960. var value = data.get(valueDim, idx);
  31961. var baseValue = data.get(baseDim, idx);
  31962. // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  31963. if (isNaN(value) || isNaN(baseValue)) {
  31964. continue;
  31965. }
  31966. var sign = value >= 0 ? 'p' : 'n';
  31967. var baseCoord = valueAxisStart;
  31968. // Because of the barMinHeight, we can not use the value in
  31969. // stackResultDimension directly.
  31970. if (stacked) {
  31971. // Only ordinal axis can be stacked.
  31972. if (!lastStackCoords[stackId][baseValue]) {
  31973. lastStackCoords[stackId][baseValue] = {
  31974. p: valueAxisStart, // Positive stack
  31975. n: valueAxisStart // Negative stack
  31976. };
  31977. }
  31978. // Should also consider #4243
  31979. baseCoord = lastStackCoords[stackId][baseValue][sign];
  31980. }
  31981. var x;
  31982. var y;
  31983. var width;
  31984. var height;
  31985. if (isValueAxisH) {
  31986. var coord = cartesian.dataToPoint([value, baseValue]);
  31987. x = baseCoord;
  31988. y = coord[1] + columnOffset;
  31989. width = coord[0] - valueAxisStart;
  31990. height = columnWidth;
  31991. if (Math.abs(width) < barMinHeight) {
  31992. width = (width < 0 ? -1 : 1) * barMinHeight;
  31993. }
  31994. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  31995. }
  31996. else {
  31997. var coord = cartesian.dataToPoint([baseValue, value]);
  31998. x = coord[0] + columnOffset;
  31999. y = baseCoord;
  32000. width = columnWidth;
  32001. height = coord[1] - valueAxisStart;
  32002. if (Math.abs(height) < barMinHeight) {
  32003. // Include zero to has a positive bar
  32004. height = (height <= 0 ? -1 : 1) * barMinHeight;
  32005. }
  32006. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  32007. }
  32008. data.setItemLayout(idx, {
  32009. x: x,
  32010. y: y,
  32011. width: width,
  32012. height: height
  32013. });
  32014. }
  32015. }, this);
  32016. }
  32017. // TODO: Do not support stack in large mode yet.
  32018. var largeLayout = {
  32019. seriesType: 'bar',
  32020. plan: createRenderPlanner(),
  32021. reset: function (seriesModel) {
  32022. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  32023. return;
  32024. }
  32025. var data = seriesModel.getData();
  32026. var cartesian = seriesModel.coordinateSystem;
  32027. var baseAxis = cartesian.getBaseAxis();
  32028. var valueAxis = cartesian.getOtherAxis(baseAxis);
  32029. var valueDim = data.mapDimension(valueAxis.dim);
  32030. var baseDim = data.mapDimension(baseAxis.dim);
  32031. var valueAxisHorizontal = valueAxis.isHorizontal();
  32032. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  32033. var barWidth = retrieveColumnLayout(
  32034. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  32035. ).width;
  32036. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  32037. barWidth = LARGE_BAR_MIN_WIDTH;
  32038. }
  32039. return {progress: progress};
  32040. function progress(params, data) {
  32041. var count = params.count;
  32042. var largePoints = new LargeArr(count * 2);
  32043. var largeDataIndices = new LargeArr(count);
  32044. var dataIndex;
  32045. var coord = [];
  32046. var valuePair = [];
  32047. var pointsOffset = 0;
  32048. var idxOffset = 0;
  32049. while ((dataIndex = params.next()) != null) {
  32050. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  32051. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  32052. coord = cartesian.dataToPoint(valuePair, null, coord);
  32053. // Data index might not be in order, depends on `progressiveChunkMode`.
  32054. largePoints[pointsOffset++] = coord[0];
  32055. largePoints[pointsOffset++] = coord[1];
  32056. largeDataIndices[idxOffset++] = dataIndex;
  32057. }
  32058. data.setLayout({
  32059. largePoints: largePoints,
  32060. largeDataIndices: largeDataIndices,
  32061. barWidth: barWidth,
  32062. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  32063. valueAxisHorizontal: valueAxisHorizontal
  32064. });
  32065. }
  32066. }
  32067. };
  32068. function isOnCartesian(seriesModel) {
  32069. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  32070. }
  32071. function isInLargeMode(seriesModel) {
  32072. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  32073. }
  32074. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  32075. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  32076. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  32077. }
  32078. /*
  32079. * Licensed to the Apache Software Foundation (ASF) under one
  32080. * or more contributor license agreements. See the NOTICE file
  32081. * distributed with this work for additional information
  32082. * regarding copyright ownership. The ASF licenses this file
  32083. * to you under the Apache License, Version 2.0 (the
  32084. * "License"); you may not use this file except in compliance
  32085. * with the License. You may obtain a copy of the License at
  32086. *
  32087. * http://www.apache.org/licenses/LICENSE-2.0
  32088. *
  32089. * Unless required by applicable law or agreed to in writing,
  32090. * software distributed under the License is distributed on an
  32091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32092. * KIND, either express or implied. See the License for the
  32093. * specific language governing permissions and limitations
  32094. * under the License.
  32095. */
  32096. /*
  32097. * A third-party license is embeded for some of the code in this file:
  32098. * The "scaleLevels" was originally copied from "d3.js" with some
  32099. * modifications made for this project.
  32100. * (See more details in the comment on the definition of "scaleLevels" below.)
  32101. * The use of the source code of this file is also subject to the terms
  32102. * and consitions of the license of "d3.js" (BSD-3Clause, see
  32103. * </licenses/LICENSE-d3>).
  32104. */
  32105. // [About UTC and local time zone]:
  32106. // In most cases, `number.parseDate` will treat input data string as local time
  32107. // (except time zone is specified in time string). And `format.formateTime` returns
  32108. // local time by default. option.useUTC is false by default. This design have
  32109. // concidered these common case:
  32110. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  32111. // in local time by default.
  32112. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  32113. // as its original time, without any time difference.
  32114. var intervalScaleProto = IntervalScale.prototype;
  32115. var mathCeil = Math.ceil;
  32116. var mathFloor = Math.floor;
  32117. var ONE_SECOND = 1000;
  32118. var ONE_MINUTE = ONE_SECOND * 60;
  32119. var ONE_HOUR = ONE_MINUTE * 60;
  32120. var ONE_DAY = ONE_HOUR * 24;
  32121. // FIXME 公用?
  32122. var bisect = function (a, x, lo, hi) {
  32123. while (lo < hi) {
  32124. var mid = lo + hi >>> 1;
  32125. if (a[mid][1] < x) {
  32126. lo = mid + 1;
  32127. }
  32128. else {
  32129. hi = mid;
  32130. }
  32131. }
  32132. return lo;
  32133. };
  32134. /**
  32135. * @alias module:echarts/coord/scale/Time
  32136. * @constructor
  32137. */
  32138. var TimeScale = IntervalScale.extend({
  32139. type: 'time',
  32140. /**
  32141. * @override
  32142. */
  32143. getLabel: function (val) {
  32144. var stepLvl = this._stepLvl;
  32145. var date = new Date(val);
  32146. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  32147. },
  32148. /**
  32149. * @override
  32150. */
  32151. niceExtent: function (opt) {
  32152. var extent = this._extent;
  32153. // If extent start and end are same, expand them
  32154. if (extent[0] === extent[1]) {
  32155. // Expand extent
  32156. extent[0] -= ONE_DAY;
  32157. extent[1] += ONE_DAY;
  32158. }
  32159. // If there are no data and extent are [Infinity, -Infinity]
  32160. if (extent[1] === -Infinity && extent[0] === Infinity) {
  32161. var d = new Date();
  32162. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  32163. extent[0] = extent[1] - ONE_DAY;
  32164. }
  32165. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  32166. // var extent = this._extent;
  32167. var interval = this._interval;
  32168. if (!opt.fixMin) {
  32169. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  32170. }
  32171. if (!opt.fixMax) {
  32172. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  32173. }
  32174. },
  32175. /**
  32176. * @override
  32177. */
  32178. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  32179. approxTickNum = approxTickNum || 10;
  32180. var extent = this._extent;
  32181. var span = extent[1] - extent[0];
  32182. var approxInterval = span / approxTickNum;
  32183. if (minInterval != null && approxInterval < minInterval) {
  32184. approxInterval = minInterval;
  32185. }
  32186. if (maxInterval != null && approxInterval > maxInterval) {
  32187. approxInterval = maxInterval;
  32188. }
  32189. var scaleLevelsLen = scaleLevels.length;
  32190. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  32191. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  32192. var interval = level[1];
  32193. // Same with interval scale if span is much larger than 1 year
  32194. if (level[0] === 'year') {
  32195. var yearSpan = span / interval;
  32196. // From "Nice Numbers for Graph Labels" of Graphic Gems
  32197. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  32198. var yearStep = nice(yearSpan / approxTickNum, true);
  32199. interval *= yearStep;
  32200. }
  32201. var timezoneOffset = this.getSetting('useUTC')
  32202. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  32203. var niceExtent = [
  32204. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  32205. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  32206. ];
  32207. fixExtent(niceExtent, extent);
  32208. this._stepLvl = level;
  32209. // Interval will be used in getTicks
  32210. this._interval = interval;
  32211. this._niceExtent = niceExtent;
  32212. },
  32213. parse: function (val) {
  32214. // val might be float.
  32215. return +parseDate(val);
  32216. }
  32217. });
  32218. each$1(['contain', 'normalize'], function (methodName) {
  32219. TimeScale.prototype[methodName] = function (val) {
  32220. return intervalScaleProto[methodName].call(this, this.parse(val));
  32221. };
  32222. });
  32223. /**
  32224. * This implementation was originally copied from "d3.js"
  32225. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  32226. * with some modifications made for this program.
  32227. * See the license statement at the head of this file.
  32228. */
  32229. var scaleLevels = [
  32230. // Format interval
  32231. ['hh:mm:ss', ONE_SECOND], // 1s
  32232. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  32233. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  32234. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  32235. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  32236. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  32237. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  32238. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  32239. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  32240. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  32241. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  32242. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  32243. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  32244. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  32245. ['MM-dd\nyyyy', ONE_DAY], // 1d
  32246. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  32247. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  32248. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  32249. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  32250. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  32251. ['week', ONE_DAY * 7], // 7d
  32252. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  32253. ['week', ONE_DAY * 14], // 2w
  32254. ['week', ONE_DAY * 21], // 3w
  32255. ['month', ONE_DAY * 31], // 1M
  32256. ['week', ONE_DAY * 42], // 6w
  32257. ['month', ONE_DAY * 62], // 2M
  32258. ['week', ONE_DAY * 70], // 10w
  32259. ['quarter', ONE_DAY * 95], // 3M
  32260. ['month', ONE_DAY * 31 * 4], // 4M
  32261. ['month', ONE_DAY * 31 * 5], // 5M
  32262. ['half-year', ONE_DAY * 380 / 2], // 6M
  32263. ['month', ONE_DAY * 31 * 8], // 8M
  32264. ['month', ONE_DAY * 31 * 10], // 10M
  32265. ['year', ONE_DAY * 380] // 1Y
  32266. ];
  32267. /**
  32268. * @param {module:echarts/model/Model}
  32269. * @return {module:echarts/scale/Time}
  32270. */
  32271. TimeScale.create = function (model) {
  32272. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  32273. };
  32274. /*
  32275. * Licensed to the Apache Software Foundation (ASF) under one
  32276. * or more contributor license agreements. See the NOTICE file
  32277. * distributed with this work for additional information
  32278. * regarding copyright ownership. The ASF licenses this file
  32279. * to you under the Apache License, Version 2.0 (the
  32280. * "License"); you may not use this file except in compliance
  32281. * with the License. You may obtain a copy of the License at
  32282. *
  32283. * http://www.apache.org/licenses/LICENSE-2.0
  32284. *
  32285. * Unless required by applicable law or agreed to in writing,
  32286. * software distributed under the License is distributed on an
  32287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32288. * KIND, either express or implied. See the License for the
  32289. * specific language governing permissions and limitations
  32290. * under the License.
  32291. */
  32292. /**
  32293. * Log scale
  32294. * @module echarts/scale/Log
  32295. */
  32296. // Use some method of IntervalScale
  32297. var scaleProto$1 = Scale.prototype;
  32298. var intervalScaleProto$1 = IntervalScale.prototype;
  32299. var getPrecisionSafe$1 = getPrecisionSafe;
  32300. var roundingErrorFix = round$1;
  32301. var mathFloor$1 = Math.floor;
  32302. var mathCeil$1 = Math.ceil;
  32303. var mathPow$1 = Math.pow;
  32304. var mathLog = Math.log;
  32305. var LogScale = Scale.extend({
  32306. type: 'log',
  32307. base: 10,
  32308. $constructor: function () {
  32309. Scale.apply(this, arguments);
  32310. this._originalScale = new IntervalScale();
  32311. },
  32312. /**
  32313. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  32314. * @return {Array.<number>}
  32315. */
  32316. getTicks: function (expandToNicedExtent) {
  32317. var originalScale = this._originalScale;
  32318. var extent = this._extent;
  32319. var originalExtent = originalScale.getExtent();
  32320. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  32321. var powVal = round$1(mathPow$1(this.base, val));
  32322. // Fix #4158
  32323. powVal = (val === extent[0] && originalScale.__fixMin)
  32324. ? fixRoundingError(powVal, originalExtent[0])
  32325. : powVal;
  32326. powVal = (val === extent[1] && originalScale.__fixMax)
  32327. ? fixRoundingError(powVal, originalExtent[1])
  32328. : powVal;
  32329. return powVal;
  32330. }, this);
  32331. },
  32332. /**
  32333. * @param {number} splitNumber
  32334. * @return {Array.<Array.<number>>}
  32335. */
  32336. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  32337. /**
  32338. * @param {number} val
  32339. * @return {string}
  32340. */
  32341. getLabel: intervalScaleProto$1.getLabel,
  32342. /**
  32343. * @param {number} val
  32344. * @return {number}
  32345. */
  32346. scale: function (val) {
  32347. val = scaleProto$1.scale.call(this, val);
  32348. return mathPow$1(this.base, val);
  32349. },
  32350. /**
  32351. * @param {number} start
  32352. * @param {number} end
  32353. */
  32354. setExtent: function (start, end) {
  32355. var base = this.base;
  32356. start = mathLog(start) / mathLog(base);
  32357. end = mathLog(end) / mathLog(base);
  32358. intervalScaleProto$1.setExtent.call(this, start, end);
  32359. },
  32360. /**
  32361. * @return {number} end
  32362. */
  32363. getExtent: function () {
  32364. var base = this.base;
  32365. var extent = scaleProto$1.getExtent.call(this);
  32366. extent[0] = mathPow$1(base, extent[0]);
  32367. extent[1] = mathPow$1(base, extent[1]);
  32368. // Fix #4158
  32369. var originalScale = this._originalScale;
  32370. var originalExtent = originalScale.getExtent();
  32371. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  32372. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  32373. return extent;
  32374. },
  32375. /**
  32376. * @param {Array.<number>} extent
  32377. */
  32378. unionExtent: function (extent) {
  32379. this._originalScale.unionExtent(extent);
  32380. var base = this.base;
  32381. extent[0] = mathLog(extent[0]) / mathLog(base);
  32382. extent[1] = mathLog(extent[1]) / mathLog(base);
  32383. scaleProto$1.unionExtent.call(this, extent);
  32384. },
  32385. /**
  32386. * @override
  32387. */
  32388. unionExtentFromData: function (data, dim) {
  32389. // TODO
  32390. // filter value that <= 0
  32391. this.unionExtent(data.getApproximateExtent(dim));
  32392. },
  32393. /**
  32394. * Update interval and extent of intervals for nice ticks
  32395. * @param {number} [approxTickNum = 10] Given approx tick number
  32396. */
  32397. niceTicks: function (approxTickNum) {
  32398. approxTickNum = approxTickNum || 10;
  32399. var extent = this._extent;
  32400. var span = extent[1] - extent[0];
  32401. if (span === Infinity || span <= 0) {
  32402. return;
  32403. }
  32404. var interval = quantity(span);
  32405. var err = approxTickNum / span * interval;
  32406. // Filter ticks to get closer to the desired count.
  32407. if (err <= 0.5) {
  32408. interval *= 10;
  32409. }
  32410. // Interval should be integer
  32411. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  32412. interval *= 10;
  32413. }
  32414. var niceExtent = [
  32415. round$1(mathCeil$1(extent[0] / interval) * interval),
  32416. round$1(mathFloor$1(extent[1] / interval) * interval)
  32417. ];
  32418. this._interval = interval;
  32419. this._niceExtent = niceExtent;
  32420. },
  32421. /**
  32422. * Nice extent.
  32423. * @override
  32424. */
  32425. niceExtent: function (opt) {
  32426. intervalScaleProto$1.niceExtent.call(this, opt);
  32427. var originalScale = this._originalScale;
  32428. originalScale.__fixMin = opt.fixMin;
  32429. originalScale.__fixMax = opt.fixMax;
  32430. }
  32431. });
  32432. each$1(['contain', 'normalize'], function (methodName) {
  32433. LogScale.prototype[methodName] = function (val) {
  32434. val = mathLog(val) / mathLog(this.base);
  32435. return scaleProto$1[methodName].call(this, val);
  32436. };
  32437. });
  32438. LogScale.create = function () {
  32439. return new LogScale();
  32440. };
  32441. function fixRoundingError(val, originalVal) {
  32442. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  32443. }
  32444. /*
  32445. * Licensed to the Apache Software Foundation (ASF) under one
  32446. * or more contributor license agreements. See the NOTICE file
  32447. * distributed with this work for additional information
  32448. * regarding copyright ownership. The ASF licenses this file
  32449. * to you under the Apache License, Version 2.0 (the
  32450. * "License"); you may not use this file except in compliance
  32451. * with the License. You may obtain a copy of the License at
  32452. *
  32453. * http://www.apache.org/licenses/LICENSE-2.0
  32454. *
  32455. * Unless required by applicable law or agreed to in writing,
  32456. * software distributed under the License is distributed on an
  32457. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32458. * KIND, either express or implied. See the License for the
  32459. * specific language governing permissions and limitations
  32460. * under the License.
  32461. */
  32462. /**
  32463. * Get axis scale extent before niced.
  32464. * Item of returned array can only be number (including Infinity and NaN).
  32465. */
  32466. function getScaleExtent(scale, model) {
  32467. var scaleType = scale.type;
  32468. var min = model.getMin();
  32469. var max = model.getMax();
  32470. var fixMin = min != null;
  32471. var fixMax = max != null;
  32472. var originalExtent = scale.getExtent();
  32473. var axisDataLen;
  32474. var boundaryGap;
  32475. var span;
  32476. if (scaleType === 'ordinal') {
  32477. axisDataLen = model.getCategories().length;
  32478. }
  32479. else {
  32480. boundaryGap = model.get('boundaryGap');
  32481. if (!isArray(boundaryGap)) {
  32482. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  32483. }
  32484. if (typeof boundaryGap[0] === 'boolean') {
  32485. if (__DEV__) {
  32486. console.warn('Boolean type for boundaryGap is only '
  32487. + 'allowed for ordinal axis. Please use string in '
  32488. + 'percentage instead, e.g., "20%". Currently, '
  32489. + 'boundaryGap is set to be 0.');
  32490. }
  32491. boundaryGap = [0, 0];
  32492. }
  32493. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  32494. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  32495. span = (originalExtent[1] - originalExtent[0])
  32496. || Math.abs(originalExtent[0]);
  32497. }
  32498. // Notice: When min/max is not set (that is, when there are null/undefined,
  32499. // which is the most common case), these cases should be ensured:
  32500. // (1) For 'ordinal', show all axis.data.
  32501. // (2) For others:
  32502. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  32503. // disabled).
  32504. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  32505. // be the result that originalExtent enlarged by boundaryGap.
  32506. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  32507. // FIXME
  32508. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  32509. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  32510. // that the results processed by boundaryGap are positive/negative?
  32511. if (min == null) {
  32512. min = scaleType === 'ordinal'
  32513. ? (axisDataLen ? 0 : NaN)
  32514. : originalExtent[0] - boundaryGap[0] * span;
  32515. }
  32516. if (max == null) {
  32517. max = scaleType === 'ordinal'
  32518. ? (axisDataLen ? axisDataLen - 1 : NaN)
  32519. : originalExtent[1] + boundaryGap[1] * span;
  32520. }
  32521. if (min === 'dataMin') {
  32522. min = originalExtent[0];
  32523. }
  32524. else if (typeof min === 'function') {
  32525. min = min({
  32526. min: originalExtent[0],
  32527. max: originalExtent[1]
  32528. });
  32529. }
  32530. if (max === 'dataMax') {
  32531. max = originalExtent[1];
  32532. }
  32533. else if (typeof max === 'function') {
  32534. max = max({
  32535. min: originalExtent[0],
  32536. max: originalExtent[1]
  32537. });
  32538. }
  32539. (min == null || !isFinite(min)) && (min = NaN);
  32540. (max == null || !isFinite(max)) && (max = NaN);
  32541. scale.setBlank(
  32542. eqNaN(min)
  32543. || eqNaN(max)
  32544. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  32545. );
  32546. // Evaluate if axis needs cross zero
  32547. if (model.getNeedCrossZero()) {
  32548. // Axis is over zero and min is not set
  32549. if (min > 0 && max > 0 && !fixMin) {
  32550. min = 0;
  32551. }
  32552. // Axis is under zero and max is not set
  32553. if (min < 0 && max < 0 && !fixMax) {
  32554. max = 0;
  32555. }
  32556. }
  32557. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  32558. // is base axis
  32559. // FIXME
  32560. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  32561. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  32562. // Should not depend on series type `bar`?
  32563. // (3) Fix that might overlap when using dataZoom.
  32564. // (4) Consider other chart types using `barGrid`?
  32565. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  32566. var ecModel = model.ecModel;
  32567. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  32568. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  32569. var isBaseAxisAndHasBarSeries;
  32570. each$1(barSeriesModels, function (seriesModel) {
  32571. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  32572. });
  32573. if (isBaseAxisAndHasBarSeries) {
  32574. // Calculate placement of bars on axis
  32575. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  32576. // Adjust axis min and max to account for overflow
  32577. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  32578. min = adjustedScale.min;
  32579. max = adjustedScale.max;
  32580. }
  32581. }
  32582. return [min, max];
  32583. }
  32584. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  32585. // Get Axis Length
  32586. var axisExtent = model.axis.getExtent();
  32587. var axisLength = axisExtent[1] - axisExtent[0];
  32588. // Get bars on current base axis and calculate min and max overflow
  32589. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  32590. if (barsOnCurrentAxis === undefined) {
  32591. return {min: min, max: max};
  32592. }
  32593. var minOverflow = Infinity;
  32594. each$1(barsOnCurrentAxis, function (item) {
  32595. minOverflow = Math.min(item.offset, minOverflow);
  32596. });
  32597. var maxOverflow = -Infinity;
  32598. each$1(barsOnCurrentAxis, function (item) {
  32599. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  32600. });
  32601. minOverflow = Math.abs(minOverflow);
  32602. maxOverflow = Math.abs(maxOverflow);
  32603. var totalOverFlow = minOverflow + maxOverflow;
  32604. // Calulate required buffer based on old range and overflow
  32605. var oldRange = max - min;
  32606. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  32607. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  32608. max += overflowBuffer * (maxOverflow / totalOverFlow);
  32609. min -= overflowBuffer * (minOverflow / totalOverFlow);
  32610. return {min: min, max: max};
  32611. }
  32612. function niceScaleExtent(scale, model) {
  32613. var extent = getScaleExtent(scale, model);
  32614. var fixMin = model.getMin() != null;
  32615. var fixMax = model.getMax() != null;
  32616. var splitNumber = model.get('splitNumber');
  32617. if (scale.type === 'log') {
  32618. scale.base = model.get('logBase');
  32619. }
  32620. var scaleType = scale.type;
  32621. scale.setExtent(extent[0], extent[1]);
  32622. scale.niceExtent({
  32623. splitNumber: splitNumber,
  32624. fixMin: fixMin,
  32625. fixMax: fixMax,
  32626. minInterval: (scaleType === 'interval' || scaleType === 'time')
  32627. ? model.get('minInterval') : null,
  32628. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  32629. ? model.get('maxInterval') : null
  32630. });
  32631. // If some one specified the min, max. And the default calculated interval
  32632. // is not good enough. He can specify the interval. It is often appeared
  32633. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  32634. // to be 60.
  32635. // FIXME
  32636. var interval = model.get('interval');
  32637. if (interval != null) {
  32638. scale.setInterval && scale.setInterval(interval);
  32639. }
  32640. }
  32641. /**
  32642. * @param {module:echarts/model/Model} model
  32643. * @param {string} [axisType] Default retrieve from model.type
  32644. * @return {module:echarts/scale/*}
  32645. */
  32646. function createScaleByModel(model, axisType) {
  32647. axisType = axisType || model.get('type');
  32648. if (axisType) {
  32649. switch (axisType) {
  32650. // Buildin scale
  32651. case 'category':
  32652. return new OrdinalScale(
  32653. model.getOrdinalMeta
  32654. ? model.getOrdinalMeta()
  32655. : model.getCategories(),
  32656. [Infinity, -Infinity]
  32657. );
  32658. case 'value':
  32659. return new IntervalScale();
  32660. // Extended scale, like time and log
  32661. default:
  32662. return (Scale.getClass(axisType) || IntervalScale).create(model);
  32663. }
  32664. }
  32665. }
  32666. /**
  32667. * Check if the axis corss 0
  32668. */
  32669. function ifAxisCrossZero(axis) {
  32670. var dataExtent = axis.scale.getExtent();
  32671. var min = dataExtent[0];
  32672. var max = dataExtent[1];
  32673. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  32674. }
  32675. /**
  32676. * @param {module:echarts/coord/Axis} axis
  32677. * @return {Function} Label formatter function.
  32678. * param: {number} tickValue,
  32679. * param: {number} idx, the index in all ticks.
  32680. * If category axis, this param is not requied.
  32681. * return: {string} label string.
  32682. */
  32683. function makeLabelFormatter(axis) {
  32684. var labelFormatter = axis.getLabelModel().get('formatter');
  32685. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  32686. if (typeof labelFormatter === 'string') {
  32687. labelFormatter = (function (tpl) {
  32688. return function (val) {
  32689. // For category axis, get raw value; for numeric axis,
  32690. // get foramtted label like '1,333,444'.
  32691. val = axis.scale.getLabel(val);
  32692. return tpl.replace('{value}', val != null ? val : '');
  32693. };
  32694. })(labelFormatter);
  32695. // Consider empty array
  32696. return labelFormatter;
  32697. }
  32698. else if (typeof labelFormatter === 'function') {
  32699. return function (tickValue, idx) {
  32700. // The original intention of `idx` is "the index of the tick in all ticks".
  32701. // But the previous implementation of category axis do not consider the
  32702. // `axisLabel.interval`, which cause that, for example, the `interval` is
  32703. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  32704. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  32705. // the definition here for back compatibility.
  32706. if (categoryTickStart != null) {
  32707. idx = tickValue - categoryTickStart;
  32708. }
  32709. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  32710. };
  32711. }
  32712. else {
  32713. return function (tick) {
  32714. return axis.scale.getLabel(tick);
  32715. };
  32716. }
  32717. }
  32718. function getAxisRawValue(axis, value) {
  32719. // In category axis with data zoom, tick is not the original
  32720. // index of axis.data. So tick should not be exposed to user
  32721. // in category axis.
  32722. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  32723. }
  32724. /**
  32725. * @param {module:echarts/coord/Axis} axis
  32726. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  32727. */
  32728. function estimateLabelUnionRect(axis) {
  32729. var axisModel = axis.model;
  32730. var scale = axis.scale;
  32731. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  32732. return;
  32733. }
  32734. var isCategory = axis.type === 'category';
  32735. var realNumberScaleTicks;
  32736. var tickCount;
  32737. var categoryScaleExtent = scale.getExtent();
  32738. // Optimize for large category data, avoid call `getTicks()`.
  32739. if (isCategory) {
  32740. tickCount = scale.count();
  32741. }
  32742. else {
  32743. realNumberScaleTicks = scale.getTicks();
  32744. tickCount = realNumberScaleTicks.length;
  32745. }
  32746. var axisLabelModel = axis.getLabelModel();
  32747. var labelFormatter = makeLabelFormatter(axis);
  32748. var rect;
  32749. var step = 1;
  32750. // Simple optimization for large amount of labels
  32751. if (tickCount > 40) {
  32752. step = Math.ceil(tickCount / 40);
  32753. }
  32754. for (var i = 0; i < tickCount; i += step) {
  32755. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  32756. var label = labelFormatter(tickValue);
  32757. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  32758. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  32759. rect ? rect.union(singleRect) : (rect = singleRect);
  32760. }
  32761. return rect;
  32762. }
  32763. function rotateTextRect(textRect, rotate) {
  32764. var rotateRadians = rotate * Math.PI / 180;
  32765. var boundingBox = textRect.plain();
  32766. var beforeWidth = boundingBox.width;
  32767. var beforeHeight = boundingBox.height;
  32768. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  32769. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  32770. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  32771. return rotatedRect;
  32772. }
  32773. /**
  32774. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  32775. * @return {number|String} Can be null|'auto'|number|function
  32776. */
  32777. function getOptionCategoryInterval(model) {
  32778. var interval = model.get('interval');
  32779. return interval == null ? 'auto' : interval;
  32780. }
  32781. /**
  32782. * Set `categoryInterval` as 0 implicitly indicates that
  32783. * show all labels reguardless of overlap.
  32784. * @param {Object} axis axisModel.axis
  32785. * @return {boolean}
  32786. */
  32787. function shouldShowAllLabels(axis) {
  32788. return axis.type === 'category'
  32789. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  32790. }
  32791. /*
  32792. * Licensed to the Apache Software Foundation (ASF) under one
  32793. * or more contributor license agreements. See the NOTICE file
  32794. * distributed with this work for additional information
  32795. * regarding copyright ownership. The ASF licenses this file
  32796. * to you under the Apache License, Version 2.0 (the
  32797. * "License"); you may not use this file except in compliance
  32798. * with the License. You may obtain a copy of the License at
  32799. *
  32800. * http://www.apache.org/licenses/LICENSE-2.0
  32801. *
  32802. * Unless required by applicable law or agreed to in writing,
  32803. * software distributed under the License is distributed on an
  32804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32805. * KIND, either express or implied. See the License for the
  32806. * specific language governing permissions and limitations
  32807. * under the License.
  32808. */
  32809. /**
  32810. * Cartesian coordinate system
  32811. * @module echarts/coord/Cartesian
  32812. *
  32813. */
  32814. function dimAxisMapper(dim) {
  32815. return this._axes[dim];
  32816. }
  32817. /**
  32818. * @alias module:echarts/coord/Cartesian
  32819. * @constructor
  32820. */
  32821. var Cartesian = function (name) {
  32822. this._axes = {};
  32823. this._dimList = [];
  32824. /**
  32825. * @type {string}
  32826. */
  32827. this.name = name || '';
  32828. };
  32829. Cartesian.prototype = {
  32830. constructor: Cartesian,
  32831. type: 'cartesian',
  32832. /**
  32833. * Get axis
  32834. * @param {number|string} dim
  32835. * @return {module:echarts/coord/Cartesian~Axis}
  32836. */
  32837. getAxis: function (dim) {
  32838. return this._axes[dim];
  32839. },
  32840. /**
  32841. * Get axes list
  32842. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  32843. */
  32844. getAxes: function () {
  32845. return map(this._dimList, dimAxisMapper, this);
  32846. },
  32847. /**
  32848. * Get axes list by given scale type
  32849. */
  32850. getAxesByScale: function (scaleType) {
  32851. scaleType = scaleType.toLowerCase();
  32852. return filter(
  32853. this.getAxes(),
  32854. function (axis) {
  32855. return axis.scale.type === scaleType;
  32856. }
  32857. );
  32858. },
  32859. /**
  32860. * Add axis
  32861. * @param {module:echarts/coord/Cartesian.Axis}
  32862. */
  32863. addAxis: function (axis) {
  32864. var dim = axis.dim;
  32865. this._axes[dim] = axis;
  32866. this._dimList.push(dim);
  32867. },
  32868. /**
  32869. * Convert data to coord in nd space
  32870. * @param {Array.<number>|Object.<string, number>} val
  32871. * @return {Array.<number>|Object.<string, number>}
  32872. */
  32873. dataToCoord: function (val) {
  32874. return this._dataCoordConvert(val, 'dataToCoord');
  32875. },
  32876. /**
  32877. * Convert coord in nd space to data
  32878. * @param {Array.<number>|Object.<string, number>} val
  32879. * @return {Array.<number>|Object.<string, number>}
  32880. */
  32881. coordToData: function (val) {
  32882. return this._dataCoordConvert(val, 'coordToData');
  32883. },
  32884. _dataCoordConvert: function (input, method) {
  32885. var dimList = this._dimList;
  32886. var output = input instanceof Array ? [] : {};
  32887. for (var i = 0; i < dimList.length; i++) {
  32888. var dim = dimList[i];
  32889. var axis = this._axes[dim];
  32890. output[dim] = axis[method](input[dim]);
  32891. }
  32892. return output;
  32893. }
  32894. };
  32895. /*
  32896. * Licensed to the Apache Software Foundation (ASF) under one
  32897. * or more contributor license agreements. See the NOTICE file
  32898. * distributed with this work for additional information
  32899. * regarding copyright ownership. The ASF licenses this file
  32900. * to you under the Apache License, Version 2.0 (the
  32901. * "License"); you may not use this file except in compliance
  32902. * with the License. You may obtain a copy of the License at
  32903. *
  32904. * http://www.apache.org/licenses/LICENSE-2.0
  32905. *
  32906. * Unless required by applicable law or agreed to in writing,
  32907. * software distributed under the License is distributed on an
  32908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32909. * KIND, either express or implied. See the License for the
  32910. * specific language governing permissions and limitations
  32911. * under the License.
  32912. */
  32913. function Cartesian2D(name) {
  32914. Cartesian.call(this, name);
  32915. }
  32916. Cartesian2D.prototype = {
  32917. constructor: Cartesian2D,
  32918. type: 'cartesian2d',
  32919. /**
  32920. * @type {Array.<string>}
  32921. * @readOnly
  32922. */
  32923. dimensions: ['x', 'y'],
  32924. /**
  32925. * Base axis will be used on stacking.
  32926. *
  32927. * @return {module:echarts/coord/cartesian/Axis2D}
  32928. */
  32929. getBaseAxis: function () {
  32930. return this.getAxesByScale('ordinal')[0]
  32931. || this.getAxesByScale('time')[0]
  32932. || this.getAxis('x');
  32933. },
  32934. /**
  32935. * If contain point
  32936. * @param {Array.<number>} point
  32937. * @return {boolean}
  32938. */
  32939. containPoint: function (point) {
  32940. var axisX = this.getAxis('x');
  32941. var axisY = this.getAxis('y');
  32942. return axisX.contain(axisX.toLocalCoord(point[0]))
  32943. && axisY.contain(axisY.toLocalCoord(point[1]));
  32944. },
  32945. /**
  32946. * If contain data
  32947. * @param {Array.<number>} data
  32948. * @return {boolean}
  32949. */
  32950. containData: function (data) {
  32951. return this.getAxis('x').containData(data[0])
  32952. && this.getAxis('y').containData(data[1]);
  32953. },
  32954. /**
  32955. * @param {Array.<number>} data
  32956. * @param {Array.<number>} out
  32957. * @return {Array.<number>}
  32958. */
  32959. dataToPoint: function (data, reserved, out) {
  32960. var xAxis = this.getAxis('x');
  32961. var yAxis = this.getAxis('y');
  32962. out = out || [];
  32963. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  32964. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  32965. return out;
  32966. },
  32967. /**
  32968. * @param {Array.<number>} data
  32969. * @param {Array.<number>} out
  32970. * @return {Array.<number>}
  32971. */
  32972. clampData: function (data, out) {
  32973. var xScale = this.getAxis('x').scale;
  32974. var yScale = this.getAxis('y').scale;
  32975. var xAxisExtent = xScale.getExtent();
  32976. var yAxisExtent = yScale.getExtent();
  32977. var x = xScale.parse(data[0]);
  32978. var y = yScale.parse(data[1]);
  32979. out = out || [];
  32980. out[0] = Math.min(
  32981. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  32982. Math.max(xAxisExtent[0], xAxisExtent[1])
  32983. );
  32984. out[1] = Math.min(
  32985. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  32986. Math.max(yAxisExtent[0], yAxisExtent[1])
  32987. );
  32988. return out;
  32989. },
  32990. /**
  32991. * @param {Array.<number>} point
  32992. * @param {Array.<number>} out
  32993. * @return {Array.<number>}
  32994. */
  32995. pointToData: function (point, out) {
  32996. var xAxis = this.getAxis('x');
  32997. var yAxis = this.getAxis('y');
  32998. out = out || [];
  32999. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  33000. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  33001. return out;
  33002. },
  33003. /**
  33004. * Get other axis
  33005. * @param {module:echarts/coord/cartesian/Axis2D} axis
  33006. */
  33007. getOtherAxis: function (axis) {
  33008. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  33009. },
  33010. /**
  33011. * Get rect area of cartesian.
  33012. * Area will have a contain function to determine if a point is in the coordinate system.
  33013. * @return {BoundingRect}
  33014. */
  33015. getArea: function () {
  33016. var xExtent = this.getAxis('x').getGlobalExtent();
  33017. var yExtent = this.getAxis('y').getGlobalExtent();
  33018. var x = Math.min(xExtent[0], xExtent[1]);
  33019. var y = Math.min(yExtent[0], yExtent[1]);
  33020. var width = Math.max(xExtent[0], xExtent[1]) - x;
  33021. var height = Math.max(yExtent[0], yExtent[1]) - y;
  33022. var rect = new BoundingRect(x, y, width, height);
  33023. return rect;
  33024. }
  33025. };
  33026. inherits(Cartesian2D, Cartesian);
  33027. /*
  33028. * Licensed to the Apache Software Foundation (ASF) under one
  33029. * or more contributor license agreements. See the NOTICE file
  33030. * distributed with this work for additional information
  33031. * regarding copyright ownership. The ASF licenses this file
  33032. * to you under the Apache License, Version 2.0 (the
  33033. * "License"); you may not use this file except in compliance
  33034. * with the License. You may obtain a copy of the License at
  33035. *
  33036. * http://www.apache.org/licenses/LICENSE-2.0
  33037. *
  33038. * Unless required by applicable law or agreed to in writing,
  33039. * software distributed under the License is distributed on an
  33040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33041. * KIND, either express or implied. See the License for the
  33042. * specific language governing permissions and limitations
  33043. * under the License.
  33044. */
  33045. var inner$6 = makeInner();
  33046. /**
  33047. * @param {module:echats/coord/Axis} axis
  33048. * @return {Object} {
  33049. * labels: [{
  33050. * formattedLabel: string,
  33051. * rawLabel: string,
  33052. * tickValue: number
  33053. * }, ...],
  33054. * labelCategoryInterval: number
  33055. * }
  33056. */
  33057. function createAxisLabels(axis) {
  33058. // Only ordinal scale support tick interval
  33059. return axis.type === 'category'
  33060. ? makeCategoryLabels(axis)
  33061. : makeRealNumberLabels(axis);
  33062. }
  33063. /**
  33064. * @param {module:echats/coord/Axis} axis
  33065. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  33066. * @return {Object} {
  33067. * ticks: Array.<number>
  33068. * tickCategoryInterval: number
  33069. * }
  33070. */
  33071. function createAxisTicks(axis, tickModel) {
  33072. // Only ordinal scale support tick interval
  33073. return axis.type === 'category'
  33074. ? makeCategoryTicks(axis, tickModel)
  33075. : {ticks: axis.scale.getTicks()};
  33076. }
  33077. function makeCategoryLabels(axis) {
  33078. var labelModel = axis.getLabelModel();
  33079. var result = makeCategoryLabelsActually(axis, labelModel);
  33080. return (!labelModel.get('show') || axis.scale.isBlank())
  33081. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  33082. : result;
  33083. }
  33084. function makeCategoryLabelsActually(axis, labelModel) {
  33085. var labelsCache = getListCache(axis, 'labels');
  33086. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  33087. var result = listCacheGet(labelsCache, optionLabelInterval);
  33088. if (result) {
  33089. return result;
  33090. }
  33091. var labels;
  33092. var numericLabelInterval;
  33093. if (isFunction$1(optionLabelInterval)) {
  33094. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  33095. }
  33096. else {
  33097. numericLabelInterval = optionLabelInterval === 'auto'
  33098. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  33099. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  33100. }
  33101. // Cache to avoid calling interval function repeatly.
  33102. return listCacheSet(labelsCache, optionLabelInterval, {
  33103. labels: labels, labelCategoryInterval: numericLabelInterval
  33104. });
  33105. }
  33106. function makeCategoryTicks(axis, tickModel) {
  33107. var ticksCache = getListCache(axis, 'ticks');
  33108. var optionTickInterval = getOptionCategoryInterval(tickModel);
  33109. var result = listCacheGet(ticksCache, optionTickInterval);
  33110. if (result) {
  33111. return result;
  33112. }
  33113. var ticks;
  33114. var tickCategoryInterval;
  33115. // Optimize for the case that large category data and no label displayed,
  33116. // we should not return all ticks.
  33117. if (!tickModel.get('show') || axis.scale.isBlank()) {
  33118. ticks = [];
  33119. }
  33120. if (isFunction$1(optionTickInterval)) {
  33121. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  33122. }
  33123. // Always use label interval by default despite label show. Consider this
  33124. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  33125. // labels. `splitLine` and `axisTick` should be consistent in this case.
  33126. else if (optionTickInterval === 'auto') {
  33127. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  33128. tickCategoryInterval = labelsResult.labelCategoryInterval;
  33129. ticks = map(labelsResult.labels, function (labelItem) {
  33130. return labelItem.tickValue;
  33131. });
  33132. }
  33133. else {
  33134. tickCategoryInterval = optionTickInterval;
  33135. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  33136. }
  33137. // Cache to avoid calling interval function repeatly.
  33138. return listCacheSet(ticksCache, optionTickInterval, {
  33139. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  33140. });
  33141. }
  33142. function makeRealNumberLabels(axis) {
  33143. var ticks = axis.scale.getTicks();
  33144. var labelFormatter = makeLabelFormatter(axis);
  33145. return {
  33146. labels: map(ticks, function (tickValue, idx) {
  33147. return {
  33148. formattedLabel: labelFormatter(tickValue, idx),
  33149. rawLabel: axis.scale.getLabel(tickValue),
  33150. tickValue: tickValue
  33151. };
  33152. })
  33153. };
  33154. }
  33155. // Large category data calculation is performence sensitive, and ticks and label
  33156. // probably be fetched by multiple times. So we cache the result.
  33157. // axis is created each time during a ec process, so we do not need to clear cache.
  33158. function getListCache(axis, prop) {
  33159. // Because key can be funciton, and cache size always be small, we use array cache.
  33160. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  33161. }
  33162. function listCacheGet(cache, key) {
  33163. for (var i = 0; i < cache.length; i++) {
  33164. if (cache[i].key === key) {
  33165. return cache[i].value;
  33166. }
  33167. }
  33168. }
  33169. function listCacheSet(cache, key, value) {
  33170. cache.push({key: key, value: value});
  33171. return value;
  33172. }
  33173. function makeAutoCategoryInterval(axis) {
  33174. var result = inner$6(axis).autoInterval;
  33175. return result != null
  33176. ? result
  33177. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  33178. }
  33179. /**
  33180. * Calculate interval for category axis ticks and labels.
  33181. * To get precise result, at least one of `getRotate` and `isHorizontal`
  33182. * should be implemented in axis.
  33183. */
  33184. function calculateCategoryInterval(axis) {
  33185. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  33186. var labelFormatter = makeLabelFormatter(axis);
  33187. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  33188. var ordinalScale = axis.scale;
  33189. var ordinalExtent = ordinalScale.getExtent();
  33190. // Providing this method is for optimization:
  33191. // avoid generating a long array by `getTicks`
  33192. // in large category data case.
  33193. var tickCount = ordinalScale.count();
  33194. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  33195. return 0;
  33196. }
  33197. var step = 1;
  33198. // Simple optimization. Empirical value: tick count should less than 40.
  33199. if (tickCount > 40) {
  33200. step = Math.max(1, Math.floor(tickCount / 40));
  33201. }
  33202. var tickValue = ordinalExtent[0];
  33203. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  33204. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  33205. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  33206. var maxW = 0;
  33207. var maxH = 0;
  33208. // Caution: Performance sensitive for large category data.
  33209. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  33210. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33211. var width = 0;
  33212. var height = 0;
  33213. // Not precise, do not consider align and vertical align
  33214. // and each distance from axis line yet.
  33215. var rect = getBoundingRect(
  33216. labelFormatter(tickValue), params.font, 'center', 'top'
  33217. );
  33218. // Magic number
  33219. width = rect.width * 1.3;
  33220. height = rect.height * 1.3;
  33221. // Min size, void long loop.
  33222. maxW = Math.max(maxW, width, 7);
  33223. maxH = Math.max(maxH, height, 7);
  33224. }
  33225. var dw = maxW / unitW;
  33226. var dh = maxH / unitH;
  33227. // 0/0 is NaN, 1/0 is Infinity.
  33228. isNaN(dw) && (dw = Infinity);
  33229. isNaN(dh) && (dh = Infinity);
  33230. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  33231. var cache = inner$6(axis.model);
  33232. var axisExtent = axis.getExtent();
  33233. var lastAutoInterval = cache.lastAutoInterval;
  33234. var lastTickCount = cache.lastTickCount;
  33235. // Use cache to keep interval stable while moving zoom window,
  33236. // otherwise the calculated interval might jitter when the zoom
  33237. // window size is close to the interval-changing size.
  33238. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  33239. // The jitter will cause that sometimes the displayed labels are
  33240. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  33241. if (lastAutoInterval != null
  33242. && lastTickCount != null
  33243. && Math.abs(lastAutoInterval - interval) <= 1
  33244. && Math.abs(lastTickCount - tickCount) <= 1
  33245. // Always choose the bigger one, otherwise the critical
  33246. // point is not the same when zooming in or zooming out.
  33247. && lastAutoInterval > interval
  33248. // If the axis change is caused by chart resize, the cache should not
  33249. // be used. Otherwise some hiden labels might not be shown again.
  33250. && cache.axisExtend0 === axisExtent[0]
  33251. && cache.axisExtend1 === axisExtent[1]
  33252. ) {
  33253. interval = lastAutoInterval;
  33254. }
  33255. // Only update cache if cache not used, otherwise the
  33256. // changing of interval is too insensitive.
  33257. else {
  33258. cache.lastTickCount = tickCount;
  33259. cache.lastAutoInterval = interval;
  33260. cache.axisExtend0 = axisExtent[0];
  33261. cache.axisExtend1 = axisExtent[1];
  33262. }
  33263. return interval;
  33264. }
  33265. function fetchAutoCategoryIntervalCalculationParams(axis) {
  33266. var labelModel = axis.getLabelModel();
  33267. return {
  33268. axisRotate: axis.getRotate
  33269. ? axis.getRotate()
  33270. : (axis.isHorizontal && !axis.isHorizontal())
  33271. ? 90
  33272. : 0,
  33273. labelRotate: labelModel.get('rotate') || 0,
  33274. font: labelModel.getFont()
  33275. };
  33276. }
  33277. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  33278. var labelFormatter = makeLabelFormatter(axis);
  33279. var ordinalScale = axis.scale;
  33280. var ordinalExtent = ordinalScale.getExtent();
  33281. var labelModel = axis.getLabelModel();
  33282. var result = [];
  33283. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  33284. var step = Math.max((categoryInterval || 0) + 1, 1);
  33285. var startTick = ordinalExtent[0];
  33286. var tickCount = ordinalScale.count();
  33287. // Calculate start tick based on zero if possible to keep label consistent
  33288. // while zooming and moving while interval > 0. Otherwise the selection
  33289. // of displayable ticks and symbols probably keep changing.
  33290. // 3 is empirical value.
  33291. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  33292. startTick = Math.round(Math.ceil(startTick / step) * step);
  33293. }
  33294. // (1) Only add min max label here but leave overlap checking
  33295. // to render stage, which also ensure the returned list
  33296. // suitable for splitLine and splitArea rendering.
  33297. // (2) Scales except category always contain min max label so
  33298. // do not need to perform this process.
  33299. var showAllLabel = shouldShowAllLabels(axis);
  33300. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  33301. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  33302. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  33303. addItem(ordinalExtent[0]);
  33304. }
  33305. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  33306. var tickValue = startTick;
  33307. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  33308. addItem(tickValue);
  33309. }
  33310. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  33311. addItem(ordinalExtent[1]);
  33312. }
  33313. function addItem(tVal) {
  33314. result.push(onlyTick
  33315. ? tVal
  33316. : {
  33317. formattedLabel: labelFormatter(tVal),
  33318. rawLabel: ordinalScale.getLabel(tVal),
  33319. tickValue: tVal
  33320. }
  33321. );
  33322. }
  33323. return result;
  33324. }
  33325. // When interval is function, the result `false` means ignore the tick.
  33326. // It is time consuming for large category data.
  33327. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  33328. var ordinalScale = axis.scale;
  33329. var labelFormatter = makeLabelFormatter(axis);
  33330. var result = [];
  33331. each$1(ordinalScale.getTicks(), function (tickValue) {
  33332. var rawLabel = ordinalScale.getLabel(tickValue);
  33333. if (categoryInterval(tickValue, rawLabel)) {
  33334. result.push(onlyTick
  33335. ? tickValue
  33336. : {
  33337. formattedLabel: labelFormatter(tickValue),
  33338. rawLabel: rawLabel,
  33339. tickValue: tickValue
  33340. }
  33341. );
  33342. }
  33343. });
  33344. return result;
  33345. }
  33346. /*
  33347. * Licensed to the Apache Software Foundation (ASF) under one
  33348. * or more contributor license agreements. See the NOTICE file
  33349. * distributed with this work for additional information
  33350. * regarding copyright ownership. The ASF licenses this file
  33351. * to you under the Apache License, Version 2.0 (the
  33352. * "License"); you may not use this file except in compliance
  33353. * with the License. You may obtain a copy of the License at
  33354. *
  33355. * http://www.apache.org/licenses/LICENSE-2.0
  33356. *
  33357. * Unless required by applicable law or agreed to in writing,
  33358. * software distributed under the License is distributed on an
  33359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33360. * KIND, either express or implied. See the License for the
  33361. * specific language governing permissions and limitations
  33362. * under the License.
  33363. */
  33364. var NORMALIZED_EXTENT = [0, 1];
  33365. /**
  33366. * Base class of Axis.
  33367. * @constructor
  33368. */
  33369. var Axis = function (dim, scale, extent) {
  33370. /**
  33371. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  33372. * @type {string}
  33373. */
  33374. this.dim = dim;
  33375. /**
  33376. * Axis scale
  33377. * @type {module:echarts/coord/scale/*}
  33378. */
  33379. this.scale = scale;
  33380. /**
  33381. * @type {Array.<number>}
  33382. * @private
  33383. */
  33384. this._extent = extent || [0, 0];
  33385. /**
  33386. * @type {boolean}
  33387. */
  33388. this.inverse = false;
  33389. /**
  33390. * Usually true when axis has a ordinal scale
  33391. * @type {boolean}
  33392. */
  33393. this.onBand = false;
  33394. };
  33395. Axis.prototype = {
  33396. constructor: Axis,
  33397. /**
  33398. * If axis extent contain given coord
  33399. * @param {number} coord
  33400. * @return {boolean}
  33401. */
  33402. contain: function (coord) {
  33403. var extent = this._extent;
  33404. var min = Math.min(extent[0], extent[1]);
  33405. var max = Math.max(extent[0], extent[1]);
  33406. return coord >= min && coord <= max;
  33407. },
  33408. /**
  33409. * If axis extent contain given data
  33410. * @param {number} data
  33411. * @return {boolean}
  33412. */
  33413. containData: function (data) {
  33414. return this.scale.contain(data);
  33415. },
  33416. /**
  33417. * Get coord extent.
  33418. * @return {Array.<number>}
  33419. */
  33420. getExtent: function () {
  33421. return this._extent.slice();
  33422. },
  33423. /**
  33424. * Get precision used for formatting
  33425. * @param {Array.<number>} [dataExtent]
  33426. * @return {number}
  33427. */
  33428. getPixelPrecision: function (dataExtent) {
  33429. return getPixelPrecision(
  33430. dataExtent || this.scale.getExtent(),
  33431. this._extent
  33432. );
  33433. },
  33434. /**
  33435. * Set coord extent
  33436. * @param {number} start
  33437. * @param {number} end
  33438. */
  33439. setExtent: function (start, end) {
  33440. var extent = this._extent;
  33441. extent[0] = start;
  33442. extent[1] = end;
  33443. },
  33444. /**
  33445. * Convert data to coord. Data is the rank if it has an ordinal scale
  33446. * @param {number} data
  33447. * @param {boolean} clamp
  33448. * @return {number}
  33449. */
  33450. dataToCoord: function (data, clamp) {
  33451. var extent = this._extent;
  33452. var scale = this.scale;
  33453. data = scale.normalize(data);
  33454. if (this.onBand && scale.type === 'ordinal') {
  33455. extent = extent.slice();
  33456. fixExtentWithBands(extent, scale.count());
  33457. }
  33458. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  33459. },
  33460. /**
  33461. * Convert coord to data. Data is the rank if it has an ordinal scale
  33462. * @param {number} coord
  33463. * @param {boolean} clamp
  33464. * @return {number}
  33465. */
  33466. coordToData: function (coord, clamp) {
  33467. var extent = this._extent;
  33468. var scale = this.scale;
  33469. if (this.onBand && scale.type === 'ordinal') {
  33470. extent = extent.slice();
  33471. fixExtentWithBands(extent, scale.count());
  33472. }
  33473. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  33474. return this.scale.scale(t);
  33475. },
  33476. /**
  33477. * Convert pixel point to data in axis
  33478. * @param {Array.<number>} point
  33479. * @param {boolean} clamp
  33480. * @return {number} data
  33481. */
  33482. pointToData: function (point, clamp) {
  33483. // Should be implemented in derived class if necessary.
  33484. },
  33485. /**
  33486. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  33487. * `axis.getTicksCoords` considers `onBand`, which is used by
  33488. * `boundaryGap:true` of category axis and splitLine and splitArea.
  33489. * @param {Object} [opt]
  33490. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  33491. * @param {boolean} [opt.clamp] If `true`, the first and the last
  33492. * tick must be at the axis end points. Otherwise, clip ticks
  33493. * that outside the axis extent.
  33494. * @return {Array.<Object>} [{
  33495. * coord: ...,
  33496. * tickValue: ...
  33497. * }, ...]
  33498. */
  33499. getTicksCoords: function (opt) {
  33500. opt = opt || {};
  33501. var tickModel = opt.tickModel || this.getTickModel();
  33502. var result = createAxisTicks(this, tickModel);
  33503. var ticks = result.ticks;
  33504. var ticksCoords = map(ticks, function (tickValue) {
  33505. return {
  33506. coord: this.dataToCoord(tickValue),
  33507. tickValue: tickValue
  33508. };
  33509. }, this);
  33510. var alignWithLabel = tickModel.get('alignWithLabel');
  33511. fixOnBandTicksCoords(
  33512. this, ticksCoords, alignWithLabel, opt.clamp
  33513. );
  33514. return ticksCoords;
  33515. },
  33516. /**
  33517. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  33518. */
  33519. getMinorTicksCoords: function () {
  33520. if (this.scale.type === 'ordinal') {
  33521. // Category axis doesn't support minor ticks
  33522. return [];
  33523. }
  33524. var minorTickModel = this.model.getModel('minorTick');
  33525. var splitNumber = minorTickModel.get('splitNumber');
  33526. // Protection.
  33527. if (!(splitNumber > 0 && splitNumber < 100)) {
  33528. splitNumber = 5;
  33529. }
  33530. var minorTicks = this.scale.getMinorTicks(splitNumber);
  33531. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  33532. return map(minorTicksGroup, function (minorTick) {
  33533. return {
  33534. coord: this.dataToCoord(minorTick),
  33535. tickValue: minorTick
  33536. };
  33537. }, this);
  33538. }, this);
  33539. return minorTicksCoords;
  33540. },
  33541. /**
  33542. * @return {Array.<Object>} [{
  33543. * formattedLabel: string,
  33544. * rawLabel: axis.scale.getLabel(tickValue)
  33545. * tickValue: number
  33546. * }, ...]
  33547. */
  33548. getViewLabels: function () {
  33549. return createAxisLabels(this).labels;
  33550. },
  33551. /**
  33552. * @return {module:echarts/coord/model/Model}
  33553. */
  33554. getLabelModel: function () {
  33555. return this.model.getModel('axisLabel');
  33556. },
  33557. /**
  33558. * Notice here we only get the default tick model. For splitLine
  33559. * or splitArea, we should pass the splitLineModel or splitAreaModel
  33560. * manually when calling `getTicksCoords`.
  33561. * In GL, this method may be overrided to:
  33562. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  33563. * @return {module:echarts/coord/model/Model}
  33564. */
  33565. getTickModel: function () {
  33566. return this.model.getModel('axisTick');
  33567. },
  33568. /**
  33569. * Get width of band
  33570. * @return {number}
  33571. */
  33572. getBandWidth: function () {
  33573. var axisExtent = this._extent;
  33574. var dataExtent = this.scale.getExtent();
  33575. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  33576. // Fix #2728, avoid NaN when only one data.
  33577. len === 0 && (len = 1);
  33578. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  33579. return Math.abs(size) / len;
  33580. },
  33581. /**
  33582. * @abstract
  33583. * @return {boolean} Is horizontal
  33584. */
  33585. isHorizontal: null,
  33586. /**
  33587. * @abstract
  33588. * @return {number} Get axis rotate, by degree.
  33589. */
  33590. getRotate: null,
  33591. /**
  33592. * Only be called in category axis.
  33593. * Can be overrided, consider other axes like in 3D.
  33594. * @return {number} Auto interval for cateogry axis tick and label
  33595. */
  33596. calculateCategoryInterval: function () {
  33597. return calculateCategoryInterval(this);
  33598. }
  33599. };
  33600. function fixExtentWithBands(extent, nTick) {
  33601. var size = extent[1] - extent[0];
  33602. var len = nTick;
  33603. var margin = size / len / 2;
  33604. extent[0] += margin;
  33605. extent[1] -= margin;
  33606. }
  33607. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  33608. // |---1---|---2---|---3---|---4---|.
  33609. // So the displayed ticks and splitLine/splitArea should between
  33610. // each data item, otherwise cause misleading (e.g., split tow bars
  33611. // of a single data item when there are two bar series).
  33612. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  33613. // splitLine/spliteArea should layout appropriately corresponding
  33614. // to displayed labels. (So we should not use `getBandWidth` in this
  33615. // case).
  33616. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  33617. var ticksLen = ticksCoords.length;
  33618. if (!axis.onBand || alignWithLabel || !ticksLen) {
  33619. return;
  33620. }
  33621. var axisExtent = axis.getExtent();
  33622. var last;
  33623. var diffSize;
  33624. if (ticksLen === 1) {
  33625. ticksCoords[0].coord = axisExtent[0];
  33626. last = ticksCoords[1] = {coord: axisExtent[0]};
  33627. }
  33628. else {
  33629. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  33630. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  33631. each$1(ticksCoords, function (ticksItem) {
  33632. ticksItem.coord -= shift / 2;
  33633. });
  33634. var dataExtent = axis.scale.getExtent();
  33635. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  33636. last = {coord: ticksCoords[ticksLen - 1].coord + shift * diffSize};
  33637. ticksCoords.push(last);
  33638. }
  33639. var inverse = axisExtent[0] > axisExtent[1];
  33640. // Handling clamp.
  33641. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  33642. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  33643. }
  33644. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  33645. ticksCoords.unshift({coord: axisExtent[0]});
  33646. }
  33647. if (littleThan(axisExtent[1], last.coord)) {
  33648. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  33649. }
  33650. if (clamp && littleThan(last.coord, axisExtent[1])) {
  33651. ticksCoords.push({coord: axisExtent[1]});
  33652. }
  33653. function littleThan(a, b) {
  33654. // Avoid rounding error cause calculated tick coord different with extent.
  33655. // It may cause an extra unecessary tick added.
  33656. a = round$1(a);
  33657. b = round$1(b);
  33658. return inverse ? a > b : a < b;
  33659. }
  33660. }
  33661. /*
  33662. * Licensed to the Apache Software Foundation (ASF) under one
  33663. * or more contributor license agreements. See the NOTICE file
  33664. * distributed with this work for additional information
  33665. * regarding copyright ownership. The ASF licenses this file
  33666. * to you under the Apache License, Version 2.0 (the
  33667. * "License"); you may not use this file except in compliance
  33668. * with the License. You may obtain a copy of the License at
  33669. *
  33670. * http://www.apache.org/licenses/LICENSE-2.0
  33671. *
  33672. * Unless required by applicable law or agreed to in writing,
  33673. * software distributed under the License is distributed on an
  33674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33675. * KIND, either express or implied. See the License for the
  33676. * specific language governing permissions and limitations
  33677. * under the License.
  33678. */
  33679. /**
  33680. * Extend axis 2d
  33681. * @constructor module:echarts/coord/cartesian/Axis2D
  33682. * @extends {module:echarts/coord/cartesian/Axis}
  33683. * @param {string} dim
  33684. * @param {*} scale
  33685. * @param {Array.<number>} coordExtent
  33686. * @param {string} axisType
  33687. * @param {string} position
  33688. */
  33689. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  33690. Axis.call(this, dim, scale, coordExtent);
  33691. /**
  33692. * Axis type
  33693. * - 'category'
  33694. * - 'value'
  33695. * - 'time'
  33696. * - 'log'
  33697. * @type {string}
  33698. */
  33699. this.type = axisType || 'value';
  33700. /**
  33701. * Axis position
  33702. * - 'top'
  33703. * - 'bottom'
  33704. * - 'left'
  33705. * - 'right'
  33706. */
  33707. this.position = position || 'bottom';
  33708. };
  33709. Axis2D.prototype = {
  33710. constructor: Axis2D,
  33711. /**
  33712. * Index of axis, can be used as key
  33713. */
  33714. index: 0,
  33715. /**
  33716. * Implemented in <module:echarts/coord/cartesian/Grid>.
  33717. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  33718. * If not on zero of other axis, return null/undefined.
  33719. * If no axes, return an empty array.
  33720. */
  33721. getAxesOnZeroOf: null,
  33722. /**
  33723. * Axis model
  33724. * @param {module:echarts/coord/cartesian/AxisModel}
  33725. */
  33726. model: null,
  33727. isHorizontal: function () {
  33728. var position = this.position;
  33729. return position === 'top' || position === 'bottom';
  33730. },
  33731. /**
  33732. * Each item cooresponds to this.getExtent(), which
  33733. * means globalExtent[0] may greater than globalExtent[1],
  33734. * unless `asc` is input.
  33735. *
  33736. * @param {boolean} [asc]
  33737. * @return {Array.<number>}
  33738. */
  33739. getGlobalExtent: function (asc) {
  33740. var ret = this.getExtent();
  33741. ret[0] = this.toGlobalCoord(ret[0]);
  33742. ret[1] = this.toGlobalCoord(ret[1]);
  33743. asc && ret[0] > ret[1] && ret.reverse();
  33744. return ret;
  33745. },
  33746. getOtherAxis: function () {
  33747. this.grid.getOtherAxis();
  33748. },
  33749. /**
  33750. * @override
  33751. */
  33752. pointToData: function (point, clamp) {
  33753. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  33754. },
  33755. /**
  33756. * Transform global coord to local coord,
  33757. * i.e. var localCoord = axis.toLocalCoord(80);
  33758. * designate by module:echarts/coord/cartesian/Grid.
  33759. * @type {Function}
  33760. */
  33761. toLocalCoord: null,
  33762. /**
  33763. * Transform global coord to local coord,
  33764. * i.e. var globalCoord = axis.toLocalCoord(40);
  33765. * designate by module:echarts/coord/cartesian/Grid.
  33766. * @type {Function}
  33767. */
  33768. toGlobalCoord: null
  33769. };
  33770. inherits(Axis2D, Axis);
  33771. /*
  33772. * Licensed to the Apache Software Foundation (ASF) under one
  33773. * or more contributor license agreements. See the NOTICE file
  33774. * distributed with this work for additional information
  33775. * regarding copyright ownership. The ASF licenses this file
  33776. * to you under the Apache License, Version 2.0 (the
  33777. * "License"); you may not use this file except in compliance
  33778. * with the License. You may obtain a copy of the License at
  33779. *
  33780. * http://www.apache.org/licenses/LICENSE-2.0
  33781. *
  33782. * Unless required by applicable law or agreed to in writing,
  33783. * software distributed under the License is distributed on an
  33784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33785. * KIND, either express or implied. See the License for the
  33786. * specific language governing permissions and limitations
  33787. * under the License.
  33788. */
  33789. var defaultOption = {
  33790. show: true,
  33791. zlevel: 0,
  33792. z: 0,
  33793. // Inverse the axis.
  33794. inverse: false,
  33795. // Axis name displayed.
  33796. name: '',
  33797. // 'start' | 'middle' | 'end'
  33798. nameLocation: 'end',
  33799. // By degree. By defualt auto rotate by nameLocation.
  33800. nameRotate: null,
  33801. nameTruncate: {
  33802. maxWidth: null,
  33803. ellipsis: '...',
  33804. placeholder: '.'
  33805. },
  33806. // Use global text style by default.
  33807. nameTextStyle: {},
  33808. // The gap between axisName and axisLine.
  33809. nameGap: 15,
  33810. // Default `false` to support tooltip.
  33811. silent: false,
  33812. // Default `false` to avoid legacy user event listener fail.
  33813. triggerEvent: false,
  33814. tooltip: {
  33815. show: false
  33816. },
  33817. axisPointer: {},
  33818. axisLine: {
  33819. show: true,
  33820. onZero: true,
  33821. onZeroAxisIndex: null,
  33822. lineStyle: {
  33823. color: '#333',
  33824. width: 1,
  33825. type: 'solid'
  33826. },
  33827. // The arrow at both ends the the axis.
  33828. symbol: ['none', 'none'],
  33829. symbolSize: [10, 15]
  33830. },
  33831. axisTick: {
  33832. show: true,
  33833. // Whether axisTick is inside the grid or outside the grid.
  33834. inside: false,
  33835. // The length of axisTick.
  33836. length: 5,
  33837. lineStyle: {
  33838. width: 1
  33839. }
  33840. },
  33841. axisLabel: {
  33842. show: true,
  33843. // Whether axisLabel is inside the grid or outside the grid.
  33844. inside: false,
  33845. rotate: 0,
  33846. // true | false | null/undefined (auto)
  33847. showMinLabel: null,
  33848. // true | false | null/undefined (auto)
  33849. showMaxLabel: null,
  33850. margin: 8,
  33851. // formatter: null,
  33852. fontSize: 12
  33853. },
  33854. splitLine: {
  33855. show: true,
  33856. lineStyle: {
  33857. color: ['#ccc'],
  33858. width: 1,
  33859. type: 'solid'
  33860. }
  33861. },
  33862. splitArea: {
  33863. show: false,
  33864. areaStyle: {
  33865. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  33866. }
  33867. }
  33868. };
  33869. var axisDefault = {};
  33870. axisDefault.categoryAxis = merge({
  33871. // The gap at both ends of the axis. For categoryAxis, boolean.
  33872. boundaryGap: true,
  33873. // Set false to faster category collection.
  33874. // Only usefull in the case like: category is
  33875. // ['2012-01-01', '2012-01-02', ...], where the input
  33876. // data has been ensured not duplicate and is large data.
  33877. // null means "auto":
  33878. // if axis.data provided, do not deduplication,
  33879. // else do deduplication.
  33880. deduplication: null,
  33881. // splitArea: {
  33882. // show: false
  33883. // },
  33884. splitLine: {
  33885. show: false
  33886. },
  33887. axisTick: {
  33888. // If tick is align with label when boundaryGap is true
  33889. alignWithLabel: false,
  33890. interval: 'auto'
  33891. },
  33892. axisLabel: {
  33893. interval: 'auto'
  33894. }
  33895. }, defaultOption);
  33896. axisDefault.valueAxis = merge({
  33897. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  33898. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  33899. boundaryGap: [0, 0],
  33900. // TODO
  33901. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  33902. // Min value of the axis. can be:
  33903. // + a number
  33904. // + 'dataMin': use the min value in data.
  33905. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  33906. // min: null,
  33907. // Max value of the axis. can be:
  33908. // + a number
  33909. // + 'dataMax': use the max value in data.
  33910. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  33911. // max: null,
  33912. // Readonly prop, specifies start value of the range when using data zoom.
  33913. // rangeStart: null
  33914. // Readonly prop, specifies end value of the range when using data zoom.
  33915. // rangeEnd: null
  33916. // Optional value can be:
  33917. // + `false`: always include value 0.
  33918. // + `true`: the extent do not consider value 0.
  33919. // scale: false,
  33920. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  33921. splitNumber: 5,
  33922. // Interval specifies the span of the ticks is mandatorily.
  33923. // interval: null
  33924. // Specify min interval when auto calculate tick interval.
  33925. // minInterval: null
  33926. // Specify max interval when auto calculate tick interval.
  33927. // maxInterval: null
  33928. minorTick: {
  33929. // Minor tick, not available for cateogry axis.
  33930. show: false,
  33931. // Split number of minor ticks. The value should be in range of (0, 100)
  33932. splitNumber: 5,
  33933. // Lenght of minor tick
  33934. length: 3,
  33935. // Same inside with axisTick
  33936. // Line style
  33937. lineStyle: {
  33938. // Default to be same with axisTick
  33939. }
  33940. },
  33941. minorSplitLine: {
  33942. show: false,
  33943. lineStyle: {
  33944. color: '#eee',
  33945. width: 1
  33946. }
  33947. }
  33948. }, defaultOption);
  33949. axisDefault.timeAxis = defaults({
  33950. scale: true,
  33951. min: 'dataMin',
  33952. max: 'dataMax'
  33953. }, axisDefault.valueAxis);
  33954. axisDefault.logAxis = defaults({
  33955. scale: true,
  33956. logBase: 10
  33957. }, axisDefault.valueAxis);
  33958. /*
  33959. * Licensed to the Apache Software Foundation (ASF) under one
  33960. * or more contributor license agreements. See the NOTICE file
  33961. * distributed with this work for additional information
  33962. * regarding copyright ownership. The ASF licenses this file
  33963. * to you under the Apache License, Version 2.0 (the
  33964. * "License"); you may not use this file except in compliance
  33965. * with the License. You may obtain a copy of the License at
  33966. *
  33967. * http://www.apache.org/licenses/LICENSE-2.0
  33968. *
  33969. * Unless required by applicable law or agreed to in writing,
  33970. * software distributed under the License is distributed on an
  33971. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33972. * KIND, either express or implied. See the License for the
  33973. * specific language governing permissions and limitations
  33974. * under the License.
  33975. */
  33976. // FIXME axisType is fixed ?
  33977. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  33978. /**
  33979. * Generate sub axis model class
  33980. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  33981. * @param {module:echarts/model/Component} BaseAxisModelClass
  33982. * @param {Function} axisTypeDefaulter
  33983. * @param {Object} [extraDefaultOption]
  33984. */
  33985. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  33986. each$1(AXIS_TYPES, function (axisType) {
  33987. BaseAxisModelClass.extend({
  33988. /**
  33989. * @readOnly
  33990. */
  33991. type: axisName + 'Axis.' + axisType,
  33992. mergeDefaultAndTheme: function (option, ecModel) {
  33993. var layoutMode = this.layoutMode;
  33994. var inputPositionParams = layoutMode
  33995. ? getLayoutParams(option) : {};
  33996. var themeModel = ecModel.getTheme();
  33997. merge(option, themeModel.get(axisType + 'Axis'));
  33998. merge(option, this.getDefaultOption());
  33999. option.type = axisTypeDefaulter(axisName, option);
  34000. if (layoutMode) {
  34001. mergeLayoutParam(option, inputPositionParams, layoutMode);
  34002. }
  34003. },
  34004. /**
  34005. * @override
  34006. */
  34007. optionUpdated: function () {
  34008. var thisOption = this.option;
  34009. if (thisOption.type === 'category') {
  34010. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  34011. }
  34012. },
  34013. /**
  34014. * Should not be called before all of 'getInitailData' finished.
  34015. * Because categories are collected during initializing data.
  34016. */
  34017. getCategories: function (rawData) {
  34018. var option = this.option;
  34019. // FIXME
  34020. // warning if called before all of 'getInitailData' finished.
  34021. if (option.type === 'category') {
  34022. if (rawData) {
  34023. return option.data;
  34024. }
  34025. return this.__ordinalMeta.categories;
  34026. }
  34027. },
  34028. getOrdinalMeta: function () {
  34029. return this.__ordinalMeta;
  34030. },
  34031. defaultOption: mergeAll(
  34032. [
  34033. {},
  34034. axisDefault[axisType + 'Axis'],
  34035. extraDefaultOption
  34036. ],
  34037. true
  34038. )
  34039. });
  34040. });
  34041. ComponentModel.registerSubTypeDefaulter(
  34042. axisName + 'Axis',
  34043. curry(axisTypeDefaulter, axisName)
  34044. );
  34045. };
  34046. /*
  34047. * Licensed to the Apache Software Foundation (ASF) under one
  34048. * or more contributor license agreements. See the NOTICE file
  34049. * distributed with this work for additional information
  34050. * regarding copyright ownership. The ASF licenses this file
  34051. * to you under the Apache License, Version 2.0 (the
  34052. * "License"); you may not use this file except in compliance
  34053. * with the License. You may obtain a copy of the License at
  34054. *
  34055. * http://www.apache.org/licenses/LICENSE-2.0
  34056. *
  34057. * Unless required by applicable law or agreed to in writing,
  34058. * software distributed under the License is distributed on an
  34059. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34060. * KIND, either express or implied. See the License for the
  34061. * specific language governing permissions and limitations
  34062. * under the License.
  34063. */
  34064. // import * as axisHelper from './axisHelper';
  34065. var axisModelCommonMixin = {
  34066. /**
  34067. * @param {boolean} origin
  34068. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  34069. */
  34070. getMin: function (origin) {
  34071. var option = this.option;
  34072. var min = (!origin && option.rangeStart != null)
  34073. ? option.rangeStart : option.min;
  34074. if (this.axis
  34075. && min != null
  34076. && min !== 'dataMin'
  34077. && typeof min !== 'function'
  34078. && !eqNaN(min)
  34079. ) {
  34080. min = this.axis.scale.parse(min);
  34081. }
  34082. return min;
  34083. },
  34084. /**
  34085. * @param {boolean} origin
  34086. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  34087. */
  34088. getMax: function (origin) {
  34089. var option = this.option;
  34090. var max = (!origin && option.rangeEnd != null)
  34091. ? option.rangeEnd : option.max;
  34092. if (this.axis
  34093. && max != null
  34094. && max !== 'dataMax'
  34095. && typeof max !== 'function'
  34096. && !eqNaN(max)
  34097. ) {
  34098. max = this.axis.scale.parse(max);
  34099. }
  34100. return max;
  34101. },
  34102. /**
  34103. * @return {boolean}
  34104. */
  34105. getNeedCrossZero: function () {
  34106. var option = this.option;
  34107. return (option.rangeStart != null || option.rangeEnd != null)
  34108. ? false : !option.scale;
  34109. },
  34110. /**
  34111. * Should be implemented by each axis model if necessary.
  34112. * @return {module:echarts/model/Component} coordinate system model
  34113. */
  34114. getCoordSysModel: noop,
  34115. /**
  34116. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  34117. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  34118. */
  34119. setRange: function (rangeStart, rangeEnd) {
  34120. this.option.rangeStart = rangeStart;
  34121. this.option.rangeEnd = rangeEnd;
  34122. },
  34123. /**
  34124. * Reset range
  34125. */
  34126. resetRange: function () {
  34127. // rangeStart and rangeEnd is readonly.
  34128. this.option.rangeStart = this.option.rangeEnd = null;
  34129. }
  34130. };
  34131. /*
  34132. * Licensed to the Apache Software Foundation (ASF) under one
  34133. * or more contributor license agreements. See the NOTICE file
  34134. * distributed with this work for additional information
  34135. * regarding copyright ownership. The ASF licenses this file
  34136. * to you under the Apache License, Version 2.0 (the
  34137. * "License"); you may not use this file except in compliance
  34138. * with the License. You may obtain a copy of the License at
  34139. *
  34140. * http://www.apache.org/licenses/LICENSE-2.0
  34141. *
  34142. * Unless required by applicable law or agreed to in writing,
  34143. * software distributed under the License is distributed on an
  34144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34145. * KIND, either express or implied. See the License for the
  34146. * specific language governing permissions and limitations
  34147. * under the License.
  34148. */
  34149. var AxisModel = ComponentModel.extend({
  34150. type: 'cartesian2dAxis',
  34151. /**
  34152. * @type {module:echarts/coord/cartesian/Axis2D}
  34153. */
  34154. axis: null,
  34155. /**
  34156. * @override
  34157. */
  34158. init: function () {
  34159. AxisModel.superApply(this, 'init', arguments);
  34160. this.resetRange();
  34161. },
  34162. /**
  34163. * @override
  34164. */
  34165. mergeOption: function () {
  34166. AxisModel.superApply(this, 'mergeOption', arguments);
  34167. this.resetRange();
  34168. },
  34169. /**
  34170. * @override
  34171. */
  34172. restoreData: function () {
  34173. AxisModel.superApply(this, 'restoreData', arguments);
  34174. this.resetRange();
  34175. },
  34176. /**
  34177. * @override
  34178. * @return {module:echarts/model/Component}
  34179. */
  34180. getCoordSysModel: function () {
  34181. return this.ecModel.queryComponents({
  34182. mainType: 'grid',
  34183. index: this.option.gridIndex,
  34184. id: this.option.gridId
  34185. })[0];
  34186. }
  34187. });
  34188. function getAxisType(axisDim, option) {
  34189. // Default axis with data is category axis
  34190. return option.type || (option.data ? 'category' : 'value');
  34191. }
  34192. merge(AxisModel.prototype, axisModelCommonMixin);
  34193. var extraOption = {
  34194. // gridIndex: 0,
  34195. // gridId: '',
  34196. // Offset is for multiple axis on the same position
  34197. offset: 0
  34198. };
  34199. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  34200. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  34201. /*
  34202. * Licensed to the Apache Software Foundation (ASF) under one
  34203. * or more contributor license agreements. See the NOTICE file
  34204. * distributed with this work for additional information
  34205. * regarding copyright ownership. The ASF licenses this file
  34206. * to you under the Apache License, Version 2.0 (the
  34207. * "License"); you may not use this file except in compliance
  34208. * with the License. You may obtain a copy of the License at
  34209. *
  34210. * http://www.apache.org/licenses/LICENSE-2.0
  34211. *
  34212. * Unless required by applicable law or agreed to in writing,
  34213. * software distributed under the License is distributed on an
  34214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34215. * KIND, either express or implied. See the License for the
  34216. * specific language governing permissions and limitations
  34217. * under the License.
  34218. */
  34219. // Grid 是在有直角坐标系的时候必须要存在的
  34220. // 所以这里也要被 Cartesian2D 依赖
  34221. ComponentModel.extend({
  34222. type: 'grid',
  34223. dependencies: ['xAxis', 'yAxis'],
  34224. layoutMode: 'box',
  34225. /**
  34226. * @type {module:echarts/coord/cartesian/Grid}
  34227. */
  34228. coordinateSystem: null,
  34229. defaultOption: {
  34230. show: false,
  34231. zlevel: 0,
  34232. z: 0,
  34233. left: '10%',
  34234. top: 60,
  34235. right: '10%',
  34236. bottom: 60,
  34237. // If grid size contain label
  34238. containLabel: false,
  34239. // width: {totalWidth} - left - right,
  34240. // height: {totalHeight} - top - bottom,
  34241. backgroundColor: 'rgba(0,0,0,0)',
  34242. borderWidth: 1,
  34243. borderColor: '#ccc'
  34244. }
  34245. });
  34246. /*
  34247. * Licensed to the Apache Software Foundation (ASF) under one
  34248. * or more contributor license agreements. See the NOTICE file
  34249. * distributed with this work for additional information
  34250. * regarding copyright ownership. The ASF licenses this file
  34251. * to you under the Apache License, Version 2.0 (the
  34252. * "License"); you may not use this file except in compliance
  34253. * with the License. You may obtain a copy of the License at
  34254. *
  34255. * http://www.apache.org/licenses/LICENSE-2.0
  34256. *
  34257. * Unless required by applicable law or agreed to in writing,
  34258. * software distributed under the License is distributed on an
  34259. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34260. * KIND, either express or implied. See the License for the
  34261. * specific language governing permissions and limitations
  34262. * under the License.
  34263. */
  34264. /**
  34265. * Grid is a region which contains at most 4 cartesian systems
  34266. *
  34267. * TODO Default cartesian
  34268. */
  34269. // Depends on GridModel, AxisModel, which performs preprocess.
  34270. /**
  34271. * Check if the axis is used in the specified grid
  34272. * @inner
  34273. */
  34274. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  34275. return axisModel.getCoordSysModel() === gridModel;
  34276. }
  34277. function Grid(gridModel, ecModel, api) {
  34278. /**
  34279. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  34280. * @private
  34281. */
  34282. this._coordsMap = {};
  34283. /**
  34284. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  34285. * @private
  34286. */
  34287. this._coordsList = [];
  34288. /**
  34289. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  34290. * @private
  34291. */
  34292. this._axesMap = {};
  34293. /**
  34294. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  34295. * @private
  34296. */
  34297. this._axesList = [];
  34298. this._initCartesian(gridModel, ecModel, api);
  34299. this.model = gridModel;
  34300. }
  34301. var gridProto = Grid.prototype;
  34302. gridProto.type = 'grid';
  34303. gridProto.axisPointerEnabled = true;
  34304. gridProto.getRect = function () {
  34305. return this._rect;
  34306. };
  34307. gridProto.update = function (ecModel, api) {
  34308. var axesMap = this._axesMap;
  34309. this._updateScale(ecModel, this.model);
  34310. each$1(axesMap.x, function (xAxis) {
  34311. niceScaleExtent(xAxis.scale, xAxis.model);
  34312. });
  34313. each$1(axesMap.y, function (yAxis) {
  34314. niceScaleExtent(yAxis.scale, yAxis.model);
  34315. });
  34316. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  34317. var onZeroRecords = {};
  34318. each$1(axesMap.x, function (xAxis) {
  34319. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  34320. });
  34321. each$1(axesMap.y, function (yAxis) {
  34322. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  34323. });
  34324. // Resize again if containLabel is enabled
  34325. // FIXME It may cause getting wrong grid size in data processing stage
  34326. this.resize(this.model, api);
  34327. };
  34328. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  34329. axis.getAxesOnZeroOf = function () {
  34330. // TODO: onZero of multiple axes.
  34331. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  34332. };
  34333. // onZero can not be enabled in these two situations:
  34334. // 1. When any other axis is a category axis.
  34335. // 2. When no axis is cross 0 point.
  34336. var otherAxes = axesMap[otherAxisDim];
  34337. var otherAxisOnZeroOf;
  34338. var axisModel = axis.model;
  34339. var onZero = axisModel.get('axisLine.onZero');
  34340. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  34341. if (!onZero) {
  34342. return;
  34343. }
  34344. // If target axis is specified.
  34345. if (onZeroAxisIndex != null) {
  34346. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  34347. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  34348. }
  34349. }
  34350. else {
  34351. // Find the first available other axis.
  34352. for (var idx in otherAxes) {
  34353. if (otherAxes.hasOwnProperty(idx)
  34354. && canOnZeroToAxis(otherAxes[idx])
  34355. // Consider that two Y axes on one value axis,
  34356. // if both onZero, the two Y axes overlap.
  34357. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  34358. ) {
  34359. otherAxisOnZeroOf = otherAxes[idx];
  34360. break;
  34361. }
  34362. }
  34363. }
  34364. if (otherAxisOnZeroOf) {
  34365. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  34366. }
  34367. function getOnZeroRecordKey(axis) {
  34368. return axis.dim + '_' + axis.index;
  34369. }
  34370. }
  34371. function canOnZeroToAxis(axis) {
  34372. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  34373. }
  34374. /**
  34375. * Resize the grid
  34376. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34377. * @param {module:echarts/ExtensionAPI} api
  34378. */
  34379. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  34380. var gridRect = getLayoutRect(
  34381. gridModel.getBoxLayoutParams(), {
  34382. width: api.getWidth(),
  34383. height: api.getHeight()
  34384. });
  34385. this._rect = gridRect;
  34386. var axesList = this._axesList;
  34387. adjustAxes();
  34388. // Minus label size
  34389. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  34390. each$1(axesList, function (axis) {
  34391. if (!axis.model.get('axisLabel.inside')) {
  34392. var labelUnionRect = estimateLabelUnionRect(axis);
  34393. if (labelUnionRect) {
  34394. var dim = axis.isHorizontal() ? 'height' : 'width';
  34395. var margin = axis.model.get('axisLabel.margin');
  34396. gridRect[dim] -= labelUnionRect[dim] + margin;
  34397. if (axis.position === 'top') {
  34398. gridRect.y += labelUnionRect.height + margin;
  34399. }
  34400. else if (axis.position === 'left') {
  34401. gridRect.x += labelUnionRect.width + margin;
  34402. }
  34403. }
  34404. }
  34405. });
  34406. adjustAxes();
  34407. }
  34408. function adjustAxes() {
  34409. each$1(axesList, function (axis) {
  34410. var isHorizontal = axis.isHorizontal();
  34411. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  34412. var idx = axis.inverse ? 1 : 0;
  34413. axis.setExtent(extent[idx], extent[1 - idx]);
  34414. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  34415. });
  34416. }
  34417. };
  34418. /**
  34419. * @param {string} axisType
  34420. * @param {number} [axisIndex]
  34421. */
  34422. gridProto.getAxis = function (axisType, axisIndex) {
  34423. var axesMapOnDim = this._axesMap[axisType];
  34424. if (axesMapOnDim != null) {
  34425. if (axisIndex == null) {
  34426. // Find first axis
  34427. for (var name in axesMapOnDim) {
  34428. if (axesMapOnDim.hasOwnProperty(name)) {
  34429. return axesMapOnDim[name];
  34430. }
  34431. }
  34432. }
  34433. return axesMapOnDim[axisIndex];
  34434. }
  34435. };
  34436. /**
  34437. * @return {Array.<module:echarts/coord/Axis>}
  34438. */
  34439. gridProto.getAxes = function () {
  34440. return this._axesList.slice();
  34441. };
  34442. /**
  34443. * Usage:
  34444. * grid.getCartesian(xAxisIndex, yAxisIndex);
  34445. * grid.getCartesian(xAxisIndex);
  34446. * grid.getCartesian(null, yAxisIndex);
  34447. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  34448. *
  34449. * @param {number|Object} [xAxisIndex]
  34450. * @param {number} [yAxisIndex]
  34451. */
  34452. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  34453. if (xAxisIndex != null && yAxisIndex != null) {
  34454. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34455. return this._coordsMap[key];
  34456. }
  34457. if (isObject$1(xAxisIndex)) {
  34458. yAxisIndex = xAxisIndex.yAxisIndex;
  34459. xAxisIndex = xAxisIndex.xAxisIndex;
  34460. }
  34461. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  34462. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  34463. if (coordList[i].getAxis('x').index === xAxisIndex
  34464. || coordList[i].getAxis('y').index === yAxisIndex
  34465. ) {
  34466. return coordList[i];
  34467. }
  34468. }
  34469. };
  34470. gridProto.getCartesians = function () {
  34471. return this._coordsList.slice();
  34472. };
  34473. /**
  34474. * @implements
  34475. * see {module:echarts/CoodinateSystem}
  34476. */
  34477. gridProto.convertToPixel = function (ecModel, finder, value) {
  34478. var target = this._findConvertTarget(ecModel, finder);
  34479. return target.cartesian
  34480. ? target.cartesian.dataToPoint(value)
  34481. : target.axis
  34482. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  34483. : null;
  34484. };
  34485. /**
  34486. * @implements
  34487. * see {module:echarts/CoodinateSystem}
  34488. */
  34489. gridProto.convertFromPixel = function (ecModel, finder, value) {
  34490. var target = this._findConvertTarget(ecModel, finder);
  34491. return target.cartesian
  34492. ? target.cartesian.pointToData(value)
  34493. : target.axis
  34494. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  34495. : null;
  34496. };
  34497. /**
  34498. * @inner
  34499. */
  34500. gridProto._findConvertTarget = function (ecModel, finder) {
  34501. var seriesModel = finder.seriesModel;
  34502. var xAxisModel = finder.xAxisModel
  34503. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  34504. var yAxisModel = finder.yAxisModel
  34505. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  34506. var gridModel = finder.gridModel;
  34507. var coordsList = this._coordsList;
  34508. var cartesian;
  34509. var axis;
  34510. if (seriesModel) {
  34511. cartesian = seriesModel.coordinateSystem;
  34512. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  34513. }
  34514. else if (xAxisModel && yAxisModel) {
  34515. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  34516. }
  34517. else if (xAxisModel) {
  34518. axis = this.getAxis('x', xAxisModel.componentIndex);
  34519. }
  34520. else if (yAxisModel) {
  34521. axis = this.getAxis('y', yAxisModel.componentIndex);
  34522. }
  34523. // Lowest priority.
  34524. else if (gridModel) {
  34525. var grid = gridModel.coordinateSystem;
  34526. if (grid === this) {
  34527. cartesian = this._coordsList[0];
  34528. }
  34529. }
  34530. return {cartesian: cartesian, axis: axis};
  34531. };
  34532. /**
  34533. * @implements
  34534. * see {module:echarts/CoodinateSystem}
  34535. */
  34536. gridProto.containPoint = function (point) {
  34537. var coord = this._coordsList[0];
  34538. if (coord) {
  34539. return coord.containPoint(point);
  34540. }
  34541. };
  34542. /**
  34543. * Initialize cartesian coordinate systems
  34544. * @private
  34545. */
  34546. gridProto._initCartesian = function (gridModel, ecModel, api) {
  34547. var axisPositionUsed = {
  34548. left: false,
  34549. right: false,
  34550. top: false,
  34551. bottom: false
  34552. };
  34553. var axesMap = {
  34554. x: {},
  34555. y: {}
  34556. };
  34557. var axesCount = {
  34558. x: 0,
  34559. y: 0
  34560. };
  34561. /// Create axis
  34562. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  34563. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  34564. if (!axesCount.x || !axesCount.y) {
  34565. // Roll back when there no either x or y axis
  34566. this._axesMap = {};
  34567. this._axesList = [];
  34568. return;
  34569. }
  34570. this._axesMap = axesMap;
  34571. /// Create cartesian2d
  34572. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  34573. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  34574. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  34575. var cartesian = new Cartesian2D(key);
  34576. cartesian.grid = this;
  34577. cartesian.model = gridModel;
  34578. this._coordsMap[key] = cartesian;
  34579. this._coordsList.push(cartesian);
  34580. cartesian.addAxis(xAxis);
  34581. cartesian.addAxis(yAxis);
  34582. }, this);
  34583. }, this);
  34584. function createAxisCreator(axisType) {
  34585. return function (axisModel, idx) {
  34586. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  34587. return;
  34588. }
  34589. var axisPosition = axisModel.get('position');
  34590. if (axisType === 'x') {
  34591. // Fix position
  34592. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  34593. // Default bottom of X
  34594. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  34595. }
  34596. }
  34597. else {
  34598. // Fix position
  34599. if (axisPosition !== 'left' && axisPosition !== 'right') {
  34600. // Default left of Y
  34601. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  34602. }
  34603. }
  34604. axisPositionUsed[axisPosition] = true;
  34605. var axis = new Axis2D(
  34606. axisType, createScaleByModel(axisModel),
  34607. [0, 0],
  34608. axisModel.get('type'),
  34609. axisPosition
  34610. );
  34611. var isCategory = axis.type === 'category';
  34612. axis.onBand = isCategory && axisModel.get('boundaryGap');
  34613. axis.inverse = axisModel.get('inverse');
  34614. // Inject axis into axisModel
  34615. axisModel.axis = axis;
  34616. // Inject axisModel into axis
  34617. axis.model = axisModel;
  34618. // Inject grid info axis
  34619. axis.grid = this;
  34620. // Index of axis, can be used as key
  34621. axis.index = idx;
  34622. this._axesList.push(axis);
  34623. axesMap[axisType][idx] = axis;
  34624. axesCount[axisType]++;
  34625. };
  34626. }
  34627. };
  34628. /**
  34629. * Update cartesian properties from series
  34630. * @param {module:echarts/model/Option} option
  34631. * @private
  34632. */
  34633. gridProto._updateScale = function (ecModel, gridModel) {
  34634. // Reset scale
  34635. each$1(this._axesList, function (axis) {
  34636. axis.scale.setExtent(Infinity, -Infinity);
  34637. });
  34638. ecModel.eachSeries(function (seriesModel) {
  34639. if (isCartesian2D(seriesModel)) {
  34640. var axesModels = findAxesModels(seriesModel, ecModel);
  34641. var xAxisModel = axesModels[0];
  34642. var yAxisModel = axesModels[1];
  34643. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  34644. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  34645. ) {
  34646. return;
  34647. }
  34648. var cartesian = this.getCartesian(
  34649. xAxisModel.componentIndex, yAxisModel.componentIndex
  34650. );
  34651. var data = seriesModel.getData();
  34652. var xAxis = cartesian.getAxis('x');
  34653. var yAxis = cartesian.getAxis('y');
  34654. if (data.type === 'list') {
  34655. unionExtent(data, xAxis, seriesModel);
  34656. unionExtent(data, yAxis, seriesModel);
  34657. }
  34658. }
  34659. }, this);
  34660. function unionExtent(data, axis, seriesModel) {
  34661. each$1(data.mapDimension(axis.dim, true), function (dim) {
  34662. axis.scale.unionExtentFromData(
  34663. // For example, the extent of the orginal dimension
  34664. // is [0.1, 0.5], the extent of the `stackResultDimension`
  34665. // is [7, 9], the final extent should not include [0.1, 0.5].
  34666. data, getStackedDimension(data, dim)
  34667. );
  34668. });
  34669. }
  34670. };
  34671. /**
  34672. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  34673. * @return {Object} {baseAxes: [], otherAxes: []}
  34674. */
  34675. gridProto.getTooltipAxes = function (dim) {
  34676. var baseAxes = [];
  34677. var otherAxes = [];
  34678. each$1(this.getCartesians(), function (cartesian) {
  34679. var baseAxis = (dim != null && dim !== 'auto')
  34680. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  34681. var otherAxis = cartesian.getOtherAxis(baseAxis);
  34682. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  34683. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  34684. });
  34685. return {baseAxes: baseAxes, otherAxes: otherAxes};
  34686. };
  34687. /**
  34688. * @inner
  34689. */
  34690. function updateAxisTransform(axis, coordBase) {
  34691. var axisExtent = axis.getExtent();
  34692. var axisExtentSum = axisExtent[0] + axisExtent[1];
  34693. // Fast transform
  34694. axis.toGlobalCoord = axis.dim === 'x'
  34695. ? function (coord) {
  34696. return coord + coordBase;
  34697. }
  34698. : function (coord) {
  34699. return axisExtentSum - coord + coordBase;
  34700. };
  34701. axis.toLocalCoord = axis.dim === 'x'
  34702. ? function (coord) {
  34703. return coord - coordBase;
  34704. }
  34705. : function (coord) {
  34706. return axisExtentSum - coord + coordBase;
  34707. };
  34708. }
  34709. var axesTypes = ['xAxis', 'yAxis'];
  34710. /**
  34711. * @inner
  34712. */
  34713. function findAxesModels(seriesModel, ecModel) {
  34714. return map(axesTypes, function (axisType) {
  34715. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  34716. if (__DEV__) {
  34717. if (!axisModel) {
  34718. throw new Error(axisType + ' "' + retrieve(
  34719. seriesModel.get(axisType + 'Index'),
  34720. seriesModel.get(axisType + 'Id'),
  34721. 0
  34722. ) + '" not found');
  34723. }
  34724. }
  34725. return axisModel;
  34726. });
  34727. }
  34728. /**
  34729. * @inner
  34730. */
  34731. function isCartesian2D(seriesModel) {
  34732. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  34733. }
  34734. Grid.create = function (ecModel, api) {
  34735. var grids = [];
  34736. ecModel.eachComponent('grid', function (gridModel, idx) {
  34737. var grid = new Grid(gridModel, ecModel, api);
  34738. grid.name = 'grid_' + idx;
  34739. // dataSampling requires axis extent, so resize
  34740. // should be performed in create stage.
  34741. grid.resize(gridModel, api, true);
  34742. gridModel.coordinateSystem = grid;
  34743. grids.push(grid);
  34744. });
  34745. // Inject the coordinateSystems into seriesModel
  34746. ecModel.eachSeries(function (seriesModel) {
  34747. if (!isCartesian2D(seriesModel)) {
  34748. return;
  34749. }
  34750. var axesModels = findAxesModels(seriesModel, ecModel);
  34751. var xAxisModel = axesModels[0];
  34752. var yAxisModel = axesModels[1];
  34753. var gridModel = xAxisModel.getCoordSysModel();
  34754. if (__DEV__) {
  34755. if (!gridModel) {
  34756. throw new Error(
  34757. 'Grid "' + retrieve(
  34758. xAxisModel.get('gridIndex'),
  34759. xAxisModel.get('gridId'),
  34760. 0
  34761. ) + '" not found'
  34762. );
  34763. }
  34764. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  34765. throw new Error('xAxis and yAxis must use the same grid');
  34766. }
  34767. }
  34768. var grid = gridModel.coordinateSystem;
  34769. seriesModel.coordinateSystem = grid.getCartesian(
  34770. xAxisModel.componentIndex, yAxisModel.componentIndex
  34771. );
  34772. });
  34773. return grids;
  34774. };
  34775. // For deciding which dimensions to use when creating list data
  34776. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  34777. CoordinateSystemManager.register('cartesian2d', Grid);
  34778. /*
  34779. * Licensed to the Apache Software Foundation (ASF) under one
  34780. * or more contributor license agreements. See the NOTICE file
  34781. * distributed with this work for additional information
  34782. * regarding copyright ownership. The ASF licenses this file
  34783. * to you under the Apache License, Version 2.0 (the
  34784. * "License"); you may not use this file except in compliance
  34785. * with the License. You may obtain a copy of the License at
  34786. *
  34787. * http://www.apache.org/licenses/LICENSE-2.0
  34788. *
  34789. * Unless required by applicable law or agreed to in writing,
  34790. * software distributed under the License is distributed on an
  34791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34792. * KIND, either express or implied. See the License for the
  34793. * specific language governing permissions and limitations
  34794. * under the License.
  34795. */
  34796. var PI$2 = Math.PI;
  34797. /**
  34798. * A final axis is translated and rotated from a "standard axis".
  34799. * So opt.position and opt.rotation is required.
  34800. *
  34801. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  34802. * for example: (0, 0) ------------> (0, 50)
  34803. *
  34804. * nameDirection or tickDirection or labelDirection is 1 means tick
  34805. * or label is below the standard axis, whereas is -1 means above
  34806. * the standard axis. labelOffset means offset between label and axis,
  34807. * which is useful when 'onZero', where axisLabel is in the grid and
  34808. * label in outside grid.
  34809. *
  34810. * Tips: like always,
  34811. * positive rotation represents anticlockwise, and negative rotation
  34812. * represents clockwise.
  34813. * The direction of position coordinate is the same as the direction
  34814. * of screen coordinate.
  34815. *
  34816. * Do not need to consider axis 'inverse', which is auto processed by
  34817. * axis extent.
  34818. *
  34819. * @param {module:zrender/container/Group} group
  34820. * @param {Object} axisModel
  34821. * @param {Object} opt Standard axis parameters.
  34822. * @param {Array.<number>} opt.position [x, y]
  34823. * @param {number} opt.rotation by radian
  34824. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  34825. * @param {number} [opt.tickDirection=1] 1 or -1
  34826. * @param {number} [opt.labelDirection=1] 1 or -1
  34827. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  34828. * @param {string} [opt.axisLabelShow] default get from axisModel.
  34829. * @param {string} [opt.axisName] default get from axisModel.
  34830. * @param {number} [opt.axisNameAvailableWidth]
  34831. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  34832. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  34833. * @param {number} [opt.nameTruncateMaxWidth]
  34834. */
  34835. var AxisBuilder = function (axisModel, opt) {
  34836. /**
  34837. * @readOnly
  34838. */
  34839. this.opt = opt;
  34840. /**
  34841. * @readOnly
  34842. */
  34843. this.axisModel = axisModel;
  34844. // Default value
  34845. defaults(
  34846. opt,
  34847. {
  34848. labelOffset: 0,
  34849. nameDirection: 1,
  34850. tickDirection: 1,
  34851. labelDirection: 1,
  34852. silent: true
  34853. }
  34854. );
  34855. /**
  34856. * @readOnly
  34857. */
  34858. this.group = new Group();
  34859. // FIXME Not use a seperate text group?
  34860. var dumbGroup = new Group({
  34861. position: opt.position.slice(),
  34862. rotation: opt.rotation
  34863. });
  34864. // this.group.add(dumbGroup);
  34865. // this._dumbGroup = dumbGroup;
  34866. dumbGroup.updateTransform();
  34867. this._transform = dumbGroup.transform;
  34868. this._dumbGroup = dumbGroup;
  34869. };
  34870. AxisBuilder.prototype = {
  34871. constructor: AxisBuilder,
  34872. hasBuilder: function (name) {
  34873. return !!builders[name];
  34874. },
  34875. add: function (name) {
  34876. builders[name].call(this);
  34877. },
  34878. getGroup: function () {
  34879. return this.group;
  34880. }
  34881. };
  34882. var builders = {
  34883. /**
  34884. * @private
  34885. */
  34886. axisLine: function () {
  34887. var opt = this.opt;
  34888. var axisModel = this.axisModel;
  34889. if (!axisModel.get('axisLine.show')) {
  34890. return;
  34891. }
  34892. var extent = this.axisModel.axis.getExtent();
  34893. var matrix = this._transform;
  34894. var pt1 = [extent[0], 0];
  34895. var pt2 = [extent[1], 0];
  34896. if (matrix) {
  34897. applyTransform(pt1, pt1, matrix);
  34898. applyTransform(pt2, pt2, matrix);
  34899. }
  34900. var lineStyle = extend(
  34901. {
  34902. lineCap: 'round'
  34903. },
  34904. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  34905. );
  34906. this.group.add(new Line({
  34907. // Id for animation
  34908. anid: 'line',
  34909. subPixelOptimize: true,
  34910. shape: {
  34911. x1: pt1[0],
  34912. y1: pt1[1],
  34913. x2: pt2[0],
  34914. y2: pt2[1]
  34915. },
  34916. style: lineStyle,
  34917. strokeContainThreshold: opt.strokeContainThreshold || 5,
  34918. silent: true,
  34919. z2: 1
  34920. }));
  34921. var arrows = axisModel.get('axisLine.symbol');
  34922. var arrowSize = axisModel.get('axisLine.symbolSize');
  34923. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  34924. if (typeof arrowOffset === 'number') {
  34925. arrowOffset = [arrowOffset, arrowOffset];
  34926. }
  34927. if (arrows != null) {
  34928. if (typeof arrows === 'string') {
  34929. // Use the same arrow for start and end point
  34930. arrows = [arrows, arrows];
  34931. }
  34932. if (typeof arrowSize === 'string'
  34933. || typeof arrowSize === 'number'
  34934. ) {
  34935. // Use the same size for width and height
  34936. arrowSize = [arrowSize, arrowSize];
  34937. }
  34938. var symbolWidth = arrowSize[0];
  34939. var symbolHeight = arrowSize[1];
  34940. each$1([{
  34941. rotate: opt.rotation + Math.PI / 2,
  34942. offset: arrowOffset[0],
  34943. r: 0
  34944. }, {
  34945. rotate: opt.rotation - Math.PI / 2,
  34946. offset: arrowOffset[1],
  34947. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  34948. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  34949. }], function (point, index) {
  34950. if (arrows[index] !== 'none' && arrows[index] != null) {
  34951. var symbol = createSymbol(
  34952. arrows[index],
  34953. -symbolWidth / 2,
  34954. -symbolHeight / 2,
  34955. symbolWidth,
  34956. symbolHeight,
  34957. lineStyle.stroke,
  34958. true
  34959. );
  34960. // Calculate arrow position with offset
  34961. var r = point.r + point.offset;
  34962. var pos = [
  34963. pt1[0] + r * Math.cos(opt.rotation),
  34964. pt1[1] - r * Math.sin(opt.rotation)
  34965. ];
  34966. symbol.attr({
  34967. rotation: point.rotate,
  34968. position: pos,
  34969. silent: true,
  34970. z2: 11
  34971. });
  34972. this.group.add(symbol);
  34973. }
  34974. }, this);
  34975. }
  34976. },
  34977. /**
  34978. * @private
  34979. */
  34980. axisTickLabel: function () {
  34981. var axisModel = this.axisModel;
  34982. var opt = this.opt;
  34983. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  34984. var labelEls = buildAxisLabel(this, axisModel, opt);
  34985. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  34986. buildAxisMinorTicks(this, axisModel, opt);
  34987. },
  34988. /**
  34989. * @private
  34990. */
  34991. axisName: function () {
  34992. var opt = this.opt;
  34993. var axisModel = this.axisModel;
  34994. var name = retrieve(opt.axisName, axisModel.get('name'));
  34995. if (!name) {
  34996. return;
  34997. }
  34998. var nameLocation = axisModel.get('nameLocation');
  34999. var nameDirection = opt.nameDirection;
  35000. var textStyleModel = axisModel.getModel('nameTextStyle');
  35001. var gap = axisModel.get('nameGap') || 0;
  35002. var extent = this.axisModel.axis.getExtent();
  35003. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  35004. var pos = [
  35005. nameLocation === 'start'
  35006. ? extent[0] - gapSignal * gap
  35007. : nameLocation === 'end'
  35008. ? extent[1] + gapSignal * gap
  35009. : (extent[0] + extent[1]) / 2, // 'middle'
  35010. // Reuse labelOffset.
  35011. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  35012. ];
  35013. var labelLayout;
  35014. var nameRotation = axisModel.get('nameRotate');
  35015. if (nameRotation != null) {
  35016. nameRotation = nameRotation * PI$2 / 180; // To radian.
  35017. }
  35018. var axisNameAvailableWidth;
  35019. if (isNameLocationCenter(nameLocation)) {
  35020. labelLayout = innerTextLayout(
  35021. opt.rotation,
  35022. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  35023. nameDirection
  35024. );
  35025. }
  35026. else {
  35027. labelLayout = endTextLayout(
  35028. opt, nameLocation, nameRotation || 0, extent
  35029. );
  35030. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  35031. if (axisNameAvailableWidth != null) {
  35032. axisNameAvailableWidth = Math.abs(
  35033. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  35034. );
  35035. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  35036. }
  35037. }
  35038. var textFont = textStyleModel.getFont();
  35039. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  35040. var ellipsis = truncateOpt.ellipsis;
  35041. var maxWidth = retrieve(
  35042. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  35043. );
  35044. // FIXME
  35045. // truncate rich text? (consider performance)
  35046. var truncatedText = (ellipsis != null && maxWidth != null)
  35047. ? truncateText$1(
  35048. name, maxWidth, textFont, ellipsis,
  35049. {minChar: 2, placeholder: truncateOpt.placeholder}
  35050. )
  35051. : name;
  35052. var tooltipOpt = axisModel.get('tooltip', true);
  35053. var mainType = axisModel.mainType;
  35054. var formatterParams = {
  35055. componentType: mainType,
  35056. name: name,
  35057. $vars: ['name']
  35058. };
  35059. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  35060. var textEl = new Text({
  35061. // Id for animation
  35062. anid: 'name',
  35063. __fullText: name,
  35064. __truncatedText: truncatedText,
  35065. position: pos,
  35066. rotation: labelLayout.rotation,
  35067. silent: isLabelSilent(axisModel),
  35068. z2: 1,
  35069. tooltip: (tooltipOpt && tooltipOpt.show)
  35070. ? extend({
  35071. content: name,
  35072. formatter: function () {
  35073. return name;
  35074. },
  35075. formatterParams: formatterParams
  35076. }, tooltipOpt)
  35077. : null
  35078. });
  35079. setTextStyle(textEl.style, textStyleModel, {
  35080. text: truncatedText,
  35081. textFont: textFont,
  35082. textFill: textStyleModel.getTextColor()
  35083. || axisModel.get('axisLine.lineStyle.color'),
  35084. textAlign: textStyleModel.get('align')
  35085. || labelLayout.textAlign,
  35086. textVerticalAlign: textStyleModel.get('verticalAlign')
  35087. || labelLayout.textVerticalAlign
  35088. });
  35089. if (axisModel.get('triggerEvent')) {
  35090. textEl.eventData = makeAxisEventDataBase(axisModel);
  35091. textEl.eventData.targetType = 'axisName';
  35092. textEl.eventData.name = name;
  35093. }
  35094. // FIXME
  35095. this._dumbGroup.add(textEl);
  35096. textEl.updateTransform();
  35097. this.group.add(textEl);
  35098. textEl.decomposeTransform();
  35099. }
  35100. };
  35101. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  35102. var eventData = {
  35103. componentType: axisModel.mainType,
  35104. componentIndex: axisModel.componentIndex
  35105. };
  35106. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  35107. return eventData;
  35108. };
  35109. /**
  35110. * @public
  35111. * @static
  35112. * @param {Object} opt
  35113. * @param {number} axisRotation in radian
  35114. * @param {number} textRotation in radian
  35115. * @param {number} direction
  35116. * @return {Object} {
  35117. * rotation, // according to axis
  35118. * textAlign,
  35119. * textVerticalAlign
  35120. * }
  35121. */
  35122. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  35123. var rotationDiff = remRadian(textRotation - axisRotation);
  35124. var textAlign;
  35125. var textVerticalAlign;
  35126. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  35127. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  35128. textAlign = 'center';
  35129. }
  35130. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  35131. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  35132. textAlign = 'center';
  35133. }
  35134. else {
  35135. textVerticalAlign = 'middle';
  35136. if (rotationDiff > 0 && rotationDiff < PI$2) {
  35137. textAlign = direction > 0 ? 'right' : 'left';
  35138. }
  35139. else {
  35140. textAlign = direction > 0 ? 'left' : 'right';
  35141. }
  35142. }
  35143. return {
  35144. rotation: rotationDiff,
  35145. textAlign: textAlign,
  35146. textVerticalAlign: textVerticalAlign
  35147. };
  35148. };
  35149. function endTextLayout(opt, textPosition, textRotate, extent) {
  35150. var rotationDiff = remRadian(textRotate - opt.rotation);
  35151. var textAlign;
  35152. var textVerticalAlign;
  35153. var inverse = extent[0] > extent[1];
  35154. var onLeft = (textPosition === 'start' && !inverse)
  35155. || (textPosition !== 'start' && inverse);
  35156. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  35157. textVerticalAlign = onLeft ? 'bottom' : 'top';
  35158. textAlign = 'center';
  35159. }
  35160. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  35161. textVerticalAlign = onLeft ? 'top' : 'bottom';
  35162. textAlign = 'center';
  35163. }
  35164. else {
  35165. textVerticalAlign = 'middle';
  35166. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  35167. textAlign = onLeft ? 'left' : 'right';
  35168. }
  35169. else {
  35170. textAlign = onLeft ? 'right' : 'left';
  35171. }
  35172. }
  35173. return {
  35174. rotation: rotationDiff,
  35175. textAlign: textAlign,
  35176. textVerticalAlign: textVerticalAlign
  35177. };
  35178. }
  35179. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  35180. var tooltipOpt = axisModel.get('tooltip');
  35181. return axisModel.get('silent')
  35182. // Consider mouse cursor, add these restrictions.
  35183. || !(
  35184. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  35185. );
  35186. };
  35187. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  35188. if (shouldShowAllLabels(axisModel.axis)) {
  35189. return;
  35190. }
  35191. // If min or max are user set, we need to check
  35192. // If the tick on min(max) are overlap on their neighbour tick
  35193. // If they are overlapped, we need to hide the min(max) tick label
  35194. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  35195. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  35196. // FIXME
  35197. // Have not consider onBand yet, where tick els is more than label els.
  35198. labelEls = labelEls || [];
  35199. tickEls = tickEls || [];
  35200. var firstLabel = labelEls[0];
  35201. var nextLabel = labelEls[1];
  35202. var lastLabel = labelEls[labelEls.length - 1];
  35203. var prevLabel = labelEls[labelEls.length - 2];
  35204. var firstTick = tickEls[0];
  35205. var nextTick = tickEls[1];
  35206. var lastTick = tickEls[tickEls.length - 1];
  35207. var prevTick = tickEls[tickEls.length - 2];
  35208. if (showMinLabel === false) {
  35209. ignoreEl(firstLabel);
  35210. ignoreEl(firstTick);
  35211. }
  35212. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  35213. if (showMinLabel) {
  35214. ignoreEl(nextLabel);
  35215. ignoreEl(nextTick);
  35216. }
  35217. else {
  35218. ignoreEl(firstLabel);
  35219. ignoreEl(firstTick);
  35220. }
  35221. }
  35222. if (showMaxLabel === false) {
  35223. ignoreEl(lastLabel);
  35224. ignoreEl(lastTick);
  35225. }
  35226. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  35227. if (showMaxLabel) {
  35228. ignoreEl(prevLabel);
  35229. ignoreEl(prevTick);
  35230. }
  35231. else {
  35232. ignoreEl(lastLabel);
  35233. ignoreEl(lastTick);
  35234. }
  35235. }
  35236. }
  35237. function ignoreEl(el) {
  35238. el && (el.ignore = true);
  35239. }
  35240. function isTwoLabelOverlapped(current, next, labelLayout) {
  35241. // current and next has the same rotation.
  35242. var firstRect = current && current.getBoundingRect().clone();
  35243. var nextRect = next && next.getBoundingRect().clone();
  35244. if (!firstRect || !nextRect) {
  35245. return;
  35246. }
  35247. // When checking intersect of two rotated labels, we use mRotationBack
  35248. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  35249. var mRotationBack = identity([]);
  35250. rotate(mRotationBack, mRotationBack, -current.rotation);
  35251. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  35252. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  35253. return firstRect.intersect(nextRect);
  35254. }
  35255. function isNameLocationCenter(nameLocation) {
  35256. return nameLocation === 'middle' || nameLocation === 'center';
  35257. }
  35258. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  35259. var tickEls = [];
  35260. var pt1 = [];
  35261. var pt2 = [];
  35262. for (var i = 0; i < ticksCoords.length; i++) {
  35263. var tickCoord = ticksCoords[i].coord;
  35264. pt1[0] = tickCoord;
  35265. pt1[1] = 0;
  35266. pt2[0] = tickCoord;
  35267. pt2[1] = tickEndCoord;
  35268. if (tickTransform) {
  35269. applyTransform(pt1, pt1, tickTransform);
  35270. applyTransform(pt2, pt2, tickTransform);
  35271. }
  35272. // Tick line, Not use group transform to have better line draw
  35273. var tickEl = new Line({
  35274. // Id for animation
  35275. anid: aniid + '_' + ticksCoords[i].tickValue,
  35276. subPixelOptimize: true,
  35277. shape: {
  35278. x1: pt1[0],
  35279. y1: pt1[1],
  35280. x2: pt2[0],
  35281. y2: pt2[1]
  35282. },
  35283. style: tickLineStyle,
  35284. z2: 2,
  35285. silent: true
  35286. });
  35287. tickEls.push(tickEl);
  35288. }
  35289. return tickEls;
  35290. }
  35291. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  35292. var axis = axisModel.axis;
  35293. var tickModel = axisModel.getModel('axisTick');
  35294. if (!tickModel.get('show') || axis.scale.isBlank()) {
  35295. return;
  35296. }
  35297. var lineStyleModel = tickModel.getModel('lineStyle');
  35298. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  35299. var ticksCoords = axis.getTicksCoords();
  35300. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(
  35301. lineStyleModel.getLineStyle(),
  35302. {
  35303. stroke: axisModel.get('axisLine.lineStyle.color')
  35304. }
  35305. ), 'ticks');
  35306. for (var i = 0; i < ticksEls.length; i++) {
  35307. axisBuilder.group.add(ticksEls[i]);
  35308. }
  35309. return ticksEls;
  35310. }
  35311. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  35312. var axis = axisModel.axis;
  35313. var minorTickModel = axisModel.getModel('minorTick');
  35314. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  35315. return;
  35316. }
  35317. var minorTicksCoords = axis.getMinorTicksCoords();
  35318. if (!minorTicksCoords.length) {
  35319. return;
  35320. }
  35321. var lineStyleModel = minorTickModel.getModel('lineStyle');
  35322. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  35323. var minorTickLineStyle = defaults(
  35324. lineStyleModel.getLineStyle(),
  35325. defaults(
  35326. axisModel.getModel('axisTick').getLineStyle(),
  35327. {
  35328. stroke: axisModel.get('axisLine.lineStyle.color')
  35329. }
  35330. )
  35331. );
  35332. for (var i = 0; i < minorTicksCoords.length; i++) {
  35333. var minorTicksEls = createTicks(
  35334. minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i
  35335. );
  35336. for (var k = 0; k < minorTicksEls.length; k++) {
  35337. axisBuilder.group.add(minorTicksEls[k]);
  35338. }
  35339. }
  35340. }
  35341. function buildAxisLabel(axisBuilder, axisModel, opt) {
  35342. var axis = axisModel.axis;
  35343. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  35344. if (!show || axis.scale.isBlank()) {
  35345. return;
  35346. }
  35347. var labelModel = axisModel.getModel('axisLabel');
  35348. var labelMargin = labelModel.get('margin');
  35349. var labels = axis.getViewLabels();
  35350. // Special label rotate.
  35351. var labelRotation = (
  35352. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  35353. ) * PI$2 / 180;
  35354. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  35355. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  35356. var labelEls = [];
  35357. var silent = isLabelSilent(axisModel);
  35358. var triggerEvent = axisModel.get('triggerEvent');
  35359. each$1(labels, function (labelItem, index) {
  35360. var tickValue = labelItem.tickValue;
  35361. var formattedLabel = labelItem.formattedLabel;
  35362. var rawLabel = labelItem.rawLabel;
  35363. var itemLabelModel = labelModel;
  35364. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  35365. itemLabelModel = new Model(
  35366. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  35367. );
  35368. }
  35369. var textColor = itemLabelModel.getTextColor()
  35370. || axisModel.get('axisLine.lineStyle.color');
  35371. var tickCoord = axis.dataToCoord(tickValue);
  35372. var pos = [
  35373. tickCoord,
  35374. opt.labelOffset + opt.labelDirection * labelMargin
  35375. ];
  35376. var textEl = new Text({
  35377. // Id for animation
  35378. anid: 'label_' + tickValue,
  35379. position: pos,
  35380. rotation: labelLayout.rotation,
  35381. silent: silent,
  35382. z2: 10
  35383. });
  35384. setTextStyle(textEl.style, itemLabelModel, {
  35385. text: formattedLabel,
  35386. textAlign: itemLabelModel.getShallow('align', true)
  35387. || labelLayout.textAlign,
  35388. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  35389. || itemLabelModel.getShallow('baseline', true)
  35390. || labelLayout.textVerticalAlign,
  35391. textFill: typeof textColor === 'function'
  35392. ? textColor(
  35393. // (1) In category axis with data zoom, tick is not the original
  35394. // index of axis.data. So tick should not be exposed to user
  35395. // in category axis.
  35396. // (2) Compatible with previous version, which always use formatted label as
  35397. // input. But in interval scale the formatted label is like '223,445', which
  35398. // maked user repalce ','. So we modify it to return original val but remain
  35399. // it as 'string' to avoid error in replacing.
  35400. axis.type === 'category'
  35401. ? rawLabel
  35402. : axis.type === 'value'
  35403. ? tickValue + ''
  35404. : tickValue,
  35405. index
  35406. )
  35407. : textColor
  35408. });
  35409. // Pack data for mouse event
  35410. if (triggerEvent) {
  35411. textEl.eventData = makeAxisEventDataBase(axisModel);
  35412. textEl.eventData.targetType = 'axisLabel';
  35413. textEl.eventData.value = rawLabel;
  35414. }
  35415. // FIXME
  35416. axisBuilder._dumbGroup.add(textEl);
  35417. textEl.updateTransform();
  35418. labelEls.push(textEl);
  35419. axisBuilder.group.add(textEl);
  35420. textEl.decomposeTransform();
  35421. });
  35422. return labelEls;
  35423. }
  35424. /*
  35425. * Licensed to the Apache Software Foundation (ASF) under one
  35426. * or more contributor license agreements. See the NOTICE file
  35427. * distributed with this work for additional information
  35428. * regarding copyright ownership. The ASF licenses this file
  35429. * to you under the Apache License, Version 2.0 (the
  35430. * "License"); you may not use this file except in compliance
  35431. * with the License. You may obtain a copy of the License at
  35432. *
  35433. * http://www.apache.org/licenses/LICENSE-2.0
  35434. *
  35435. * Unless required by applicable law or agreed to in writing,
  35436. * software distributed under the License is distributed on an
  35437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35438. * KIND, either express or implied. See the License for the
  35439. * specific language governing permissions and limitations
  35440. * under the License.
  35441. */
  35442. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  35443. // allAxesInfo should be updated when setOption performed.
  35444. function fixValue(axisModel) {
  35445. var axisInfo = getAxisInfo(axisModel);
  35446. if (!axisInfo) {
  35447. return;
  35448. }
  35449. var axisPointerModel = axisInfo.axisPointerModel;
  35450. var scale = axisInfo.axis.scale;
  35451. var option = axisPointerModel.option;
  35452. var status = axisPointerModel.get('status');
  35453. var value = axisPointerModel.get('value');
  35454. // Parse init value for category and time axis.
  35455. if (value != null) {
  35456. value = scale.parse(value);
  35457. }
  35458. var useHandle = isHandleTrigger(axisPointerModel);
  35459. // If `handle` used, `axisPointer` will always be displayed, so value
  35460. // and status should be initialized.
  35461. if (status == null) {
  35462. option.status = useHandle ? 'show' : 'hide';
  35463. }
  35464. var extent = scale.getExtent().slice();
  35465. extent[0] > extent[1] && extent.reverse();
  35466. if (// Pick a value on axis when initializing.
  35467. value == null
  35468. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  35469. // where we should re-pick a value to keep `handle` displaying normally.
  35470. || value > extent[1]
  35471. ) {
  35472. // Make handle displayed on the end of the axis when init, which looks better.
  35473. value = extent[1];
  35474. }
  35475. if (value < extent[0]) {
  35476. value = extent[0];
  35477. }
  35478. option.value = value;
  35479. if (useHandle) {
  35480. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  35481. }
  35482. }
  35483. function getAxisInfo(axisModel) {
  35484. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  35485. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  35486. }
  35487. function getAxisPointerModel(axisModel) {
  35488. var axisInfo = getAxisInfo(axisModel);
  35489. return axisInfo && axisInfo.axisPointerModel;
  35490. }
  35491. function isHandleTrigger(axisPointerModel) {
  35492. return !!axisPointerModel.get('handle.show');
  35493. }
  35494. /**
  35495. * @param {module:echarts/model/Model} model
  35496. * @return {string} unique key
  35497. */
  35498. function makeKey(model) {
  35499. return model.type + '||' + model.id;
  35500. }
  35501. /*
  35502. * Licensed to the Apache Software Foundation (ASF) under one
  35503. * or more contributor license agreements. See the NOTICE file
  35504. * distributed with this work for additional information
  35505. * regarding copyright ownership. The ASF licenses this file
  35506. * to you under the Apache License, Version 2.0 (the
  35507. * "License"); you may not use this file except in compliance
  35508. * with the License. You may obtain a copy of the License at
  35509. *
  35510. * http://www.apache.org/licenses/LICENSE-2.0
  35511. *
  35512. * Unless required by applicable law or agreed to in writing,
  35513. * software distributed under the License is distributed on an
  35514. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35515. * KIND, either express or implied. See the License for the
  35516. * specific language governing permissions and limitations
  35517. * under the License.
  35518. */
  35519. /**
  35520. * Base class of AxisView.
  35521. */
  35522. var AxisView = extendComponentView({
  35523. type: 'axis',
  35524. /**
  35525. * @private
  35526. */
  35527. _axisPointer: null,
  35528. /**
  35529. * @protected
  35530. * @type {string}
  35531. */
  35532. axisPointerClass: null,
  35533. /**
  35534. * @override
  35535. */
  35536. render: function (axisModel, ecModel, api, payload) {
  35537. // FIXME
  35538. // This process should proformed after coordinate systems updated
  35539. // (axis scale updated), and should be performed each time update.
  35540. // So put it here temporarily, although it is not appropriate to
  35541. // put a model-writing procedure in `view`.
  35542. this.axisPointerClass && fixValue(axisModel);
  35543. AxisView.superApply(this, 'render', arguments);
  35544. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  35545. },
  35546. /**
  35547. * Action handler.
  35548. * @public
  35549. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35550. * @param {module:echarts/model/Global} ecModel
  35551. * @param {module:echarts/ExtensionAPI} api
  35552. * @param {Object} payload
  35553. */
  35554. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  35555. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  35556. },
  35557. /**
  35558. * @override
  35559. */
  35560. remove: function (ecModel, api) {
  35561. var axisPointer = this._axisPointer;
  35562. axisPointer && axisPointer.remove(api);
  35563. AxisView.superApply(this, 'remove', arguments);
  35564. },
  35565. /**
  35566. * @override
  35567. */
  35568. dispose: function (ecModel, api) {
  35569. disposeAxisPointer(this, api);
  35570. AxisView.superApply(this, 'dispose', arguments);
  35571. }
  35572. });
  35573. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  35574. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  35575. if (!Clazz) {
  35576. return;
  35577. }
  35578. var axisPointerModel = getAxisPointerModel(axisModel);
  35579. axisPointerModel
  35580. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  35581. .render(axisModel, axisPointerModel, api, forceRender)
  35582. : disposeAxisPointer(axisView, api);
  35583. }
  35584. function disposeAxisPointer(axisView, ecModel, api) {
  35585. var axisPointer = axisView._axisPointer;
  35586. axisPointer && axisPointer.dispose(ecModel, api);
  35587. axisView._axisPointer = null;
  35588. }
  35589. var axisPointerClazz = [];
  35590. AxisView.registerAxisPointerClass = function (type, clazz) {
  35591. if (__DEV__) {
  35592. if (axisPointerClazz[type]) {
  35593. throw new Error('axisPointer ' + type + ' exists');
  35594. }
  35595. }
  35596. axisPointerClazz[type] = clazz;
  35597. };
  35598. AxisView.getAxisPointerClass = function (type) {
  35599. return type && axisPointerClazz[type];
  35600. };
  35601. /*
  35602. * Licensed to the Apache Software Foundation (ASF) under one
  35603. * or more contributor license agreements. See the NOTICE file
  35604. * distributed with this work for additional information
  35605. * regarding copyright ownership. The ASF licenses this file
  35606. * to you under the Apache License, Version 2.0 (the
  35607. * "License"); you may not use this file except in compliance
  35608. * with the License. You may obtain a copy of the License at
  35609. *
  35610. * http://www.apache.org/licenses/LICENSE-2.0
  35611. *
  35612. * Unless required by applicable law or agreed to in writing,
  35613. * software distributed under the License is distributed on an
  35614. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35615. * KIND, either express or implied. See the License for the
  35616. * specific language governing permissions and limitations
  35617. * under the License.
  35618. */
  35619. /**
  35620. * Can only be called after coordinate system creation stage.
  35621. * (Can be called before coordinate system update stage).
  35622. *
  35623. * @param {Object} opt {labelInside}
  35624. * @return {Object} {
  35625. * position, rotation, labelDirection, labelOffset,
  35626. * tickDirection, labelRotate, z2
  35627. * }
  35628. */
  35629. function layout$1(gridModel, axisModel, opt) {
  35630. opt = opt || {};
  35631. var grid = gridModel.coordinateSystem;
  35632. var axis = axisModel.axis;
  35633. var layout = {};
  35634. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  35635. var rawAxisPosition = axis.position;
  35636. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  35637. var axisDim = axis.dim;
  35638. var rect = grid.getRect();
  35639. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  35640. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  35641. var axisOffset = axisModel.get('offset') || 0;
  35642. var posBound = axisDim === 'x'
  35643. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  35644. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  35645. if (otherAxisOnZeroOf) {
  35646. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  35647. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  35648. }
  35649. // Axis position
  35650. layout.position = [
  35651. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  35652. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  35653. ];
  35654. // Axis rotation
  35655. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  35656. // Tick and label direction, x y is axisDim
  35657. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  35658. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  35659. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  35660. if (axisModel.get('axisTick.inside')) {
  35661. layout.tickDirection = -layout.tickDirection;
  35662. }
  35663. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  35664. layout.labelDirection = -layout.labelDirection;
  35665. }
  35666. // Special label rotation
  35667. var labelRotate = axisModel.get('axisLabel.rotate');
  35668. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  35669. // Over splitLine and splitArea
  35670. layout.z2 = 1;
  35671. return layout;
  35672. }
  35673. /*
  35674. * Licensed to the Apache Software Foundation (ASF) under one
  35675. * or more contributor license agreements. See the NOTICE file
  35676. * distributed with this work for additional information
  35677. * regarding copyright ownership. The ASF licenses this file
  35678. * to you under the Apache License, Version 2.0 (the
  35679. * "License"); you may not use this file except in compliance
  35680. * with the License. You may obtain a copy of the License at
  35681. *
  35682. * http://www.apache.org/licenses/LICENSE-2.0
  35683. *
  35684. * Unless required by applicable law or agreed to in writing,
  35685. * software distributed under the License is distributed on an
  35686. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35687. * KIND, either express or implied. See the License for the
  35688. * specific language governing permissions and limitations
  35689. * under the License.
  35690. */
  35691. var axisBuilderAttrs = [
  35692. 'axisLine', 'axisTickLabel', 'axisName'
  35693. ];
  35694. var selfBuilderAttrs = [
  35695. 'splitArea', 'splitLine', 'minorSplitLine'
  35696. ];
  35697. var CartesianAxisView = AxisView.extend({
  35698. type: 'cartesianAxis',
  35699. axisPointerClass: 'CartesianAxisPointer',
  35700. /**
  35701. * @override
  35702. */
  35703. render: function (axisModel, ecModel, api, payload) {
  35704. this.group.removeAll();
  35705. var oldAxisGroup = this._axisGroup;
  35706. this._axisGroup = new Group();
  35707. this.group.add(this._axisGroup);
  35708. if (!axisModel.get('show')) {
  35709. return;
  35710. }
  35711. var gridModel = axisModel.getCoordSysModel();
  35712. var layout = layout$1(gridModel, axisModel);
  35713. var axisBuilder = new AxisBuilder(axisModel, layout);
  35714. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  35715. this._axisGroup.add(axisBuilder.getGroup());
  35716. each$1(selfBuilderAttrs, function (name) {
  35717. if (axisModel.get(name + '.show')) {
  35718. this['_' + name](axisModel, gridModel);
  35719. }
  35720. }, this);
  35721. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  35722. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  35723. },
  35724. remove: function () {
  35725. this._splitAreaColors = null;
  35726. },
  35727. /**
  35728. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35729. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35730. * @private
  35731. */
  35732. _splitLine: function (axisModel, gridModel) {
  35733. var axis = axisModel.axis;
  35734. if (axis.scale.isBlank()) {
  35735. return;
  35736. }
  35737. var splitLineModel = axisModel.getModel('splitLine');
  35738. var lineStyleModel = splitLineModel.getModel('lineStyle');
  35739. var lineColors = lineStyleModel.get('color');
  35740. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  35741. var gridRect = gridModel.coordinateSystem.getRect();
  35742. var isHorizontal = axis.isHorizontal();
  35743. var lineCount = 0;
  35744. var ticksCoords = axis.getTicksCoords({
  35745. tickModel: splitLineModel
  35746. });
  35747. var p1 = [];
  35748. var p2 = [];
  35749. var lineStyle = lineStyleModel.getLineStyle();
  35750. for (var i = 0; i < ticksCoords.length; i++) {
  35751. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35752. if (isHorizontal) {
  35753. p1[0] = tickCoord;
  35754. p1[1] = gridRect.y;
  35755. p2[0] = tickCoord;
  35756. p2[1] = gridRect.y + gridRect.height;
  35757. }
  35758. else {
  35759. p1[0] = gridRect.x;
  35760. p1[1] = tickCoord;
  35761. p2[0] = gridRect.x + gridRect.width;
  35762. p2[1] = tickCoord;
  35763. }
  35764. var colorIndex = (lineCount++) % lineColors.length;
  35765. var tickValue = ticksCoords[i].tickValue;
  35766. this._axisGroup.add(new Line({
  35767. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  35768. subPixelOptimize: true,
  35769. shape: {
  35770. x1: p1[0],
  35771. y1: p1[1],
  35772. x2: p2[0],
  35773. y2: p2[1]
  35774. },
  35775. style: defaults({
  35776. stroke: lineColors[colorIndex]
  35777. }, lineStyle),
  35778. silent: true
  35779. }));
  35780. }
  35781. },
  35782. /**
  35783. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35784. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35785. * @private
  35786. */
  35787. _minorSplitLine: function (axisModel, gridModel) {
  35788. var axis = axisModel.axis;
  35789. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  35790. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  35791. var gridRect = gridModel.coordinateSystem.getRect();
  35792. var isHorizontal = axis.isHorizontal();
  35793. var minorTicksCoords = axis.getMinorTicksCoords();
  35794. if (!minorTicksCoords.length) {
  35795. return;
  35796. }
  35797. var p1 = [];
  35798. var p2 = [];
  35799. var lineStyle = lineStyleModel.getLineStyle();
  35800. for (var i = 0; i < minorTicksCoords.length; i++) {
  35801. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  35802. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  35803. if (isHorizontal) {
  35804. p1[0] = tickCoord;
  35805. p1[1] = gridRect.y;
  35806. p2[0] = tickCoord;
  35807. p2[1] = gridRect.y + gridRect.height;
  35808. }
  35809. else {
  35810. p1[0] = gridRect.x;
  35811. p1[1] = tickCoord;
  35812. p2[0] = gridRect.x + gridRect.width;
  35813. p2[1] = tickCoord;
  35814. }
  35815. this._axisGroup.add(new Line({
  35816. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  35817. subPixelOptimize: true,
  35818. shape: {
  35819. x1: p1[0],
  35820. y1: p1[1],
  35821. x2: p2[0],
  35822. y2: p2[1]
  35823. },
  35824. style: lineStyle,
  35825. silent: true
  35826. }));
  35827. }
  35828. }
  35829. },
  35830. /**
  35831. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  35832. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  35833. * @private
  35834. */
  35835. _splitArea: function (axisModel, gridModel) {
  35836. var axis = axisModel.axis;
  35837. if (axis.scale.isBlank()) {
  35838. return;
  35839. }
  35840. var splitAreaModel = axisModel.getModel('splitArea');
  35841. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  35842. var areaColors = areaStyleModel.get('color');
  35843. var gridRect = gridModel.coordinateSystem.getRect();
  35844. var ticksCoords = axis.getTicksCoords({
  35845. tickModel: splitAreaModel,
  35846. clamp: true
  35847. });
  35848. if (!ticksCoords.length) {
  35849. return;
  35850. }
  35851. // For Making appropriate splitArea animation, the color and anid
  35852. // should be corresponding to previous one if possible.
  35853. var areaColorsLen = areaColors.length;
  35854. var lastSplitAreaColors = this._splitAreaColors;
  35855. var newSplitAreaColors = createHashMap();
  35856. var colorIndex = 0;
  35857. if (lastSplitAreaColors) {
  35858. for (var i = 0; i < ticksCoords.length; i++) {
  35859. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  35860. if (cIndex != null) {
  35861. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  35862. break;
  35863. }
  35864. }
  35865. }
  35866. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  35867. var areaStyle = areaStyleModel.getAreaStyle();
  35868. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  35869. for (var i = 1; i < ticksCoords.length; i++) {
  35870. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  35871. var x;
  35872. var y;
  35873. var width;
  35874. var height;
  35875. if (axis.isHorizontal()) {
  35876. x = prev;
  35877. y = gridRect.y;
  35878. width = tickCoord - x;
  35879. height = gridRect.height;
  35880. prev = x + width;
  35881. }
  35882. else {
  35883. x = gridRect.x;
  35884. y = prev;
  35885. width = gridRect.width;
  35886. height = tickCoord - y;
  35887. prev = y + height;
  35888. }
  35889. var tickValue = ticksCoords[i - 1].tickValue;
  35890. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  35891. this._axisGroup.add(new Rect({
  35892. anid: tickValue != null ? 'area_' + tickValue : null,
  35893. shape: {
  35894. x: x,
  35895. y: y,
  35896. width: width,
  35897. height: height
  35898. },
  35899. style: defaults({
  35900. fill: areaColors[colorIndex]
  35901. }, areaStyle),
  35902. silent: true
  35903. }));
  35904. colorIndex = (colorIndex + 1) % areaColorsLen;
  35905. }
  35906. this._splitAreaColors = newSplitAreaColors;
  35907. }
  35908. });
  35909. CartesianAxisView.extend({
  35910. type: 'xAxis'
  35911. });
  35912. CartesianAxisView.extend({
  35913. type: 'yAxis'
  35914. });
  35915. /*
  35916. * Licensed to the Apache Software Foundation (ASF) under one
  35917. * or more contributor license agreements. See the NOTICE file
  35918. * distributed with this work for additional information
  35919. * regarding copyright ownership. The ASF licenses this file
  35920. * to you under the Apache License, Version 2.0 (the
  35921. * "License"); you may not use this file except in compliance
  35922. * with the License. You may obtain a copy of the License at
  35923. *
  35924. * http://www.apache.org/licenses/LICENSE-2.0
  35925. *
  35926. * Unless required by applicable law or agreed to in writing,
  35927. * software distributed under the License is distributed on an
  35928. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35929. * KIND, either express or implied. See the License for the
  35930. * specific language governing permissions and limitations
  35931. * under the License.
  35932. */
  35933. /*
  35934. * Licensed to the Apache Software Foundation (ASF) under one
  35935. * or more contributor license agreements. See the NOTICE file
  35936. * distributed with this work for additional information
  35937. * regarding copyright ownership. The ASF licenses this file
  35938. * to you under the Apache License, Version 2.0 (the
  35939. * "License"); you may not use this file except in compliance
  35940. * with the License. You may obtain a copy of the License at
  35941. *
  35942. * http://www.apache.org/licenses/LICENSE-2.0
  35943. *
  35944. * Unless required by applicable law or agreed to in writing,
  35945. * software distributed under the License is distributed on an
  35946. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35947. * KIND, either express or implied. See the License for the
  35948. * specific language governing permissions and limitations
  35949. * under the License.
  35950. */
  35951. // Grid view
  35952. extendComponentView({
  35953. type: 'grid',
  35954. render: function (gridModel, ecModel) {
  35955. this.group.removeAll();
  35956. if (gridModel.get('show')) {
  35957. this.group.add(new Rect({
  35958. shape: gridModel.coordinateSystem.getRect(),
  35959. style: defaults({
  35960. fill: gridModel.get('backgroundColor')
  35961. }, gridModel.getItemStyle()),
  35962. silent: true,
  35963. z2: -1
  35964. }));
  35965. }
  35966. }
  35967. });
  35968. registerPreprocessor(function (option) {
  35969. // Only create grid when need
  35970. if (option.xAxis && option.yAxis && !option.grid) {
  35971. option.grid = {};
  35972. }
  35973. });
  35974. /*
  35975. * Licensed to the Apache Software Foundation (ASF) under one
  35976. * or more contributor license agreements. See the NOTICE file
  35977. * distributed with this work for additional information
  35978. * regarding copyright ownership. The ASF licenses this file
  35979. * to you under the Apache License, Version 2.0 (the
  35980. * "License"); you may not use this file except in compliance
  35981. * with the License. You may obtain a copy of the License at
  35982. *
  35983. * http://www.apache.org/licenses/LICENSE-2.0
  35984. *
  35985. * Unless required by applicable law or agreed to in writing,
  35986. * software distributed under the License is distributed on an
  35987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35988. * KIND, either express or implied. See the License for the
  35989. * specific language governing permissions and limitations
  35990. * under the License.
  35991. */
  35992. // In case developer forget to include grid component
  35993. registerVisual(visualSymbol('line', 'circle', 'line'));
  35994. registerLayout(layoutPoints('line'));
  35995. // Down sample after filter
  35996. registerProcessor(
  35997. PRIORITY.PROCESSOR.STATISTIC,
  35998. dataSample('line')
  35999. );
  36000. /*
  36001. * Licensed to the Apache Software Foundation (ASF) under one
  36002. * or more contributor license agreements. See the NOTICE file
  36003. * distributed with this work for additional information
  36004. * regarding copyright ownership. The ASF licenses this file
  36005. * to you under the Apache License, Version 2.0 (the
  36006. * "License"); you may not use this file except in compliance
  36007. * with the License. You may obtain a copy of the License at
  36008. *
  36009. * http://www.apache.org/licenses/LICENSE-2.0
  36010. *
  36011. * Unless required by applicable law or agreed to in writing,
  36012. * software distributed under the License is distributed on an
  36013. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36014. * KIND, either express or implied. See the License for the
  36015. * specific language governing permissions and limitations
  36016. * under the License.
  36017. */
  36018. var BaseBarSeries = SeriesModel.extend({
  36019. type: 'series.__base_bar__',
  36020. getInitialData: function (option, ecModel) {
  36021. return createListFromArray(this.getSource(), this, {useEncodeDefaulter: true});
  36022. },
  36023. getMarkerPosition: function (value) {
  36024. var coordSys = this.coordinateSystem;
  36025. if (coordSys) {
  36026. // PENDING if clamp ?
  36027. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  36028. var data = this.getData();
  36029. var offset = data.getLayout('offset');
  36030. var size = data.getLayout('size');
  36031. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36032. pt[offsetIndex] += offset + size / 2;
  36033. return pt;
  36034. }
  36035. return [NaN, NaN];
  36036. },
  36037. defaultOption: {
  36038. zlevel: 0, // 一级层叠
  36039. z: 2, // 二级层叠
  36040. coordinateSystem: 'cartesian2d',
  36041. legendHoverLink: true,
  36042. // stack: null
  36043. // Cartesian coordinate system
  36044. // xAxisIndex: 0,
  36045. // yAxisIndex: 0,
  36046. // 最小高度改为0
  36047. barMinHeight: 0,
  36048. // 最小角度为0,仅对极坐标系下的柱状图有效
  36049. barMinAngle: 0,
  36050. // cursor: null,
  36051. large: false,
  36052. largeThreshold: 400,
  36053. progressive: 3e3,
  36054. progressiveChunkMode: 'mod',
  36055. // barMaxWidth: null,
  36056. // In cartesian, the default value is 1. Otherwise null.
  36057. // barMinWidth: null,
  36058. // 默认自适应
  36059. // barWidth: null,
  36060. // 柱间距离,默认为柱形宽度的30%,可设固定值
  36061. // barGap: '30%',
  36062. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  36063. // barCategoryGap: '20%',
  36064. // label: {
  36065. // show: false
  36066. // },
  36067. itemStyle: {},
  36068. emphasis: {}
  36069. }
  36070. });
  36071. /*
  36072. * Licensed to the Apache Software Foundation (ASF) under one
  36073. * or more contributor license agreements. See the NOTICE file
  36074. * distributed with this work for additional information
  36075. * regarding copyright ownership. The ASF licenses this file
  36076. * to you under the Apache License, Version 2.0 (the
  36077. * "License"); you may not use this file except in compliance
  36078. * with the License. You may obtain a copy of the License at
  36079. *
  36080. * http://www.apache.org/licenses/LICENSE-2.0
  36081. *
  36082. * Unless required by applicable law or agreed to in writing,
  36083. * software distributed under the License is distributed on an
  36084. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36085. * KIND, either express or implied. See the License for the
  36086. * specific language governing permissions and limitations
  36087. * under the License.
  36088. */
  36089. BaseBarSeries.extend({
  36090. type: 'series.bar',
  36091. dependencies: ['grid', 'polar'],
  36092. brushSelector: 'rect',
  36093. /**
  36094. * @override
  36095. */
  36096. getProgressive: function () {
  36097. // Do not support progressive in normal mode.
  36098. return this.get('large')
  36099. ? this.get('progressive')
  36100. : false;
  36101. },
  36102. /**
  36103. * @override
  36104. */
  36105. getProgressiveThreshold: function () {
  36106. // Do not support progressive in normal mode.
  36107. var progressiveThreshold = this.get('progressiveThreshold');
  36108. var largeThreshold = this.get('largeThreshold');
  36109. if (largeThreshold > progressiveThreshold) {
  36110. progressiveThreshold = largeThreshold;
  36111. }
  36112. return progressiveThreshold;
  36113. },
  36114. defaultOption: {
  36115. // If clipped
  36116. // Only available on cartesian2d
  36117. clip: true,
  36118. // If use caps on two sides of bars
  36119. // Only available on tangential polar bar
  36120. roundCap: false
  36121. }
  36122. });
  36123. /*
  36124. * Licensed to the Apache Software Foundation (ASF) under one
  36125. * or more contributor license agreements. See the NOTICE file
  36126. * distributed with this work for additional information
  36127. * regarding copyright ownership. The ASF licenses this file
  36128. * to you under the Apache License, Version 2.0 (the
  36129. * "License"); you may not use this file except in compliance
  36130. * with the License. You may obtain a copy of the License at
  36131. *
  36132. * http://www.apache.org/licenses/LICENSE-2.0
  36133. *
  36134. * Unless required by applicable law or agreed to in writing,
  36135. * software distributed under the License is distributed on an
  36136. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36137. * KIND, either express or implied. See the License for the
  36138. * specific language governing permissions and limitations
  36139. * under the License.
  36140. */
  36141. function setLabel(
  36142. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  36143. ) {
  36144. var labelModel = itemModel.getModel('label');
  36145. var hoverLabelModel = itemModel.getModel('emphasis.label');
  36146. setLabelStyle(
  36147. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  36148. {
  36149. labelFetcher: seriesModel,
  36150. labelDataIndex: dataIndex,
  36151. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  36152. isRectText: true,
  36153. autoColor: color
  36154. }
  36155. );
  36156. fixPosition(normalStyle);
  36157. fixPosition(hoverStyle);
  36158. }
  36159. function fixPosition(style, labelPositionOutside) {
  36160. if (style.textPosition === 'outside') {
  36161. style.textPosition = labelPositionOutside;
  36162. }
  36163. }
  36164. /*
  36165. * Licensed to the Apache Software Foundation (ASF) under one
  36166. * or more contributor license agreements. See the NOTICE file
  36167. * distributed with this work for additional information
  36168. * regarding copyright ownership. The ASF licenses this file
  36169. * to you under the Apache License, Version 2.0 (the
  36170. * "License"); you may not use this file except in compliance
  36171. * with the License. You may obtain a copy of the License at
  36172. *
  36173. * http://www.apache.org/licenses/LICENSE-2.0
  36174. *
  36175. * Unless required by applicable law or agreed to in writing,
  36176. * software distributed under the License is distributed on an
  36177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36178. * KIND, either express or implied. See the License for the
  36179. * specific language governing permissions and limitations
  36180. * under the License.
  36181. */
  36182. var getBarItemStyle = makeStyleMapper(
  36183. [
  36184. ['fill', 'color'],
  36185. ['stroke', 'borderColor'],
  36186. ['lineWidth', 'borderWidth'],
  36187. // Compatitable with 2
  36188. ['stroke', 'barBorderColor'],
  36189. ['lineWidth', 'barBorderWidth'],
  36190. ['opacity'],
  36191. ['shadowBlur'],
  36192. ['shadowOffsetX'],
  36193. ['shadowOffsetY'],
  36194. ['shadowColor']
  36195. ]
  36196. );
  36197. var barItemStyle = {
  36198. getBarItemStyle: function (excludes) {
  36199. var style = getBarItemStyle(this, excludes);
  36200. if (this.getBorderLineDash) {
  36201. var lineDash = this.getBorderLineDash();
  36202. lineDash && (style.lineDash = lineDash);
  36203. }
  36204. return style;
  36205. }
  36206. };
  36207. /*
  36208. * Licensed to the Apache Software Foundation (ASF) under one
  36209. * or more contributor license agreements. See the NOTICE file
  36210. * distributed with this work for additional information
  36211. * regarding copyright ownership. The ASF licenses this file
  36212. * to you under the Apache License, Version 2.0 (the
  36213. * "License"); you may not use this file except in compliance
  36214. * with the License. You may obtain a copy of the License at
  36215. *
  36216. * http://www.apache.org/licenses/LICENSE-2.0
  36217. *
  36218. * Unless required by applicable law or agreed to in writing,
  36219. * software distributed under the License is distributed on an
  36220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36221. * KIND, either express or implied. See the License for the
  36222. * specific language governing permissions and limitations
  36223. * under the License.
  36224. */
  36225. /**
  36226. * Sausage: similar to sector, but have half circle on both sides
  36227. * @public
  36228. */
  36229. var Sausage = extendShape({
  36230. type: 'sausage',
  36231. shape: {
  36232. cx: 0,
  36233. cy: 0,
  36234. r0: 0,
  36235. r: 0,
  36236. startAngle: 0,
  36237. endAngle: Math.PI * 2,
  36238. clockwise: true
  36239. },
  36240. buildPath: function (ctx, shape) {
  36241. var x = shape.cx;
  36242. var y = shape.cy;
  36243. var r0 = Math.max(shape.r0 || 0, 0);
  36244. var r = Math.max(shape.r, 0);
  36245. var dr = (r - r0) * 0.5;
  36246. var rCenter = r0 + dr;
  36247. var startAngle = shape.startAngle;
  36248. var endAngle = shape.endAngle;
  36249. var clockwise = shape.clockwise;
  36250. var unitStartX = Math.cos(startAngle);
  36251. var unitStartY = Math.sin(startAngle);
  36252. var unitEndX = Math.cos(endAngle);
  36253. var unitEndY = Math.sin(endAngle);
  36254. var lessThanCircle = clockwise
  36255. ? endAngle - startAngle < Math.PI * 2
  36256. : startAngle - endAngle < Math.PI * 2;
  36257. if (lessThanCircle) {
  36258. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  36259. ctx.arc(
  36260. unitStartX * rCenter + x, unitStartY * rCenter + y, dr,
  36261. -Math.PI + startAngle, startAngle, !clockwise
  36262. );
  36263. }
  36264. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  36265. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  36266. ctx.arc(
  36267. unitEndX * rCenter + x, unitEndY * rCenter + y, dr,
  36268. endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise
  36269. );
  36270. if (r0 !== 0) {
  36271. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  36272. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  36273. }
  36274. ctx.closePath();
  36275. }
  36276. });
  36277. /*
  36278. * Licensed to the Apache Software Foundation (ASF) under one
  36279. * or more contributor license agreements. See the NOTICE file
  36280. * distributed with this work for additional information
  36281. * regarding copyright ownership. The ASF licenses this file
  36282. * to you under the Apache License, Version 2.0 (the
  36283. * "License"); you may not use this file except in compliance
  36284. * with the License. You may obtain a copy of the License at
  36285. *
  36286. * http://www.apache.org/licenses/LICENSE-2.0
  36287. *
  36288. * Unless required by applicable law or agreed to in writing,
  36289. * software distributed under the License is distributed on an
  36290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36291. * KIND, either express or implied. See the License for the
  36292. * specific language governing permissions and limitations
  36293. * under the License.
  36294. */
  36295. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  36296. var _eventPos = [0, 0];
  36297. // FIXME
  36298. // Just for compatible with ec2.
  36299. extend(Model.prototype, barItemStyle);
  36300. function getClipArea(coord, data) {
  36301. var coordSysClipArea = coord.getArea && coord.getArea();
  36302. if (coord.type === 'cartesian2d') {
  36303. var baseAxis = coord.getBaseAxis();
  36304. // When boundaryGap is false or using time axis. bar may exceed the grid.
  36305. // We should not clip this part.
  36306. // See test/bar2.html
  36307. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  36308. var expandWidth = data.getLayout('bandWidth');
  36309. if (baseAxis.isHorizontal()) {
  36310. coordSysClipArea.x -= expandWidth;
  36311. coordSysClipArea.width += expandWidth * 2;
  36312. }
  36313. else {
  36314. coordSysClipArea.y -= expandWidth;
  36315. coordSysClipArea.height += expandWidth * 2;
  36316. }
  36317. }
  36318. }
  36319. return coordSysClipArea;
  36320. }
  36321. extendChartView({
  36322. type: 'bar',
  36323. render: function (seriesModel, ecModel, api) {
  36324. this._updateDrawMode(seriesModel);
  36325. var coordinateSystemType = seriesModel.get('coordinateSystem');
  36326. if (coordinateSystemType === 'cartesian2d'
  36327. || coordinateSystemType === 'polar'
  36328. ) {
  36329. this._isLargeDraw
  36330. ? this._renderLarge(seriesModel, ecModel, api)
  36331. : this._renderNormal(seriesModel, ecModel, api);
  36332. }
  36333. else if (__DEV__) {
  36334. console.warn('Only cartesian2d and polar supported for bar.');
  36335. }
  36336. return this.group;
  36337. },
  36338. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36339. this._clear();
  36340. this._updateDrawMode(seriesModel);
  36341. },
  36342. incrementalRender: function (params, seriesModel, ecModel, api) {
  36343. // Do not support progressive in normal mode.
  36344. this._incrementalRenderLarge(params, seriesModel);
  36345. },
  36346. _updateDrawMode: function (seriesModel) {
  36347. var isLargeDraw = seriesModel.pipelineContext.large;
  36348. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  36349. this._isLargeDraw = isLargeDraw;
  36350. this._clear();
  36351. }
  36352. },
  36353. _renderNormal: function (seriesModel, ecModel, api) {
  36354. var group = this.group;
  36355. var data = seriesModel.getData();
  36356. var oldData = this._data;
  36357. var coord = seriesModel.coordinateSystem;
  36358. var baseAxis = coord.getBaseAxis();
  36359. var isHorizontalOrRadial;
  36360. if (coord.type === 'cartesian2d') {
  36361. isHorizontalOrRadial = baseAxis.isHorizontal();
  36362. }
  36363. else if (coord.type === 'polar') {
  36364. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36365. }
  36366. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  36367. var needsClip = seriesModel.get('clip', true);
  36368. var coordSysClipArea = getClipArea(coord, data);
  36369. // If there is clipPath created in large mode. Remove it.
  36370. group.removeClipPath();
  36371. // We don't use clipPath in normal mode because we needs a perfect animation
  36372. // And don't want the label are clipped.
  36373. var roundCap = seriesModel.get('roundCap', true);
  36374. data.diff(oldData)
  36375. .add(function (dataIndex) {
  36376. if (!data.hasValue(dataIndex)) {
  36377. return;
  36378. }
  36379. var itemModel = data.getItemModel(dataIndex);
  36380. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  36381. if (needsClip) {
  36382. // Clip will modify the layout params.
  36383. // And return a boolean to determine if the shape are fully clipped.
  36384. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36385. if (isClipped) {
  36386. group.remove(el);
  36387. return;
  36388. }
  36389. }
  36390. var el = elementCreator[coord.type](
  36391. dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap
  36392. );
  36393. data.setItemGraphicEl(dataIndex, el);
  36394. group.add(el);
  36395. updateStyle(
  36396. el, data, dataIndex, itemModel, layout,
  36397. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36398. );
  36399. })
  36400. .update(function (newIndex, oldIndex) {
  36401. var el = oldData.getItemGraphicEl(oldIndex);
  36402. if (!data.hasValue(newIndex)) {
  36403. group.remove(el);
  36404. return;
  36405. }
  36406. var itemModel = data.getItemModel(newIndex);
  36407. var layout = getLayout[coord.type](data, newIndex, itemModel);
  36408. if (needsClip) {
  36409. var isClipped = clip[coord.type](coordSysClipArea, layout);
  36410. if (isClipped) {
  36411. group.remove(el);
  36412. return;
  36413. }
  36414. }
  36415. if (el) {
  36416. updateProps(el, {shape: layout}, animationModel, newIndex);
  36417. }
  36418. else {
  36419. el = elementCreator[coord.type](
  36420. newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap
  36421. );
  36422. }
  36423. data.setItemGraphicEl(newIndex, el);
  36424. // Add back
  36425. group.add(el);
  36426. updateStyle(
  36427. el, data, newIndex, itemModel, layout,
  36428. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  36429. );
  36430. })
  36431. .remove(function (dataIndex) {
  36432. var el = oldData.getItemGraphicEl(dataIndex);
  36433. if (coord.type === 'cartesian2d') {
  36434. el && removeRect(dataIndex, animationModel, el);
  36435. }
  36436. else {
  36437. el && removeSector(dataIndex, animationModel, el);
  36438. }
  36439. })
  36440. .execute();
  36441. this._data = data;
  36442. },
  36443. _renderLarge: function (seriesModel, ecModel, api) {
  36444. this._clear();
  36445. createLarge(seriesModel, this.group);
  36446. // Use clipPath in large mode.
  36447. var clipPath = seriesModel.get('clip', true)
  36448. ? createClipPath(seriesModel.coordinateSystem, false, seriesModel)
  36449. : null;
  36450. if (clipPath) {
  36451. this.group.setClipPath(clipPath);
  36452. }
  36453. else {
  36454. this.group.removeClipPath();
  36455. }
  36456. },
  36457. _incrementalRenderLarge: function (params, seriesModel) {
  36458. createLarge(seriesModel, this.group, true);
  36459. },
  36460. dispose: noop,
  36461. remove: function (ecModel) {
  36462. this._clear(ecModel);
  36463. },
  36464. _clear: function (ecModel) {
  36465. var group = this.group;
  36466. var data = this._data;
  36467. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  36468. data.eachItemGraphicEl(function (el) {
  36469. if (el.type === 'sector') {
  36470. removeSector(el.dataIndex, ecModel, el);
  36471. }
  36472. else {
  36473. removeRect(el.dataIndex, ecModel, el);
  36474. }
  36475. });
  36476. }
  36477. else {
  36478. group.removeAll();
  36479. }
  36480. this._data = null;
  36481. }
  36482. });
  36483. var mathMax$4 = Math.max;
  36484. var mathMin$4 = Math.min;
  36485. var clip = {
  36486. cartesian2d: function (coordSysBoundingRect, layout) {
  36487. var signWidth = layout.width < 0 ? -1 : 1;
  36488. var signHeight = layout.height < 0 ? -1 : 1;
  36489. // Needs positive width and height
  36490. if (signWidth < 0) {
  36491. layout.x += layout.width;
  36492. layout.width = -layout.width;
  36493. }
  36494. if (signHeight < 0) {
  36495. layout.y += layout.height;
  36496. layout.height = -layout.height;
  36497. }
  36498. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  36499. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  36500. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  36501. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  36502. layout.x = x;
  36503. layout.y = y;
  36504. layout.width = x2 - x;
  36505. layout.height = y2 - y;
  36506. var clipped = layout.width < 0 || layout.height < 0;
  36507. // Reverse back
  36508. if (signWidth < 0) {
  36509. layout.x += layout.width;
  36510. layout.width = -layout.width;
  36511. }
  36512. if (signHeight < 0) {
  36513. layout.y += layout.height;
  36514. layout.height = -layout.height;
  36515. }
  36516. return clipped;
  36517. },
  36518. polar: function (coordSysClipArea) {
  36519. return false;
  36520. }
  36521. };
  36522. var elementCreator = {
  36523. cartesian2d: function (
  36524. dataIndex, layout, isHorizontal,
  36525. animationModel, isUpdate
  36526. ) {
  36527. var rect = new Rect({shape: extend({}, layout)});
  36528. // Animation
  36529. if (animationModel) {
  36530. var rectShape = rect.shape;
  36531. var animateProperty = isHorizontal ? 'height' : 'width';
  36532. var animateTarget = {};
  36533. rectShape[animateProperty] = 0;
  36534. animateTarget[animateProperty] = layout[animateProperty];
  36535. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  36536. shape: animateTarget
  36537. }, animationModel, dataIndex);
  36538. }
  36539. return rect;
  36540. },
  36541. polar: function (
  36542. dataIndex, layout, isRadial,
  36543. animationModel, isUpdate, roundCap
  36544. ) {
  36545. // Keep the same logic with bar in catesion: use end value to control
  36546. // direction. Notice that if clockwise is true (by default), the sector
  36547. // will always draw clockwisely, no matter whether endAngle is greater
  36548. // or less than startAngle.
  36549. var clockwise = layout.startAngle < layout.endAngle;
  36550. var ShapeClass = (!isRadial && roundCap) ? Sausage : Sector;
  36551. var sector = new ShapeClass({
  36552. shape: defaults({clockwise: clockwise}, layout)
  36553. });
  36554. // Animation
  36555. if (animationModel) {
  36556. var sectorShape = sector.shape;
  36557. var animateProperty = isRadial ? 'r' : 'endAngle';
  36558. var animateTarget = {};
  36559. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  36560. animateTarget[animateProperty] = layout[animateProperty];
  36561. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  36562. shape: animateTarget
  36563. }, animationModel, dataIndex);
  36564. }
  36565. return sector;
  36566. }
  36567. };
  36568. function removeRect(dataIndex, animationModel, el) {
  36569. // Not show text when animating
  36570. el.style.text = null;
  36571. updateProps(el, {
  36572. shape: {
  36573. width: 0
  36574. }
  36575. }, animationModel, dataIndex, function () {
  36576. el.parent && el.parent.remove(el);
  36577. });
  36578. }
  36579. function removeSector(dataIndex, animationModel, el) {
  36580. // Not show text when animating
  36581. el.style.text = null;
  36582. updateProps(el, {
  36583. shape: {
  36584. r: el.shape.r0
  36585. }
  36586. }, animationModel, dataIndex, function () {
  36587. el.parent && el.parent.remove(el);
  36588. });
  36589. }
  36590. var getLayout = {
  36591. cartesian2d: function (data, dataIndex, itemModel) {
  36592. var layout = data.getItemLayout(dataIndex);
  36593. var fixedLineWidth = getLineWidth(itemModel, layout);
  36594. // fix layout with lineWidth
  36595. var signX = layout.width > 0 ? 1 : -1;
  36596. var signY = layout.height > 0 ? 1 : -1;
  36597. return {
  36598. x: layout.x + signX * fixedLineWidth / 2,
  36599. y: layout.y + signY * fixedLineWidth / 2,
  36600. width: layout.width - signX * fixedLineWidth,
  36601. height: layout.height - signY * fixedLineWidth
  36602. };
  36603. },
  36604. polar: function (data, dataIndex, itemModel) {
  36605. var layout = data.getItemLayout(dataIndex);
  36606. return {
  36607. cx: layout.cx,
  36608. cy: layout.cy,
  36609. r0: layout.r0,
  36610. r: layout.r,
  36611. startAngle: layout.startAngle,
  36612. endAngle: layout.endAngle
  36613. };
  36614. }
  36615. };
  36616. function isZeroOnPolar(layout) {
  36617. return layout.startAngle != null
  36618. && layout.endAngle != null
  36619. && layout.startAngle === layout.endAngle;
  36620. }
  36621. function updateStyle(
  36622. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  36623. ) {
  36624. var color = data.getItemVisual(dataIndex, 'color');
  36625. var opacity = data.getItemVisual(dataIndex, 'opacity');
  36626. var stroke = data.getVisual('borderColor');
  36627. var itemStyleModel = itemModel.getModel('itemStyle');
  36628. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  36629. if (!isPolar) {
  36630. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  36631. }
  36632. el.useStyle(defaults(
  36633. {
  36634. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  36635. fill: isZeroOnPolar(layout) ? 'none' : color,
  36636. opacity: opacity
  36637. },
  36638. itemStyleModel.getBarItemStyle()
  36639. ));
  36640. var cursorStyle = itemModel.getShallow('cursor');
  36641. cursorStyle && el.attr('cursor', cursorStyle);
  36642. var labelPositionOutside = isHorizontal
  36643. ? (layout.height > 0 ? 'bottom' : 'top')
  36644. : (layout.width > 0 ? 'left' : 'right');
  36645. if (!isPolar) {
  36646. setLabel(
  36647. el.style, hoverStyle, itemModel, color,
  36648. seriesModel, dataIndex, labelPositionOutside
  36649. );
  36650. }
  36651. if (isZeroOnPolar(layout)) {
  36652. hoverStyle.fill = hoverStyle.stroke = 'none';
  36653. }
  36654. setHoverStyle(el, hoverStyle);
  36655. }
  36656. // In case width or height are too small.
  36657. function getLineWidth(itemModel, rawLayout) {
  36658. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  36659. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  36660. }
  36661. var LargePath = Path.extend({
  36662. type: 'largeBar',
  36663. shape: {points: []},
  36664. buildPath: function (ctx, shape) {
  36665. // Drawing lines is more efficient than drawing
  36666. // a whole line or drawing rects.
  36667. var points = shape.points;
  36668. var startPoint = this.__startPoint;
  36669. var baseDimIdx = this.__baseDimIdx;
  36670. for (var i = 0; i < points.length; i += 2) {
  36671. startPoint[baseDimIdx] = points[i + baseDimIdx];
  36672. ctx.moveTo(startPoint[0], startPoint[1]);
  36673. ctx.lineTo(points[i], points[i + 1]);
  36674. }
  36675. }
  36676. });
  36677. function createLarge(seriesModel, group, incremental) {
  36678. // TODO support polar
  36679. var data = seriesModel.getData();
  36680. var startPoint = [];
  36681. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  36682. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  36683. var el = new LargePath({
  36684. shape: {points: data.getLayout('largePoints')},
  36685. incremental: !!incremental,
  36686. __startPoint: startPoint,
  36687. __baseDimIdx: baseDimIdx,
  36688. __largeDataIndices: data.getLayout('largeDataIndices'),
  36689. __barWidth: data.getLayout('barWidth')
  36690. });
  36691. group.add(el);
  36692. setLargeStyle(el, seriesModel, data);
  36693. // Enable tooltip and user mouse/touch event handlers.
  36694. el.seriesIndex = seriesModel.seriesIndex;
  36695. if (!seriesModel.get('silent')) {
  36696. el.on('mousedown', largePathUpdateDataIndex);
  36697. el.on('mousemove', largePathUpdateDataIndex);
  36698. }
  36699. }
  36700. // Use throttle to avoid frequently traverse to find dataIndex.
  36701. var largePathUpdateDataIndex = throttle(function (event) {
  36702. var largePath = this;
  36703. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  36704. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  36705. }, 30, false);
  36706. function largePathFindDataIndex(largePath, x, y) {
  36707. var baseDimIdx = largePath.__baseDimIdx;
  36708. var valueDimIdx = 1 - baseDimIdx;
  36709. var points = largePath.shape.points;
  36710. var largeDataIndices = largePath.__largeDataIndices;
  36711. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  36712. var startValueVal = largePath.__startPoint[valueDimIdx];
  36713. _eventPos[0] = x;
  36714. _eventPos[1] = y;
  36715. var pointerBaseVal = _eventPos[baseDimIdx];
  36716. var pointerValueVal = _eventPos[1 - baseDimIdx];
  36717. var baseLowerBound = pointerBaseVal - barWidthHalf;
  36718. var baseUpperBound = pointerBaseVal + barWidthHalf;
  36719. for (var i = 0, len = points.length / 2; i < len; i++) {
  36720. var ii = i * 2;
  36721. var barBaseVal = points[ii + baseDimIdx];
  36722. var barValueVal = points[ii + valueDimIdx];
  36723. if (
  36724. barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound
  36725. && (
  36726. startValueVal <= barValueVal
  36727. ? (pointerValueVal >= startValueVal && pointerValueVal <= barValueVal)
  36728. : (pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)
  36729. )
  36730. ) {
  36731. return largeDataIndices[i];
  36732. }
  36733. }
  36734. return -1;
  36735. }
  36736. function setLargeStyle(el, seriesModel, data) {
  36737. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  36738. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  36739. el.useStyle(itemStyle);
  36740. el.style.fill = null;
  36741. el.style.stroke = borderColor;
  36742. el.style.lineWidth = data.getLayout('barWidth');
  36743. }
  36744. /*
  36745. * Licensed to the Apache Software Foundation (ASF) under one
  36746. * or more contributor license agreements. See the NOTICE file
  36747. * distributed with this work for additional information
  36748. * regarding copyright ownership. The ASF licenses this file
  36749. * to you under the Apache License, Version 2.0 (the
  36750. * "License"); you may not use this file except in compliance
  36751. * with the License. You may obtain a copy of the License at
  36752. *
  36753. * http://www.apache.org/licenses/LICENSE-2.0
  36754. *
  36755. * Unless required by applicable law or agreed to in writing,
  36756. * software distributed under the License is distributed on an
  36757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36758. * KIND, either express or implied. See the License for the
  36759. * specific language governing permissions and limitations
  36760. * under the License.
  36761. */
  36762. // In case developer forget to include grid component
  36763. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar'));
  36764. // Use higher prority to avoid to be blocked by other overall layout, which do not
  36765. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  36766. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  36767. registerVisual({
  36768. seriesType: 'bar',
  36769. reset: function (seriesModel) {
  36770. // Visual coding for legend
  36771. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  36772. }
  36773. });
  36774. /*
  36775. * Licensed to the Apache Software Foundation (ASF) under one
  36776. * or more contributor license agreements. See the NOTICE file
  36777. * distributed with this work for additional information
  36778. * regarding copyright ownership. The ASF licenses this file
  36779. * to you under the Apache License, Version 2.0 (the
  36780. * "License"); you may not use this file except in compliance
  36781. * with the License. You may obtain a copy of the License at
  36782. *
  36783. * http://www.apache.org/licenses/LICENSE-2.0
  36784. *
  36785. * Unless required by applicable law or agreed to in writing,
  36786. * software distributed under the License is distributed on an
  36787. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36788. * KIND, either express or implied. See the License for the
  36789. * specific language governing permissions and limitations
  36790. * under the License.
  36791. */
  36792. /**
  36793. * [Usage]:
  36794. * (1)
  36795. * createListSimply(seriesModel, ['value']);
  36796. * (2)
  36797. * createListSimply(seriesModel, {
  36798. * coordDimensions: ['value'],
  36799. * dimensionsCount: 5
  36800. * });
  36801. *
  36802. * @param {module:echarts/model/Series} seriesModel
  36803. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  36804. * The options in opt, see `echarts/data/helper/createDimensions`
  36805. * @param {Array.<string>} [nameList]
  36806. * @return {module:echarts/data/List}
  36807. */
  36808. var createListSimply = function (seriesModel, opt, nameList) {
  36809. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  36810. var source = seriesModel.getSource();
  36811. var dimensionsInfo = createDimensions(source, opt);
  36812. var list = new List(dimensionsInfo, seriesModel);
  36813. list.initData(source, nameList);
  36814. return list;
  36815. };
  36816. /*
  36817. * Licensed to the Apache Software Foundation (ASF) under one
  36818. * or more contributor license agreements. See the NOTICE file
  36819. * distributed with this work for additional information
  36820. * regarding copyright ownership. The ASF licenses this file
  36821. * to you under the Apache License, Version 2.0 (the
  36822. * "License"); you may not use this file except in compliance
  36823. * with the License. You may obtain a copy of the License at
  36824. *
  36825. * http://www.apache.org/licenses/LICENSE-2.0
  36826. *
  36827. * Unless required by applicable law or agreed to in writing,
  36828. * software distributed under the License is distributed on an
  36829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36830. * KIND, either express or implied. See the License for the
  36831. * specific language governing permissions and limitations
  36832. * under the License.
  36833. */
  36834. /**
  36835. * Data selectable mixin for chart series.
  36836. * To eanble data select, option of series must have `selectedMode`.
  36837. * And each data item will use `selected` to toggle itself selected status
  36838. */
  36839. var dataSelectableMixin = {
  36840. /**
  36841. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  36842. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  36843. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  36844. */
  36845. updateSelectedMap: function (targetList) {
  36846. this._targetList = isArray(targetList) ? targetList.slice() : [];
  36847. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  36848. targetMap.set(target.name, target);
  36849. return targetMap;
  36850. }, createHashMap());
  36851. },
  36852. /**
  36853. * Either name or id should be passed as input here.
  36854. * If both of them are defined, id is used.
  36855. *
  36856. * @param {string|undefined} name name of data
  36857. * @param {number|undefined} id dataIndex of data
  36858. */
  36859. // PENGING If selectedMode is null ?
  36860. select: function (name, id) {
  36861. var target = id != null
  36862. ? this._targetList[id]
  36863. : this._selectTargetMap.get(name);
  36864. var selectedMode = this.get('selectedMode');
  36865. if (selectedMode === 'single') {
  36866. this._selectTargetMap.each(function (target) {
  36867. target.selected = false;
  36868. });
  36869. }
  36870. target && (target.selected = true);
  36871. },
  36872. /**
  36873. * Either name or id should be passed as input here.
  36874. * If both of them are defined, id is used.
  36875. *
  36876. * @param {string|undefined} name name of data
  36877. * @param {number|undefined} id dataIndex of data
  36878. */
  36879. unSelect: function (name, id) {
  36880. var target = id != null
  36881. ? this._targetList[id]
  36882. : this._selectTargetMap.get(name);
  36883. // var selectedMode = this.get('selectedMode');
  36884. // selectedMode !== 'single' && target && (target.selected = false);
  36885. target && (target.selected = false);
  36886. },
  36887. /**
  36888. * Either name or id should be passed as input here.
  36889. * If both of them are defined, id is used.
  36890. *
  36891. * @param {string|undefined} name name of data
  36892. * @param {number|undefined} id dataIndex of data
  36893. */
  36894. toggleSelected: function (name, id) {
  36895. var target = id != null
  36896. ? this._targetList[id]
  36897. : this._selectTargetMap.get(name);
  36898. if (target != null) {
  36899. this[target.selected ? 'unSelect' : 'select'](name, id);
  36900. return target.selected;
  36901. }
  36902. },
  36903. /**
  36904. * Either name or id should be passed as input here.
  36905. * If both of them are defined, id is used.
  36906. *
  36907. * @param {string|undefined} name name of data
  36908. * @param {number|undefined} id dataIndex of data
  36909. */
  36910. isSelected: function (name, id) {
  36911. var target = id != null
  36912. ? this._targetList[id]
  36913. : this._selectTargetMap.get(name);
  36914. return target && target.selected;
  36915. }
  36916. };
  36917. /*
  36918. * Licensed to the Apache Software Foundation (ASF) under one
  36919. * or more contributor license agreements. See the NOTICE file
  36920. * distributed with this work for additional information
  36921. * regarding copyright ownership. The ASF licenses this file
  36922. * to you under the Apache License, Version 2.0 (the
  36923. * "License"); you may not use this file except in compliance
  36924. * with the License. You may obtain a copy of the License at
  36925. *
  36926. * http://www.apache.org/licenses/LICENSE-2.0
  36927. *
  36928. * Unless required by applicable law or agreed to in writing,
  36929. * software distributed under the License is distributed on an
  36930. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36931. * KIND, either express or implied. See the License for the
  36932. * specific language governing permissions and limitations
  36933. * under the License.
  36934. */
  36935. /**
  36936. * LegendVisualProvider is an bridge that pick encoded color from data and
  36937. * provide to the legend component.
  36938. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  36939. * @param {Function} getRawData Function to get raw data before filtered.
  36940. */
  36941. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  36942. this.getAllNames = function () {
  36943. var rawData = getRawData();
  36944. // We find the name from the raw data. In case it's filtered by the legend component.
  36945. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  36946. return rawData.mapArray(rawData.getName);
  36947. };
  36948. this.containName = function (name) {
  36949. var rawData = getRawData();
  36950. return rawData.indexOfName(name) >= 0;
  36951. };
  36952. this.indexOfName = function (name) {
  36953. // Only get data when necessary.
  36954. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  36955. // Invoking Series#getData immediately will throw an error.
  36956. var dataWithEncodedVisual = getDataWithEncodedVisual();
  36957. return dataWithEncodedVisual.indexOfName(name);
  36958. };
  36959. this.getItemVisual = function (dataIndex, key) {
  36960. // Get encoded visual properties from final filtered data.
  36961. var dataWithEncodedVisual = getDataWithEncodedVisual();
  36962. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  36963. };
  36964. }
  36965. /*
  36966. * Licensed to the Apache Software Foundation (ASF) under one
  36967. * or more contributor license agreements. See the NOTICE file
  36968. * distributed with this work for additional information
  36969. * regarding copyright ownership. The ASF licenses this file
  36970. * to you under the Apache License, Version 2.0 (the
  36971. * "License"); you may not use this file except in compliance
  36972. * with the License. You may obtain a copy of the License at
  36973. *
  36974. * http://www.apache.org/licenses/LICENSE-2.0
  36975. *
  36976. * Unless required by applicable law or agreed to in writing,
  36977. * software distributed under the License is distributed on an
  36978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36979. * KIND, either express or implied. See the License for the
  36980. * specific language governing permissions and limitations
  36981. * under the License.
  36982. */
  36983. var PieSeries = extendSeriesModel({
  36984. type: 'series.pie',
  36985. // Overwrite
  36986. init: function (option) {
  36987. PieSeries.superApply(this, 'init', arguments);
  36988. // Enable legend selection for each data item
  36989. // Use a function instead of direct access because data reference may changed
  36990. this.legendVisualProvider = new LegendVisualProvider(
  36991. bind(this.getData, this), bind(this.getRawData, this)
  36992. );
  36993. this.updateSelectedMap(this._createSelectableList());
  36994. this._defaultLabelLine(option);
  36995. },
  36996. // Overwrite
  36997. mergeOption: function (newOption) {
  36998. PieSeries.superCall(this, 'mergeOption', newOption);
  36999. this.updateSelectedMap(this._createSelectableList());
  37000. },
  37001. getInitialData: function (option, ecModel) {
  37002. return createListSimply(this, {
  37003. coordDimensions: ['value'],
  37004. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  37005. });
  37006. },
  37007. _createSelectableList: function () {
  37008. var data = this.getRawData();
  37009. var valueDim = data.mapDimension('value');
  37010. var targetList = [];
  37011. for (var i = 0, len = data.count(); i < len; i++) {
  37012. targetList.push({
  37013. name: data.getName(i),
  37014. value: data.get(valueDim, i),
  37015. selected: retrieveRawAttr(data, i, 'selected')
  37016. });
  37017. }
  37018. return targetList;
  37019. },
  37020. // Overwrite
  37021. getDataParams: function (dataIndex) {
  37022. var data = this.getData();
  37023. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  37024. // FIXME toFixed?
  37025. var valueList = [];
  37026. data.each(data.mapDimension('value'), function (value) {
  37027. valueList.push(value);
  37028. });
  37029. params.percent = getPercentWithPrecision(
  37030. valueList,
  37031. dataIndex,
  37032. data.hostModel.get('percentPrecision')
  37033. );
  37034. params.$vars.push('percent');
  37035. return params;
  37036. },
  37037. _defaultLabelLine: function (option) {
  37038. // Extend labelLine emphasis
  37039. defaultEmphasis(option, 'labelLine', ['show']);
  37040. var labelLineNormalOpt = option.labelLine;
  37041. var labelLineEmphasisOpt = option.emphasis.labelLine;
  37042. // Not show label line if `label.normal.show = false`
  37043. labelLineNormalOpt.show = labelLineNormalOpt.show
  37044. && option.label.show;
  37045. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  37046. && option.emphasis.label.show;
  37047. },
  37048. defaultOption: {
  37049. zlevel: 0,
  37050. z: 2,
  37051. legendHoverLink: true,
  37052. hoverAnimation: true,
  37053. // 默认全局居中
  37054. center: ['50%', '50%'],
  37055. radius: [0, '75%'],
  37056. // 默认顺时针
  37057. clockwise: true,
  37058. startAngle: 90,
  37059. // 最小角度改为0
  37060. minAngle: 0,
  37061. // If the angle of a sector less than `minShowLabelAngle`,
  37062. // the label will not be displayed.
  37063. minShowLabelAngle: 0,
  37064. // 选中时扇区偏移量
  37065. selectedOffset: 10,
  37066. // 高亮扇区偏移量
  37067. hoverOffset: 10,
  37068. // If use strategy to avoid label overlapping
  37069. avoidLabelOverlap: true,
  37070. // 选择模式,默认关闭,可选single,multiple
  37071. // selectedMode: false,
  37072. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  37073. // roseType: null,
  37074. percentPrecision: 2,
  37075. // If still show when all data zero.
  37076. stillShowZeroSum: true,
  37077. // cursor: null,
  37078. left: 0,
  37079. top: 0,
  37080. right: 0,
  37081. bottom: 0,
  37082. width: null,
  37083. height: null,
  37084. label: {
  37085. // If rotate around circle
  37086. rotate: false,
  37087. show: true,
  37088. // 'outer', 'inside', 'center'
  37089. position: 'outer',
  37090. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  37091. alignTo: 'none',
  37092. // Closest distance between label and chart edge.
  37093. // Works only position is 'outer' and alignTo is 'edge'.
  37094. margin: '25%',
  37095. // Works only position is 'outer' and alignTo is not 'edge'.
  37096. bleedMargin: 10,
  37097. // Distance between text and label line.
  37098. distanceToLabelLine: 5
  37099. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  37100. // 默认使用全局文本样式,详见TEXTSTYLE
  37101. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  37102. },
  37103. // Enabled when label.normal.position is 'outer'
  37104. labelLine: {
  37105. show: true,
  37106. // 引导线两段中的第一段长度
  37107. length: 15,
  37108. // 引导线两段中的第二段长度
  37109. length2: 15,
  37110. smooth: false,
  37111. lineStyle: {
  37112. // color: 各异,
  37113. width: 1,
  37114. type: 'solid'
  37115. }
  37116. },
  37117. itemStyle: {
  37118. borderWidth: 1
  37119. },
  37120. // Animation type. Valid values: expansion, scale
  37121. animationType: 'expansion',
  37122. // Animation type when update. Valid values: transition, expansion
  37123. animationTypeUpdate: 'transition',
  37124. animationEasing: 'cubicOut'
  37125. }
  37126. });
  37127. mixin(PieSeries, dataSelectableMixin);
  37128. /*
  37129. * Licensed to the Apache Software Foundation (ASF) under one
  37130. * or more contributor license agreements. See the NOTICE file
  37131. * distributed with this work for additional information
  37132. * regarding copyright ownership. The ASF licenses this file
  37133. * to you under the Apache License, Version 2.0 (the
  37134. * "License"); you may not use this file except in compliance
  37135. * with the License. You may obtain a copy of the License at
  37136. *
  37137. * http://www.apache.org/licenses/LICENSE-2.0
  37138. *
  37139. * Unless required by applicable law or agreed to in writing,
  37140. * software distributed under the License is distributed on an
  37141. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37142. * KIND, either express or implied. See the License for the
  37143. * specific language governing permissions and limitations
  37144. * under the License.
  37145. */
  37146. /**
  37147. * @param {module:echarts/model/Series} seriesModel
  37148. * @param {boolean} hasAnimation
  37149. * @inner
  37150. */
  37151. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  37152. var data = seriesModel.getData();
  37153. var dataIndex = this.dataIndex;
  37154. var name = data.getName(dataIndex);
  37155. var selectedOffset = seriesModel.get('selectedOffset');
  37156. api.dispatchAction({
  37157. type: 'pieToggleSelect',
  37158. from: uid,
  37159. name: name,
  37160. seriesId: seriesModel.id
  37161. });
  37162. data.each(function (idx) {
  37163. toggleItemSelected(
  37164. data.getItemGraphicEl(idx),
  37165. data.getItemLayout(idx),
  37166. seriesModel.isSelected(data.getName(idx)),
  37167. selectedOffset,
  37168. hasAnimation
  37169. );
  37170. });
  37171. }
  37172. /**
  37173. * @param {module:zrender/graphic/Sector} el
  37174. * @param {Object} layout
  37175. * @param {boolean} isSelected
  37176. * @param {number} selectedOffset
  37177. * @param {boolean} hasAnimation
  37178. * @inner
  37179. */
  37180. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  37181. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37182. var dx = Math.cos(midAngle);
  37183. var dy = Math.sin(midAngle);
  37184. var offset = isSelected ? selectedOffset : 0;
  37185. var position = [dx * offset, dy * offset];
  37186. hasAnimation
  37187. // animateTo will stop revious animation like update transition
  37188. ? el.animate()
  37189. .when(200, {
  37190. position: position
  37191. })
  37192. .start('bounceOut')
  37193. : el.attr('position', position);
  37194. }
  37195. /**
  37196. * Piece of pie including Sector, Label, LabelLine
  37197. * @constructor
  37198. * @extends {module:zrender/graphic/Group}
  37199. */
  37200. function PiePiece(data, idx) {
  37201. Group.call(this);
  37202. var sector = new Sector({
  37203. z2: 2
  37204. });
  37205. var polyline = new Polyline();
  37206. var text = new Text();
  37207. this.add(sector);
  37208. this.add(polyline);
  37209. this.add(text);
  37210. this.updateData(data, idx, true);
  37211. }
  37212. var piePieceProto = PiePiece.prototype;
  37213. piePieceProto.updateData = function (data, idx, firstCreate) {
  37214. var sector = this.childAt(0);
  37215. var labelLine = this.childAt(1);
  37216. var labelText = this.childAt(2);
  37217. var seriesModel = data.hostModel;
  37218. var itemModel = data.getItemModel(idx);
  37219. var layout = data.getItemLayout(idx);
  37220. var sectorShape = extend({}, layout);
  37221. sectorShape.label = null;
  37222. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  37223. if (firstCreate) {
  37224. sector.setShape(sectorShape);
  37225. var animationType = seriesModel.getShallow('animationType');
  37226. if (animationType === 'scale') {
  37227. sector.shape.r = layout.r0;
  37228. initProps(sector, {
  37229. shape: {
  37230. r: layout.r
  37231. }
  37232. }, seriesModel, idx);
  37233. }
  37234. // Expansion
  37235. else {
  37236. sector.shape.endAngle = layout.startAngle;
  37237. updateProps(sector, {
  37238. shape: {
  37239. endAngle: layout.endAngle
  37240. }
  37241. }, seriesModel, idx);
  37242. }
  37243. }
  37244. else {
  37245. if (animationTypeUpdate === 'expansion') {
  37246. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  37247. sector.setShape(sectorShape);
  37248. }
  37249. else {
  37250. // Transition animation from the old shape
  37251. updateProps(sector, {
  37252. shape: sectorShape
  37253. }, seriesModel, idx);
  37254. }
  37255. }
  37256. // Update common style
  37257. var visualColor = data.getItemVisual(idx, 'color');
  37258. sector.useStyle(
  37259. defaults(
  37260. {
  37261. lineJoin: 'bevel',
  37262. fill: visualColor
  37263. },
  37264. itemModel.getModel('itemStyle').getItemStyle()
  37265. )
  37266. );
  37267. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  37268. var cursorStyle = itemModel.getShallow('cursor');
  37269. cursorStyle && sector.attr('cursor', cursorStyle);
  37270. // Toggle selected
  37271. toggleItemSelected(
  37272. this,
  37273. data.getItemLayout(idx),
  37274. seriesModel.isSelected(null, idx),
  37275. seriesModel.get('selectedOffset'),
  37276. seriesModel.get('animation')
  37277. );
  37278. // Label and text animation should be applied only for transition type animation when update
  37279. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  37280. this._updateLabel(data, idx, withAnimation);
  37281. this.highDownOnUpdate = (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled())
  37282. ? function (fromState, toState) {
  37283. if (toState === 'emphasis') {
  37284. labelLine.ignore = labelLine.hoverIgnore;
  37285. labelText.ignore = labelText.hoverIgnore;
  37286. // Sector may has animation of updating data. Force to move to the last frame
  37287. // Or it may stopped on the wrong shape
  37288. sector.stopAnimation(true);
  37289. sector.animateTo({
  37290. shape: {
  37291. r: layout.r + seriesModel.get('hoverOffset')
  37292. }
  37293. }, 300, 'elasticOut');
  37294. }
  37295. else {
  37296. labelLine.ignore = labelLine.normalIgnore;
  37297. labelText.ignore = labelText.normalIgnore;
  37298. sector.stopAnimation(true);
  37299. sector.animateTo({
  37300. shape: {
  37301. r: layout.r
  37302. }
  37303. }, 300, 'elasticOut');
  37304. }
  37305. }
  37306. : null;
  37307. setHoverStyle(this);
  37308. };
  37309. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  37310. var labelLine = this.childAt(1);
  37311. var labelText = this.childAt(2);
  37312. var seriesModel = data.hostModel;
  37313. var itemModel = data.getItemModel(idx);
  37314. var layout = data.getItemLayout(idx);
  37315. var labelLayout = layout.label;
  37316. var visualColor = data.getItemVisual(idx, 'color');
  37317. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  37318. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore =
  37319. labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  37320. return;
  37321. }
  37322. var targetLineShape = {
  37323. points: labelLayout.linePoints || [
  37324. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  37325. ]
  37326. };
  37327. var targetTextStyle = {
  37328. x: labelLayout.x,
  37329. y: labelLayout.y
  37330. };
  37331. if (withAnimation) {
  37332. updateProps(labelLine, {
  37333. shape: targetLineShape
  37334. }, seriesModel, idx);
  37335. updateProps(labelText, {
  37336. style: targetTextStyle
  37337. }, seriesModel, idx);
  37338. }
  37339. else {
  37340. labelLine.attr({
  37341. shape: targetLineShape
  37342. });
  37343. labelText.attr({
  37344. style: targetTextStyle
  37345. });
  37346. }
  37347. labelText.attr({
  37348. rotation: labelLayout.rotation,
  37349. origin: [labelLayout.x, labelLayout.y],
  37350. z2: 10
  37351. });
  37352. var labelModel = itemModel.getModel('label');
  37353. var labelHoverModel = itemModel.getModel('emphasis.label');
  37354. var labelLineModel = itemModel.getModel('labelLine');
  37355. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  37356. var visualColor = data.getItemVisual(idx, 'color');
  37357. setLabelStyle(
  37358. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  37359. {
  37360. labelFetcher: data.hostModel,
  37361. labelDataIndex: idx,
  37362. defaultText: labelLayout.text,
  37363. autoColor: visualColor,
  37364. useInsideStyle: !!labelLayout.inside
  37365. },
  37366. {
  37367. textAlign: labelLayout.textAlign,
  37368. textVerticalAlign: labelLayout.verticalAlign,
  37369. opacity: data.getItemVisual(idx, 'opacity')
  37370. }
  37371. );
  37372. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  37373. labelText.hoverIgnore = !labelHoverModel.get('show');
  37374. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  37375. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  37376. // Default use item visual color
  37377. labelLine.setStyle({
  37378. stroke: visualColor,
  37379. opacity: data.getItemVisual(idx, 'opacity')
  37380. });
  37381. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  37382. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  37383. var smooth = labelLineModel.get('smooth');
  37384. if (smooth && smooth === true) {
  37385. smooth = 0.4;
  37386. }
  37387. labelLine.setShape({
  37388. smooth: smooth
  37389. });
  37390. };
  37391. inherits(PiePiece, Group);
  37392. // Pie view
  37393. var PieView = Chart.extend({
  37394. type: 'pie',
  37395. init: function () {
  37396. var sectorGroup = new Group();
  37397. this._sectorGroup = sectorGroup;
  37398. },
  37399. render: function (seriesModel, ecModel, api, payload) {
  37400. if (payload && (payload.from === this.uid)) {
  37401. return;
  37402. }
  37403. var data = seriesModel.getData();
  37404. var oldData = this._data;
  37405. var group = this.group;
  37406. var hasAnimation = ecModel.get('animation');
  37407. var isFirstRender = !oldData;
  37408. var animationType = seriesModel.get('animationType');
  37409. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  37410. var onSectorClick = curry(
  37411. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  37412. );
  37413. var selectedMode = seriesModel.get('selectedMode');
  37414. data.diff(oldData)
  37415. .add(function (idx) {
  37416. var piePiece = new PiePiece(data, idx);
  37417. // Default expansion animation
  37418. if (isFirstRender && animationType !== 'scale') {
  37419. piePiece.eachChild(function (child) {
  37420. child.stopAnimation(true);
  37421. });
  37422. }
  37423. selectedMode && piePiece.on('click', onSectorClick);
  37424. data.setItemGraphicEl(idx, piePiece);
  37425. group.add(piePiece);
  37426. })
  37427. .update(function (newIdx, oldIdx) {
  37428. var piePiece = oldData.getItemGraphicEl(oldIdx);
  37429. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  37430. piePiece.eachChild(function (child) {
  37431. child.stopAnimation(true);
  37432. });
  37433. }
  37434. piePiece.updateData(data, newIdx);
  37435. piePiece.off('click');
  37436. selectedMode && piePiece.on('click', onSectorClick);
  37437. group.add(piePiece);
  37438. data.setItemGraphicEl(newIdx, piePiece);
  37439. })
  37440. .remove(function (idx) {
  37441. var piePiece = oldData.getItemGraphicEl(idx);
  37442. group.remove(piePiece);
  37443. })
  37444. .execute();
  37445. if (
  37446. hasAnimation && data.count() > 0
  37447. && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')
  37448. ) {
  37449. var shape = data.getItemLayout(0);
  37450. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  37451. shape = data.getItemLayout(s);
  37452. }
  37453. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  37454. var removeClipPath = bind(group.removeClipPath, group);
  37455. group.setClipPath(this._createClipPath(
  37456. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender
  37457. ));
  37458. }
  37459. else {
  37460. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  37461. group.removeClipPath();
  37462. }
  37463. this._data = data;
  37464. },
  37465. dispose: function () {},
  37466. _createClipPath: function (
  37467. cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender
  37468. ) {
  37469. var clipPath = new Sector({
  37470. shape: {
  37471. cx: cx,
  37472. cy: cy,
  37473. r0: 0,
  37474. r: r,
  37475. startAngle: startAngle,
  37476. endAngle: startAngle,
  37477. clockwise: clockwise
  37478. }
  37479. });
  37480. var initOrUpdate = isFirstRender ? initProps : updateProps;
  37481. initOrUpdate(clipPath, {
  37482. shape: {
  37483. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  37484. }
  37485. }, seriesModel, cb);
  37486. return clipPath;
  37487. },
  37488. /**
  37489. * @implement
  37490. */
  37491. containPoint: function (point, seriesModel) {
  37492. var data = seriesModel.getData();
  37493. var itemLayout = data.getItemLayout(0);
  37494. if (itemLayout) {
  37495. var dx = point[0] - itemLayout.cx;
  37496. var dy = point[1] - itemLayout.cy;
  37497. var radius = Math.sqrt(dx * dx + dy * dy);
  37498. return radius <= itemLayout.r && radius >= itemLayout.r0;
  37499. }
  37500. }
  37501. });
  37502. /*
  37503. * Licensed to the Apache Software Foundation (ASF) under one
  37504. * or more contributor license agreements. See the NOTICE file
  37505. * distributed with this work for additional information
  37506. * regarding copyright ownership. The ASF licenses this file
  37507. * to you under the Apache License, Version 2.0 (the
  37508. * "License"); you may not use this file except in compliance
  37509. * with the License. You may obtain a copy of the License at
  37510. *
  37511. * http://www.apache.org/licenses/LICENSE-2.0
  37512. *
  37513. * Unless required by applicable law or agreed to in writing,
  37514. * software distributed under the License is distributed on an
  37515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37516. * KIND, either express or implied. See the License for the
  37517. * specific language governing permissions and limitations
  37518. * under the License.
  37519. */
  37520. var createDataSelectAction = function (seriesType, actionInfos) {
  37521. each$1(actionInfos, function (actionInfo) {
  37522. actionInfo.update = 'updateView';
  37523. /**
  37524. * @payload
  37525. * @property {string} seriesName
  37526. * @property {string} name
  37527. */
  37528. registerAction(actionInfo, function (payload, ecModel) {
  37529. var selected = {};
  37530. ecModel.eachComponent(
  37531. {mainType: 'series', subType: seriesType, query: payload},
  37532. function (seriesModel) {
  37533. if (seriesModel[actionInfo.method]) {
  37534. seriesModel[actionInfo.method](
  37535. payload.name,
  37536. payload.dataIndex
  37537. );
  37538. }
  37539. var data = seriesModel.getData();
  37540. // Create selected map
  37541. data.each(function (idx) {
  37542. var name = data.getName(idx);
  37543. selected[name] = seriesModel.isSelected(name)
  37544. || false;
  37545. });
  37546. }
  37547. );
  37548. return {
  37549. name: payload.name,
  37550. selected: selected,
  37551. seriesId: payload.seriesId
  37552. };
  37553. });
  37554. });
  37555. };
  37556. /*
  37557. * Licensed to the Apache Software Foundation (ASF) under one
  37558. * or more contributor license agreements. See the NOTICE file
  37559. * distributed with this work for additional information
  37560. * regarding copyright ownership. The ASF licenses this file
  37561. * to you under the Apache License, Version 2.0 (the
  37562. * "License"); you may not use this file except in compliance
  37563. * with the License. You may obtain a copy of the License at
  37564. *
  37565. * http://www.apache.org/licenses/LICENSE-2.0
  37566. *
  37567. * Unless required by applicable law or agreed to in writing,
  37568. * software distributed under the License is distributed on an
  37569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37570. * KIND, either express or implied. See the License for the
  37571. * specific language governing permissions and limitations
  37572. * under the License.
  37573. */
  37574. // Pick color from palette for each data item.
  37575. // Applicable for charts that require applying color palette
  37576. // in data level (like pie, funnel, chord).
  37577. var dataColor = function (seriesType) {
  37578. return {
  37579. getTargetSeries: function (ecModel) {
  37580. // Pie and funnel may use diferrent scope
  37581. var paletteScope = {};
  37582. var seiresModelMap = createHashMap();
  37583. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37584. seriesModel.__paletteScope = paletteScope;
  37585. seiresModelMap.set(seriesModel.uid, seriesModel);
  37586. });
  37587. return seiresModelMap;
  37588. },
  37589. reset: function (seriesModel, ecModel) {
  37590. var dataAll = seriesModel.getRawData();
  37591. var idxMap = {};
  37592. var data = seriesModel.getData();
  37593. data.each(function (idx) {
  37594. var rawIdx = data.getRawIndex(idx);
  37595. idxMap[rawIdx] = idx;
  37596. });
  37597. dataAll.each(function (rawIdx) {
  37598. var filteredIdx = idxMap[rawIdx];
  37599. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  37600. var singleDataColor = filteredIdx != null
  37601. && data.getItemVisual(filteredIdx, 'color', true);
  37602. var singleDataBorderColor = filteredIdx != null
  37603. && data.getItemVisual(filteredIdx, 'borderColor', true);
  37604. var itemModel;
  37605. if (!singleDataColor || !singleDataBorderColor) {
  37606. // FIXME Performance
  37607. itemModel = dataAll.getItemModel(rawIdx);
  37608. }
  37609. if (!singleDataColor) {
  37610. var color = itemModel.get('itemStyle.color')
  37611. || seriesModel.getColorFromPalette(
  37612. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  37613. dataAll.count()
  37614. );
  37615. // Data is not filtered
  37616. if (filteredIdx != null) {
  37617. data.setItemVisual(filteredIdx, 'color', color);
  37618. }
  37619. }
  37620. if (!singleDataBorderColor) {
  37621. var borderColor = itemModel.get('itemStyle.borderColor');
  37622. // Data is not filtered
  37623. if (filteredIdx != null) {
  37624. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  37625. }
  37626. }
  37627. });
  37628. }
  37629. };
  37630. };
  37631. /*
  37632. * Licensed to the Apache Software Foundation (ASF) under one
  37633. * or more contributor license agreements. See the NOTICE file
  37634. * distributed with this work for additional information
  37635. * regarding copyright ownership. The ASF licenses this file
  37636. * to you under the Apache License, Version 2.0 (the
  37637. * "License"); you may not use this file except in compliance
  37638. * with the License. You may obtain a copy of the License at
  37639. *
  37640. * http://www.apache.org/licenses/LICENSE-2.0
  37641. *
  37642. * Unless required by applicable law or agreed to in writing,
  37643. * software distributed under the License is distributed on an
  37644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37645. * KIND, either express or implied. See the License for the
  37646. * specific language governing permissions and limitations
  37647. * under the License.
  37648. */
  37649. // FIXME emphasis label position is not same with normal label position
  37650. var RADIAN$1 = Math.PI / 180;
  37651. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  37652. list.sort(function (a, b) {
  37653. return a.y - b.y;
  37654. });
  37655. function shiftDown(start, end, delta, dir) {
  37656. for (var j = start; j < end; j++) {
  37657. if (list[j].y + delta > viewTop + viewHeight) {
  37658. break;
  37659. }
  37660. list[j].y += delta;
  37661. if (j > start
  37662. && j + 1 < end
  37663. && list[j + 1].y > list[j].y + list[j].height
  37664. ) {
  37665. shiftUp(j, delta / 2);
  37666. return;
  37667. }
  37668. }
  37669. shiftUp(end - 1, delta / 2);
  37670. }
  37671. function shiftUp(end, delta) {
  37672. for (var j = end; j >= 0; j--) {
  37673. if (list[j].y - delta < viewTop) {
  37674. break;
  37675. }
  37676. list[j].y -= delta;
  37677. if (j > 0
  37678. && list[j].y > list[j - 1].y + list[j - 1].height
  37679. ) {
  37680. break;
  37681. }
  37682. }
  37683. }
  37684. function changeX(list, isDownList, cx, cy, r, dir) {
  37685. var lastDeltaX = dir > 0
  37686. ? isDownList // right-side
  37687. ? Number.MAX_VALUE // down
  37688. : 0 // up
  37689. : isDownList // left-side
  37690. ? Number.MAX_VALUE // down
  37691. : 0; // up
  37692. for (var i = 0, l = list.length; i < l; i++) {
  37693. if (list[i].labelAlignTo !== 'none') {
  37694. continue;
  37695. }
  37696. var deltaY = Math.abs(list[i].y - cy);
  37697. var length = list[i].len;
  37698. var length2 = list[i].len2;
  37699. var deltaX = (deltaY < r + length)
  37700. ? Math.sqrt(
  37701. (r + length + length2) * (r + length + length2)
  37702. - deltaY * deltaY
  37703. )
  37704. : Math.abs(list[i].x - cx);
  37705. if (isDownList && deltaX >= lastDeltaX) {
  37706. // right-down, left-down
  37707. deltaX = lastDeltaX - 10;
  37708. }
  37709. if (!isDownList && deltaX <= lastDeltaX) {
  37710. // right-up, left-up
  37711. deltaX = lastDeltaX + 10;
  37712. }
  37713. list[i].x = cx + deltaX * dir;
  37714. lastDeltaX = deltaX;
  37715. }
  37716. }
  37717. var lastY = 0;
  37718. var delta;
  37719. var len = list.length;
  37720. var upList = [];
  37721. var downList = [];
  37722. for (var i = 0; i < len; i++) {
  37723. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  37724. var dx = list[i].x - farthestX;
  37725. list[i].linePoints[1][0] += dx;
  37726. list[i].x = farthestX;
  37727. }
  37728. delta = list[i].y - lastY;
  37729. if (delta < 0) {
  37730. shiftDown(i, len, -delta, dir);
  37731. }
  37732. lastY = list[i].y + list[i].height;
  37733. }
  37734. if (viewHeight - lastY < 0) {
  37735. shiftUp(len - 1, lastY - viewHeight);
  37736. }
  37737. for (var i = 0; i < len; i++) {
  37738. if (list[i].y >= cy) {
  37739. downList.push(list[i]);
  37740. }
  37741. else {
  37742. upList.push(list[i]);
  37743. }
  37744. }
  37745. changeX(upList, false, cx, cy, r, dir);
  37746. changeX(downList, true, cx, cy, r, dir);
  37747. }
  37748. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37749. var leftList = [];
  37750. var rightList = [];
  37751. var leftmostX = Number.MAX_VALUE;
  37752. var rightmostX = -Number.MAX_VALUE;
  37753. for (var i = 0; i < labelLayoutList.length; i++) {
  37754. if (isPositionCenter(labelLayoutList[i])) {
  37755. continue;
  37756. }
  37757. if (labelLayoutList[i].x < cx) {
  37758. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  37759. leftList.push(labelLayoutList[i]);
  37760. }
  37761. else {
  37762. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  37763. rightList.push(labelLayoutList[i]);
  37764. }
  37765. }
  37766. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  37767. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  37768. for (var i = 0; i < labelLayoutList.length; i++) {
  37769. var layout = labelLayoutList[i];
  37770. if (isPositionCenter(layout)) {
  37771. continue;
  37772. }
  37773. var linePoints = layout.linePoints;
  37774. if (linePoints) {
  37775. var isAlignToEdge = layout.labelAlignTo === 'edge';
  37776. var realTextWidth = layout.textRect.width;
  37777. var targetTextWidth;
  37778. if (isAlignToEdge) {
  37779. if (layout.x < cx) {
  37780. targetTextWidth = linePoints[2][0] - layout.labelDistance
  37781. - viewLeft - layout.labelMargin;
  37782. }
  37783. else {
  37784. targetTextWidth = viewLeft + viewWidth - layout.labelMargin
  37785. - linePoints[2][0] - layout.labelDistance;
  37786. }
  37787. }
  37788. else {
  37789. if (layout.x < cx) {
  37790. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  37791. }
  37792. else {
  37793. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  37794. }
  37795. }
  37796. if (targetTextWidth < layout.textRect.width) {
  37797. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  37798. if (layout.labelAlignTo === 'edge') {
  37799. realTextWidth = getWidth(layout.text, layout.font);
  37800. }
  37801. }
  37802. var dist = linePoints[1][0] - linePoints[2][0];
  37803. if (isAlignToEdge) {
  37804. if (layout.x < cx) {
  37805. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  37806. }
  37807. else {
  37808. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin
  37809. - realTextWidth - layout.labelDistance;
  37810. }
  37811. }
  37812. else {
  37813. if (layout.x < cx) {
  37814. linePoints[2][0] = layout.x + layout.labelDistance;
  37815. }
  37816. else {
  37817. linePoints[2][0] = layout.x - layout.labelDistance;
  37818. }
  37819. linePoints[1][0] = linePoints[2][0] + dist;
  37820. }
  37821. linePoints[1][1] = linePoints[2][1] = layout.y;
  37822. }
  37823. }
  37824. }
  37825. function isPositionCenter(layout) {
  37826. // Not change x for center label
  37827. return layout.position === 'center';
  37828. }
  37829. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  37830. var data = seriesModel.getData();
  37831. var labelLayoutList = [];
  37832. var cx;
  37833. var cy;
  37834. var hasLabelRotate = false;
  37835. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  37836. data.each(function (idx) {
  37837. var layout = data.getItemLayout(idx);
  37838. var itemModel = data.getItemModel(idx);
  37839. var labelModel = itemModel.getModel('label');
  37840. // Use position in normal or emphasis
  37841. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  37842. var labelDistance = labelModel.get('distanceToLabelLine');
  37843. var labelAlignTo = labelModel.get('alignTo');
  37844. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  37845. var bleedMargin = labelModel.get('bleedMargin');
  37846. var font = labelModel.getFont();
  37847. var labelLineModel = itemModel.getModel('labelLine');
  37848. var labelLineLen = labelLineModel.get('length');
  37849. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  37850. var labelLineLen2 = labelLineModel.get('length2');
  37851. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  37852. if (layout.angle < minShowLabelRadian) {
  37853. return;
  37854. }
  37855. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  37856. var dx = Math.cos(midAngle);
  37857. var dy = Math.sin(midAngle);
  37858. var textX;
  37859. var textY;
  37860. var linePoints;
  37861. var textAlign;
  37862. cx = layout.cx;
  37863. cy = layout.cy;
  37864. var text = seriesModel.getFormattedLabel(idx, 'normal')
  37865. || data.getName(idx);
  37866. var textRect = getBoundingRect(
  37867. text, font, textAlign, 'top'
  37868. );
  37869. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  37870. if (labelPosition === 'center') {
  37871. textX = layout.cx;
  37872. textY = layout.cy;
  37873. textAlign = 'center';
  37874. }
  37875. else {
  37876. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  37877. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  37878. textX = x1 + dx * 3;
  37879. textY = y1 + dy * 3;
  37880. if (!isLabelInside) {
  37881. // For roseType
  37882. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  37883. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  37884. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  37885. var y3 = y2;
  37886. if (labelAlignTo === 'edge') {
  37887. // Adjust textX because text align of edge is opposite
  37888. textX = dx < 0
  37889. ? viewLeft + labelMargin
  37890. : viewLeft + viewWidth - labelMargin;
  37891. }
  37892. else {
  37893. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  37894. }
  37895. textY = y3;
  37896. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  37897. }
  37898. textAlign = isLabelInside
  37899. ? 'center'
  37900. : (labelAlignTo === 'edge'
  37901. ? (dx > 0 ? 'right' : 'left')
  37902. : (dx > 0 ? 'left' : 'right'));
  37903. }
  37904. var labelRotate;
  37905. var rotate = labelModel.get('rotate');
  37906. if (typeof rotate === 'number') {
  37907. labelRotate = rotate * (Math.PI / 180);
  37908. }
  37909. else {
  37910. labelRotate = rotate
  37911. ? (dx < 0 ? -midAngle + Math.PI : -midAngle)
  37912. : 0;
  37913. }
  37914. hasLabelRotate = !!labelRotate;
  37915. layout.label = {
  37916. x: textX,
  37917. y: textY,
  37918. position: labelPosition,
  37919. height: textRect.height,
  37920. len: labelLineLen,
  37921. len2: labelLineLen2,
  37922. linePoints: linePoints,
  37923. textAlign: textAlign,
  37924. verticalAlign: 'middle',
  37925. rotation: labelRotate,
  37926. inside: isLabelInside,
  37927. labelDistance: labelDistance,
  37928. labelAlignTo: labelAlignTo,
  37929. labelMargin:labelMargin,
  37930. bleedMargin: bleedMargin,
  37931. textRect: textRect,
  37932. text: text,
  37933. font: font
  37934. };
  37935. // Not layout the inside label
  37936. if (!isLabelInside) {
  37937. labelLayoutList.push(layout.label);
  37938. }
  37939. });
  37940. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  37941. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  37942. }
  37943. };
  37944. /*
  37945. * Licensed to the Apache Software Foundation (ASF) under one
  37946. * or more contributor license agreements. See the NOTICE file
  37947. * distributed with this work for additional information
  37948. * regarding copyright ownership. The ASF licenses this file
  37949. * to you under the Apache License, Version 2.0 (the
  37950. * "License"); you may not use this file except in compliance
  37951. * with the License. You may obtain a copy of the License at
  37952. *
  37953. * http://www.apache.org/licenses/LICENSE-2.0
  37954. *
  37955. * Unless required by applicable law or agreed to in writing,
  37956. * software distributed under the License is distributed on an
  37957. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37958. * KIND, either express or implied. See the License for the
  37959. * specific language governing permissions and limitations
  37960. * under the License.
  37961. */
  37962. var PI2$4 = Math.PI * 2;
  37963. var RADIAN = Math.PI / 180;
  37964. function getViewRect(seriesModel, api) {
  37965. return getLayoutRect(
  37966. seriesModel.getBoxLayoutParams(), {
  37967. width: api.getWidth(),
  37968. height: api.getHeight()
  37969. }
  37970. );
  37971. }
  37972. var pieLayout = function (seriesType, ecModel, api, payload) {
  37973. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37974. var data = seriesModel.getData();
  37975. var valueDim = data.mapDimension('value');
  37976. var viewRect = getViewRect(seriesModel, api);
  37977. var center = seriesModel.get('center');
  37978. var radius = seriesModel.get('radius');
  37979. if (!isArray(radius)) {
  37980. radius = [0, radius];
  37981. }
  37982. if (!isArray(center)) {
  37983. center = [center, center];
  37984. }
  37985. var width = parsePercent$1(viewRect.width, api.getWidth());
  37986. var height = parsePercent$1(viewRect.height, api.getHeight());
  37987. var size = Math.min(width, height);
  37988. var cx = parsePercent$1(center[0], width) + viewRect.x;
  37989. var cy = parsePercent$1(center[1], height) + viewRect.y;
  37990. var r0 = parsePercent$1(radius[0], size / 2);
  37991. var r = parsePercent$1(radius[1], size / 2);
  37992. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37993. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37994. var validDataCount = 0;
  37995. data.each(valueDim, function (value) {
  37996. !isNaN(value) && validDataCount++;
  37997. });
  37998. var sum = data.getSum(valueDim);
  37999. // Sum may be 0
  38000. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  38001. var clockwise = seriesModel.get('clockwise');
  38002. var roseType = seriesModel.get('roseType');
  38003. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  38004. // [0...max]
  38005. var extent = data.getDataExtent(valueDim);
  38006. extent[0] = 0;
  38007. // In the case some sector angle is smaller than minAngle
  38008. var restAngle = PI2$4;
  38009. var valueSumLargerThanMinAngle = 0;
  38010. var currentAngle = startAngle;
  38011. var dir = clockwise ? 1 : -1;
  38012. data.each(valueDim, function (value, idx) {
  38013. var angle;
  38014. if (isNaN(value)) {
  38015. data.setItemLayout(idx, {
  38016. angle: NaN,
  38017. startAngle: NaN,
  38018. endAngle: NaN,
  38019. clockwise: clockwise,
  38020. cx: cx,
  38021. cy: cy,
  38022. r0: r0,
  38023. r: roseType
  38024. ? NaN
  38025. : r,
  38026. viewRect: viewRect
  38027. });
  38028. return;
  38029. }
  38030. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  38031. if (roseType !== 'area') {
  38032. angle = (sum === 0 && stillShowZeroSum)
  38033. ? unitRadian : (value * unitRadian);
  38034. }
  38035. else {
  38036. angle = PI2$4 / validDataCount;
  38037. }
  38038. if (angle < minAngle) {
  38039. angle = minAngle;
  38040. restAngle -= minAngle;
  38041. }
  38042. else {
  38043. valueSumLargerThanMinAngle += value;
  38044. }
  38045. var endAngle = currentAngle + dir * angle;
  38046. data.setItemLayout(idx, {
  38047. angle: angle,
  38048. startAngle: currentAngle,
  38049. endAngle: endAngle,
  38050. clockwise: clockwise,
  38051. cx: cx,
  38052. cy: cy,
  38053. r0: r0,
  38054. r: roseType
  38055. ? linearMap(value, extent, [r0, r])
  38056. : r,
  38057. viewRect: viewRect
  38058. });
  38059. currentAngle = endAngle;
  38060. });
  38061. // Some sector is constrained by minAngle
  38062. // Rest sectors needs recalculate angle
  38063. if (restAngle < PI2$4 && validDataCount) {
  38064. // Average the angle if rest angle is not enough after all angles is
  38065. // Constrained by minAngle
  38066. if (restAngle <= 1e-3) {
  38067. var angle = PI2$4 / validDataCount;
  38068. data.each(valueDim, function (value, idx) {
  38069. if (!isNaN(value)) {
  38070. var layout = data.getItemLayout(idx);
  38071. layout.angle = angle;
  38072. layout.startAngle = startAngle + dir * idx * angle;
  38073. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  38074. }
  38075. });
  38076. }
  38077. else {
  38078. unitRadian = restAngle / valueSumLargerThanMinAngle;
  38079. currentAngle = startAngle;
  38080. data.each(valueDim, function (value, idx) {
  38081. if (!isNaN(value)) {
  38082. var layout = data.getItemLayout(idx);
  38083. var angle = layout.angle === minAngle
  38084. ? minAngle : value * unitRadian;
  38085. layout.startAngle = currentAngle;
  38086. layout.endAngle = currentAngle + dir * angle;
  38087. currentAngle += dir * angle;
  38088. }
  38089. });
  38090. }
  38091. }
  38092. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  38093. });
  38094. };
  38095. /*
  38096. * Licensed to the Apache Software Foundation (ASF) under one
  38097. * or more contributor license agreements. See the NOTICE file
  38098. * distributed with this work for additional information
  38099. * regarding copyright ownership. The ASF licenses this file
  38100. * to you under the Apache License, Version 2.0 (the
  38101. * "License"); you may not use this file except in compliance
  38102. * with the License. You may obtain a copy of the License at
  38103. *
  38104. * http://www.apache.org/licenses/LICENSE-2.0
  38105. *
  38106. * Unless required by applicable law or agreed to in writing,
  38107. * software distributed under the License is distributed on an
  38108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38109. * KIND, either express or implied. See the License for the
  38110. * specific language governing permissions and limitations
  38111. * under the License.
  38112. */
  38113. var dataFilter = function (seriesType) {
  38114. return {
  38115. seriesType: seriesType,
  38116. reset: function (seriesModel, ecModel) {
  38117. var legendModels = ecModel.findComponents({
  38118. mainType: 'legend'
  38119. });
  38120. if (!legendModels || !legendModels.length) {
  38121. return;
  38122. }
  38123. var data = seriesModel.getData();
  38124. data.filterSelf(function (idx) {
  38125. var name = data.getName(idx);
  38126. // If in any legend component the status is not selected.
  38127. for (var i = 0; i < legendModels.length; i++) {
  38128. if (!legendModels[i].isSelected(name)) {
  38129. return false;
  38130. }
  38131. }
  38132. return true;
  38133. });
  38134. }
  38135. };
  38136. };
  38137. /*
  38138. * Licensed to the Apache Software Foundation (ASF) under one
  38139. * or more contributor license agreements. See the NOTICE file
  38140. * distributed with this work for additional information
  38141. * regarding copyright ownership. The ASF licenses this file
  38142. * to you under the Apache License, Version 2.0 (the
  38143. * "License"); you may not use this file except in compliance
  38144. * with the License. You may obtain a copy of the License at
  38145. *
  38146. * http://www.apache.org/licenses/LICENSE-2.0
  38147. *
  38148. * Unless required by applicable law or agreed to in writing,
  38149. * software distributed under the License is distributed on an
  38150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38151. * KIND, either express or implied. See the License for the
  38152. * specific language governing permissions and limitations
  38153. * under the License.
  38154. */
  38155. createDataSelectAction('pie', [{
  38156. type: 'pieToggleSelect',
  38157. event: 'pieselectchanged',
  38158. method: 'toggleSelected'
  38159. }, {
  38160. type: 'pieSelect',
  38161. event: 'pieselected',
  38162. method: 'select'
  38163. }, {
  38164. type: 'pieUnSelect',
  38165. event: 'pieunselected',
  38166. method: 'unSelect'
  38167. }]);
  38168. registerVisual(dataColor('pie'));
  38169. registerLayout(curry(pieLayout, 'pie'));
  38170. registerProcessor(dataFilter('pie'));
  38171. /*
  38172. * Licensed to the Apache Software Foundation (ASF) under one
  38173. * or more contributor license agreements. See the NOTICE file
  38174. * distributed with this work for additional information
  38175. * regarding copyright ownership. The ASF licenses this file
  38176. * to you under the Apache License, Version 2.0 (the
  38177. * "License"); you may not use this file except in compliance
  38178. * with the License. You may obtain a copy of the License at
  38179. *
  38180. * http://www.apache.org/licenses/LICENSE-2.0
  38181. *
  38182. * Unless required by applicable law or agreed to in writing,
  38183. * software distributed under the License is distributed on an
  38184. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38185. * KIND, either express or implied. See the License for the
  38186. * specific language governing permissions and limitations
  38187. * under the License.
  38188. */
  38189. exports.version = version;
  38190. exports.dependencies = dependencies;
  38191. exports.PRIORITY = PRIORITY;
  38192. exports.init = init;
  38193. exports.connect = connect;
  38194. exports.disConnect = disConnect;
  38195. exports.disconnect = disconnect;
  38196. exports.dispose = dispose;
  38197. exports.getInstanceByDom = getInstanceByDom;
  38198. exports.getInstanceById = getInstanceById;
  38199. exports.registerTheme = registerTheme;
  38200. exports.registerPreprocessor = registerPreprocessor;
  38201. exports.registerProcessor = registerProcessor;
  38202. exports.registerPostUpdate = registerPostUpdate;
  38203. exports.registerAction = registerAction;
  38204. exports.registerCoordinateSystem = registerCoordinateSystem;
  38205. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  38206. exports.registerLayout = registerLayout;
  38207. exports.registerVisual = registerVisual;
  38208. exports.registerLoading = registerLoading;
  38209. exports.extendComponentModel = extendComponentModel;
  38210. exports.extendComponentView = extendComponentView;
  38211. exports.extendSeriesModel = extendSeriesModel;
  38212. exports.extendChartView = extendChartView;
  38213. exports.setCanvasCreator = setCanvasCreator;
  38214. exports.registerMap = registerMap;
  38215. exports.getMap = getMap;
  38216. exports.dataTool = dataTool;
  38217. })));