echarts.simple.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832
  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. var env = {};
  59. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  60. // In Weixin Application
  61. env = {
  62. browser: {},
  63. os: {},
  64. node: false,
  65. wxa: true, // Weixin Application
  66. canvasSupported: true,
  67. svgSupported: false,
  68. touchEventsSupported: true,
  69. domSupported: false
  70. };
  71. }
  72. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  73. // In worker
  74. env = {
  75. browser: {},
  76. os: {},
  77. node: false,
  78. worker: true,
  79. canvasSupported: true,
  80. domSupported: false
  81. };
  82. }
  83. else if (typeof navigator === 'undefined') {
  84. // In node
  85. env = {
  86. browser: {},
  87. os: {},
  88. node: true,
  89. worker: false,
  90. // Assume canvas is supported
  91. canvasSupported: true,
  92. svgSupported: true,
  93. domSupported: false
  94. };
  95. }
  96. else {
  97. env = detect(navigator.userAgent);
  98. }
  99. var env$1 = env;
  100. // Zepto.js
  101. // (c) 2010-2013 Thomas Fuchs
  102. // Zepto.js may be freely distributed under the MIT license.
  103. function detect(ua) {
  104. var os = {};
  105. var browser = {};
  106. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  107. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  108. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  109. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  110. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  111. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  112. // var touchpad = webos && ua.match(/TouchPad/);
  113. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  114. // var silk = ua.match(/Silk\/([\d._]+)/);
  115. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  116. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  117. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  118. // var playbook = ua.match(/PlayBook/);
  119. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  120. var firefox = ua.match(/Firefox\/([\d.]+)/);
  121. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  122. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  123. var ie = ua.match(/MSIE\s([\d.]+)/)
  124. // IE 11 Trident/7.0; rv:11.0
  125. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  126. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  127. var weChat = (/micromessenger/i).test(ua);
  128. // Todo: clean this up with a better OS/browser seperation:
  129. // - discern (more) between multiple browsers on android
  130. // - decide if kindle fire in silk mode is android or not
  131. // - Firefox on Android doesn't specify the Android version
  132. // - possibly devide in os, device and browser hashes
  133. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  134. // if (android) os.android = true, os.version = android[2];
  135. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  136. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  137. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  138. // if (webos) os.webos = true, os.version = webos[2];
  139. // if (touchpad) os.touchpad = true;
  140. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  141. // if (bb10) os.bb10 = true, os.version = bb10[2];
  142. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  143. // if (playbook) browser.playbook = true;
  144. // if (kindle) os.kindle = true, os.version = kindle[1];
  145. // if (silk) browser.silk = true, browser.version = silk[1];
  146. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  147. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  148. if (firefox) {
  149. browser.firefox = true;
  150. browser.version = firefox[1];
  151. }
  152. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  153. // if (webview) browser.webview = true;
  154. if (ie) {
  155. browser.ie = true;
  156. browser.version = ie[1];
  157. }
  158. if (edge) {
  159. browser.edge = true;
  160. browser.version = edge[1];
  161. }
  162. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  163. // not be set on win phone. So we do not consider Win Phone.
  164. if (weChat) {
  165. browser.weChat = true;
  166. }
  167. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  168. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  169. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  170. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  171. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  172. return {
  173. browser: browser,
  174. os: os,
  175. node: false,
  176. // 原生canvas支持,改极端点了
  177. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  178. canvasSupported: !!document.createElement('canvas').getContext,
  179. svgSupported: typeof SVGRect !== 'undefined',
  180. // works on most browsers
  181. // IE10/11 does not support touch event, and MS Edge supports them but not by
  182. // default, so we dont check navigator.maxTouchPoints for them here.
  183. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  184. // <http://caniuse.com/#search=pointer%20event>.
  185. pointerEventsSupported: 'onpointerdown' in window
  186. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  187. // events currently. So we dont use that on other browsers unless tested sufficiently.
  188. // Although IE 10 supports pointer event, it use old style and is different from the
  189. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  190. && (browser.edge || (browser.ie && browser.version >= 11)),
  191. // passiveSupported: detectPassiveSupport()
  192. domSupported: typeof document !== 'undefined'
  193. };
  194. }
  195. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  196. // function detectPassiveSupport() {
  197. // // Test via a getter in the options object to see if the passive property is accessed
  198. // var supportsPassive = false;
  199. // try {
  200. // var opts = Object.defineProperty({}, 'passive', {
  201. // get: function() {
  202. // supportsPassive = true;
  203. // }
  204. // });
  205. // window.addEventListener('testPassive', function() {}, opts);
  206. // } catch (e) {
  207. // }
  208. // return supportsPassive;
  209. // }
  210. /**
  211. * @module zrender/core/util
  212. */
  213. // 用于处理merge时无法遍历Date等对象的问题
  214. var BUILTIN_OBJECT = {
  215. '[object Function]': 1,
  216. '[object RegExp]': 1,
  217. '[object Date]': 1,
  218. '[object Error]': 1,
  219. '[object CanvasGradient]': 1,
  220. '[object CanvasPattern]': 1,
  221. // For node-canvas
  222. '[object Image]': 1,
  223. '[object Canvas]': 1
  224. };
  225. var TYPED_ARRAY = {
  226. '[object Int8Array]': 1,
  227. '[object Uint8Array]': 1,
  228. '[object Uint8ClampedArray]': 1,
  229. '[object Int16Array]': 1,
  230. '[object Uint16Array]': 1,
  231. '[object Int32Array]': 1,
  232. '[object Uint32Array]': 1,
  233. '[object Float32Array]': 1,
  234. '[object Float64Array]': 1
  235. };
  236. var objToString = Object.prototype.toString;
  237. var arrayProto = Array.prototype;
  238. var nativeForEach = arrayProto.forEach;
  239. var nativeFilter = arrayProto.filter;
  240. var nativeSlice = arrayProto.slice;
  241. var nativeMap = arrayProto.map;
  242. var nativeReduce = arrayProto.reduce;
  243. // Avoid assign to an exported variable, for transforming to cjs.
  244. var methods = {};
  245. function $override(name, fn) {
  246. // Clear ctx instance for different environment
  247. if (name === 'createCanvas') {
  248. _ctx = null;
  249. }
  250. methods[name] = fn;
  251. }
  252. /**
  253. * Those data types can be cloned:
  254. * Plain object, Array, TypedArray, number, string, null, undefined.
  255. * Those data types will be assgined using the orginal data:
  256. * BUILTIN_OBJECT
  257. * Instance of user defined class will be cloned to a plain object, without
  258. * properties in prototype.
  259. * Other data types is not supported (not sure what will happen).
  260. *
  261. * Caution: do not support clone Date, for performance consideration.
  262. * (There might be a large number of date in `series.data`).
  263. * So date should not be modified in and out of echarts.
  264. *
  265. * @param {*} source
  266. * @return {*} new
  267. */
  268. function clone(source) {
  269. if (source == null || typeof source !== 'object') {
  270. return source;
  271. }
  272. var result = source;
  273. var typeStr = objToString.call(source);
  274. if (typeStr === '[object Array]') {
  275. if (!isPrimitive(source)) {
  276. result = [];
  277. for (var i = 0, len = source.length; i < len; i++) {
  278. result[i] = clone(source[i]);
  279. }
  280. }
  281. }
  282. else if (TYPED_ARRAY[typeStr]) {
  283. if (!isPrimitive(source)) {
  284. var Ctor = source.constructor;
  285. if (source.constructor.from) {
  286. result = Ctor.from(source);
  287. }
  288. else {
  289. result = new Ctor(source.length);
  290. for (var i = 0, len = source.length; i < len; i++) {
  291. result[i] = clone(source[i]);
  292. }
  293. }
  294. }
  295. }
  296. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  297. result = {};
  298. for (var key in source) {
  299. if (source.hasOwnProperty(key)) {
  300. result[key] = clone(source[key]);
  301. }
  302. }
  303. }
  304. return result;
  305. }
  306. /**
  307. * @memberOf module:zrender/core/util
  308. * @param {*} target
  309. * @param {*} source
  310. * @param {boolean} [overwrite=false]
  311. */
  312. function merge(target, source, overwrite) {
  313. // We should escapse that source is string
  314. // and enter for ... in ...
  315. if (!isObject$1(source) || !isObject$1(target)) {
  316. return overwrite ? clone(source) : target;
  317. }
  318. for (var key in source) {
  319. if (source.hasOwnProperty(key)) {
  320. var targetProp = target[key];
  321. var sourceProp = source[key];
  322. if (isObject$1(sourceProp)
  323. && isObject$1(targetProp)
  324. && !isArray(sourceProp)
  325. && !isArray(targetProp)
  326. && !isDom(sourceProp)
  327. && !isDom(targetProp)
  328. && !isBuiltInObject(sourceProp)
  329. && !isBuiltInObject(targetProp)
  330. && !isPrimitive(sourceProp)
  331. && !isPrimitive(targetProp)
  332. ) {
  333. // 如果需要递归覆盖,就递归调用merge
  334. merge(targetProp, sourceProp, overwrite);
  335. }
  336. else if (overwrite || !(key in target)) {
  337. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  338. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  339. target[key] = clone(source[key], true);
  340. }
  341. }
  342. }
  343. return target;
  344. }
  345. /**
  346. * @param {Array} targetAndSources The first item is target, and the rests are source.
  347. * @param {boolean} [overwrite=false]
  348. * @return {*} target
  349. */
  350. function mergeAll(targetAndSources, overwrite) {
  351. var result = targetAndSources[0];
  352. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  353. result = merge(result, targetAndSources[i], overwrite);
  354. }
  355. return result;
  356. }
  357. /**
  358. * @param {*} target
  359. * @param {*} source
  360. * @memberOf module:zrender/core/util
  361. */
  362. function extend(target, source) {
  363. for (var key in source) {
  364. if (source.hasOwnProperty(key)) {
  365. target[key] = source[key];
  366. }
  367. }
  368. return target;
  369. }
  370. /**
  371. * @param {*} target
  372. * @param {*} source
  373. * @param {boolean} [overlay=false]
  374. * @memberOf module:zrender/core/util
  375. */
  376. function defaults(target, source, overlay) {
  377. for (var key in source) {
  378. if (source.hasOwnProperty(key)
  379. && (overlay ? source[key] != null : target[key] == null)
  380. ) {
  381. target[key] = source[key];
  382. }
  383. }
  384. return target;
  385. }
  386. var createCanvas = function () {
  387. return methods.createCanvas();
  388. };
  389. methods.createCanvas = function () {
  390. return document.createElement('canvas');
  391. };
  392. // FIXME
  393. var _ctx;
  394. function getContext() {
  395. if (!_ctx) {
  396. // Use util.createCanvas instead of createCanvas
  397. // because createCanvas may be overwritten in different environment
  398. _ctx = createCanvas().getContext('2d');
  399. }
  400. return _ctx;
  401. }
  402. /**
  403. * 查询数组中元素的index
  404. * @memberOf module:zrender/core/util
  405. */
  406. function indexOf(array, value) {
  407. if (array) {
  408. if (array.indexOf) {
  409. return array.indexOf(value);
  410. }
  411. for (var i = 0, len = array.length; i < len; i++) {
  412. if (array[i] === value) {
  413. return i;
  414. }
  415. }
  416. }
  417. return -1;
  418. }
  419. /**
  420. * 构造类继承关系
  421. *
  422. * @memberOf module:zrender/core/util
  423. * @param {Function} clazz 源类
  424. * @param {Function} baseClazz 基类
  425. */
  426. function inherits(clazz, baseClazz) {
  427. var clazzPrototype = clazz.prototype;
  428. function F() {}
  429. F.prototype = baseClazz.prototype;
  430. clazz.prototype = new F();
  431. for (var prop in clazzPrototype) {
  432. clazz.prototype[prop] = clazzPrototype[prop];
  433. }
  434. clazz.prototype.constructor = clazz;
  435. clazz.superClass = baseClazz;
  436. }
  437. /**
  438. * @memberOf module:zrender/core/util
  439. * @param {Object|Function} target
  440. * @param {Object|Function} sorce
  441. * @param {boolean} overlay
  442. */
  443. function mixin(target, source, overlay) {
  444. target = 'prototype' in target ? target.prototype : target;
  445. source = 'prototype' in source ? source.prototype : source;
  446. defaults(target, source, overlay);
  447. }
  448. /**
  449. * Consider typed array.
  450. * @param {Array|TypedArray} data
  451. */
  452. function isArrayLike(data) {
  453. if (!data) {
  454. return;
  455. }
  456. if (typeof data === 'string') {
  457. return false;
  458. }
  459. return typeof data.length === 'number';
  460. }
  461. /**
  462. * 数组或对象遍历
  463. * @memberOf module:zrender/core/util
  464. * @param {Object|Array} obj
  465. * @param {Function} cb
  466. * @param {*} [context]
  467. */
  468. function each$1(obj, cb, context) {
  469. if (!(obj && cb)) {
  470. return;
  471. }
  472. if (obj.forEach && obj.forEach === nativeForEach) {
  473. obj.forEach(cb, context);
  474. }
  475. else if (obj.length === +obj.length) {
  476. for (var i = 0, len = obj.length; i < len; i++) {
  477. cb.call(context, obj[i], i, obj);
  478. }
  479. }
  480. else {
  481. for (var key in obj) {
  482. if (obj.hasOwnProperty(key)) {
  483. cb.call(context, obj[key], key, obj);
  484. }
  485. }
  486. }
  487. }
  488. /**
  489. * 数组映射
  490. * @memberOf module:zrender/core/util
  491. * @param {Array} obj
  492. * @param {Function} cb
  493. * @param {*} [context]
  494. * @return {Array}
  495. */
  496. function map(obj, cb, context) {
  497. if (!(obj && cb)) {
  498. return;
  499. }
  500. if (obj.map && obj.map === nativeMap) {
  501. return obj.map(cb, context);
  502. }
  503. else {
  504. var result = [];
  505. for (var i = 0, len = obj.length; i < len; i++) {
  506. result.push(cb.call(context, obj[i], i, obj));
  507. }
  508. return result;
  509. }
  510. }
  511. /**
  512. * @memberOf module:zrender/core/util
  513. * @param {Array} obj
  514. * @param {Function} cb
  515. * @param {Object} [memo]
  516. * @param {*} [context]
  517. * @return {Array}
  518. */
  519. function reduce(obj, cb, memo, context) {
  520. if (!(obj && cb)) {
  521. return;
  522. }
  523. if (obj.reduce && obj.reduce === nativeReduce) {
  524. return obj.reduce(cb, memo, context);
  525. }
  526. else {
  527. for (var i = 0, len = obj.length; i < len; i++) {
  528. memo = cb.call(context, memo, obj[i], i, obj);
  529. }
  530. return memo;
  531. }
  532. }
  533. /**
  534. * 数组过滤
  535. * @memberOf module:zrender/core/util
  536. * @param {Array} obj
  537. * @param {Function} cb
  538. * @param {*} [context]
  539. * @return {Array}
  540. */
  541. function filter(obj, cb, context) {
  542. if (!(obj && cb)) {
  543. return;
  544. }
  545. if (obj.filter && obj.filter === nativeFilter) {
  546. return obj.filter(cb, context);
  547. }
  548. else {
  549. var result = [];
  550. for (var i = 0, len = obj.length; i < len; i++) {
  551. if (cb.call(context, obj[i], i, obj)) {
  552. result.push(obj[i]);
  553. }
  554. }
  555. return result;
  556. }
  557. }
  558. /**
  559. * 数组项查找
  560. * @memberOf module:zrender/core/util
  561. * @param {Array} obj
  562. * @param {Function} cb
  563. * @param {*} [context]
  564. * @return {*}
  565. */
  566. /**
  567. * @memberOf module:zrender/core/util
  568. * @param {Function} func
  569. * @param {*} context
  570. * @return {Function}
  571. */
  572. function bind(func, context) {
  573. var args = nativeSlice.call(arguments, 2);
  574. return function () {
  575. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  576. };
  577. }
  578. /**
  579. * @memberOf module:zrender/core/util
  580. * @param {Function} func
  581. * @return {Function}
  582. */
  583. function curry(func) {
  584. var args = nativeSlice.call(arguments, 1);
  585. return function () {
  586. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  587. };
  588. }
  589. /**
  590. * @memberOf module:zrender/core/util
  591. * @param {*} value
  592. * @return {boolean}
  593. */
  594. function isArray(value) {
  595. return objToString.call(value) === '[object Array]';
  596. }
  597. /**
  598. * @memberOf module:zrender/core/util
  599. * @param {*} value
  600. * @return {boolean}
  601. */
  602. function isFunction$1(value) {
  603. return typeof value === 'function';
  604. }
  605. /**
  606. * @memberOf module:zrender/core/util
  607. * @param {*} value
  608. * @return {boolean}
  609. */
  610. function isString(value) {
  611. return objToString.call(value) === '[object String]';
  612. }
  613. /**
  614. * @memberOf module:zrender/core/util
  615. * @param {*} value
  616. * @return {boolean}
  617. */
  618. function isObject$1(value) {
  619. // Avoid a V8 JIT bug in Chrome 19-20.
  620. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  621. var type = typeof value;
  622. return type === 'function' || (!!value && type === 'object');
  623. }
  624. /**
  625. * @memberOf module:zrender/core/util
  626. * @param {*} value
  627. * @return {boolean}
  628. */
  629. function isBuiltInObject(value) {
  630. return !!BUILTIN_OBJECT[objToString.call(value)];
  631. }
  632. /**
  633. * @memberOf module:zrender/core/util
  634. * @param {*} value
  635. * @return {boolean}
  636. */
  637. function isTypedArray(value) {
  638. return !!TYPED_ARRAY[objToString.call(value)];
  639. }
  640. /**
  641. * @memberOf module:zrender/core/util
  642. * @param {*} value
  643. * @return {boolean}
  644. */
  645. function isDom(value) {
  646. return typeof value === 'object'
  647. && typeof value.nodeType === 'number'
  648. && typeof value.ownerDocument === 'object';
  649. }
  650. /**
  651. * Whether is exactly NaN. Notice isNaN('a') returns true.
  652. * @param {*} value
  653. * @return {boolean}
  654. */
  655. function eqNaN(value) {
  656. return value !== value;
  657. }
  658. /**
  659. * If value1 is not null, then return value1, otherwise judget rest of values.
  660. * Low performance.
  661. * @memberOf module:zrender/core/util
  662. * @return {*} Final value
  663. */
  664. function retrieve(values) {
  665. for (var i = 0, len = arguments.length; i < len; i++) {
  666. if (arguments[i] != null) {
  667. return arguments[i];
  668. }
  669. }
  670. }
  671. function retrieve2(value0, value1) {
  672. return value0 != null
  673. ? value0
  674. : value1;
  675. }
  676. function retrieve3(value0, value1, value2) {
  677. return value0 != null
  678. ? value0
  679. : value1 != null
  680. ? value1
  681. : value2;
  682. }
  683. /**
  684. * @memberOf module:zrender/core/util
  685. * @param {Array} arr
  686. * @param {number} startIndex
  687. * @param {number} endIndex
  688. * @return {Array}
  689. */
  690. function slice() {
  691. return Function.call.apply(nativeSlice, arguments);
  692. }
  693. /**
  694. * Normalize css liked array configuration
  695. * e.g.
  696. * 3 => [3, 3, 3, 3]
  697. * [4, 2] => [4, 2, 4, 2]
  698. * [4, 3, 2] => [4, 3, 2, 3]
  699. * @param {number|Array.<number>} val
  700. * @return {Array.<number>}
  701. */
  702. function normalizeCssArray(val) {
  703. if (typeof (val) === 'number') {
  704. return [val, val, val, val];
  705. }
  706. var len = val.length;
  707. if (len === 2) {
  708. // vertical | horizontal
  709. return [val[0], val[1], val[0], val[1]];
  710. }
  711. else if (len === 3) {
  712. // top | horizontal | bottom
  713. return [val[0], val[1], val[2], val[1]];
  714. }
  715. return val;
  716. }
  717. /**
  718. * @memberOf module:zrender/core/util
  719. * @param {boolean} condition
  720. * @param {string} message
  721. */
  722. function assert$1(condition, message) {
  723. if (!condition) {
  724. throw new Error(message);
  725. }
  726. }
  727. /**
  728. * @memberOf module:zrender/core/util
  729. * @param {string} str string to be trimed
  730. * @return {string} trimed string
  731. */
  732. function trim(str) {
  733. if (str == null) {
  734. return null;
  735. }
  736. else if (typeof str.trim === 'function') {
  737. return str.trim();
  738. }
  739. else {
  740. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  741. }
  742. }
  743. var primitiveKey = '__ec_primitive__';
  744. /**
  745. * Set an object as primitive to be ignored traversing children in clone or merge
  746. */
  747. function setAsPrimitive(obj) {
  748. obj[primitiveKey] = true;
  749. }
  750. function isPrimitive(obj) {
  751. return obj[primitiveKey];
  752. }
  753. /**
  754. * @constructor
  755. * @param {Object} obj Only apply `ownProperty`.
  756. */
  757. function HashMap(obj) {
  758. var isArr = isArray(obj);
  759. // Key should not be set on this, otherwise
  760. // methods get/set/... may be overrided.
  761. this.data = {};
  762. var thisMap = this;
  763. (obj instanceof HashMap)
  764. ? obj.each(visit)
  765. : (obj && each$1(obj, visit));
  766. function visit(value, key) {
  767. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  768. }
  769. }
  770. HashMap.prototype = {
  771. constructor: HashMap,
  772. // Do not provide `has` method to avoid defining what is `has`.
  773. // (We usually treat `null` and `undefined` as the same, different
  774. // from ES6 Map).
  775. get: function (key) {
  776. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  777. },
  778. set: function (key, value) {
  779. // Comparing with invocation chaining, `return value` is more commonly
  780. // used in this case: `var someVal = map.set('a', genVal());`
  781. return (this.data[key] = value);
  782. },
  783. // Although util.each can be performed on this hashMap directly, user
  784. // should not use the exposed keys, who are prefixed.
  785. each: function (cb, context) {
  786. context !== void 0 && (cb = bind(cb, context));
  787. for (var key in this.data) {
  788. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  789. }
  790. },
  791. // Do not use this method if performance sensitive.
  792. removeKey: function (key) {
  793. delete this.data[key];
  794. }
  795. };
  796. function createHashMap(obj) {
  797. return new HashMap(obj);
  798. }
  799. function noop() {}
  800. var ArrayCtor = typeof Float32Array === 'undefined'
  801. ? Array
  802. : Float32Array;
  803. /**
  804. * 创建一个向量
  805. * @param {number} [x=0]
  806. * @param {number} [y=0]
  807. * @return {Vector2}
  808. */
  809. function create(x, y) {
  810. var out = new ArrayCtor(2);
  811. if (x == null) {
  812. x = 0;
  813. }
  814. if (y == null) {
  815. y = 0;
  816. }
  817. out[0] = x;
  818. out[1] = y;
  819. return out;
  820. }
  821. /**
  822. * 复制向量数据
  823. * @param {Vector2} out
  824. * @param {Vector2} v
  825. * @return {Vector2}
  826. */
  827. function copy(out, v) {
  828. out[0] = v[0];
  829. out[1] = v[1];
  830. return out;
  831. }
  832. /**
  833. * 克隆一个向量
  834. * @param {Vector2} v
  835. * @return {Vector2}
  836. */
  837. function clone$1(v) {
  838. var out = new ArrayCtor(2);
  839. out[0] = v[0];
  840. out[1] = v[1];
  841. return out;
  842. }
  843. /**
  844. * 设置向量的两个项
  845. * @param {Vector2} out
  846. * @param {number} a
  847. * @param {number} b
  848. * @return {Vector2} 结果
  849. */
  850. /**
  851. * 向量相加
  852. * @param {Vector2} out
  853. * @param {Vector2} v1
  854. * @param {Vector2} v2
  855. */
  856. function add(out, v1, v2) {
  857. out[0] = v1[0] + v2[0];
  858. out[1] = v1[1] + v2[1];
  859. return out;
  860. }
  861. /**
  862. * 向量缩放后相加
  863. * @param {Vector2} out
  864. * @param {Vector2} v1
  865. * @param {Vector2} v2
  866. * @param {number} a
  867. */
  868. function scaleAndAdd(out, v1, v2, a) {
  869. out[0] = v1[0] + v2[0] * a;
  870. out[1] = v1[1] + v2[1] * a;
  871. return out;
  872. }
  873. /**
  874. * 向量相减
  875. * @param {Vector2} out
  876. * @param {Vector2} v1
  877. * @param {Vector2} v2
  878. */
  879. function sub(out, v1, v2) {
  880. out[0] = v1[0] - v2[0];
  881. out[1] = v1[1] - v2[1];
  882. return out;
  883. }
  884. /**
  885. * 向量长度
  886. * @param {Vector2} v
  887. * @return {number}
  888. */
  889. function len(v) {
  890. return Math.sqrt(lenSquare(v));
  891. }
  892. // jshint ignore:line
  893. /**
  894. * 向量长度平方
  895. * @param {Vector2} v
  896. * @return {number}
  897. */
  898. function lenSquare(v) {
  899. return v[0] * v[0] + v[1] * v[1];
  900. }
  901. /**
  902. * 向量乘法
  903. * @param {Vector2} out
  904. * @param {Vector2} v1
  905. * @param {Vector2} v2
  906. */
  907. /**
  908. * 向量除法
  909. * @param {Vector2} out
  910. * @param {Vector2} v1
  911. * @param {Vector2} v2
  912. */
  913. /**
  914. * 向量点乘
  915. * @param {Vector2} v1
  916. * @param {Vector2} v2
  917. * @return {number}
  918. */
  919. /**
  920. * 向量缩放
  921. * @param {Vector2} out
  922. * @param {Vector2} v
  923. * @param {number} s
  924. */
  925. function scale(out, v, s) {
  926. out[0] = v[0] * s;
  927. out[1] = v[1] * s;
  928. return out;
  929. }
  930. /**
  931. * 向量归一化
  932. * @param {Vector2} out
  933. * @param {Vector2} v
  934. */
  935. function normalize(out, v) {
  936. var d = len(v);
  937. if (d === 0) {
  938. out[0] = 0;
  939. out[1] = 0;
  940. }
  941. else {
  942. out[0] = v[0] / d;
  943. out[1] = v[1] / d;
  944. }
  945. return out;
  946. }
  947. /**
  948. * 计算向量间距离
  949. * @param {Vector2} v1
  950. * @param {Vector2} v2
  951. * @return {number}
  952. */
  953. function distance(v1, v2) {
  954. return Math.sqrt(
  955. (v1[0] - v2[0]) * (v1[0] - v2[0])
  956. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  957. );
  958. }
  959. var dist = distance;
  960. /**
  961. * 向量距离平方
  962. * @param {Vector2} v1
  963. * @param {Vector2} v2
  964. * @return {number}
  965. */
  966. function distanceSquare(v1, v2) {
  967. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  968. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  969. }
  970. var distSquare = distanceSquare;
  971. /**
  972. * 求负向量
  973. * @param {Vector2} out
  974. * @param {Vector2} v
  975. */
  976. /**
  977. * 插值两个点
  978. * @param {Vector2} out
  979. * @param {Vector2} v1
  980. * @param {Vector2} v2
  981. * @param {number} t
  982. */
  983. /**
  984. * 矩阵左乘向量
  985. * @param {Vector2} out
  986. * @param {Vector2} v
  987. * @param {Vector2} m
  988. */
  989. function applyTransform(out, v, m) {
  990. var x = v[0];
  991. var y = v[1];
  992. out[0] = m[0] * x + m[2] * y + m[4];
  993. out[1] = m[1] * x + m[3] * y + m[5];
  994. return out;
  995. }
  996. /**
  997. * 求两个向量最小值
  998. * @param {Vector2} out
  999. * @param {Vector2} v1
  1000. * @param {Vector2} v2
  1001. */
  1002. function min(out, v1, v2) {
  1003. out[0] = Math.min(v1[0], v2[0]);
  1004. out[1] = Math.min(v1[1], v2[1]);
  1005. return out;
  1006. }
  1007. /**
  1008. * 求两个向量最大值
  1009. * @param {Vector2} out
  1010. * @param {Vector2} v1
  1011. * @param {Vector2} v2
  1012. */
  1013. function max(out, v1, v2) {
  1014. out[0] = Math.max(v1[0], v2[0]);
  1015. out[1] = Math.max(v1[1], v2[1]);
  1016. return out;
  1017. }
  1018. // TODO Draggable for group
  1019. // FIXME Draggable on element which has parent rotation or scale
  1020. function Draggable() {
  1021. this.on('mousedown', this._dragStart, this);
  1022. this.on('mousemove', this._drag, this);
  1023. this.on('mouseup', this._dragEnd, this);
  1024. this.on('globalout', this._dragEnd, this);
  1025. // this._dropTarget = null;
  1026. // this._draggingTarget = null;
  1027. // this._x = 0;
  1028. // this._y = 0;
  1029. }
  1030. Draggable.prototype = {
  1031. constructor: Draggable,
  1032. _dragStart: function (e) {
  1033. var draggingTarget = e.target;
  1034. if (draggingTarget && draggingTarget.draggable) {
  1035. this._draggingTarget = draggingTarget;
  1036. draggingTarget.dragging = true;
  1037. this._x = e.offsetX;
  1038. this._y = e.offsetY;
  1039. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1040. }
  1041. },
  1042. _drag: function (e) {
  1043. var draggingTarget = this._draggingTarget;
  1044. if (draggingTarget) {
  1045. var x = e.offsetX;
  1046. var y = e.offsetY;
  1047. var dx = x - this._x;
  1048. var dy = y - this._y;
  1049. this._x = x;
  1050. this._y = y;
  1051. draggingTarget.drift(dx, dy, e);
  1052. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1053. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1054. var lastDropTarget = this._dropTarget;
  1055. this._dropTarget = dropTarget;
  1056. if (draggingTarget !== dropTarget) {
  1057. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1058. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1059. }
  1060. if (dropTarget && dropTarget !== lastDropTarget) {
  1061. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1062. }
  1063. }
  1064. }
  1065. },
  1066. _dragEnd: function (e) {
  1067. var draggingTarget = this._draggingTarget;
  1068. if (draggingTarget) {
  1069. draggingTarget.dragging = false;
  1070. }
  1071. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1072. if (this._dropTarget) {
  1073. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1074. }
  1075. this._draggingTarget = null;
  1076. this._dropTarget = null;
  1077. }
  1078. };
  1079. function param(target, e) {
  1080. return {target: target, topTarget: e && e.topTarget};
  1081. }
  1082. /**
  1083. * Event Mixin
  1084. * @module zrender/mixin/Eventful
  1085. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1086. * pissang (https://www.github.com/pissang)
  1087. */
  1088. var arrySlice = Array.prototype.slice;
  1089. /**
  1090. * Event dispatcher.
  1091. *
  1092. * @alias module:zrender/mixin/Eventful
  1093. * @constructor
  1094. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1095. * `eventProcessor.xxx` called.
  1096. * @param {Function} [eventProcessor.normalizeQuery]
  1097. * param: {string|Object} Raw query.
  1098. * return: {string|Object} Normalized query.
  1099. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1100. * if it returns `true`.
  1101. * param: {string} eventType
  1102. * param: {string|Object} query
  1103. * return: {boolean}
  1104. * @param {Function} [eventProcessor.afterTrigger] Call after all handlers called.
  1105. * param: {string} eventType
  1106. */
  1107. var Eventful = function (eventProcessor) {
  1108. this._$handlers = {};
  1109. this._$eventProcessor = eventProcessor;
  1110. };
  1111. Eventful.prototype = {
  1112. constructor: Eventful,
  1113. /**
  1114. * The handler can only be triggered once, then removed.
  1115. *
  1116. * @param {string} event The event name.
  1117. * @param {string|Object} [query] Condition used on event filter.
  1118. * @param {Function} handler The event handler.
  1119. * @param {Object} context
  1120. */
  1121. one: function (event, query, handler, context) {
  1122. return on(this, event, query, handler, context, true);
  1123. },
  1124. /**
  1125. * Bind a handler.
  1126. *
  1127. * @param {string} event The event name.
  1128. * @param {string|Object} [query] Condition used on event filter.
  1129. * @param {Function} handler The event handler.
  1130. * @param {Object} [context]
  1131. */
  1132. on: function (event, query, handler, context) {
  1133. return on(this, event, query, handler, context, false);
  1134. },
  1135. /**
  1136. * Whether any handler has bound.
  1137. *
  1138. * @param {string} event
  1139. * @return {boolean}
  1140. */
  1141. isSilent: function (event) {
  1142. var _h = this._$handlers;
  1143. return !_h[event] || !_h[event].length;
  1144. },
  1145. /**
  1146. * Unbind a event.
  1147. *
  1148. * @param {string} event The event name.
  1149. * @param {Function} [handler] The event handler.
  1150. */
  1151. off: function (event, handler) {
  1152. var _h = this._$handlers;
  1153. if (!event) {
  1154. this._$handlers = {};
  1155. return this;
  1156. }
  1157. if (handler) {
  1158. if (_h[event]) {
  1159. var newList = [];
  1160. for (var i = 0, l = _h[event].length; i < l; i++) {
  1161. if (_h[event][i].h !== handler) {
  1162. newList.push(_h[event][i]);
  1163. }
  1164. }
  1165. _h[event] = newList;
  1166. }
  1167. if (_h[event] && _h[event].length === 0) {
  1168. delete _h[event];
  1169. }
  1170. }
  1171. else {
  1172. delete _h[event];
  1173. }
  1174. return this;
  1175. },
  1176. /**
  1177. * Dispatch a event.
  1178. *
  1179. * @param {string} type The event name.
  1180. */
  1181. trigger: function (type) {
  1182. var _h = this._$handlers[type];
  1183. var eventProcessor = this._$eventProcessor;
  1184. if (_h) {
  1185. var args = arguments;
  1186. var argLen = args.length;
  1187. if (argLen > 3) {
  1188. args = arrySlice.call(args, 1);
  1189. }
  1190. var len = _h.length;
  1191. for (var i = 0; i < len;) {
  1192. var hItem = _h[i];
  1193. if (eventProcessor
  1194. && eventProcessor.filter
  1195. && hItem.query != null
  1196. && !eventProcessor.filter(type, hItem.query)
  1197. ) {
  1198. i++;
  1199. continue;
  1200. }
  1201. // Optimize advise from backbone
  1202. switch (argLen) {
  1203. case 1:
  1204. hItem.h.call(hItem.ctx);
  1205. break;
  1206. case 2:
  1207. hItem.h.call(hItem.ctx, args[1]);
  1208. break;
  1209. case 3:
  1210. hItem.h.call(hItem.ctx, args[1], args[2]);
  1211. break;
  1212. default:
  1213. // have more than 2 given arguments
  1214. hItem.h.apply(hItem.ctx, args);
  1215. break;
  1216. }
  1217. if (hItem.one) {
  1218. _h.splice(i, 1);
  1219. len--;
  1220. }
  1221. else {
  1222. i++;
  1223. }
  1224. }
  1225. }
  1226. eventProcessor && eventProcessor.afterTrigger
  1227. && eventProcessor.afterTrigger(type);
  1228. return this;
  1229. },
  1230. /**
  1231. * Dispatch a event with context, which is specified at the last parameter.
  1232. *
  1233. * @param {string} type The event name.
  1234. */
  1235. triggerWithContext: function (type) {
  1236. var _h = this._$handlers[type];
  1237. var eventProcessor = this._$eventProcessor;
  1238. if (_h) {
  1239. var args = arguments;
  1240. var argLen = args.length;
  1241. if (argLen > 4) {
  1242. args = arrySlice.call(args, 1, args.length - 1);
  1243. }
  1244. var ctx = args[args.length - 1];
  1245. var len = _h.length;
  1246. for (var i = 0; i < len;) {
  1247. var hItem = _h[i];
  1248. if (eventProcessor
  1249. && eventProcessor.filter
  1250. && hItem.query != null
  1251. && !eventProcessor.filter(type, hItem.query)
  1252. ) {
  1253. i++;
  1254. continue;
  1255. }
  1256. // Optimize advise from backbone
  1257. switch (argLen) {
  1258. case 1:
  1259. hItem.h.call(ctx);
  1260. break;
  1261. case 2:
  1262. hItem.h.call(ctx, args[1]);
  1263. break;
  1264. case 3:
  1265. hItem.h.call(ctx, args[1], args[2]);
  1266. break;
  1267. default:
  1268. // have more than 2 given arguments
  1269. hItem.h.apply(ctx, args);
  1270. break;
  1271. }
  1272. if (hItem.one) {
  1273. _h.splice(i, 1);
  1274. len--;
  1275. }
  1276. else {
  1277. i++;
  1278. }
  1279. }
  1280. }
  1281. eventProcessor && eventProcessor.afterTrigger
  1282. && eventProcessor.afterTrigger(type);
  1283. return this;
  1284. }
  1285. };
  1286. function normalizeQuery(host, query) {
  1287. var eventProcessor = host._$eventProcessor;
  1288. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1289. query = eventProcessor.normalizeQuery(query);
  1290. }
  1291. return query;
  1292. }
  1293. function on(eventful, event, query, handler, context, isOnce) {
  1294. var _h = eventful._$handlers;
  1295. if (typeof query === 'function') {
  1296. context = handler;
  1297. handler = query;
  1298. query = null;
  1299. }
  1300. if (!handler || !event) {
  1301. return eventful;
  1302. }
  1303. query = normalizeQuery(eventful, query);
  1304. if (!_h[event]) {
  1305. _h[event] = [];
  1306. }
  1307. for (var i = 0; i < _h[event].length; i++) {
  1308. if (_h[event][i].h === handler) {
  1309. return eventful;
  1310. }
  1311. }
  1312. var wrap = {
  1313. h: handler,
  1314. one: isOnce,
  1315. query: query,
  1316. ctx: context || eventful,
  1317. // FIXME
  1318. // Do not publish this feature util it is proved that it makes sense.
  1319. callAtLast: handler.zrEventfulCallAtLast
  1320. };
  1321. var lastIndex = _h[event].length - 1;
  1322. var lastWrap = _h[event][lastIndex];
  1323. (lastWrap && lastWrap.callAtLast)
  1324. ? _h[event].splice(lastIndex, 0, wrap)
  1325. : _h[event].push(wrap);
  1326. return eventful;
  1327. }
  1328. /**
  1329. * 事件辅助类
  1330. * @module zrender/core/event
  1331. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1332. */
  1333. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1334. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1335. function getBoundingClientRect(el) {
  1336. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  1337. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  1338. }
  1339. // `calculate` is optional, default false
  1340. function clientToLocal(el, e, out, calculate) {
  1341. out = out || {};
  1342. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1343. // to the padding edge of the target element. The only browser using this convention
  1344. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1345. // not support the properties.
  1346. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1347. // In zr painter.dom, padding edge equals to border edge.
  1348. // FIXME
  1349. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  1350. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  1351. // is too complex. So css-transfrom dont support in this case temporarily.
  1352. if (calculate || !env$1.canvasSupported) {
  1353. defaultGetZrXY(el, e, out);
  1354. }
  1355. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1356. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1357. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1358. // zoom-factor, overflow / opacity layers, transforms ...)
  1359. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1360. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1361. // BTW3, In ff, offsetX/offsetY is always 0.
  1362. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1363. out.zrX = e.layerX;
  1364. out.zrY = e.layerY;
  1365. }
  1366. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1367. else if (e.offsetX != null) {
  1368. out.zrX = e.offsetX;
  1369. out.zrY = e.offsetY;
  1370. }
  1371. // For some other device, e.g., IOS safari.
  1372. else {
  1373. defaultGetZrXY(el, e, out);
  1374. }
  1375. return out;
  1376. }
  1377. function defaultGetZrXY(el, e, out) {
  1378. // This well-known method below does not support css transform.
  1379. var box = getBoundingClientRect(el);
  1380. out.zrX = e.clientX - box.left;
  1381. out.zrY = e.clientY - box.top;
  1382. }
  1383. /**
  1384. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  1385. * `calculate` is optional, default false.
  1386. */
  1387. function normalizeEvent(el, e, calculate) {
  1388. e = e || window.event;
  1389. if (e.zrX != null) {
  1390. return e;
  1391. }
  1392. var eventType = e.type;
  1393. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1394. if (!isTouch) {
  1395. clientToLocal(el, e, e, calculate);
  1396. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1397. }
  1398. else {
  1399. var touch = eventType !== 'touchend'
  1400. ? e.targetTouches[0]
  1401. : e.changedTouches[0];
  1402. touch && clientToLocal(el, touch, e, calculate);
  1403. }
  1404. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1405. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1406. // If e.which has been defined, if may be readonly,
  1407. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1408. var button = e.button;
  1409. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1410. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1411. }
  1412. // [Caution]: `e.which` from browser is not always reliable. For example,
  1413. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1414. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1415. // `mousedown (pointerdown)` is the same as Chrome does.
  1416. return e;
  1417. }
  1418. /**
  1419. * @param {HTMLElement} el
  1420. * @param {string} name
  1421. * @param {Function} handler
  1422. */
  1423. function addEventListener(el, name, handler) {
  1424. if (isDomLevel2) {
  1425. // Reproduct the console warning:
  1426. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1427. // Consider marking event handler as 'passive' to make the page more responsive.
  1428. // Just set console log level: verbose in chrome dev tool.
  1429. // then the warning log will be printed when addEventListener called.
  1430. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1431. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1432. // listener delegate all of the upper events of element. Some of those events need
  1433. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1434. // Before passive can be adopted, these issues should be considered:
  1435. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1436. // passive or not.
  1437. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1438. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1439. // compatibility should be handled.
  1440. // var opts = (env.passiveSupported && name === 'mousewheel')
  1441. // ? {passive: true}
  1442. // // By default, the third param of el.addEventListener is `capture: false`.
  1443. // : void 0;
  1444. // el.addEventListener(name, handler /* , opts */);
  1445. el.addEventListener(name, handler);
  1446. }
  1447. else {
  1448. el.attachEvent('on' + name, handler);
  1449. }
  1450. }
  1451. function removeEventListener(el, name, handler) {
  1452. if (isDomLevel2) {
  1453. el.removeEventListener(name, handler);
  1454. }
  1455. else {
  1456. el.detachEvent('on' + name, handler);
  1457. }
  1458. }
  1459. /**
  1460. * preventDefault and stopPropagation.
  1461. * Notice: do not do that in zrender. Upper application
  1462. * do that if necessary.
  1463. *
  1464. * @memberOf module:zrender/core/event
  1465. * @method
  1466. * @param {Event} e : event对象
  1467. */
  1468. var stop = isDomLevel2
  1469. ? function (e) {
  1470. e.preventDefault();
  1471. e.stopPropagation();
  1472. e.cancelBubble = true;
  1473. }
  1474. : function (e) {
  1475. e.returnValue = false;
  1476. e.cancelBubble = true;
  1477. };
  1478. /**
  1479. * This method only works for mouseup and mousedown. The functionality is restricted
  1480. * for fault tolerance, See the `e.which` compatibility above.
  1481. *
  1482. * @param {MouseEvent} e
  1483. * @return {boolean}
  1484. */
  1485. /**
  1486. * To be removed.
  1487. * @deprecated
  1488. */
  1489. /**
  1490. * Only implements needed gestures for mobile.
  1491. */
  1492. var GestureMgr = function () {
  1493. /**
  1494. * @private
  1495. * @type {Array.<Object>}
  1496. */
  1497. this._track = [];
  1498. };
  1499. GestureMgr.prototype = {
  1500. constructor: GestureMgr,
  1501. recognize: function (event, target, root) {
  1502. this._doTrack(event, target, root);
  1503. return this._recognize(event);
  1504. },
  1505. clear: function () {
  1506. this._track.length = 0;
  1507. return this;
  1508. },
  1509. _doTrack: function (event, target, root) {
  1510. var touches = event.touches;
  1511. if (!touches) {
  1512. return;
  1513. }
  1514. var trackItem = {
  1515. points: [],
  1516. touches: [],
  1517. target: target,
  1518. event: event
  1519. };
  1520. for (var i = 0, len = touches.length; i < len; i++) {
  1521. var touch = touches[i];
  1522. var pos = clientToLocal(root, touch, {});
  1523. trackItem.points.push([pos.zrX, pos.zrY]);
  1524. trackItem.touches.push(touch);
  1525. }
  1526. this._track.push(trackItem);
  1527. },
  1528. _recognize: function (event) {
  1529. for (var eventName in recognizers) {
  1530. if (recognizers.hasOwnProperty(eventName)) {
  1531. var gestureInfo = recognizers[eventName](this._track, event);
  1532. if (gestureInfo) {
  1533. return gestureInfo;
  1534. }
  1535. }
  1536. }
  1537. }
  1538. };
  1539. function dist$1(pointPair) {
  1540. var dx = pointPair[1][0] - pointPair[0][0];
  1541. var dy = pointPair[1][1] - pointPair[0][1];
  1542. return Math.sqrt(dx * dx + dy * dy);
  1543. }
  1544. function center(pointPair) {
  1545. return [
  1546. (pointPair[0][0] + pointPair[1][0]) / 2,
  1547. (pointPair[0][1] + pointPair[1][1]) / 2
  1548. ];
  1549. }
  1550. var recognizers = {
  1551. pinch: function (track, event) {
  1552. var trackLen = track.length;
  1553. if (!trackLen) {
  1554. return;
  1555. }
  1556. var pinchEnd = (track[trackLen - 1] || {}).points;
  1557. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1558. if (pinchPre
  1559. && pinchPre.length > 1
  1560. && pinchEnd
  1561. && pinchEnd.length > 1
  1562. ) {
  1563. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1564. !isFinite(pinchScale) && (pinchScale = 1);
  1565. event.pinchScale = pinchScale;
  1566. var pinchCenter = center(pinchEnd);
  1567. event.pinchX = pinchCenter[0];
  1568. event.pinchY = pinchCenter[1];
  1569. return {
  1570. type: 'pinch',
  1571. target: track[0].target,
  1572. event: event
  1573. };
  1574. }
  1575. }
  1576. // Only pinch currently.
  1577. };
  1578. var SILENT = 'silent';
  1579. function makeEventPacket(eveType, targetInfo, event) {
  1580. return {
  1581. type: eveType,
  1582. event: event,
  1583. // target can only be an element that is not silent.
  1584. target: targetInfo.target,
  1585. // topTarget can be a silent element.
  1586. topTarget: targetInfo.topTarget,
  1587. cancelBubble: false,
  1588. offsetX: event.zrX,
  1589. offsetY: event.zrY,
  1590. gestureEvent: event.gestureEvent,
  1591. pinchX: event.pinchX,
  1592. pinchY: event.pinchY,
  1593. pinchScale: event.pinchScale,
  1594. wheelDelta: event.zrDelta,
  1595. zrByTouch: event.zrByTouch,
  1596. which: event.which,
  1597. stop: stopEvent
  1598. };
  1599. }
  1600. function stopEvent(event) {
  1601. stop(this.event);
  1602. }
  1603. function EmptyProxy() {}
  1604. EmptyProxy.prototype.dispose = function () {};
  1605. var handlerNames = [
  1606. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1607. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1608. ];
  1609. /**
  1610. * @alias module:zrender/Handler
  1611. * @constructor
  1612. * @extends module:zrender/mixin/Eventful
  1613. * @param {module:zrender/Storage} storage Storage instance.
  1614. * @param {module:zrender/Painter} painter Painter instance.
  1615. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1616. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1617. */
  1618. var Handler = function (storage, painter, proxy, painterRoot) {
  1619. Eventful.call(this);
  1620. this.storage = storage;
  1621. this.painter = painter;
  1622. this.painterRoot = painterRoot;
  1623. proxy = proxy || new EmptyProxy();
  1624. /**
  1625. * Proxy of event. can be Dom, WebGLSurface, etc.
  1626. */
  1627. this.proxy = null;
  1628. /**
  1629. * {target, topTarget, x, y}
  1630. * @private
  1631. * @type {Object}
  1632. */
  1633. this._hovered = {};
  1634. /**
  1635. * @private
  1636. * @type {Date}
  1637. */
  1638. this._lastTouchMoment;
  1639. /**
  1640. * @private
  1641. * @type {number}
  1642. */
  1643. this._lastX;
  1644. /**
  1645. * @private
  1646. * @type {number}
  1647. */
  1648. this._lastY;
  1649. /**
  1650. * @private
  1651. * @type {module:zrender/core/GestureMgr}
  1652. */
  1653. this._gestureMgr;
  1654. Draggable.call(this);
  1655. this.setHandlerProxy(proxy);
  1656. };
  1657. Handler.prototype = {
  1658. constructor: Handler,
  1659. setHandlerProxy: function (proxy) {
  1660. if (this.proxy) {
  1661. this.proxy.dispose();
  1662. }
  1663. if (proxy) {
  1664. each$1(handlerNames, function (name) {
  1665. proxy.on && proxy.on(name, this[name], this);
  1666. }, this);
  1667. // Attach handler
  1668. proxy.handler = this;
  1669. }
  1670. this.proxy = proxy;
  1671. },
  1672. mousemove: function (event) {
  1673. var x = event.zrX;
  1674. var y = event.zrY;
  1675. var lastHovered = this._hovered;
  1676. var lastHoveredTarget = lastHovered.target;
  1677. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1678. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1679. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1680. // See #6198.
  1681. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1682. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1683. lastHoveredTarget = lastHovered.target;
  1684. }
  1685. var hovered = this._hovered = this.findHover(x, y);
  1686. var hoveredTarget = hovered.target;
  1687. var proxy = this.proxy;
  1688. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1689. // Mouse out on previous hovered element
  1690. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1691. this.dispatchToElement(lastHovered, 'mouseout', event);
  1692. }
  1693. // Mouse moving on one element
  1694. this.dispatchToElement(hovered, 'mousemove', event);
  1695. // Mouse over on a new element
  1696. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1697. this.dispatchToElement(hovered, 'mouseover', event);
  1698. }
  1699. },
  1700. mouseout: function (event) {
  1701. this.dispatchToElement(this._hovered, 'mouseout', event);
  1702. // There might be some doms created by upper layer application
  1703. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1704. // dom created by echarts), where 'globalout' event should not
  1705. // be triggered when mouse enters these doms. (But 'mouseout'
  1706. // should be triggered at the original hovered element as usual).
  1707. var element = event.toElement || event.relatedTarget;
  1708. var innerDom;
  1709. do {
  1710. element = element && element.parentNode;
  1711. }
  1712. while (element && element.nodeType !== 9 && !(
  1713. innerDom = element === this.painterRoot
  1714. ));
  1715. !innerDom && this.trigger('globalout', {event: event});
  1716. },
  1717. /**
  1718. * Resize
  1719. */
  1720. resize: function (event) {
  1721. this._hovered = {};
  1722. },
  1723. /**
  1724. * Dispatch event
  1725. * @param {string} eventName
  1726. * @param {event=} eventArgs
  1727. */
  1728. dispatch: function (eventName, eventArgs) {
  1729. var handler = this[eventName];
  1730. handler && handler.call(this, eventArgs);
  1731. },
  1732. /**
  1733. * Dispose
  1734. */
  1735. dispose: function () {
  1736. this.proxy.dispose();
  1737. this.storage =
  1738. this.proxy =
  1739. this.painter = null;
  1740. },
  1741. /**
  1742. * 设置默认的cursor style
  1743. * @param {string} [cursorStyle='default'] 例如 crosshair
  1744. */
  1745. setCursorStyle: function (cursorStyle) {
  1746. var proxy = this.proxy;
  1747. proxy.setCursor && proxy.setCursor(cursorStyle);
  1748. },
  1749. /**
  1750. * 事件分发代理
  1751. *
  1752. * @private
  1753. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1754. * @param {string} eventName 事件名称
  1755. * @param {Object} event 事件对象
  1756. */
  1757. dispatchToElement: function (targetInfo, eventName, event) {
  1758. targetInfo = targetInfo || {};
  1759. var el = targetInfo.target;
  1760. if (el && el.silent) {
  1761. return;
  1762. }
  1763. var eventHandler = 'on' + eventName;
  1764. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1765. while (el) {
  1766. el[eventHandler]
  1767. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1768. el.trigger(eventName, eventPacket);
  1769. el = el.parent;
  1770. if (eventPacket.cancelBubble) {
  1771. break;
  1772. }
  1773. }
  1774. if (!eventPacket.cancelBubble) {
  1775. // 冒泡到顶级 zrender 对象
  1776. this.trigger(eventName, eventPacket);
  1777. // 分发事件到用户自定义层
  1778. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1779. this.painter && this.painter.eachOtherLayer(function (layer) {
  1780. if (typeof (layer[eventHandler]) === 'function') {
  1781. layer[eventHandler].call(layer, eventPacket);
  1782. }
  1783. if (layer.trigger) {
  1784. layer.trigger(eventName, eventPacket);
  1785. }
  1786. });
  1787. }
  1788. },
  1789. /**
  1790. * @private
  1791. * @param {number} x
  1792. * @param {number} y
  1793. * @param {module:zrender/graphic/Displayable} exclude
  1794. * @return {model:zrender/Element}
  1795. * @method
  1796. */
  1797. findHover: function (x, y, exclude) {
  1798. var list = this.storage.getDisplayList();
  1799. var out = {x: x, y: y};
  1800. for (var i = list.length - 1; i >= 0; i--) {
  1801. var hoverCheckResult;
  1802. if (list[i] !== exclude
  1803. // getDisplayList may include ignored item in VML mode
  1804. && !list[i].ignore
  1805. && (hoverCheckResult = isHover(list[i], x, y))
  1806. ) {
  1807. !out.topTarget && (out.topTarget = list[i]);
  1808. if (hoverCheckResult !== SILENT) {
  1809. out.target = list[i];
  1810. break;
  1811. }
  1812. }
  1813. }
  1814. return out;
  1815. },
  1816. processGesture: function (event, stage) {
  1817. if (!this._gestureMgr) {
  1818. this._gestureMgr = new GestureMgr();
  1819. }
  1820. var gestureMgr = this._gestureMgr;
  1821. stage === 'start' && gestureMgr.clear();
  1822. var gestureInfo = gestureMgr.recognize(
  1823. event,
  1824. this.findHover(event.zrX, event.zrY, null).target,
  1825. this.proxy.dom
  1826. );
  1827. stage === 'end' && gestureMgr.clear();
  1828. // Do not do any preventDefault here. Upper application do that if necessary.
  1829. if (gestureInfo) {
  1830. var type = gestureInfo.type;
  1831. event.gestureEvent = type;
  1832. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  1833. }
  1834. }
  1835. };
  1836. // Common handlers
  1837. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1838. Handler.prototype[name] = function (event) {
  1839. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1840. var hovered = this.findHover(event.zrX, event.zrY);
  1841. var hoveredTarget = hovered.target;
  1842. if (name === 'mousedown') {
  1843. this._downEl = hoveredTarget;
  1844. this._downPoint = [event.zrX, event.zrY];
  1845. // In case click triggered before mouseup
  1846. this._upEl = hoveredTarget;
  1847. }
  1848. else if (name === 'mouseup') {
  1849. this._upEl = hoveredTarget;
  1850. }
  1851. else if (name === 'click') {
  1852. if (this._downEl !== this._upEl
  1853. // Original click event is triggered on the whole canvas element,
  1854. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1855. // which should be filtered, otherwise it will bring trouble to
  1856. // pan and zoom.
  1857. || !this._downPoint
  1858. // Arbitrary value
  1859. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1860. ) {
  1861. return;
  1862. }
  1863. this._downPoint = null;
  1864. }
  1865. this.dispatchToElement(hovered, name, event);
  1866. };
  1867. });
  1868. function isHover(displayable, x, y) {
  1869. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1870. var el = displayable;
  1871. var isSilent;
  1872. while (el) {
  1873. // If clipped by ancestor.
  1874. // FIXME: If clipPath has neither stroke nor fill,
  1875. // el.clipPath.contain(x, y) will always return false.
  1876. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1877. return false;
  1878. }
  1879. if (el.silent) {
  1880. isSilent = true;
  1881. }
  1882. el = el.parent;
  1883. }
  1884. return isSilent ? SILENT : true;
  1885. }
  1886. return false;
  1887. }
  1888. mixin(Handler, Eventful);
  1889. mixin(Handler, Draggable);
  1890. /**
  1891. * 3x2矩阵操作类
  1892. * @exports zrender/tool/matrix
  1893. */
  1894. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1895. ? Array
  1896. : Float32Array;
  1897. /**
  1898. * Create a identity matrix.
  1899. * @return {Float32Array|Array.<number>}
  1900. */
  1901. function create$1() {
  1902. var out = new ArrayCtor$1(6);
  1903. identity(out);
  1904. return out;
  1905. }
  1906. /**
  1907. * 设置矩阵为单位矩阵
  1908. * @param {Float32Array|Array.<number>} out
  1909. */
  1910. function identity(out) {
  1911. out[0] = 1;
  1912. out[1] = 0;
  1913. out[2] = 0;
  1914. out[3] = 1;
  1915. out[4] = 0;
  1916. out[5] = 0;
  1917. return out;
  1918. }
  1919. /**
  1920. * 复制矩阵
  1921. * @param {Float32Array|Array.<number>} out
  1922. * @param {Float32Array|Array.<number>} m
  1923. */
  1924. function copy$1(out, m) {
  1925. out[0] = m[0];
  1926. out[1] = m[1];
  1927. out[2] = m[2];
  1928. out[3] = m[3];
  1929. out[4] = m[4];
  1930. out[5] = m[5];
  1931. return out;
  1932. }
  1933. /**
  1934. * 矩阵相乘
  1935. * @param {Float32Array|Array.<number>} out
  1936. * @param {Float32Array|Array.<number>} m1
  1937. * @param {Float32Array|Array.<number>} m2
  1938. */
  1939. function mul$1(out, m1, m2) {
  1940. // Consider matrix.mul(m, m2, m);
  1941. // where out is the same as m2.
  1942. // So use temp variable to escape error.
  1943. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1944. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1945. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1946. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1947. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1948. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1949. out[0] = out0;
  1950. out[1] = out1;
  1951. out[2] = out2;
  1952. out[3] = out3;
  1953. out[4] = out4;
  1954. out[5] = out5;
  1955. return out;
  1956. }
  1957. /**
  1958. * 平移变换
  1959. * @param {Float32Array|Array.<number>} out
  1960. * @param {Float32Array|Array.<number>} a
  1961. * @param {Float32Array|Array.<number>} v
  1962. */
  1963. function translate(out, a, v) {
  1964. out[0] = a[0];
  1965. out[1] = a[1];
  1966. out[2] = a[2];
  1967. out[3] = a[3];
  1968. out[4] = a[4] + v[0];
  1969. out[5] = a[5] + v[1];
  1970. return out;
  1971. }
  1972. /**
  1973. * 旋转变换
  1974. * @param {Float32Array|Array.<number>} out
  1975. * @param {Float32Array|Array.<number>} a
  1976. * @param {number} rad
  1977. */
  1978. function rotate(out, a, rad) {
  1979. var aa = a[0];
  1980. var ac = a[2];
  1981. var atx = a[4];
  1982. var ab = a[1];
  1983. var ad = a[3];
  1984. var aty = a[5];
  1985. var st = Math.sin(rad);
  1986. var ct = Math.cos(rad);
  1987. out[0] = aa * ct + ab * st;
  1988. out[1] = -aa * st + ab * ct;
  1989. out[2] = ac * ct + ad * st;
  1990. out[3] = -ac * st + ct * ad;
  1991. out[4] = ct * atx + st * aty;
  1992. out[5] = ct * aty - st * atx;
  1993. return out;
  1994. }
  1995. /**
  1996. * 缩放变换
  1997. * @param {Float32Array|Array.<number>} out
  1998. * @param {Float32Array|Array.<number>} a
  1999. * @param {Float32Array|Array.<number>} v
  2000. */
  2001. function scale$1(out, a, v) {
  2002. var vx = v[0];
  2003. var vy = v[1];
  2004. out[0] = a[0] * vx;
  2005. out[1] = a[1] * vy;
  2006. out[2] = a[2] * vx;
  2007. out[3] = a[3] * vy;
  2008. out[4] = a[4] * vx;
  2009. out[5] = a[5] * vy;
  2010. return out;
  2011. }
  2012. /**
  2013. * 求逆矩阵
  2014. * @param {Float32Array|Array.<number>} out
  2015. * @param {Float32Array|Array.<number>} a
  2016. */
  2017. function invert(out, a) {
  2018. var aa = a[0];
  2019. var ac = a[2];
  2020. var atx = a[4];
  2021. var ab = a[1];
  2022. var ad = a[3];
  2023. var aty = a[5];
  2024. var det = aa * ad - ab * ac;
  2025. if (!det) {
  2026. return null;
  2027. }
  2028. det = 1.0 / det;
  2029. out[0] = ad * det;
  2030. out[1] = -ab * det;
  2031. out[2] = -ac * det;
  2032. out[3] = aa * det;
  2033. out[4] = (ac * aty - ad * atx) * det;
  2034. out[5] = (ab * atx - aa * aty) * det;
  2035. return out;
  2036. }
  2037. /**
  2038. * Clone a new matrix.
  2039. * @param {Float32Array|Array.<number>} a
  2040. */
  2041. /**
  2042. * 提供变换扩展
  2043. * @module zrender/mixin/Transformable
  2044. * @author pissang (https://www.github.com/pissang)
  2045. */
  2046. var mIdentity = identity;
  2047. var EPSILON = 5e-5;
  2048. function isNotAroundZero(val) {
  2049. return val > EPSILON || val < -EPSILON;
  2050. }
  2051. /**
  2052. * @alias module:zrender/mixin/Transformable
  2053. * @constructor
  2054. */
  2055. var Transformable = function (opts) {
  2056. opts = opts || {};
  2057. // If there are no given position, rotation, scale
  2058. if (!opts.position) {
  2059. /**
  2060. * 平移
  2061. * @type {Array.<number>}
  2062. * @default [0, 0]
  2063. */
  2064. this.position = [0, 0];
  2065. }
  2066. if (opts.rotation == null) {
  2067. /**
  2068. * 旋转
  2069. * @type {Array.<number>}
  2070. * @default 0
  2071. */
  2072. this.rotation = 0;
  2073. }
  2074. if (!opts.scale) {
  2075. /**
  2076. * 缩放
  2077. * @type {Array.<number>}
  2078. * @default [1, 1]
  2079. */
  2080. this.scale = [1, 1];
  2081. }
  2082. /**
  2083. * 旋转和缩放的原点
  2084. * @type {Array.<number>}
  2085. * @default null
  2086. */
  2087. this.origin = this.origin || null;
  2088. };
  2089. var transformableProto = Transformable.prototype;
  2090. transformableProto.transform = null;
  2091. /**
  2092. * 判断是否需要有坐标变换
  2093. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2094. */
  2095. transformableProto.needLocalTransform = function () {
  2096. return isNotAroundZero(this.rotation)
  2097. || isNotAroundZero(this.position[0])
  2098. || isNotAroundZero(this.position[1])
  2099. || isNotAroundZero(this.scale[0] - 1)
  2100. || isNotAroundZero(this.scale[1] - 1);
  2101. };
  2102. var scaleTmp = [];
  2103. transformableProto.updateTransform = function () {
  2104. var parent = this.parent;
  2105. var parentHasTransform = parent && parent.transform;
  2106. var needLocalTransform = this.needLocalTransform();
  2107. var m = this.transform;
  2108. if (!(needLocalTransform || parentHasTransform)) {
  2109. m && mIdentity(m);
  2110. return;
  2111. }
  2112. m = m || create$1();
  2113. if (needLocalTransform) {
  2114. this.getLocalTransform(m);
  2115. }
  2116. else {
  2117. mIdentity(m);
  2118. }
  2119. // 应用父节点变换
  2120. if (parentHasTransform) {
  2121. if (needLocalTransform) {
  2122. mul$1(m, parent.transform, m);
  2123. }
  2124. else {
  2125. copy$1(m, parent.transform);
  2126. }
  2127. }
  2128. // 保存这个变换矩阵
  2129. this.transform = m;
  2130. var globalScaleRatio = this.globalScaleRatio;
  2131. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2132. this.getGlobalScale(scaleTmp);
  2133. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2134. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2135. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2136. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2137. m[0] *= sx;
  2138. m[1] *= sx;
  2139. m[2] *= sy;
  2140. m[3] *= sy;
  2141. }
  2142. this.invTransform = this.invTransform || create$1();
  2143. invert(this.invTransform, m);
  2144. };
  2145. transformableProto.getLocalTransform = function (m) {
  2146. return Transformable.getLocalTransform(this, m);
  2147. };
  2148. /**
  2149. * 将自己的transform应用到context上
  2150. * @param {CanvasRenderingContext2D} ctx
  2151. */
  2152. transformableProto.setTransform = function (ctx) {
  2153. var m = this.transform;
  2154. var dpr = ctx.dpr || 1;
  2155. if (m) {
  2156. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2157. }
  2158. else {
  2159. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2160. }
  2161. };
  2162. transformableProto.restoreTransform = function (ctx) {
  2163. var dpr = ctx.dpr || 1;
  2164. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2165. };
  2166. var tmpTransform = [];
  2167. var originTransform = create$1();
  2168. transformableProto.setLocalTransform = function (m) {
  2169. if (!m) {
  2170. // TODO return or set identity?
  2171. return;
  2172. }
  2173. var sx = m[0] * m[0] + m[1] * m[1];
  2174. var sy = m[2] * m[2] + m[3] * m[3];
  2175. var position = this.position;
  2176. var scale$$1 = this.scale;
  2177. if (isNotAroundZero(sx - 1)) {
  2178. sx = Math.sqrt(sx);
  2179. }
  2180. if (isNotAroundZero(sy - 1)) {
  2181. sy = Math.sqrt(sy);
  2182. }
  2183. if (m[0] < 0) {
  2184. sx = -sx;
  2185. }
  2186. if (m[3] < 0) {
  2187. sy = -sy;
  2188. }
  2189. position[0] = m[4];
  2190. position[1] = m[5];
  2191. scale$$1[0] = sx;
  2192. scale$$1[1] = sy;
  2193. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2194. };
  2195. /**
  2196. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2197. */
  2198. transformableProto.decomposeTransform = function () {
  2199. if (!this.transform) {
  2200. return;
  2201. }
  2202. var parent = this.parent;
  2203. var m = this.transform;
  2204. if (parent && parent.transform) {
  2205. // Get local transform and decompose them to position, scale, rotation
  2206. mul$1(tmpTransform, parent.invTransform, m);
  2207. m = tmpTransform;
  2208. }
  2209. var origin = this.origin;
  2210. if (origin && (origin[0] || origin[1])) {
  2211. originTransform[4] = origin[0];
  2212. originTransform[5] = origin[1];
  2213. mul$1(tmpTransform, m, originTransform);
  2214. tmpTransform[4] -= origin[0];
  2215. tmpTransform[5] -= origin[1];
  2216. m = tmpTransform;
  2217. }
  2218. this.setLocalTransform(m);
  2219. };
  2220. /**
  2221. * Get global scale
  2222. * @return {Array.<number>}
  2223. */
  2224. transformableProto.getGlobalScale = function (out) {
  2225. var m = this.transform;
  2226. out = out || [];
  2227. if (!m) {
  2228. out[0] = 1;
  2229. out[1] = 1;
  2230. return out;
  2231. }
  2232. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2233. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2234. if (m[0] < 0) {
  2235. out[0] = -out[0];
  2236. }
  2237. if (m[3] < 0) {
  2238. out[1] = -out[1];
  2239. }
  2240. return out;
  2241. };
  2242. /**
  2243. * 变换坐标位置到 shape 的局部坐标空间
  2244. * @method
  2245. * @param {number} x
  2246. * @param {number} y
  2247. * @return {Array.<number>}
  2248. */
  2249. transformableProto.transformCoordToLocal = function (x, y) {
  2250. var v2 = [x, y];
  2251. var invTransform = this.invTransform;
  2252. if (invTransform) {
  2253. applyTransform(v2, v2, invTransform);
  2254. }
  2255. return v2;
  2256. };
  2257. /**
  2258. * 变换局部坐标位置到全局坐标空间
  2259. * @method
  2260. * @param {number} x
  2261. * @param {number} y
  2262. * @return {Array.<number>}
  2263. */
  2264. transformableProto.transformCoordToGlobal = function (x, y) {
  2265. var v2 = [x, y];
  2266. var transform = this.transform;
  2267. if (transform) {
  2268. applyTransform(v2, v2, transform);
  2269. }
  2270. return v2;
  2271. };
  2272. /**
  2273. * @static
  2274. * @param {Object} target
  2275. * @param {Array.<number>} target.origin
  2276. * @param {number} target.rotation
  2277. * @param {Array.<number>} target.position
  2278. * @param {Array.<number>} [m]
  2279. */
  2280. Transformable.getLocalTransform = function (target, m) {
  2281. m = m || [];
  2282. mIdentity(m);
  2283. var origin = target.origin;
  2284. var scale$$1 = target.scale || [1, 1];
  2285. var rotation = target.rotation || 0;
  2286. var position = target.position || [0, 0];
  2287. if (origin) {
  2288. // Translate to origin
  2289. m[4] -= origin[0];
  2290. m[5] -= origin[1];
  2291. }
  2292. scale$1(m, m, scale$$1);
  2293. if (rotation) {
  2294. rotate(m, m, rotation);
  2295. }
  2296. if (origin) {
  2297. // Translate back from origin
  2298. m[4] += origin[0];
  2299. m[5] += origin[1];
  2300. }
  2301. m[4] += position[0];
  2302. m[5] += position[1];
  2303. return m;
  2304. };
  2305. /**
  2306. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2307. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2308. * @exports zrender/animation/easing
  2309. */
  2310. var easing = {
  2311. /**
  2312. * @param {number} k
  2313. * @return {number}
  2314. */
  2315. linear: function (k) {
  2316. return k;
  2317. },
  2318. /**
  2319. * @param {number} k
  2320. * @return {number}
  2321. */
  2322. quadraticIn: function (k) {
  2323. return k * k;
  2324. },
  2325. /**
  2326. * @param {number} k
  2327. * @return {number}
  2328. */
  2329. quadraticOut: function (k) {
  2330. return k * (2 - k);
  2331. },
  2332. /**
  2333. * @param {number} k
  2334. * @return {number}
  2335. */
  2336. quadraticInOut: function (k) {
  2337. if ((k *= 2) < 1) {
  2338. return 0.5 * k * k;
  2339. }
  2340. return -0.5 * (--k * (k - 2) - 1);
  2341. },
  2342. // 三次方的缓动(t^3)
  2343. /**
  2344. * @param {number} k
  2345. * @return {number}
  2346. */
  2347. cubicIn: function (k) {
  2348. return k * k * k;
  2349. },
  2350. /**
  2351. * @param {number} k
  2352. * @return {number}
  2353. */
  2354. cubicOut: function (k) {
  2355. return --k * k * k + 1;
  2356. },
  2357. /**
  2358. * @param {number} k
  2359. * @return {number}
  2360. */
  2361. cubicInOut: function (k) {
  2362. if ((k *= 2) < 1) {
  2363. return 0.5 * k * k * k;
  2364. }
  2365. return 0.5 * ((k -= 2) * k * k + 2);
  2366. },
  2367. // 四次方的缓动(t^4)
  2368. /**
  2369. * @param {number} k
  2370. * @return {number}
  2371. */
  2372. quarticIn: function (k) {
  2373. return k * k * k * k;
  2374. },
  2375. /**
  2376. * @param {number} k
  2377. * @return {number}
  2378. */
  2379. quarticOut: function (k) {
  2380. return 1 - (--k * k * k * k);
  2381. },
  2382. /**
  2383. * @param {number} k
  2384. * @return {number}
  2385. */
  2386. quarticInOut: function (k) {
  2387. if ((k *= 2) < 1) {
  2388. return 0.5 * k * k * k * k;
  2389. }
  2390. return -0.5 * ((k -= 2) * k * k * k - 2);
  2391. },
  2392. // 五次方的缓动(t^5)
  2393. /**
  2394. * @param {number} k
  2395. * @return {number}
  2396. */
  2397. quinticIn: function (k) {
  2398. return k * k * k * k * k;
  2399. },
  2400. /**
  2401. * @param {number} k
  2402. * @return {number}
  2403. */
  2404. quinticOut: function (k) {
  2405. return --k * k * k * k * k + 1;
  2406. },
  2407. /**
  2408. * @param {number} k
  2409. * @return {number}
  2410. */
  2411. quinticInOut: function (k) {
  2412. if ((k *= 2) < 1) {
  2413. return 0.5 * k * k * k * k * k;
  2414. }
  2415. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2416. },
  2417. // 正弦曲线的缓动(sin(t))
  2418. /**
  2419. * @param {number} k
  2420. * @return {number}
  2421. */
  2422. sinusoidalIn: function (k) {
  2423. return 1 - Math.cos(k * Math.PI / 2);
  2424. },
  2425. /**
  2426. * @param {number} k
  2427. * @return {number}
  2428. */
  2429. sinusoidalOut: function (k) {
  2430. return Math.sin(k * Math.PI / 2);
  2431. },
  2432. /**
  2433. * @param {number} k
  2434. * @return {number}
  2435. */
  2436. sinusoidalInOut: function (k) {
  2437. return 0.5 * (1 - Math.cos(Math.PI * k));
  2438. },
  2439. // 指数曲线的缓动(2^t)
  2440. /**
  2441. * @param {number} k
  2442. * @return {number}
  2443. */
  2444. exponentialIn: function (k) {
  2445. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2446. },
  2447. /**
  2448. * @param {number} k
  2449. * @return {number}
  2450. */
  2451. exponentialOut: function (k) {
  2452. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2453. },
  2454. /**
  2455. * @param {number} k
  2456. * @return {number}
  2457. */
  2458. exponentialInOut: function (k) {
  2459. if (k === 0) {
  2460. return 0;
  2461. }
  2462. if (k === 1) {
  2463. return 1;
  2464. }
  2465. if ((k *= 2) < 1) {
  2466. return 0.5 * Math.pow(1024, k - 1);
  2467. }
  2468. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2469. },
  2470. // 圆形曲线的缓动(sqrt(1-t^2))
  2471. /**
  2472. * @param {number} k
  2473. * @return {number}
  2474. */
  2475. circularIn: function (k) {
  2476. return 1 - Math.sqrt(1 - k * k);
  2477. },
  2478. /**
  2479. * @param {number} k
  2480. * @return {number}
  2481. */
  2482. circularOut: function (k) {
  2483. return Math.sqrt(1 - (--k * k));
  2484. },
  2485. /**
  2486. * @param {number} k
  2487. * @return {number}
  2488. */
  2489. circularInOut: function (k) {
  2490. if ((k *= 2) < 1) {
  2491. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2492. }
  2493. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2494. },
  2495. // 创建类似于弹簧在停止前来回振荡的动画
  2496. /**
  2497. * @param {number} k
  2498. * @return {number}
  2499. */
  2500. elasticIn: function (k) {
  2501. var s;
  2502. var a = 0.1;
  2503. var p = 0.4;
  2504. if (k === 0) {
  2505. return 0;
  2506. }
  2507. if (k === 1) {
  2508. return 1;
  2509. }
  2510. if (!a || a < 1) {
  2511. a = 1;
  2512. s = p / 4;
  2513. }
  2514. else {
  2515. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2516. }
  2517. return -(a * Math.pow(2, 10 * (k -= 1))
  2518. * Math.sin((k - s) * (2 * Math.PI) / p));
  2519. },
  2520. /**
  2521. * @param {number} k
  2522. * @return {number}
  2523. */
  2524. elasticOut: function (k) {
  2525. var s;
  2526. var a = 0.1;
  2527. var p = 0.4;
  2528. if (k === 0) {
  2529. return 0;
  2530. }
  2531. if (k === 1) {
  2532. return 1;
  2533. }
  2534. if (!a || a < 1) {
  2535. a = 1;
  2536. s = p / 4;
  2537. }
  2538. else {
  2539. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2540. }
  2541. return (a * Math.pow(2, -10 * k)
  2542. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2543. },
  2544. /**
  2545. * @param {number} k
  2546. * @return {number}
  2547. */
  2548. elasticInOut: function (k) {
  2549. var s;
  2550. var a = 0.1;
  2551. var p = 0.4;
  2552. if (k === 0) {
  2553. return 0;
  2554. }
  2555. if (k === 1) {
  2556. return 1;
  2557. }
  2558. if (!a || a < 1) {
  2559. a = 1;
  2560. s = p / 4;
  2561. }
  2562. else {
  2563. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2564. }
  2565. if ((k *= 2) < 1) {
  2566. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2567. * Math.sin((k - s) * (2 * Math.PI) / p));
  2568. }
  2569. return a * Math.pow(2, -10 * (k -= 1))
  2570. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2571. },
  2572. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2573. /**
  2574. * @param {number} k
  2575. * @return {number}
  2576. */
  2577. backIn: function (k) {
  2578. var s = 1.70158;
  2579. return k * k * ((s + 1) * k - s);
  2580. },
  2581. /**
  2582. * @param {number} k
  2583. * @return {number}
  2584. */
  2585. backOut: function (k) {
  2586. var s = 1.70158;
  2587. return --k * k * ((s + 1) * k + s) + 1;
  2588. },
  2589. /**
  2590. * @param {number} k
  2591. * @return {number}
  2592. */
  2593. backInOut: function (k) {
  2594. var s = 1.70158 * 1.525;
  2595. if ((k *= 2) < 1) {
  2596. return 0.5 * (k * k * ((s + 1) * k - s));
  2597. }
  2598. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2599. },
  2600. // 创建弹跳效果
  2601. /**
  2602. * @param {number} k
  2603. * @return {number}
  2604. */
  2605. bounceIn: function (k) {
  2606. return 1 - easing.bounceOut(1 - k);
  2607. },
  2608. /**
  2609. * @param {number} k
  2610. * @return {number}
  2611. */
  2612. bounceOut: function (k) {
  2613. if (k < (1 / 2.75)) {
  2614. return 7.5625 * k * k;
  2615. }
  2616. else if (k < (2 / 2.75)) {
  2617. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2618. }
  2619. else if (k < (2.5 / 2.75)) {
  2620. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2621. }
  2622. else {
  2623. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2624. }
  2625. },
  2626. /**
  2627. * @param {number} k
  2628. * @return {number}
  2629. */
  2630. bounceInOut: function (k) {
  2631. if (k < 0.5) {
  2632. return easing.bounceIn(k * 2) * 0.5;
  2633. }
  2634. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2635. }
  2636. };
  2637. /**
  2638. * 动画主控制器
  2639. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2640. * @config life(1000) 动画时长
  2641. * @config delay(0) 动画延迟时间
  2642. * @config loop(true)
  2643. * @config gap(0) 循环的间隔时间
  2644. * @config onframe
  2645. * @config easing(optional)
  2646. * @config ondestroy(optional)
  2647. * @config onrestart(optional)
  2648. *
  2649. * TODO pause
  2650. */
  2651. function Clip(options) {
  2652. this._target = options.target;
  2653. // 生命周期
  2654. this._life = options.life || 1000;
  2655. // 延时
  2656. this._delay = options.delay || 0;
  2657. // 开始时间
  2658. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2659. this._initialized = false;
  2660. // 是否循环
  2661. this.loop = options.loop == null ? false : options.loop;
  2662. this.gap = options.gap || 0;
  2663. this.easing = options.easing || 'Linear';
  2664. this.onframe = options.onframe;
  2665. this.ondestroy = options.ondestroy;
  2666. this.onrestart = options.onrestart;
  2667. this._pausedTime = 0;
  2668. this._paused = false;
  2669. }
  2670. Clip.prototype = {
  2671. constructor: Clip,
  2672. step: function (globalTime, deltaTime) {
  2673. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2674. // PENDING
  2675. if (!this._initialized) {
  2676. this._startTime = globalTime + this._delay;
  2677. this._initialized = true;
  2678. }
  2679. if (this._paused) {
  2680. this._pausedTime += deltaTime;
  2681. return;
  2682. }
  2683. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2684. // 还没开始
  2685. if (percent < 0) {
  2686. return;
  2687. }
  2688. percent = Math.min(percent, 1);
  2689. var easing$$1 = this.easing;
  2690. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  2691. var schedule = typeof easingFunc === 'function'
  2692. ? easingFunc(percent)
  2693. : percent;
  2694. this.fire('frame', schedule);
  2695. // 结束
  2696. if (percent === 1) {
  2697. if (this.loop) {
  2698. this.restart(globalTime);
  2699. // 重新开始周期
  2700. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2701. return 'restart';
  2702. }
  2703. // 动画完成将这个控制器标识为待删除
  2704. // 在Animation.update中进行批量删除
  2705. this._needsRemove = true;
  2706. return 'destroy';
  2707. }
  2708. return null;
  2709. },
  2710. restart: function (globalTime) {
  2711. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2712. this._startTime = globalTime - remainder + this.gap;
  2713. this._pausedTime = 0;
  2714. this._needsRemove = false;
  2715. },
  2716. fire: function (eventType, arg) {
  2717. eventType = 'on' + eventType;
  2718. if (this[eventType]) {
  2719. this[eventType](this._target, arg);
  2720. }
  2721. },
  2722. pause: function () {
  2723. this._paused = true;
  2724. },
  2725. resume: function () {
  2726. this._paused = false;
  2727. }
  2728. };
  2729. // Simple LRU cache use doubly linked list
  2730. // @module zrender/core/LRU
  2731. /**
  2732. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2733. * @constructor
  2734. */
  2735. var LinkedList = function () {
  2736. /**
  2737. * @type {module:zrender/core/LRU~Entry}
  2738. */
  2739. this.head = null;
  2740. /**
  2741. * @type {module:zrender/core/LRU~Entry}
  2742. */
  2743. this.tail = null;
  2744. this._len = 0;
  2745. };
  2746. var linkedListProto = LinkedList.prototype;
  2747. /**
  2748. * Insert a new value at the tail
  2749. * @param {} val
  2750. * @return {module:zrender/core/LRU~Entry}
  2751. */
  2752. linkedListProto.insert = function (val) {
  2753. var entry = new Entry(val);
  2754. this.insertEntry(entry);
  2755. return entry;
  2756. };
  2757. /**
  2758. * Insert an entry at the tail
  2759. * @param {module:zrender/core/LRU~Entry} entry
  2760. */
  2761. linkedListProto.insertEntry = function (entry) {
  2762. if (!this.head) {
  2763. this.head = this.tail = entry;
  2764. }
  2765. else {
  2766. this.tail.next = entry;
  2767. entry.prev = this.tail;
  2768. entry.next = null;
  2769. this.tail = entry;
  2770. }
  2771. this._len++;
  2772. };
  2773. /**
  2774. * Remove entry.
  2775. * @param {module:zrender/core/LRU~Entry} entry
  2776. */
  2777. linkedListProto.remove = function (entry) {
  2778. var prev = entry.prev;
  2779. var next = entry.next;
  2780. if (prev) {
  2781. prev.next = next;
  2782. }
  2783. else {
  2784. // Is head
  2785. this.head = next;
  2786. }
  2787. if (next) {
  2788. next.prev = prev;
  2789. }
  2790. else {
  2791. // Is tail
  2792. this.tail = prev;
  2793. }
  2794. entry.next = entry.prev = null;
  2795. this._len--;
  2796. };
  2797. /**
  2798. * @return {number}
  2799. */
  2800. linkedListProto.len = function () {
  2801. return this._len;
  2802. };
  2803. /**
  2804. * Clear list
  2805. */
  2806. linkedListProto.clear = function () {
  2807. this.head = this.tail = null;
  2808. this._len = 0;
  2809. };
  2810. /**
  2811. * @constructor
  2812. * @param {} val
  2813. */
  2814. var Entry = function (val) {
  2815. /**
  2816. * @type {}
  2817. */
  2818. this.value = val;
  2819. /**
  2820. * @type {module:zrender/core/LRU~Entry}
  2821. */
  2822. this.next;
  2823. /**
  2824. * @type {module:zrender/core/LRU~Entry}
  2825. */
  2826. this.prev;
  2827. };
  2828. /**
  2829. * LRU Cache
  2830. * @constructor
  2831. * @alias module:zrender/core/LRU
  2832. */
  2833. var LRU = function (maxSize) {
  2834. this._list = new LinkedList();
  2835. this._map = {};
  2836. this._maxSize = maxSize || 10;
  2837. this._lastRemovedEntry = null;
  2838. };
  2839. var LRUProto = LRU.prototype;
  2840. /**
  2841. * @param {string} key
  2842. * @param {} value
  2843. * @return {} Removed value
  2844. */
  2845. LRUProto.put = function (key, value) {
  2846. var list = this._list;
  2847. var map = this._map;
  2848. var removed = null;
  2849. if (map[key] == null) {
  2850. var len = list.len();
  2851. // Reuse last removed entry
  2852. var entry = this._lastRemovedEntry;
  2853. if (len >= this._maxSize && len > 0) {
  2854. // Remove the least recently used
  2855. var leastUsedEntry = list.head;
  2856. list.remove(leastUsedEntry);
  2857. delete map[leastUsedEntry.key];
  2858. removed = leastUsedEntry.value;
  2859. this._lastRemovedEntry = leastUsedEntry;
  2860. }
  2861. if (entry) {
  2862. entry.value = value;
  2863. }
  2864. else {
  2865. entry = new Entry(value);
  2866. }
  2867. entry.key = key;
  2868. list.insertEntry(entry);
  2869. map[key] = entry;
  2870. }
  2871. return removed;
  2872. };
  2873. /**
  2874. * @param {string} key
  2875. * @return {}
  2876. */
  2877. LRUProto.get = function (key) {
  2878. var entry = this._map[key];
  2879. var list = this._list;
  2880. if (entry != null) {
  2881. // Put the latest used entry in the tail
  2882. if (entry !== list.tail) {
  2883. list.remove(entry);
  2884. list.insertEntry(entry);
  2885. }
  2886. return entry.value;
  2887. }
  2888. };
  2889. /**
  2890. * Clear the cache
  2891. */
  2892. LRUProto.clear = function () {
  2893. this._list.clear();
  2894. this._map = {};
  2895. };
  2896. var kCSSColorTable = {
  2897. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  2898. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  2899. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  2900. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  2901. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  2902. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  2903. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  2904. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  2905. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  2906. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  2907. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  2908. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  2909. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  2910. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  2911. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  2912. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  2913. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  2914. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  2915. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  2916. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  2917. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  2918. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  2919. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  2920. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  2921. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  2922. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  2923. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  2924. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  2925. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  2926. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  2927. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  2928. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  2929. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  2930. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  2931. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  2932. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  2933. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  2934. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  2935. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  2936. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  2937. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  2938. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  2939. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  2940. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  2941. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  2942. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  2943. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  2944. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  2945. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  2946. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  2947. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  2948. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  2949. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  2950. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  2951. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  2952. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  2953. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  2954. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  2955. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  2956. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  2957. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  2958. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  2959. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  2960. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  2961. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  2962. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  2963. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  2964. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  2965. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  2966. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  2967. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  2968. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  2969. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  2970. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  2971. };
  2972. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2973. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2974. return i < 0 ? 0 : i > 255 ? 255 : i;
  2975. }
  2976. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2977. return f < 0 ? 0 : f > 1 ? 1 : f;
  2978. }
  2979. function parseCssInt(str) { // int or percentage.
  2980. if (str.length && str.charAt(str.length - 1) === '%') {
  2981. return clampCssByte(parseFloat(str) / 100 * 255);
  2982. }
  2983. return clampCssByte(parseInt(str, 10));
  2984. }
  2985. function parseCssFloat(str) { // float or percentage.
  2986. if (str.length && str.charAt(str.length - 1) === '%') {
  2987. return clampCssFloat(parseFloat(str) / 100);
  2988. }
  2989. return clampCssFloat(parseFloat(str));
  2990. }
  2991. function cssHueToRgb(m1, m2, h) {
  2992. if (h < 0) {
  2993. h += 1;
  2994. }
  2995. else if (h > 1) {
  2996. h -= 1;
  2997. }
  2998. if (h * 6 < 1) {
  2999. return m1 + (m2 - m1) * h * 6;
  3000. }
  3001. if (h * 2 < 1) {
  3002. return m2;
  3003. }
  3004. if (h * 3 < 2) {
  3005. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3006. }
  3007. return m1;
  3008. }
  3009. function setRgba(out, r, g, b, a) {
  3010. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  3011. return out;
  3012. }
  3013. function copyRgba(out, a) {
  3014. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  3015. return out;
  3016. }
  3017. var colorCache = new LRU(20);
  3018. var lastRemovedArr = null;
  3019. function putToCache(colorStr, rgbaArr) {
  3020. // Reuse removed array
  3021. if (lastRemovedArr) {
  3022. copyRgba(lastRemovedArr, rgbaArr);
  3023. }
  3024. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3025. }
  3026. /**
  3027. * @param {string} colorStr
  3028. * @param {Array.<number>} out
  3029. * @return {Array.<number>}
  3030. * @memberOf module:zrender/util/color
  3031. */
  3032. function parse(colorStr, rgbaArr) {
  3033. if (!colorStr) {
  3034. return;
  3035. }
  3036. rgbaArr = rgbaArr || [];
  3037. var cached = colorCache.get(colorStr);
  3038. if (cached) {
  3039. return copyRgba(rgbaArr, cached);
  3040. }
  3041. // colorStr may be not string
  3042. colorStr = colorStr + '';
  3043. // Remove all whitespace, not compliant, but should just be more accepting.
  3044. var str = colorStr.replace(/ /g, '').toLowerCase();
  3045. // Color keywords (and transparent) lookup.
  3046. if (str in kCSSColorTable) {
  3047. copyRgba(rgbaArr, kCSSColorTable[str]);
  3048. putToCache(colorStr, rgbaArr);
  3049. return rgbaArr;
  3050. }
  3051. // #abc and #abc123 syntax.
  3052. if (str.charAt(0) === '#') {
  3053. if (str.length === 4) {
  3054. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3055. if (!(iv >= 0 && iv <= 0xfff)) {
  3056. setRgba(rgbaArr, 0, 0, 0, 1);
  3057. return; // Covers NaN.
  3058. }
  3059. setRgba(rgbaArr,
  3060. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3061. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3062. (iv & 0xf) | ((iv & 0xf) << 4),
  3063. 1
  3064. );
  3065. putToCache(colorStr, rgbaArr);
  3066. return rgbaArr;
  3067. }
  3068. else if (str.length === 7) {
  3069. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3070. if (!(iv >= 0 && iv <= 0xffffff)) {
  3071. setRgba(rgbaArr, 0, 0, 0, 1);
  3072. return; // Covers NaN.
  3073. }
  3074. setRgba(rgbaArr,
  3075. (iv & 0xff0000) >> 16,
  3076. (iv & 0xff00) >> 8,
  3077. iv & 0xff,
  3078. 1
  3079. );
  3080. putToCache(colorStr, rgbaArr);
  3081. return rgbaArr;
  3082. }
  3083. return;
  3084. }
  3085. var op = str.indexOf('(');
  3086. var ep = str.indexOf(')');
  3087. if (op !== -1 && ep + 1 === str.length) {
  3088. var fname = str.substr(0, op);
  3089. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3090. var alpha = 1; // To allow case fallthrough.
  3091. switch (fname) {
  3092. case 'rgba':
  3093. if (params.length !== 4) {
  3094. setRgba(rgbaArr, 0, 0, 0, 1);
  3095. return;
  3096. }
  3097. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3098. // Fall through.
  3099. case 'rgb':
  3100. if (params.length !== 3) {
  3101. setRgba(rgbaArr, 0, 0, 0, 1);
  3102. return;
  3103. }
  3104. setRgba(rgbaArr,
  3105. parseCssInt(params[0]),
  3106. parseCssInt(params[1]),
  3107. parseCssInt(params[2]),
  3108. alpha
  3109. );
  3110. putToCache(colorStr, rgbaArr);
  3111. return rgbaArr;
  3112. case 'hsla':
  3113. if (params.length !== 4) {
  3114. setRgba(rgbaArr, 0, 0, 0, 1);
  3115. return;
  3116. }
  3117. params[3] = parseCssFloat(params[3]);
  3118. hsla2rgba(params, rgbaArr);
  3119. putToCache(colorStr, rgbaArr);
  3120. return rgbaArr;
  3121. case 'hsl':
  3122. if (params.length !== 3) {
  3123. setRgba(rgbaArr, 0, 0, 0, 1);
  3124. return;
  3125. }
  3126. hsla2rgba(params, rgbaArr);
  3127. putToCache(colorStr, rgbaArr);
  3128. return rgbaArr;
  3129. default:
  3130. return;
  3131. }
  3132. }
  3133. setRgba(rgbaArr, 0, 0, 0, 1);
  3134. return;
  3135. }
  3136. /**
  3137. * @param {Array.<number>} hsla
  3138. * @param {Array.<number>} rgba
  3139. * @return {Array.<number>} rgba
  3140. */
  3141. function hsla2rgba(hsla, rgba) {
  3142. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3143. // NOTE(deanm): According to the CSS spec s/l should only be
  3144. // percentages, but we don't bother and let float or percentage.
  3145. var s = parseCssFloat(hsla[1]);
  3146. var l = parseCssFloat(hsla[2]);
  3147. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3148. var m1 = l * 2 - m2;
  3149. rgba = rgba || [];
  3150. setRgba(rgba,
  3151. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3152. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3153. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3154. 1
  3155. );
  3156. if (hsla.length === 4) {
  3157. rgba[3] = hsla[3];
  3158. }
  3159. return rgba;
  3160. }
  3161. /**
  3162. * @param {string} color
  3163. * @param {number} level
  3164. * @return {string}
  3165. * @memberOf module:zrender/util/color
  3166. */
  3167. function lift(color, level) {
  3168. var colorArr = parse(color);
  3169. if (colorArr) {
  3170. for (var i = 0; i < 3; i++) {
  3171. if (level < 0) {
  3172. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3173. }
  3174. else {
  3175. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3176. }
  3177. if (colorArr[i] > 255) {
  3178. colorArr[i] = 255;
  3179. }
  3180. else if (color[i] < 0) {
  3181. colorArr[i] = 0;
  3182. }
  3183. }
  3184. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3185. }
  3186. }
  3187. /**
  3188. * @param {string} color
  3189. * @return {string}
  3190. * @memberOf module:zrender/util/color
  3191. */
  3192. /**
  3193. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3194. * @param {number} normalizedValue A float between 0 and 1.
  3195. * @param {Array.<Array.<number>>} colors List of rgba color array
  3196. * @param {Array.<number>} [out] Mapped gba color array
  3197. * @return {Array.<number>} will be null/undefined if input illegal.
  3198. */
  3199. /**
  3200. * @deprecated
  3201. */
  3202. /**
  3203. * @param {number} normalizedValue A float between 0 and 1.
  3204. * @param {Array.<string>} colors Color list.
  3205. * @param {boolean=} fullOutput Default false.
  3206. * @return {(string|Object)} Result color. If fullOutput,
  3207. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3208. * @memberOf module:zrender/util/color
  3209. */
  3210. /**
  3211. * @deprecated
  3212. */
  3213. /**
  3214. * @param {string} color
  3215. * @param {number=} h 0 ~ 360, ignore when null.
  3216. * @param {number=} s 0 ~ 1, ignore when null.
  3217. * @param {number=} l 0 ~ 1, ignore when null.
  3218. * @return {string} Color string in rgba format.
  3219. * @memberOf module:zrender/util/color
  3220. */
  3221. /**
  3222. * @param {string} color
  3223. * @param {number=} alpha 0 ~ 1
  3224. * @return {string} Color string in rgba format.
  3225. * @memberOf module:zrender/util/color
  3226. */
  3227. /**
  3228. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3229. * @param {string} type 'rgba', 'hsva', ...
  3230. * @return {string} Result color. (If input illegal, return undefined).
  3231. */
  3232. function stringify(arrColor, type) {
  3233. if (!arrColor || !arrColor.length) {
  3234. return;
  3235. }
  3236. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3237. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3238. colorStr += ',' + arrColor[3];
  3239. }
  3240. return type + '(' + colorStr + ')';
  3241. }
  3242. /**
  3243. * @module echarts/animation/Animator
  3244. */
  3245. var arraySlice = Array.prototype.slice;
  3246. function defaultGetter(target, key) {
  3247. return target[key];
  3248. }
  3249. function defaultSetter(target, key, value) {
  3250. target[key] = value;
  3251. }
  3252. /**
  3253. * @param {number} p0
  3254. * @param {number} p1
  3255. * @param {number} percent
  3256. * @return {number}
  3257. */
  3258. function interpolateNumber(p0, p1, percent) {
  3259. return (p1 - p0) * percent + p0;
  3260. }
  3261. /**
  3262. * @param {string} p0
  3263. * @param {string} p1
  3264. * @param {number} percent
  3265. * @return {string}
  3266. */
  3267. function interpolateString(p0, p1, percent) {
  3268. return percent > 0.5 ? p1 : p0;
  3269. }
  3270. /**
  3271. * @param {Array} p0
  3272. * @param {Array} p1
  3273. * @param {number} percent
  3274. * @param {Array} out
  3275. * @param {number} arrDim
  3276. */
  3277. function interpolateArray(p0, p1, percent, out, arrDim) {
  3278. var len = p0.length;
  3279. if (arrDim === 1) {
  3280. for (var i = 0; i < len; i++) {
  3281. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3282. }
  3283. }
  3284. else {
  3285. var len2 = len && p0[0].length;
  3286. for (var i = 0; i < len; i++) {
  3287. for (var j = 0; j < len2; j++) {
  3288. out[i][j] = interpolateNumber(
  3289. p0[i][j], p1[i][j], percent
  3290. );
  3291. }
  3292. }
  3293. }
  3294. }
  3295. // arr0 is source array, arr1 is target array.
  3296. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3297. function fillArr(arr0, arr1, arrDim) {
  3298. var arr0Len = arr0.length;
  3299. var arr1Len = arr1.length;
  3300. if (arr0Len !== arr1Len) {
  3301. // FIXME Not work for TypedArray
  3302. var isPreviousLarger = arr0Len > arr1Len;
  3303. if (isPreviousLarger) {
  3304. // Cut the previous
  3305. arr0.length = arr1Len;
  3306. }
  3307. else {
  3308. // Fill the previous
  3309. for (var i = arr0Len; i < arr1Len; i++) {
  3310. arr0.push(
  3311. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3312. );
  3313. }
  3314. }
  3315. }
  3316. // Handling NaN value
  3317. var len2 = arr0[0] && arr0[0].length;
  3318. for (var i = 0; i < arr0.length; i++) {
  3319. if (arrDim === 1) {
  3320. if (isNaN(arr0[i])) {
  3321. arr0[i] = arr1[i];
  3322. }
  3323. }
  3324. else {
  3325. for (var j = 0; j < len2; j++) {
  3326. if (isNaN(arr0[i][j])) {
  3327. arr0[i][j] = arr1[i][j];
  3328. }
  3329. }
  3330. }
  3331. }
  3332. }
  3333. /**
  3334. * @param {Array} arr0
  3335. * @param {Array} arr1
  3336. * @param {number} arrDim
  3337. * @return {boolean}
  3338. */
  3339. function isArraySame(arr0, arr1, arrDim) {
  3340. if (arr0 === arr1) {
  3341. return true;
  3342. }
  3343. var len = arr0.length;
  3344. if (len !== arr1.length) {
  3345. return false;
  3346. }
  3347. if (arrDim === 1) {
  3348. for (var i = 0; i < len; i++) {
  3349. if (arr0[i] !== arr1[i]) {
  3350. return false;
  3351. }
  3352. }
  3353. }
  3354. else {
  3355. var len2 = arr0[0].length;
  3356. for (var i = 0; i < len; i++) {
  3357. for (var j = 0; j < len2; j++) {
  3358. if (arr0[i][j] !== arr1[i][j]) {
  3359. return false;
  3360. }
  3361. }
  3362. }
  3363. }
  3364. return true;
  3365. }
  3366. /**
  3367. * Catmull Rom interpolate array
  3368. * @param {Array} p0
  3369. * @param {Array} p1
  3370. * @param {Array} p2
  3371. * @param {Array} p3
  3372. * @param {number} t
  3373. * @param {number} t2
  3374. * @param {number} t3
  3375. * @param {Array} out
  3376. * @param {number} arrDim
  3377. */
  3378. function catmullRomInterpolateArray(
  3379. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3380. ) {
  3381. var len = p0.length;
  3382. if (arrDim === 1) {
  3383. for (var i = 0; i < len; i++) {
  3384. out[i] = catmullRomInterpolate(
  3385. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3386. );
  3387. }
  3388. }
  3389. else {
  3390. var len2 = p0[0].length;
  3391. for (var i = 0; i < len; i++) {
  3392. for (var j = 0; j < len2; j++) {
  3393. out[i][j] = catmullRomInterpolate(
  3394. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3395. t, t2, t3
  3396. );
  3397. }
  3398. }
  3399. }
  3400. }
  3401. /**
  3402. * Catmull Rom interpolate number
  3403. * @param {number} p0
  3404. * @param {number} p1
  3405. * @param {number} p2
  3406. * @param {number} p3
  3407. * @param {number} t
  3408. * @param {number} t2
  3409. * @param {number} t3
  3410. * @return {number}
  3411. */
  3412. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3413. var v0 = (p2 - p0) * 0.5;
  3414. var v1 = (p3 - p1) * 0.5;
  3415. return (2 * (p1 - p2) + v0 + v1) * t3
  3416. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3417. + v0 * t + p1;
  3418. }
  3419. function cloneValue(value) {
  3420. if (isArrayLike(value)) {
  3421. var len = value.length;
  3422. if (isArrayLike(value[0])) {
  3423. var ret = [];
  3424. for (var i = 0; i < len; i++) {
  3425. ret.push(arraySlice.call(value[i]));
  3426. }
  3427. return ret;
  3428. }
  3429. return arraySlice.call(value);
  3430. }
  3431. return value;
  3432. }
  3433. function rgba2String(rgba) {
  3434. rgba[0] = Math.floor(rgba[0]);
  3435. rgba[1] = Math.floor(rgba[1]);
  3436. rgba[2] = Math.floor(rgba[2]);
  3437. return 'rgba(' + rgba.join(',') + ')';
  3438. }
  3439. function getArrayDim(keyframes) {
  3440. var lastValue = keyframes[keyframes.length - 1].value;
  3441. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3442. }
  3443. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3444. var getter = animator._getter;
  3445. var setter = animator._setter;
  3446. var useSpline = easing === 'spline';
  3447. var trackLen = keyframes.length;
  3448. if (!trackLen) {
  3449. return;
  3450. }
  3451. // Guess data type
  3452. var firstVal = keyframes[0].value;
  3453. var isValueArray = isArrayLike(firstVal);
  3454. var isValueColor = false;
  3455. var isValueString = false;
  3456. // For vertices morphing
  3457. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3458. var trackMaxTime;
  3459. // Sort keyframe as ascending
  3460. keyframes.sort(function (a, b) {
  3461. return a.time - b.time;
  3462. });
  3463. trackMaxTime = keyframes[trackLen - 1].time;
  3464. // Percents of each keyframe
  3465. var kfPercents = [];
  3466. // Value of each keyframe
  3467. var kfValues = [];
  3468. var prevValue = keyframes[0].value;
  3469. var isAllValueEqual = true;
  3470. for (var i = 0; i < trackLen; i++) {
  3471. kfPercents.push(keyframes[i].time / trackMaxTime);
  3472. // Assume value is a color when it is a string
  3473. var value = keyframes[i].value;
  3474. // Check if value is equal, deep check if value is array
  3475. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3476. || (!isValueArray && value === prevValue))) {
  3477. isAllValueEqual = false;
  3478. }
  3479. prevValue = value;
  3480. // Try converting a string to a color array
  3481. if (typeof value === 'string') {
  3482. var colorArray = parse(value);
  3483. if (colorArray) {
  3484. value = colorArray;
  3485. isValueColor = true;
  3486. }
  3487. else {
  3488. isValueString = true;
  3489. }
  3490. }
  3491. kfValues.push(value);
  3492. }
  3493. if (!forceAnimate && isAllValueEqual) {
  3494. return;
  3495. }
  3496. var lastValue = kfValues[trackLen - 1];
  3497. // Polyfill array and NaN value
  3498. for (var i = 0; i < trackLen - 1; i++) {
  3499. if (isValueArray) {
  3500. fillArr(kfValues[i], lastValue, arrDim);
  3501. }
  3502. else {
  3503. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3504. kfValues[i] = lastValue;
  3505. }
  3506. }
  3507. }
  3508. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3509. // Cache the key of last frame to speed up when
  3510. // animation playback is sequency
  3511. var lastFrame = 0;
  3512. var lastFramePercent = 0;
  3513. var start;
  3514. var w;
  3515. var p0;
  3516. var p1;
  3517. var p2;
  3518. var p3;
  3519. if (isValueColor) {
  3520. var rgba = [0, 0, 0, 0];
  3521. }
  3522. var onframe = function (target, percent) {
  3523. // Find the range keyframes
  3524. // kf1-----kf2---------current--------kf3
  3525. // find kf2 and kf3 and do interpolation
  3526. var frame;
  3527. // In the easing function like elasticOut, percent may less than 0
  3528. if (percent < 0) {
  3529. frame = 0;
  3530. }
  3531. else if (percent < lastFramePercent) {
  3532. // Start from next key
  3533. // PENDING start from lastFrame ?
  3534. start = Math.min(lastFrame + 1, trackLen - 1);
  3535. for (frame = start; frame >= 0; frame--) {
  3536. if (kfPercents[frame] <= percent) {
  3537. break;
  3538. }
  3539. }
  3540. // PENDING really need to do this ?
  3541. frame = Math.min(frame, trackLen - 2);
  3542. }
  3543. else {
  3544. for (frame = lastFrame; frame < trackLen; frame++) {
  3545. if (kfPercents[frame] > percent) {
  3546. break;
  3547. }
  3548. }
  3549. frame = Math.min(frame - 1, trackLen - 2);
  3550. }
  3551. lastFrame = frame;
  3552. lastFramePercent = percent;
  3553. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3554. if (range === 0) {
  3555. return;
  3556. }
  3557. else {
  3558. w = (percent - kfPercents[frame]) / range;
  3559. }
  3560. if (useSpline) {
  3561. p1 = kfValues[frame];
  3562. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3563. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3564. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3565. if (isValueArray) {
  3566. catmullRomInterpolateArray(
  3567. p0, p1, p2, p3, w, w * w, w * w * w,
  3568. getter(target, propName),
  3569. arrDim
  3570. );
  3571. }
  3572. else {
  3573. var value;
  3574. if (isValueColor) {
  3575. value = catmullRomInterpolateArray(
  3576. p0, p1, p2, p3, w, w * w, w * w * w,
  3577. rgba, 1
  3578. );
  3579. value = rgba2String(rgba);
  3580. }
  3581. else if (isValueString) {
  3582. // String is step(0.5)
  3583. return interpolateString(p1, p2, w);
  3584. }
  3585. else {
  3586. value = catmullRomInterpolate(
  3587. p0, p1, p2, p3, w, w * w, w * w * w
  3588. );
  3589. }
  3590. setter(
  3591. target,
  3592. propName,
  3593. value
  3594. );
  3595. }
  3596. }
  3597. else {
  3598. if (isValueArray) {
  3599. interpolateArray(
  3600. kfValues[frame], kfValues[frame + 1], w,
  3601. getter(target, propName),
  3602. arrDim
  3603. );
  3604. }
  3605. else {
  3606. var value;
  3607. if (isValueColor) {
  3608. interpolateArray(
  3609. kfValues[frame], kfValues[frame + 1], w,
  3610. rgba, 1
  3611. );
  3612. value = rgba2String(rgba);
  3613. }
  3614. else if (isValueString) {
  3615. // String is step(0.5)
  3616. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3617. }
  3618. else {
  3619. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3620. }
  3621. setter(
  3622. target,
  3623. propName,
  3624. value
  3625. );
  3626. }
  3627. }
  3628. };
  3629. var clip = new Clip({
  3630. target: animator._target,
  3631. life: trackMaxTime,
  3632. loop: animator._loop,
  3633. delay: animator._delay,
  3634. onframe: onframe,
  3635. ondestroy: oneTrackDone
  3636. });
  3637. if (easing && easing !== 'spline') {
  3638. clip.easing = easing;
  3639. }
  3640. return clip;
  3641. }
  3642. /**
  3643. * @alias module:zrender/animation/Animator
  3644. * @constructor
  3645. * @param {Object} target
  3646. * @param {boolean} loop
  3647. * @param {Function} getter
  3648. * @param {Function} setter
  3649. */
  3650. var Animator = function (target, loop, getter, setter) {
  3651. this._tracks = {};
  3652. this._target = target;
  3653. this._loop = loop || false;
  3654. this._getter = getter || defaultGetter;
  3655. this._setter = setter || defaultSetter;
  3656. this._clipCount = 0;
  3657. this._delay = 0;
  3658. this._doneList = [];
  3659. this._onframeList = [];
  3660. this._clipList = [];
  3661. };
  3662. Animator.prototype = {
  3663. /**
  3664. * 设置动画关键帧
  3665. * @param {number} time 关键帧时间,单位是ms
  3666. * @param {Object} props 关键帧的属性值,key-value表示
  3667. * @return {module:zrender/animation/Animator}
  3668. */
  3669. when: function (time /* ms */, props) {
  3670. var tracks = this._tracks;
  3671. for (var propName in props) {
  3672. if (!props.hasOwnProperty(propName)) {
  3673. continue;
  3674. }
  3675. if (!tracks[propName]) {
  3676. tracks[propName] = [];
  3677. // Invalid value
  3678. var value = this._getter(this._target, propName);
  3679. if (value == null) {
  3680. // zrLog('Invalid property ' + propName);
  3681. continue;
  3682. }
  3683. // If time is 0
  3684. // Then props is given initialize value
  3685. // Else
  3686. // Initialize value from current prop value
  3687. if (time !== 0) {
  3688. tracks[propName].push({
  3689. time: 0,
  3690. value: cloneValue(value)
  3691. });
  3692. }
  3693. }
  3694. tracks[propName].push({
  3695. time: time,
  3696. value: props[propName]
  3697. });
  3698. }
  3699. return this;
  3700. },
  3701. /**
  3702. * 添加动画每一帧的回调函数
  3703. * @param {Function} callback
  3704. * @return {module:zrender/animation/Animator}
  3705. */
  3706. during: function (callback) {
  3707. this._onframeList.push(callback);
  3708. return this;
  3709. },
  3710. pause: function () {
  3711. for (var i = 0; i < this._clipList.length; i++) {
  3712. this._clipList[i].pause();
  3713. }
  3714. this._paused = true;
  3715. },
  3716. resume: function () {
  3717. for (var i = 0; i < this._clipList.length; i++) {
  3718. this._clipList[i].resume();
  3719. }
  3720. this._paused = false;
  3721. },
  3722. isPaused: function () {
  3723. return !!this._paused;
  3724. },
  3725. _doneCallback: function () {
  3726. // Clear all tracks
  3727. this._tracks = {};
  3728. // Clear all clips
  3729. this._clipList.length = 0;
  3730. var doneList = this._doneList;
  3731. var len = doneList.length;
  3732. for (var i = 0; i < len; i++) {
  3733. doneList[i].call(this);
  3734. }
  3735. },
  3736. /**
  3737. * 开始执行动画
  3738. * @param {string|Function} [easing]
  3739. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3740. * @param {boolean} forceAnimate
  3741. * @return {module:zrender/animation/Animator}
  3742. */
  3743. start: function (easing, forceAnimate) {
  3744. var self = this;
  3745. var clipCount = 0;
  3746. var oneTrackDone = function () {
  3747. clipCount--;
  3748. if (!clipCount) {
  3749. self._doneCallback();
  3750. }
  3751. };
  3752. var lastClip;
  3753. for (var propName in this._tracks) {
  3754. if (!this._tracks.hasOwnProperty(propName)) {
  3755. continue;
  3756. }
  3757. var clip = createTrackClip(
  3758. this, easing, oneTrackDone,
  3759. this._tracks[propName], propName, forceAnimate
  3760. );
  3761. if (clip) {
  3762. this._clipList.push(clip);
  3763. clipCount++;
  3764. // If start after added to animation
  3765. if (this.animation) {
  3766. this.animation.addClip(clip);
  3767. }
  3768. lastClip = clip;
  3769. }
  3770. }
  3771. // Add during callback on the last clip
  3772. if (lastClip) {
  3773. var oldOnFrame = lastClip.onframe;
  3774. lastClip.onframe = function (target, percent) {
  3775. oldOnFrame(target, percent);
  3776. for (var i = 0; i < self._onframeList.length; i++) {
  3777. self._onframeList[i](target, percent);
  3778. }
  3779. };
  3780. }
  3781. // This optimization will help the case that in the upper application
  3782. // the view may be refreshed frequently, where animation will be
  3783. // called repeatly but nothing changed.
  3784. if (!clipCount) {
  3785. this._doneCallback();
  3786. }
  3787. return this;
  3788. },
  3789. /**
  3790. * 停止动画
  3791. * @param {boolean} forwardToLast If move to last frame before stop
  3792. */
  3793. stop: function (forwardToLast) {
  3794. var clipList = this._clipList;
  3795. var animation = this.animation;
  3796. for (var i = 0; i < clipList.length; i++) {
  3797. var clip = clipList[i];
  3798. if (forwardToLast) {
  3799. // Move to last frame before stop
  3800. clip.onframe(this._target, 1);
  3801. }
  3802. animation && animation.removeClip(clip);
  3803. }
  3804. clipList.length = 0;
  3805. },
  3806. /**
  3807. * 设置动画延迟开始的时间
  3808. * @param {number} time 单位ms
  3809. * @return {module:zrender/animation/Animator}
  3810. */
  3811. delay: function (time) {
  3812. this._delay = time;
  3813. return this;
  3814. },
  3815. /**
  3816. * 添加动画结束的回调
  3817. * @param {Function} cb
  3818. * @return {module:zrender/animation/Animator}
  3819. */
  3820. done: function (cb) {
  3821. if (cb) {
  3822. this._doneList.push(cb);
  3823. }
  3824. return this;
  3825. },
  3826. /**
  3827. * @return {Array.<module:zrender/animation/Clip>}
  3828. */
  3829. getClips: function () {
  3830. return this._clipList;
  3831. }
  3832. };
  3833. var dpr = 1;
  3834. // If in browser environment
  3835. if (typeof window !== 'undefined') {
  3836. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3837. }
  3838. /**
  3839. * config默认配置项
  3840. * @exports zrender/config
  3841. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3842. */
  3843. /**
  3844. * debug日志选项:catchBrushException为true下有效
  3845. * 0 : 不生成debug数据,发布用
  3846. * 1 : 异常抛出,调试用
  3847. * 2 : 控制台输出,调试用
  3848. */
  3849. var debugMode = 0;
  3850. // retina 屏幕优化
  3851. var devicePixelRatio = dpr;
  3852. var log = function () {
  3853. };
  3854. if (debugMode === 1) {
  3855. log = function () {
  3856. for (var k in arguments) {
  3857. throw new Error(arguments[k]);
  3858. }
  3859. };
  3860. }
  3861. else if (debugMode > 1) {
  3862. log = function () {
  3863. for (var k in arguments) {
  3864. console.log(arguments[k]);
  3865. }
  3866. };
  3867. }
  3868. var log$1 = log;
  3869. /**
  3870. * @alias modue:zrender/mixin/Animatable
  3871. * @constructor
  3872. */
  3873. var Animatable = function () {
  3874. /**
  3875. * @type {Array.<module:zrender/animation/Animator>}
  3876. * @readOnly
  3877. */
  3878. this.animators = [];
  3879. };
  3880. Animatable.prototype = {
  3881. constructor: Animatable,
  3882. /**
  3883. * 动画
  3884. *
  3885. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3886. * @param {boolean} [loop] Whether to loop animation.
  3887. * @return {module:zrender/animation/Animator}
  3888. * @example:
  3889. * el.animate('style', false)
  3890. * .when(1000, {x: 10} )
  3891. * .done(function(){ // Animation done })
  3892. * .start()
  3893. */
  3894. animate: function (path, loop) {
  3895. var target;
  3896. var animatingShape = false;
  3897. var el = this;
  3898. var zr = this.__zr;
  3899. if (path) {
  3900. var pathSplitted = path.split('.');
  3901. var prop = el;
  3902. // If animating shape
  3903. animatingShape = pathSplitted[0] === 'shape';
  3904. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3905. if (!prop) {
  3906. continue;
  3907. }
  3908. prop = prop[pathSplitted[i]];
  3909. }
  3910. if (prop) {
  3911. target = prop;
  3912. }
  3913. }
  3914. else {
  3915. target = el;
  3916. }
  3917. if (!target) {
  3918. log$1(
  3919. 'Property "'
  3920. + path
  3921. + '" is not existed in element '
  3922. + el.id
  3923. );
  3924. return;
  3925. }
  3926. var animators = el.animators;
  3927. var animator = new Animator(target, loop);
  3928. animator.during(function (target) {
  3929. el.dirty(animatingShape);
  3930. })
  3931. .done(function () {
  3932. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3933. animators.splice(indexOf(animators, animator), 1);
  3934. });
  3935. animators.push(animator);
  3936. // If animate after added to the zrender
  3937. if (zr) {
  3938. zr.animation.addAnimator(animator);
  3939. }
  3940. return animator;
  3941. },
  3942. /**
  3943. * 停止动画
  3944. * @param {boolean} forwardToLast If move to last frame before stop
  3945. */
  3946. stopAnimation: function (forwardToLast) {
  3947. var animators = this.animators;
  3948. var len = animators.length;
  3949. for (var i = 0; i < len; i++) {
  3950. animators[i].stop(forwardToLast);
  3951. }
  3952. animators.length = 0;
  3953. return this;
  3954. },
  3955. /**
  3956. * Caution: this method will stop previous animation.
  3957. * So do not use this method to one element twice before
  3958. * animation starts, unless you know what you are doing.
  3959. * @param {Object} target
  3960. * @param {number} [time=500] Time in ms
  3961. * @param {string} [easing='linear']
  3962. * @param {number} [delay=0]
  3963. * @param {Function} [callback]
  3964. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3965. * immediently when target values are the same as current values.
  3966. *
  3967. * @example
  3968. * // Animate position
  3969. * el.animateTo({
  3970. * position: [10, 10]
  3971. * }, function () { // done })
  3972. *
  3973. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3974. * el.animateTo({
  3975. * shape: {
  3976. * width: 500
  3977. * },
  3978. * style: {
  3979. * fill: 'red'
  3980. * }
  3981. * position: [10, 10]
  3982. * }, 100, 100, 'cubicOut', function () { // done })
  3983. */
  3984. // TODO Return animation key
  3985. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3986. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  3987. },
  3988. /**
  3989. * Animate from the target state to current state.
  3990. * The params and the return value are the same as `this.animateTo`.
  3991. */
  3992. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  3993. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  3994. }
  3995. };
  3996. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  3997. // animateTo(target, time, easing, callback);
  3998. if (isString(delay)) {
  3999. callback = easing;
  4000. easing = delay;
  4001. delay = 0;
  4002. }
  4003. // animateTo(target, time, delay, callback);
  4004. else if (isFunction$1(easing)) {
  4005. callback = easing;
  4006. easing = 'linear';
  4007. delay = 0;
  4008. }
  4009. // animateTo(target, time, callback);
  4010. else if (isFunction$1(delay)) {
  4011. callback = delay;
  4012. delay = 0;
  4013. }
  4014. // animateTo(target, callback)
  4015. else if (isFunction$1(time)) {
  4016. callback = time;
  4017. time = 500;
  4018. }
  4019. // animateTo(target)
  4020. else if (!time) {
  4021. time = 500;
  4022. }
  4023. // Stop all previous animations
  4024. animatable.stopAnimation();
  4025. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4026. // Animators may be removed immediately after start
  4027. // if there is nothing to animate
  4028. var animators = animatable.animators.slice();
  4029. var count = animators.length;
  4030. function done() {
  4031. count--;
  4032. if (!count) {
  4033. callback && callback();
  4034. }
  4035. }
  4036. // No animators. This should be checked before animators[i].start(),
  4037. // because 'done' may be executed immediately if no need to animate.
  4038. if (!count) {
  4039. callback && callback();
  4040. }
  4041. // Start after all animators created
  4042. // Incase any animator is done immediately when all animation properties are not changed
  4043. for (var i = 0; i < animators.length; i++) {
  4044. animators[i]
  4045. .done(done)
  4046. .start(easing, forceAnimate);
  4047. }
  4048. }
  4049. /**
  4050. * @param {string} path=''
  4051. * @param {Object} source=animatable
  4052. * @param {Object} target
  4053. * @param {number} [time=500]
  4054. * @param {number} [delay=0]
  4055. * @param {boolean} [reverse] If `true`, animate
  4056. * from the `target` to current state.
  4057. *
  4058. * @example
  4059. * // Animate position
  4060. * el._animateToShallow({
  4061. * position: [10, 10]
  4062. * })
  4063. *
  4064. * // Animate shape, style and position in 100ms, delayed 100ms
  4065. * el._animateToShallow({
  4066. * shape: {
  4067. * width: 500
  4068. * },
  4069. * style: {
  4070. * fill: 'red'
  4071. * }
  4072. * position: [10, 10]
  4073. * }, 100, 100)
  4074. */
  4075. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4076. var objShallow = {};
  4077. var propertyCount = 0;
  4078. for (var name in target) {
  4079. if (!target.hasOwnProperty(name)) {
  4080. continue;
  4081. }
  4082. if (source[name] != null) {
  4083. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4084. animateToShallow(
  4085. animatable,
  4086. path ? path + '.' + name : name,
  4087. source[name],
  4088. target[name],
  4089. time,
  4090. delay,
  4091. reverse
  4092. );
  4093. }
  4094. else {
  4095. if (reverse) {
  4096. objShallow[name] = source[name];
  4097. setAttrByPath(animatable, path, name, target[name]);
  4098. }
  4099. else {
  4100. objShallow[name] = target[name];
  4101. }
  4102. propertyCount++;
  4103. }
  4104. }
  4105. else if (target[name] != null && !reverse) {
  4106. setAttrByPath(animatable, path, name, target[name]);
  4107. }
  4108. }
  4109. if (propertyCount > 0) {
  4110. animatable.animate(path, false)
  4111. .when(time == null ? 500 : time, objShallow)
  4112. .delay(delay || 0);
  4113. }
  4114. }
  4115. function setAttrByPath(el, path, name, value) {
  4116. // Attr directly if not has property
  4117. // FIXME, if some property not needed for element ?
  4118. if (!path) {
  4119. el.attr(name, value);
  4120. }
  4121. else {
  4122. // Only support set shape or style
  4123. var props = {};
  4124. props[path] = {};
  4125. props[path][name] = value;
  4126. el.attr(props);
  4127. }
  4128. }
  4129. /**
  4130. * @alias module:zrender/Element
  4131. * @constructor
  4132. * @extends {module:zrender/mixin/Animatable}
  4133. * @extends {module:zrender/mixin/Transformable}
  4134. * @extends {module:zrender/mixin/Eventful}
  4135. */
  4136. var Element = function (opts) { // jshint ignore:line
  4137. Transformable.call(this, opts);
  4138. Eventful.call(this, opts);
  4139. Animatable.call(this, opts);
  4140. /**
  4141. * 画布元素ID
  4142. * @type {string}
  4143. */
  4144. this.id = opts.id || guid();
  4145. };
  4146. Element.prototype = {
  4147. /**
  4148. * 元素类型
  4149. * Element type
  4150. * @type {string}
  4151. */
  4152. type: 'element',
  4153. /**
  4154. * 元素名字
  4155. * Element name
  4156. * @type {string}
  4157. */
  4158. name: '',
  4159. /**
  4160. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4161. * ZRender instance will be assigned when element is associated with zrender
  4162. * @name module:/zrender/Element#__zr
  4163. * @type {module:zrender/ZRender}
  4164. */
  4165. __zr: null,
  4166. /**
  4167. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4168. * If ignore drawing and events of the element object
  4169. * @name module:/zrender/Element#ignore
  4170. * @type {boolean}
  4171. * @default false
  4172. */
  4173. ignore: false,
  4174. /**
  4175. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4176. * 该路径会继承被裁减对象的变换
  4177. * @type {module:zrender/graphic/Path}
  4178. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4179. * @readOnly
  4180. */
  4181. clipPath: null,
  4182. /**
  4183. * 是否是 Group
  4184. * @type {boolean}
  4185. */
  4186. isGroup: false,
  4187. /**
  4188. * Drift element
  4189. * @param {number} dx dx on the global space
  4190. * @param {number} dy dy on the global space
  4191. */
  4192. drift: function (dx, dy) {
  4193. switch (this.draggable) {
  4194. case 'horizontal':
  4195. dy = 0;
  4196. break;
  4197. case 'vertical':
  4198. dx = 0;
  4199. break;
  4200. }
  4201. var m = this.transform;
  4202. if (!m) {
  4203. m = this.transform = [1, 0, 0, 1, 0, 0];
  4204. }
  4205. m[4] += dx;
  4206. m[5] += dy;
  4207. this.decomposeTransform();
  4208. this.dirty(false);
  4209. },
  4210. /**
  4211. * Hook before update
  4212. */
  4213. beforeUpdate: function () {},
  4214. /**
  4215. * Hook after update
  4216. */
  4217. afterUpdate: function () {},
  4218. /**
  4219. * Update each frame
  4220. */
  4221. update: function () {
  4222. this.updateTransform();
  4223. },
  4224. /**
  4225. * @param {Function} cb
  4226. * @param {} context
  4227. */
  4228. traverse: function (cb, context) {},
  4229. /**
  4230. * @protected
  4231. */
  4232. attrKV: function (key, value) {
  4233. if (key === 'position' || key === 'scale' || key === 'origin') {
  4234. // Copy the array
  4235. if (value) {
  4236. var target = this[key];
  4237. if (!target) {
  4238. target = this[key] = [];
  4239. }
  4240. target[0] = value[0];
  4241. target[1] = value[1];
  4242. }
  4243. }
  4244. else {
  4245. this[key] = value;
  4246. }
  4247. },
  4248. /**
  4249. * Hide the element
  4250. */
  4251. hide: function () {
  4252. this.ignore = true;
  4253. this.__zr && this.__zr.refresh();
  4254. },
  4255. /**
  4256. * Show the element
  4257. */
  4258. show: function () {
  4259. this.ignore = false;
  4260. this.__zr && this.__zr.refresh();
  4261. },
  4262. /**
  4263. * @param {string|Object} key
  4264. * @param {*} value
  4265. */
  4266. attr: function (key, value) {
  4267. if (typeof key === 'string') {
  4268. this.attrKV(key, value);
  4269. }
  4270. else if (isObject$1(key)) {
  4271. for (var name in key) {
  4272. if (key.hasOwnProperty(name)) {
  4273. this.attrKV(name, key[name]);
  4274. }
  4275. }
  4276. }
  4277. this.dirty(false);
  4278. return this;
  4279. },
  4280. /**
  4281. * @param {module:zrender/graphic/Path} clipPath
  4282. */
  4283. setClipPath: function (clipPath) {
  4284. var zr = this.__zr;
  4285. if (zr) {
  4286. clipPath.addSelfToZr(zr);
  4287. }
  4288. // Remove previous clip path
  4289. if (this.clipPath && this.clipPath !== clipPath) {
  4290. this.removeClipPath();
  4291. }
  4292. this.clipPath = clipPath;
  4293. clipPath.__zr = zr;
  4294. clipPath.__clipTarget = this;
  4295. this.dirty(false);
  4296. },
  4297. /**
  4298. */
  4299. removeClipPath: function () {
  4300. var clipPath = this.clipPath;
  4301. if (clipPath) {
  4302. if (clipPath.__zr) {
  4303. clipPath.removeSelfFromZr(clipPath.__zr);
  4304. }
  4305. clipPath.__zr = null;
  4306. clipPath.__clipTarget = null;
  4307. this.clipPath = null;
  4308. this.dirty(false);
  4309. }
  4310. },
  4311. /**
  4312. * Add self from zrender instance.
  4313. * Not recursively because it will be invoked when element added to storage.
  4314. * @param {module:zrender/ZRender} zr
  4315. */
  4316. addSelfToZr: function (zr) {
  4317. this.__zr = zr;
  4318. // 添加动画
  4319. var animators = this.animators;
  4320. if (animators) {
  4321. for (var i = 0; i < animators.length; i++) {
  4322. zr.animation.addAnimator(animators[i]);
  4323. }
  4324. }
  4325. if (this.clipPath) {
  4326. this.clipPath.addSelfToZr(zr);
  4327. }
  4328. },
  4329. /**
  4330. * Remove self from zrender instance.
  4331. * Not recursively because it will be invoked when element added to storage.
  4332. * @param {module:zrender/ZRender} zr
  4333. */
  4334. removeSelfFromZr: function (zr) {
  4335. this.__zr = null;
  4336. // 移除动画
  4337. var animators = this.animators;
  4338. if (animators) {
  4339. for (var i = 0; i < animators.length; i++) {
  4340. zr.animation.removeAnimator(animators[i]);
  4341. }
  4342. }
  4343. if (this.clipPath) {
  4344. this.clipPath.removeSelfFromZr(zr);
  4345. }
  4346. }
  4347. };
  4348. mixin(Element, Animatable);
  4349. mixin(Element, Transformable);
  4350. mixin(Element, Eventful);
  4351. /**
  4352. * @module echarts/core/BoundingRect
  4353. */
  4354. var v2ApplyTransform = applyTransform;
  4355. var mathMin = Math.min;
  4356. var mathMax = Math.max;
  4357. /**
  4358. * @alias module:echarts/core/BoundingRect
  4359. */
  4360. function BoundingRect(x, y, width, height) {
  4361. if (width < 0) {
  4362. x = x + width;
  4363. width = -width;
  4364. }
  4365. if (height < 0) {
  4366. y = y + height;
  4367. height = -height;
  4368. }
  4369. /**
  4370. * @type {number}
  4371. */
  4372. this.x = x;
  4373. /**
  4374. * @type {number}
  4375. */
  4376. this.y = y;
  4377. /**
  4378. * @type {number}
  4379. */
  4380. this.width = width;
  4381. /**
  4382. * @type {number}
  4383. */
  4384. this.height = height;
  4385. }
  4386. BoundingRect.prototype = {
  4387. constructor: BoundingRect,
  4388. /**
  4389. * @param {module:echarts/core/BoundingRect} other
  4390. */
  4391. union: function (other) {
  4392. var x = mathMin(other.x, this.x);
  4393. var y = mathMin(other.y, this.y);
  4394. this.width = mathMax(
  4395. other.x + other.width,
  4396. this.x + this.width
  4397. ) - x;
  4398. this.height = mathMax(
  4399. other.y + other.height,
  4400. this.y + this.height
  4401. ) - y;
  4402. this.x = x;
  4403. this.y = y;
  4404. },
  4405. /**
  4406. * @param {Array.<number>} m
  4407. * @methods
  4408. */
  4409. applyTransform: (function () {
  4410. var lt = [];
  4411. var rb = [];
  4412. var lb = [];
  4413. var rt = [];
  4414. return function (m) {
  4415. // In case usage like this
  4416. // el.getBoundingRect().applyTransform(el.transform)
  4417. // And element has no transform
  4418. if (!m) {
  4419. return;
  4420. }
  4421. lt[0] = lb[0] = this.x;
  4422. lt[1] = rt[1] = this.y;
  4423. rb[0] = rt[0] = this.x + this.width;
  4424. rb[1] = lb[1] = this.y + this.height;
  4425. v2ApplyTransform(lt, lt, m);
  4426. v2ApplyTransform(rb, rb, m);
  4427. v2ApplyTransform(lb, lb, m);
  4428. v2ApplyTransform(rt, rt, m);
  4429. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4430. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4431. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4432. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4433. this.width = maxX - this.x;
  4434. this.height = maxY - this.y;
  4435. };
  4436. })(),
  4437. /**
  4438. * Calculate matrix of transforming from self to target rect
  4439. * @param {module:zrender/core/BoundingRect} b
  4440. * @return {Array.<number>}
  4441. */
  4442. calculateTransform: function (b) {
  4443. var a = this;
  4444. var sx = b.width / a.width;
  4445. var sy = b.height / a.height;
  4446. var m = create$1();
  4447. // 矩阵右乘
  4448. translate(m, m, [-a.x, -a.y]);
  4449. scale$1(m, m, [sx, sy]);
  4450. translate(m, m, [b.x, b.y]);
  4451. return m;
  4452. },
  4453. /**
  4454. * @param {(module:echarts/core/BoundingRect|Object)} b
  4455. * @return {boolean}
  4456. */
  4457. intersect: function (b) {
  4458. if (!b) {
  4459. return false;
  4460. }
  4461. if (!(b instanceof BoundingRect)) {
  4462. // Normalize negative width/height.
  4463. b = BoundingRect.create(b);
  4464. }
  4465. var a = this;
  4466. var ax0 = a.x;
  4467. var ax1 = a.x + a.width;
  4468. var ay0 = a.y;
  4469. var ay1 = a.y + a.height;
  4470. var bx0 = b.x;
  4471. var bx1 = b.x + b.width;
  4472. var by0 = b.y;
  4473. var by1 = b.y + b.height;
  4474. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4475. },
  4476. contain: function (x, y) {
  4477. var rect = this;
  4478. return x >= rect.x
  4479. && x <= (rect.x + rect.width)
  4480. && y >= rect.y
  4481. && y <= (rect.y + rect.height);
  4482. },
  4483. /**
  4484. * @return {module:echarts/core/BoundingRect}
  4485. */
  4486. clone: function () {
  4487. return new BoundingRect(this.x, this.y, this.width, this.height);
  4488. },
  4489. /**
  4490. * Copy from another rect
  4491. */
  4492. copy: function (other) {
  4493. this.x = other.x;
  4494. this.y = other.y;
  4495. this.width = other.width;
  4496. this.height = other.height;
  4497. },
  4498. plain: function () {
  4499. return {
  4500. x: this.x,
  4501. y: this.y,
  4502. width: this.width,
  4503. height: this.height
  4504. };
  4505. }
  4506. };
  4507. /**
  4508. * @param {Object|module:zrender/core/BoundingRect} rect
  4509. * @param {number} rect.x
  4510. * @param {number} rect.y
  4511. * @param {number} rect.width
  4512. * @param {number} rect.height
  4513. * @return {module:zrender/core/BoundingRect}
  4514. */
  4515. BoundingRect.create = function (rect) {
  4516. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4517. };
  4518. /**
  4519. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4520. * @module zrender/graphic/Group
  4521. * @example
  4522. * var Group = require('zrender/container/Group');
  4523. * var Circle = require('zrender/graphic/shape/Circle');
  4524. * var g = new Group();
  4525. * g.position[0] = 100;
  4526. * g.position[1] = 100;
  4527. * g.add(new Circle({
  4528. * style: {
  4529. * x: 100,
  4530. * y: 100,
  4531. * r: 20,
  4532. * }
  4533. * }));
  4534. * zr.add(g);
  4535. */
  4536. /**
  4537. * @alias module:zrender/graphic/Group
  4538. * @constructor
  4539. * @extends module:zrender/mixin/Transformable
  4540. * @extends module:zrender/mixin/Eventful
  4541. */
  4542. var Group = function (opts) {
  4543. opts = opts || {};
  4544. Element.call(this, opts);
  4545. for (var key in opts) {
  4546. if (opts.hasOwnProperty(key)) {
  4547. this[key] = opts[key];
  4548. }
  4549. }
  4550. this._children = [];
  4551. this.__storage = null;
  4552. this.__dirty = true;
  4553. };
  4554. Group.prototype = {
  4555. constructor: Group,
  4556. isGroup: true,
  4557. /**
  4558. * @type {string}
  4559. */
  4560. type: 'group',
  4561. /**
  4562. * 所有子孙元素是否响应鼠标事件
  4563. * @name module:/zrender/container/Group#silent
  4564. * @type {boolean}
  4565. * @default false
  4566. */
  4567. silent: false,
  4568. /**
  4569. * @return {Array.<module:zrender/Element>}
  4570. */
  4571. children: function () {
  4572. return this._children.slice();
  4573. },
  4574. /**
  4575. * 获取指定 index 的儿子节点
  4576. * @param {number} idx
  4577. * @return {module:zrender/Element}
  4578. */
  4579. childAt: function (idx) {
  4580. return this._children[idx];
  4581. },
  4582. /**
  4583. * 获取指定名字的儿子节点
  4584. * @param {string} name
  4585. * @return {module:zrender/Element}
  4586. */
  4587. childOfName: function (name) {
  4588. var children = this._children;
  4589. for (var i = 0; i < children.length; i++) {
  4590. if (children[i].name === name) {
  4591. return children[i];
  4592. }
  4593. }
  4594. },
  4595. /**
  4596. * @return {number}
  4597. */
  4598. childCount: function () {
  4599. return this._children.length;
  4600. },
  4601. /**
  4602. * 添加子节点到最后
  4603. * @param {module:zrender/Element} child
  4604. */
  4605. add: function (child) {
  4606. if (child && child !== this && child.parent !== this) {
  4607. this._children.push(child);
  4608. this._doAdd(child);
  4609. }
  4610. return this;
  4611. },
  4612. /**
  4613. * 添加子节点在 nextSibling 之前
  4614. * @param {module:zrender/Element} child
  4615. * @param {module:zrender/Element} nextSibling
  4616. */
  4617. addBefore: function (child, nextSibling) {
  4618. if (child && child !== this && child.parent !== this
  4619. && nextSibling && nextSibling.parent === this) {
  4620. var children = this._children;
  4621. var idx = children.indexOf(nextSibling);
  4622. if (idx >= 0) {
  4623. children.splice(idx, 0, child);
  4624. this._doAdd(child);
  4625. }
  4626. }
  4627. return this;
  4628. },
  4629. _doAdd: function (child) {
  4630. if (child.parent) {
  4631. child.parent.remove(child);
  4632. }
  4633. child.parent = this;
  4634. var storage = this.__storage;
  4635. var zr = this.__zr;
  4636. if (storage && storage !== child.__storage) {
  4637. storage.addToStorage(child);
  4638. if (child instanceof Group) {
  4639. child.addChildrenToStorage(storage);
  4640. }
  4641. }
  4642. zr && zr.refresh();
  4643. },
  4644. /**
  4645. * 移除子节点
  4646. * @param {module:zrender/Element} child
  4647. */
  4648. remove: function (child) {
  4649. var zr = this.__zr;
  4650. var storage = this.__storage;
  4651. var children = this._children;
  4652. var idx = indexOf(children, child);
  4653. if (idx < 0) {
  4654. return this;
  4655. }
  4656. children.splice(idx, 1);
  4657. child.parent = null;
  4658. if (storage) {
  4659. storage.delFromStorage(child);
  4660. if (child instanceof Group) {
  4661. child.delChildrenFromStorage(storage);
  4662. }
  4663. }
  4664. zr && zr.refresh();
  4665. return this;
  4666. },
  4667. /**
  4668. * 移除所有子节点
  4669. */
  4670. removeAll: function () {
  4671. var children = this._children;
  4672. var storage = this.__storage;
  4673. var child;
  4674. var i;
  4675. for (i = 0; i < children.length; i++) {
  4676. child = children[i];
  4677. if (storage) {
  4678. storage.delFromStorage(child);
  4679. if (child instanceof Group) {
  4680. child.delChildrenFromStorage(storage);
  4681. }
  4682. }
  4683. child.parent = null;
  4684. }
  4685. children.length = 0;
  4686. return this;
  4687. },
  4688. /**
  4689. * 遍历所有子节点
  4690. * @param {Function} cb
  4691. * @param {} context
  4692. */
  4693. eachChild: function (cb, context) {
  4694. var children = this._children;
  4695. for (var i = 0; i < children.length; i++) {
  4696. var child = children[i];
  4697. cb.call(context, child, i);
  4698. }
  4699. return this;
  4700. },
  4701. /**
  4702. * 深度优先遍历所有子孙节点
  4703. * @param {Function} cb
  4704. * @param {} context
  4705. */
  4706. traverse: function (cb, context) {
  4707. for (var i = 0; i < this._children.length; i++) {
  4708. var child = this._children[i];
  4709. cb.call(context, child);
  4710. if (child.type === 'group') {
  4711. child.traverse(cb, context);
  4712. }
  4713. }
  4714. return this;
  4715. },
  4716. addChildrenToStorage: function (storage) {
  4717. for (var i = 0; i < this._children.length; i++) {
  4718. var child = this._children[i];
  4719. storage.addToStorage(child);
  4720. if (child instanceof Group) {
  4721. child.addChildrenToStorage(storage);
  4722. }
  4723. }
  4724. },
  4725. delChildrenFromStorage: function (storage) {
  4726. for (var i = 0; i < this._children.length; i++) {
  4727. var child = this._children[i];
  4728. storage.delFromStorage(child);
  4729. if (child instanceof Group) {
  4730. child.delChildrenFromStorage(storage);
  4731. }
  4732. }
  4733. },
  4734. dirty: function () {
  4735. this.__dirty = true;
  4736. this.__zr && this.__zr.refresh();
  4737. return this;
  4738. },
  4739. /**
  4740. * @return {module:zrender/core/BoundingRect}
  4741. */
  4742. getBoundingRect: function (includeChildren) {
  4743. // TODO Caching
  4744. var rect = null;
  4745. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4746. var children = includeChildren || this._children;
  4747. var tmpMat = [];
  4748. for (var i = 0; i < children.length; i++) {
  4749. var child = children[i];
  4750. if (child.ignore || child.invisible) {
  4751. continue;
  4752. }
  4753. var childRect = child.getBoundingRect();
  4754. var transform = child.getLocalTransform(tmpMat);
  4755. // TODO
  4756. // The boundingRect cacluated by transforming original
  4757. // rect may be bigger than the actual bundingRect when rotation
  4758. // is used. (Consider a circle rotated aginst its center, where
  4759. // the actual boundingRect should be the same as that not be
  4760. // rotated.) But we can not find better approach to calculate
  4761. // actual boundingRect yet, considering performance.
  4762. if (transform) {
  4763. tmpRect.copy(childRect);
  4764. tmpRect.applyTransform(transform);
  4765. rect = rect || tmpRect.clone();
  4766. rect.union(tmpRect);
  4767. }
  4768. else {
  4769. rect = rect || childRect.clone();
  4770. rect.union(childRect);
  4771. }
  4772. }
  4773. return rect || tmpRect;
  4774. }
  4775. };
  4776. inherits(Group, Element);
  4777. // https://github.com/mziccard/node-timsort
  4778. var DEFAULT_MIN_MERGE = 32;
  4779. var DEFAULT_MIN_GALLOPING = 7;
  4780. function minRunLength(n) {
  4781. var r = 0;
  4782. while (n >= DEFAULT_MIN_MERGE) {
  4783. r |= n & 1;
  4784. n >>= 1;
  4785. }
  4786. return n + r;
  4787. }
  4788. function makeAscendingRun(array, lo, hi, compare) {
  4789. var runHi = lo + 1;
  4790. if (runHi === hi) {
  4791. return 1;
  4792. }
  4793. if (compare(array[runHi++], array[lo]) < 0) {
  4794. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4795. runHi++;
  4796. }
  4797. reverseRun(array, lo, runHi);
  4798. }
  4799. else {
  4800. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4801. runHi++;
  4802. }
  4803. }
  4804. return runHi - lo;
  4805. }
  4806. function reverseRun(array, lo, hi) {
  4807. hi--;
  4808. while (lo < hi) {
  4809. var t = array[lo];
  4810. array[lo++] = array[hi];
  4811. array[hi--] = t;
  4812. }
  4813. }
  4814. function binaryInsertionSort(array, lo, hi, start, compare) {
  4815. if (start === lo) {
  4816. start++;
  4817. }
  4818. for (; start < hi; start++) {
  4819. var pivot = array[start];
  4820. var left = lo;
  4821. var right = start;
  4822. var mid;
  4823. while (left < right) {
  4824. mid = left + right >>> 1;
  4825. if (compare(pivot, array[mid]) < 0) {
  4826. right = mid;
  4827. }
  4828. else {
  4829. left = mid + 1;
  4830. }
  4831. }
  4832. var n = start - left;
  4833. switch (n) {
  4834. case 3:
  4835. array[left + 3] = array[left + 2];
  4836. case 2:
  4837. array[left + 2] = array[left + 1];
  4838. case 1:
  4839. array[left + 1] = array[left];
  4840. break;
  4841. default:
  4842. while (n > 0) {
  4843. array[left + n] = array[left + n - 1];
  4844. n--;
  4845. }
  4846. }
  4847. array[left] = pivot;
  4848. }
  4849. }
  4850. function gallopLeft(value, array, start, length, hint, compare) {
  4851. var lastOffset = 0;
  4852. var maxOffset = 0;
  4853. var offset = 1;
  4854. if (compare(value, array[start + hint]) > 0) {
  4855. maxOffset = length - hint;
  4856. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4857. lastOffset = offset;
  4858. offset = (offset << 1) + 1;
  4859. if (offset <= 0) {
  4860. offset = maxOffset;
  4861. }
  4862. }
  4863. if (offset > maxOffset) {
  4864. offset = maxOffset;
  4865. }
  4866. lastOffset += hint;
  4867. offset += hint;
  4868. }
  4869. else {
  4870. maxOffset = hint + 1;
  4871. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4872. lastOffset = offset;
  4873. offset = (offset << 1) + 1;
  4874. if (offset <= 0) {
  4875. offset = maxOffset;
  4876. }
  4877. }
  4878. if (offset > maxOffset) {
  4879. offset = maxOffset;
  4880. }
  4881. var tmp = lastOffset;
  4882. lastOffset = hint - offset;
  4883. offset = hint - tmp;
  4884. }
  4885. lastOffset++;
  4886. while (lastOffset < offset) {
  4887. var m = lastOffset + (offset - lastOffset >>> 1);
  4888. if (compare(value, array[start + m]) > 0) {
  4889. lastOffset = m + 1;
  4890. }
  4891. else {
  4892. offset = m;
  4893. }
  4894. }
  4895. return offset;
  4896. }
  4897. function gallopRight(value, array, start, length, hint, compare) {
  4898. var lastOffset = 0;
  4899. var maxOffset = 0;
  4900. var offset = 1;
  4901. if (compare(value, array[start + hint]) < 0) {
  4902. maxOffset = hint + 1;
  4903. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4904. lastOffset = offset;
  4905. offset = (offset << 1) + 1;
  4906. if (offset <= 0) {
  4907. offset = maxOffset;
  4908. }
  4909. }
  4910. if (offset > maxOffset) {
  4911. offset = maxOffset;
  4912. }
  4913. var tmp = lastOffset;
  4914. lastOffset = hint - offset;
  4915. offset = hint - tmp;
  4916. }
  4917. else {
  4918. maxOffset = length - hint;
  4919. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4920. lastOffset = offset;
  4921. offset = (offset << 1) + 1;
  4922. if (offset <= 0) {
  4923. offset = maxOffset;
  4924. }
  4925. }
  4926. if (offset > maxOffset) {
  4927. offset = maxOffset;
  4928. }
  4929. lastOffset += hint;
  4930. offset += hint;
  4931. }
  4932. lastOffset++;
  4933. while (lastOffset < offset) {
  4934. var m = lastOffset + (offset - lastOffset >>> 1);
  4935. if (compare(value, array[start + m]) < 0) {
  4936. offset = m;
  4937. }
  4938. else {
  4939. lastOffset = m + 1;
  4940. }
  4941. }
  4942. return offset;
  4943. }
  4944. function TimSort(array, compare) {
  4945. var minGallop = DEFAULT_MIN_GALLOPING;
  4946. var runStart;
  4947. var runLength;
  4948. var stackSize = 0;
  4949. var tmp = [];
  4950. runStart = [];
  4951. runLength = [];
  4952. function pushRun(_runStart, _runLength) {
  4953. runStart[stackSize] = _runStart;
  4954. runLength[stackSize] = _runLength;
  4955. stackSize += 1;
  4956. }
  4957. function mergeRuns() {
  4958. while (stackSize > 1) {
  4959. var n = stackSize - 2;
  4960. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4961. if (runLength[n - 1] < runLength[n + 1]) {
  4962. n--;
  4963. }
  4964. }
  4965. else if (runLength[n] > runLength[n + 1]) {
  4966. break;
  4967. }
  4968. mergeAt(n);
  4969. }
  4970. }
  4971. function forceMergeRuns() {
  4972. while (stackSize > 1) {
  4973. var n = stackSize - 2;
  4974. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4975. n--;
  4976. }
  4977. mergeAt(n);
  4978. }
  4979. }
  4980. function mergeAt(i) {
  4981. var start1 = runStart[i];
  4982. var length1 = runLength[i];
  4983. var start2 = runStart[i + 1];
  4984. var length2 = runLength[i + 1];
  4985. runLength[i] = length1 + length2;
  4986. if (i === stackSize - 3) {
  4987. runStart[i + 1] = runStart[i + 2];
  4988. runLength[i + 1] = runLength[i + 2];
  4989. }
  4990. stackSize--;
  4991. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4992. start1 += k;
  4993. length1 -= k;
  4994. if (length1 === 0) {
  4995. return;
  4996. }
  4997. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4998. if (length2 === 0) {
  4999. return;
  5000. }
  5001. if (length1 <= length2) {
  5002. mergeLow(start1, length1, start2, length2);
  5003. }
  5004. else {
  5005. mergeHigh(start1, length1, start2, length2);
  5006. }
  5007. }
  5008. function mergeLow(start1, length1, start2, length2) {
  5009. var i = 0;
  5010. for (i = 0; i < length1; i++) {
  5011. tmp[i] = array[start1 + i];
  5012. }
  5013. var cursor1 = 0;
  5014. var cursor2 = start2;
  5015. var dest = start1;
  5016. array[dest++] = array[cursor2++];
  5017. if (--length2 === 0) {
  5018. for (i = 0; i < length1; i++) {
  5019. array[dest + i] = tmp[cursor1 + i];
  5020. }
  5021. return;
  5022. }
  5023. if (length1 === 1) {
  5024. for (i = 0; i < length2; i++) {
  5025. array[dest + i] = array[cursor2 + i];
  5026. }
  5027. array[dest + length2] = tmp[cursor1];
  5028. return;
  5029. }
  5030. var _minGallop = minGallop;
  5031. var count1, count2, exit;
  5032. while (1) {
  5033. count1 = 0;
  5034. count2 = 0;
  5035. exit = false;
  5036. do {
  5037. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5038. array[dest++] = array[cursor2++];
  5039. count2++;
  5040. count1 = 0;
  5041. if (--length2 === 0) {
  5042. exit = true;
  5043. break;
  5044. }
  5045. }
  5046. else {
  5047. array[dest++] = tmp[cursor1++];
  5048. count1++;
  5049. count2 = 0;
  5050. if (--length1 === 1) {
  5051. exit = true;
  5052. break;
  5053. }
  5054. }
  5055. } while ((count1 | count2) < _minGallop);
  5056. if (exit) {
  5057. break;
  5058. }
  5059. do {
  5060. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5061. if (count1 !== 0) {
  5062. for (i = 0; i < count1; i++) {
  5063. array[dest + i] = tmp[cursor1 + i];
  5064. }
  5065. dest += count1;
  5066. cursor1 += count1;
  5067. length1 -= count1;
  5068. if (length1 <= 1) {
  5069. exit = true;
  5070. break;
  5071. }
  5072. }
  5073. array[dest++] = array[cursor2++];
  5074. if (--length2 === 0) {
  5075. exit = true;
  5076. break;
  5077. }
  5078. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5079. if (count2 !== 0) {
  5080. for (i = 0; i < count2; i++) {
  5081. array[dest + i] = array[cursor2 + i];
  5082. }
  5083. dest += count2;
  5084. cursor2 += count2;
  5085. length2 -= count2;
  5086. if (length2 === 0) {
  5087. exit = true;
  5088. break;
  5089. }
  5090. }
  5091. array[dest++] = tmp[cursor1++];
  5092. if (--length1 === 1) {
  5093. exit = true;
  5094. break;
  5095. }
  5096. _minGallop--;
  5097. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5098. if (exit) {
  5099. break;
  5100. }
  5101. if (_minGallop < 0) {
  5102. _minGallop = 0;
  5103. }
  5104. _minGallop += 2;
  5105. }
  5106. minGallop = _minGallop;
  5107. minGallop < 1 && (minGallop = 1);
  5108. if (length1 === 1) {
  5109. for (i = 0; i < length2; i++) {
  5110. array[dest + i] = array[cursor2 + i];
  5111. }
  5112. array[dest + length2] = tmp[cursor1];
  5113. }
  5114. else if (length1 === 0) {
  5115. throw new Error();
  5116. // throw new Error('mergeLow preconditions were not respected');
  5117. }
  5118. else {
  5119. for (i = 0; i < length1; i++) {
  5120. array[dest + i] = tmp[cursor1 + i];
  5121. }
  5122. }
  5123. }
  5124. function mergeHigh(start1, length1, start2, length2) {
  5125. var i = 0;
  5126. for (i = 0; i < length2; i++) {
  5127. tmp[i] = array[start2 + i];
  5128. }
  5129. var cursor1 = start1 + length1 - 1;
  5130. var cursor2 = length2 - 1;
  5131. var dest = start2 + length2 - 1;
  5132. var customCursor = 0;
  5133. var customDest = 0;
  5134. array[dest--] = array[cursor1--];
  5135. if (--length1 === 0) {
  5136. customCursor = dest - (length2 - 1);
  5137. for (i = 0; i < length2; i++) {
  5138. array[customCursor + i] = tmp[i];
  5139. }
  5140. return;
  5141. }
  5142. if (length2 === 1) {
  5143. dest -= length1;
  5144. cursor1 -= length1;
  5145. customDest = dest + 1;
  5146. customCursor = cursor1 + 1;
  5147. for (i = length1 - 1; i >= 0; i--) {
  5148. array[customDest + i] = array[customCursor + i];
  5149. }
  5150. array[dest] = tmp[cursor2];
  5151. return;
  5152. }
  5153. var _minGallop = minGallop;
  5154. while (true) {
  5155. var count1 = 0;
  5156. var count2 = 0;
  5157. var exit = false;
  5158. do {
  5159. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5160. array[dest--] = array[cursor1--];
  5161. count1++;
  5162. count2 = 0;
  5163. if (--length1 === 0) {
  5164. exit = true;
  5165. break;
  5166. }
  5167. }
  5168. else {
  5169. array[dest--] = tmp[cursor2--];
  5170. count2++;
  5171. count1 = 0;
  5172. if (--length2 === 1) {
  5173. exit = true;
  5174. break;
  5175. }
  5176. }
  5177. } while ((count1 | count2) < _minGallop);
  5178. if (exit) {
  5179. break;
  5180. }
  5181. do {
  5182. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5183. if (count1 !== 0) {
  5184. dest -= count1;
  5185. cursor1 -= count1;
  5186. length1 -= count1;
  5187. customDest = dest + 1;
  5188. customCursor = cursor1 + 1;
  5189. for (i = count1 - 1; i >= 0; i--) {
  5190. array[customDest + i] = array[customCursor + i];
  5191. }
  5192. if (length1 === 0) {
  5193. exit = true;
  5194. break;
  5195. }
  5196. }
  5197. array[dest--] = tmp[cursor2--];
  5198. if (--length2 === 1) {
  5199. exit = true;
  5200. break;
  5201. }
  5202. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5203. if (count2 !== 0) {
  5204. dest -= count2;
  5205. cursor2 -= count2;
  5206. length2 -= count2;
  5207. customDest = dest + 1;
  5208. customCursor = cursor2 + 1;
  5209. for (i = 0; i < count2; i++) {
  5210. array[customDest + i] = tmp[customCursor + i];
  5211. }
  5212. if (length2 <= 1) {
  5213. exit = true;
  5214. break;
  5215. }
  5216. }
  5217. array[dest--] = array[cursor1--];
  5218. if (--length1 === 0) {
  5219. exit = true;
  5220. break;
  5221. }
  5222. _minGallop--;
  5223. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5224. if (exit) {
  5225. break;
  5226. }
  5227. if (_minGallop < 0) {
  5228. _minGallop = 0;
  5229. }
  5230. _minGallop += 2;
  5231. }
  5232. minGallop = _minGallop;
  5233. if (minGallop < 1) {
  5234. minGallop = 1;
  5235. }
  5236. if (length2 === 1) {
  5237. dest -= length1;
  5238. cursor1 -= length1;
  5239. customDest = dest + 1;
  5240. customCursor = cursor1 + 1;
  5241. for (i = length1 - 1; i >= 0; i--) {
  5242. array[customDest + i] = array[customCursor + i];
  5243. }
  5244. array[dest] = tmp[cursor2];
  5245. }
  5246. else if (length2 === 0) {
  5247. throw new Error();
  5248. // throw new Error('mergeHigh preconditions were not respected');
  5249. }
  5250. else {
  5251. customCursor = dest - (length2 - 1);
  5252. for (i = 0; i < length2; i++) {
  5253. array[customCursor + i] = tmp[i];
  5254. }
  5255. }
  5256. }
  5257. this.mergeRuns = mergeRuns;
  5258. this.forceMergeRuns = forceMergeRuns;
  5259. this.pushRun = pushRun;
  5260. }
  5261. function sort(array, compare, lo, hi) {
  5262. if (!lo) {
  5263. lo = 0;
  5264. }
  5265. if (!hi) {
  5266. hi = array.length;
  5267. }
  5268. var remaining = hi - lo;
  5269. if (remaining < 2) {
  5270. return;
  5271. }
  5272. var runLength = 0;
  5273. if (remaining < DEFAULT_MIN_MERGE) {
  5274. runLength = makeAscendingRun(array, lo, hi, compare);
  5275. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5276. return;
  5277. }
  5278. var ts = new TimSort(array, compare);
  5279. var minRun = minRunLength(remaining);
  5280. do {
  5281. runLength = makeAscendingRun(array, lo, hi, compare);
  5282. if (runLength < minRun) {
  5283. var force = remaining;
  5284. if (force > minRun) {
  5285. force = minRun;
  5286. }
  5287. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5288. runLength = force;
  5289. }
  5290. ts.pushRun(lo, runLength);
  5291. ts.mergeRuns();
  5292. remaining -= runLength;
  5293. lo += runLength;
  5294. } while (remaining !== 0);
  5295. ts.forceMergeRuns();
  5296. }
  5297. // Use timsort because in most case elements are partially sorted
  5298. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5299. function shapeCompareFunc(a, b) {
  5300. if (a.zlevel === b.zlevel) {
  5301. if (a.z === b.z) {
  5302. // if (a.z2 === b.z2) {
  5303. // // FIXME Slow has renderidx compare
  5304. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5305. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5306. // return a.__renderidx - b.__renderidx;
  5307. // }
  5308. return a.z2 - b.z2;
  5309. }
  5310. return a.z - b.z;
  5311. }
  5312. return a.zlevel - b.zlevel;
  5313. }
  5314. /**
  5315. * 内容仓库 (M)
  5316. * @alias module:zrender/Storage
  5317. * @constructor
  5318. */
  5319. var Storage = function () { // jshint ignore:line
  5320. this._roots = [];
  5321. this._displayList = [];
  5322. this._displayListLen = 0;
  5323. };
  5324. Storage.prototype = {
  5325. constructor: Storage,
  5326. /**
  5327. * @param {Function} cb
  5328. *
  5329. */
  5330. traverse: function (cb, context) {
  5331. for (var i = 0; i < this._roots.length; i++) {
  5332. this._roots[i].traverse(cb, context);
  5333. }
  5334. },
  5335. /**
  5336. * 返回所有图形的绘制队列
  5337. * @param {boolean} [update=false] 是否在返回前更新该数组
  5338. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5339. *
  5340. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5341. * @return {Array.<module:zrender/graphic/Displayable>}
  5342. */
  5343. getDisplayList: function (update, includeIgnore) {
  5344. includeIgnore = includeIgnore || false;
  5345. if (update) {
  5346. this.updateDisplayList(includeIgnore);
  5347. }
  5348. return this._displayList;
  5349. },
  5350. /**
  5351. * 更新图形的绘制队列。
  5352. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5353. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5354. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5355. */
  5356. updateDisplayList: function (includeIgnore) {
  5357. this._displayListLen = 0;
  5358. var roots = this._roots;
  5359. var displayList = this._displayList;
  5360. for (var i = 0, len = roots.length; i < len; i++) {
  5361. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5362. }
  5363. displayList.length = this._displayListLen;
  5364. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5365. },
  5366. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5367. if (el.ignore && !includeIgnore) {
  5368. return;
  5369. }
  5370. el.beforeUpdate();
  5371. if (el.__dirty) {
  5372. el.update();
  5373. }
  5374. el.afterUpdate();
  5375. var userSetClipPath = el.clipPath;
  5376. if (userSetClipPath) {
  5377. // FIXME 效率影响
  5378. if (clipPaths) {
  5379. clipPaths = clipPaths.slice();
  5380. }
  5381. else {
  5382. clipPaths = [];
  5383. }
  5384. var currentClipPath = userSetClipPath;
  5385. var parentClipPath = el;
  5386. // Recursively add clip path
  5387. while (currentClipPath) {
  5388. // clipPath 的变换是基于使用这个 clipPath 的元素
  5389. currentClipPath.parent = parentClipPath;
  5390. currentClipPath.updateTransform();
  5391. clipPaths.push(currentClipPath);
  5392. parentClipPath = currentClipPath;
  5393. currentClipPath = currentClipPath.clipPath;
  5394. }
  5395. }
  5396. if (el.isGroup) {
  5397. var children = el._children;
  5398. for (var i = 0; i < children.length; i++) {
  5399. var child = children[i];
  5400. // Force to mark as dirty if group is dirty
  5401. // FIXME __dirtyPath ?
  5402. if (el.__dirty) {
  5403. child.__dirty = true;
  5404. }
  5405. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5406. }
  5407. // Mark group clean here
  5408. el.__dirty = false;
  5409. }
  5410. else {
  5411. el.__clipPaths = clipPaths;
  5412. this._displayList[this._displayListLen++] = el;
  5413. }
  5414. },
  5415. /**
  5416. * 添加图形(Shape)或者组(Group)到根节点
  5417. * @param {module:zrender/Element} el
  5418. */
  5419. addRoot: function (el) {
  5420. if (el.__storage === this) {
  5421. return;
  5422. }
  5423. if (el instanceof Group) {
  5424. el.addChildrenToStorage(this);
  5425. }
  5426. this.addToStorage(el);
  5427. this._roots.push(el);
  5428. },
  5429. /**
  5430. * 删除指定的图形(Shape)或者组(Group)
  5431. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5432. */
  5433. delRoot: function (el) {
  5434. if (el == null) {
  5435. // 不指定el清空
  5436. for (var i = 0; i < this._roots.length; i++) {
  5437. var root = this._roots[i];
  5438. if (root instanceof Group) {
  5439. root.delChildrenFromStorage(this);
  5440. }
  5441. }
  5442. this._roots = [];
  5443. this._displayList = [];
  5444. this._displayListLen = 0;
  5445. return;
  5446. }
  5447. if (el instanceof Array) {
  5448. for (var i = 0, l = el.length; i < l; i++) {
  5449. this.delRoot(el[i]);
  5450. }
  5451. return;
  5452. }
  5453. var idx = indexOf(this._roots, el);
  5454. if (idx >= 0) {
  5455. this.delFromStorage(el);
  5456. this._roots.splice(idx, 1);
  5457. if (el instanceof Group) {
  5458. el.delChildrenFromStorage(this);
  5459. }
  5460. }
  5461. },
  5462. addToStorage: function (el) {
  5463. if (el) {
  5464. el.__storage = this;
  5465. el.dirty(false);
  5466. }
  5467. return this;
  5468. },
  5469. delFromStorage: function (el) {
  5470. if (el) {
  5471. el.__storage = null;
  5472. }
  5473. return this;
  5474. },
  5475. /**
  5476. * 清空并且释放Storage
  5477. */
  5478. dispose: function () {
  5479. this._renderList =
  5480. this._roots = null;
  5481. },
  5482. displayableSortFunc: shapeCompareFunc
  5483. };
  5484. var SHADOW_PROPS = {
  5485. 'shadowBlur': 1,
  5486. 'shadowOffsetX': 1,
  5487. 'shadowOffsetY': 1,
  5488. 'textShadowBlur': 1,
  5489. 'textShadowOffsetX': 1,
  5490. 'textShadowOffsetY': 1,
  5491. 'textBoxShadowBlur': 1,
  5492. 'textBoxShadowOffsetX': 1,
  5493. 'textBoxShadowOffsetY': 1
  5494. };
  5495. var fixShadow = function (ctx, propName, value) {
  5496. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5497. return value *= ctx.dpr;
  5498. }
  5499. return value;
  5500. };
  5501. var ContextCachedBy = {
  5502. NONE: 0,
  5503. STYLE_BIND: 1,
  5504. PLAIN_TEXT: 2
  5505. };
  5506. // Avoid confused with 0/false.
  5507. var WILL_BE_RESTORED = 9;
  5508. var STYLE_COMMON_PROPS = [
  5509. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5510. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5511. ];
  5512. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5513. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5514. var Style = function (opts) {
  5515. this.extendFrom(opts, false);
  5516. };
  5517. function createLinearGradient(ctx, obj, rect) {
  5518. var x = obj.x == null ? 0 : obj.x;
  5519. var x2 = obj.x2 == null ? 1 : obj.x2;
  5520. var y = obj.y == null ? 0 : obj.y;
  5521. var y2 = obj.y2 == null ? 0 : obj.y2;
  5522. if (!obj.global) {
  5523. x = x * rect.width + rect.x;
  5524. x2 = x2 * rect.width + rect.x;
  5525. y = y * rect.height + rect.y;
  5526. y2 = y2 * rect.height + rect.y;
  5527. }
  5528. // Fix NaN when rect is Infinity
  5529. x = isNaN(x) ? 0 : x;
  5530. x2 = isNaN(x2) ? 1 : x2;
  5531. y = isNaN(y) ? 0 : y;
  5532. y2 = isNaN(y2) ? 0 : y2;
  5533. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5534. return canvasGradient;
  5535. }
  5536. function createRadialGradient(ctx, obj, rect) {
  5537. var width = rect.width;
  5538. var height = rect.height;
  5539. var min = Math.min(width, height);
  5540. var x = obj.x == null ? 0.5 : obj.x;
  5541. var y = obj.y == null ? 0.5 : obj.y;
  5542. var r = obj.r == null ? 0.5 : obj.r;
  5543. if (!obj.global) {
  5544. x = x * width + rect.x;
  5545. y = y * height + rect.y;
  5546. r = r * min;
  5547. }
  5548. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5549. return canvasGradient;
  5550. }
  5551. Style.prototype = {
  5552. constructor: Style,
  5553. /**
  5554. * @type {string}
  5555. */
  5556. fill: '#000',
  5557. /**
  5558. * @type {string}
  5559. */
  5560. stroke: null,
  5561. /**
  5562. * @type {number}
  5563. */
  5564. opacity: 1,
  5565. /**
  5566. * @type {number}
  5567. */
  5568. fillOpacity: null,
  5569. /**
  5570. * @type {number}
  5571. */
  5572. strokeOpacity: null,
  5573. /**
  5574. * @type {Array.<number>}
  5575. */
  5576. lineDash: null,
  5577. /**
  5578. * @type {number}
  5579. */
  5580. lineDashOffset: 0,
  5581. /**
  5582. * @type {number}
  5583. */
  5584. shadowBlur: 0,
  5585. /**
  5586. * @type {number}
  5587. */
  5588. shadowOffsetX: 0,
  5589. /**
  5590. * @type {number}
  5591. */
  5592. shadowOffsetY: 0,
  5593. /**
  5594. * @type {number}
  5595. */
  5596. lineWidth: 1,
  5597. /**
  5598. * If stroke ignore scale
  5599. * @type {Boolean}
  5600. */
  5601. strokeNoScale: false,
  5602. // Bounding rect text configuration
  5603. // Not affected by element transform
  5604. /**
  5605. * @type {string}
  5606. */
  5607. text: null,
  5608. /**
  5609. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5610. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5611. * So do not visit it directly in upper application (like echarts),
  5612. * but use `contain/text#makeFont` instead.
  5613. * @type {string}
  5614. */
  5615. font: null,
  5616. /**
  5617. * The same as font. Use font please.
  5618. * @deprecated
  5619. * @type {string}
  5620. */
  5621. textFont: null,
  5622. /**
  5623. * It helps merging respectively, rather than parsing an entire font string.
  5624. * @type {string}
  5625. */
  5626. fontStyle: null,
  5627. /**
  5628. * It helps merging respectively, rather than parsing an entire font string.
  5629. * @type {string}
  5630. */
  5631. fontWeight: null,
  5632. /**
  5633. * It helps merging respectively, rather than parsing an entire font string.
  5634. * Should be 12 but not '12px'.
  5635. * @type {number}
  5636. */
  5637. fontSize: null,
  5638. /**
  5639. * It helps merging respectively, rather than parsing an entire font string.
  5640. * @type {string}
  5641. */
  5642. fontFamily: null,
  5643. /**
  5644. * Reserved for special functinality, like 'hr'.
  5645. * @type {string}
  5646. */
  5647. textTag: null,
  5648. /**
  5649. * @type {string}
  5650. */
  5651. textFill: '#000',
  5652. /**
  5653. * @type {string}
  5654. */
  5655. textStroke: null,
  5656. /**
  5657. * @type {number}
  5658. */
  5659. textWidth: null,
  5660. /**
  5661. * Only for textBackground.
  5662. * @type {number}
  5663. */
  5664. textHeight: null,
  5665. /**
  5666. * textStroke may be set as some color as a default
  5667. * value in upper applicaion, where the default value
  5668. * of textStrokeWidth should be 0 to make sure that
  5669. * user can choose to do not use text stroke.
  5670. * @type {number}
  5671. */
  5672. textStrokeWidth: 0,
  5673. /**
  5674. * @type {number}
  5675. */
  5676. textLineHeight: null,
  5677. /**
  5678. * 'inside', 'left', 'right', 'top', 'bottom'
  5679. * [x, y]
  5680. * Based on x, y of rect.
  5681. * @type {string|Array.<number>}
  5682. * @default 'inside'
  5683. */
  5684. textPosition: 'inside',
  5685. /**
  5686. * If not specified, use the boundingRect of a `displayable`.
  5687. * @type {Object}
  5688. */
  5689. textRect: null,
  5690. /**
  5691. * [x, y]
  5692. * @type {Array.<number>}
  5693. */
  5694. textOffset: null,
  5695. /**
  5696. * @type {string}
  5697. */
  5698. textAlign: null,
  5699. /**
  5700. * @type {string}
  5701. */
  5702. textVerticalAlign: null,
  5703. /**
  5704. * @type {number}
  5705. */
  5706. textDistance: 5,
  5707. /**
  5708. * @type {string}
  5709. */
  5710. textShadowColor: 'transparent',
  5711. /**
  5712. * @type {number}
  5713. */
  5714. textShadowBlur: 0,
  5715. /**
  5716. * @type {number}
  5717. */
  5718. textShadowOffsetX: 0,
  5719. /**
  5720. * @type {number}
  5721. */
  5722. textShadowOffsetY: 0,
  5723. /**
  5724. * @type {string}
  5725. */
  5726. textBoxShadowColor: 'transparent',
  5727. /**
  5728. * @type {number}
  5729. */
  5730. textBoxShadowBlur: 0,
  5731. /**
  5732. * @type {number}
  5733. */
  5734. textBoxShadowOffsetX: 0,
  5735. /**
  5736. * @type {number}
  5737. */
  5738. textBoxShadowOffsetY: 0,
  5739. /**
  5740. * Whether transform text.
  5741. * Only useful in Path and Image element
  5742. * @type {boolean}
  5743. */
  5744. transformText: false,
  5745. /**
  5746. * Text rotate around position of Path or Image
  5747. * Only useful in Path and Image element and transformText is false.
  5748. */
  5749. textRotation: 0,
  5750. /**
  5751. * Text origin of text rotation, like [10, 40].
  5752. * Based on x, y of rect.
  5753. * Useful in label rotation of circular symbol.
  5754. * By default, this origin is textPosition.
  5755. * Can be 'center'.
  5756. * @type {string|Array.<number>}
  5757. */
  5758. textOrigin: null,
  5759. /**
  5760. * @type {string}
  5761. */
  5762. textBackgroundColor: null,
  5763. /**
  5764. * @type {string}
  5765. */
  5766. textBorderColor: null,
  5767. /**
  5768. * @type {number}
  5769. */
  5770. textBorderWidth: 0,
  5771. /**
  5772. * @type {number}
  5773. */
  5774. textBorderRadius: 0,
  5775. /**
  5776. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5777. * @type {number|Array.<number>}
  5778. */
  5779. textPadding: null,
  5780. /**
  5781. * Text styles for rich text.
  5782. * @type {Object}
  5783. */
  5784. rich: null,
  5785. /**
  5786. * {outerWidth, outerHeight, ellipsis, placeholder}
  5787. * @type {Object}
  5788. */
  5789. truncate: null,
  5790. /**
  5791. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5792. * @type {string}
  5793. */
  5794. blend: null,
  5795. /**
  5796. * @param {CanvasRenderingContext2D} ctx
  5797. */
  5798. bind: function (ctx, el, prevEl) {
  5799. var style = this;
  5800. var prevStyle = prevEl && prevEl.style;
  5801. // If no prevStyle, it means first draw.
  5802. // Only apply cache if the last time cachced by this function.
  5803. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  5804. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  5805. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5806. var prop = STYLE_COMMON_PROPS[i];
  5807. var styleName = prop[0];
  5808. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  5809. // FIXME Invalid property value will cause style leak from previous element.
  5810. ctx[styleName] =
  5811. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5812. }
  5813. }
  5814. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  5815. ctx.fillStyle = style.fill;
  5816. }
  5817. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  5818. ctx.strokeStyle = style.stroke;
  5819. }
  5820. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  5821. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5822. }
  5823. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  5824. ctx.globalCompositeOperation = style.blend || 'source-over';
  5825. }
  5826. if (this.hasStroke()) {
  5827. var lineWidth = style.lineWidth;
  5828. ctx.lineWidth = lineWidth / (
  5829. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5830. );
  5831. }
  5832. },
  5833. hasFill: function () {
  5834. var fill = this.fill;
  5835. return fill != null && fill !== 'none';
  5836. },
  5837. hasStroke: function () {
  5838. var stroke = this.stroke;
  5839. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5840. },
  5841. /**
  5842. * Extend from other style
  5843. * @param {zrender/graphic/Style} otherStyle
  5844. * @param {boolean} overwrite true: overwrirte any way.
  5845. * false: overwrite only when !target.hasOwnProperty
  5846. * others: overwrite when property is not null/undefined.
  5847. */
  5848. extendFrom: function (otherStyle, overwrite) {
  5849. if (otherStyle) {
  5850. for (var name in otherStyle) {
  5851. if (otherStyle.hasOwnProperty(name)
  5852. && (overwrite === true
  5853. || (
  5854. overwrite === false
  5855. ? !this.hasOwnProperty(name)
  5856. : otherStyle[name] != null
  5857. )
  5858. )
  5859. ) {
  5860. this[name] = otherStyle[name];
  5861. }
  5862. }
  5863. }
  5864. },
  5865. /**
  5866. * Batch setting style with a given object
  5867. * @param {Object|string} obj
  5868. * @param {*} [obj]
  5869. */
  5870. set: function (obj, value) {
  5871. if (typeof obj === 'string') {
  5872. this[obj] = value;
  5873. }
  5874. else {
  5875. this.extendFrom(obj, true);
  5876. }
  5877. },
  5878. /**
  5879. * Clone
  5880. * @return {zrender/graphic/Style} [description]
  5881. */
  5882. clone: function () {
  5883. var newStyle = new this.constructor();
  5884. newStyle.extendFrom(this, true);
  5885. return newStyle;
  5886. },
  5887. getGradient: function (ctx, obj, rect) {
  5888. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5889. var canvasGradient = method(ctx, obj, rect);
  5890. var colorStops = obj.colorStops;
  5891. for (var i = 0; i < colorStops.length; i++) {
  5892. canvasGradient.addColorStop(
  5893. colorStops[i].offset, colorStops[i].color
  5894. );
  5895. }
  5896. return canvasGradient;
  5897. }
  5898. };
  5899. var styleProto = Style.prototype;
  5900. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5901. var prop = STYLE_COMMON_PROPS[i];
  5902. if (!(prop[0] in styleProto)) {
  5903. styleProto[prop[0]] = prop[1];
  5904. }
  5905. }
  5906. // Provide for others
  5907. Style.getGradient = styleProto.getGradient;
  5908. var Pattern = function (image, repeat) {
  5909. // Should do nothing more in this constructor. Because gradient can be
  5910. // declard by `color: {image: ...}`, where this constructor will not be called.
  5911. this.image = image;
  5912. this.repeat = repeat;
  5913. // Can be cloned
  5914. this.type = 'pattern';
  5915. };
  5916. Pattern.prototype.getCanvasPattern = function (ctx) {
  5917. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5918. };
  5919. /**
  5920. * @module zrender/Layer
  5921. * @author pissang(https://www.github.com/pissang)
  5922. */
  5923. function returnFalse() {
  5924. return false;
  5925. }
  5926. /**
  5927. * 创建dom
  5928. *
  5929. * @inner
  5930. * @param {string} id dom id 待用
  5931. * @param {Painter} painter painter instance
  5932. * @param {number} number
  5933. */
  5934. function createDom(id, painter, dpr) {
  5935. var newDom = createCanvas();
  5936. var width = painter.getWidth();
  5937. var height = painter.getHeight();
  5938. var newDomStyle = newDom.style;
  5939. if (newDomStyle) { // In node or some other non-browser environment
  5940. newDomStyle.position = 'absolute';
  5941. newDomStyle.left = 0;
  5942. newDomStyle.top = 0;
  5943. newDomStyle.width = width + 'px';
  5944. newDomStyle.height = height + 'px';
  5945. newDom.setAttribute('data-zr-dom-id', id);
  5946. }
  5947. newDom.width = width * dpr;
  5948. newDom.height = height * dpr;
  5949. return newDom;
  5950. }
  5951. /**
  5952. * @alias module:zrender/Layer
  5953. * @constructor
  5954. * @extends module:zrender/mixin/Transformable
  5955. * @param {string} id
  5956. * @param {module:zrender/Painter} painter
  5957. * @param {number} [dpr]
  5958. */
  5959. var Layer = function (id, painter, dpr) {
  5960. var dom;
  5961. dpr = dpr || devicePixelRatio;
  5962. if (typeof id === 'string') {
  5963. dom = createDom(id, painter, dpr);
  5964. }
  5965. // Not using isDom because in node it will return false
  5966. else if (isObject$1(id)) {
  5967. dom = id;
  5968. id = dom.id;
  5969. }
  5970. this.id = id;
  5971. this.dom = dom;
  5972. var domStyle = dom.style;
  5973. if (domStyle) { // Not in node
  5974. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5975. domStyle['-webkit-user-select'] = 'none';
  5976. domStyle['user-select'] = 'none';
  5977. domStyle['-webkit-touch-callout'] = 'none';
  5978. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5979. domStyle['padding'] = 0;
  5980. domStyle['margin'] = 0;
  5981. domStyle['border-width'] = 0;
  5982. }
  5983. this.domBack = null;
  5984. this.ctxBack = null;
  5985. this.painter = painter;
  5986. this.config = null;
  5987. // Configs
  5988. /**
  5989. * 每次清空画布的颜色
  5990. * @type {string}
  5991. * @default 0
  5992. */
  5993. this.clearColor = 0;
  5994. /**
  5995. * 是否开启动态模糊
  5996. * @type {boolean}
  5997. * @default false
  5998. */
  5999. this.motionBlur = false;
  6000. /**
  6001. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6002. * @type {number}
  6003. * @default 0.7
  6004. */
  6005. this.lastFrameAlpha = 0.7;
  6006. /**
  6007. * Layer dpr
  6008. * @type {number}
  6009. */
  6010. this.dpr = dpr;
  6011. };
  6012. Layer.prototype = {
  6013. constructor: Layer,
  6014. __dirty: true,
  6015. __used: false,
  6016. __drawIndex: 0,
  6017. __startIndex: 0,
  6018. __endIndex: 0,
  6019. incremental: false,
  6020. getElementCount: function () {
  6021. return this.__endIndex - this.__startIndex;
  6022. },
  6023. initContext: function () {
  6024. this.ctx = this.dom.getContext('2d');
  6025. this.ctx.dpr = this.dpr;
  6026. },
  6027. createBackBuffer: function () {
  6028. var dpr = this.dpr;
  6029. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6030. this.ctxBack = this.domBack.getContext('2d');
  6031. if (dpr !== 1) {
  6032. this.ctxBack.scale(dpr, dpr);
  6033. }
  6034. },
  6035. /**
  6036. * @param {number} width
  6037. * @param {number} height
  6038. */
  6039. resize: function (width, height) {
  6040. var dpr = this.dpr;
  6041. var dom = this.dom;
  6042. var domStyle = dom.style;
  6043. var domBack = this.domBack;
  6044. if (domStyle) {
  6045. domStyle.width = width + 'px';
  6046. domStyle.height = height + 'px';
  6047. }
  6048. dom.width = width * dpr;
  6049. dom.height = height * dpr;
  6050. if (domBack) {
  6051. domBack.width = width * dpr;
  6052. domBack.height = height * dpr;
  6053. if (dpr !== 1) {
  6054. this.ctxBack.scale(dpr, dpr);
  6055. }
  6056. }
  6057. },
  6058. /**
  6059. * 清空该层画布
  6060. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6061. * @param {Color} [clearColor]
  6062. */
  6063. clear: function (clearAll, clearColor) {
  6064. var dom = this.dom;
  6065. var ctx = this.ctx;
  6066. var width = dom.width;
  6067. var height = dom.height;
  6068. var clearColor = clearColor || this.clearColor;
  6069. var haveMotionBLur = this.motionBlur && !clearAll;
  6070. var lastFrameAlpha = this.lastFrameAlpha;
  6071. var dpr = this.dpr;
  6072. if (haveMotionBLur) {
  6073. if (!this.domBack) {
  6074. this.createBackBuffer();
  6075. }
  6076. this.ctxBack.globalCompositeOperation = 'copy';
  6077. this.ctxBack.drawImage(
  6078. dom, 0, 0,
  6079. width / dpr,
  6080. height / dpr
  6081. );
  6082. }
  6083. ctx.clearRect(0, 0, width, height);
  6084. if (clearColor && clearColor !== 'transparent') {
  6085. var clearColorGradientOrPattern;
  6086. // Gradient
  6087. if (clearColor.colorStops) {
  6088. // Cache canvas gradient
  6089. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6090. x: 0,
  6091. y: 0,
  6092. width: width,
  6093. height: height
  6094. });
  6095. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6096. }
  6097. // Pattern
  6098. else if (clearColor.image) {
  6099. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6100. }
  6101. ctx.save();
  6102. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6103. ctx.fillRect(0, 0, width, height);
  6104. ctx.restore();
  6105. }
  6106. if (haveMotionBLur) {
  6107. var domBack = this.domBack;
  6108. ctx.save();
  6109. ctx.globalAlpha = lastFrameAlpha;
  6110. ctx.drawImage(domBack, 0, 0, width, height);
  6111. ctx.restore();
  6112. }
  6113. }
  6114. };
  6115. var requestAnimationFrame = (
  6116. typeof window !== 'undefined'
  6117. && (
  6118. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6119. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6120. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6121. || window.mozRequestAnimationFrame
  6122. || window.webkitRequestAnimationFrame
  6123. )
  6124. ) || function (func) {
  6125. setTimeout(func, 16);
  6126. };
  6127. var globalImageCache = new LRU(50);
  6128. /**
  6129. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6130. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6131. */
  6132. function findExistImage(newImageOrSrc) {
  6133. if (typeof newImageOrSrc === 'string') {
  6134. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6135. return cachedImgObj && cachedImgObj.image;
  6136. }
  6137. else {
  6138. return newImageOrSrc;
  6139. }
  6140. }
  6141. /**
  6142. * Caution: User should cache loaded images, but not just count on LRU.
  6143. * Consider if required images more than LRU size, will dead loop occur?
  6144. *
  6145. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6146. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6147. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6148. * @param {Function} [cb] params: (image, cbPayload)
  6149. * @param {Object} [cbPayload] Payload on cb calling.
  6150. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6151. */
  6152. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6153. if (!newImageOrSrc) {
  6154. return image;
  6155. }
  6156. else if (typeof newImageOrSrc === 'string') {
  6157. // Image should not be loaded repeatly.
  6158. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6159. return image;
  6160. }
  6161. // Only when there is no existent image or existent image src
  6162. // is different, this method is responsible for load.
  6163. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6164. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6165. if (cachedImgObj) {
  6166. image = cachedImgObj.image;
  6167. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6168. }
  6169. else {
  6170. image = new Image();
  6171. image.onload = image.onerror = imageOnLoad;
  6172. globalImageCache.put(
  6173. newImageOrSrc,
  6174. image.__cachedImgObj = {
  6175. image: image,
  6176. pending: [pendingWrap]
  6177. }
  6178. );
  6179. image.src = image.__zrImageSrc = newImageOrSrc;
  6180. }
  6181. return image;
  6182. }
  6183. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6184. else {
  6185. return newImageOrSrc;
  6186. }
  6187. }
  6188. function imageOnLoad() {
  6189. var cachedImgObj = this.__cachedImgObj;
  6190. this.onload = this.onerror = this.__cachedImgObj = null;
  6191. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6192. var pendingWrap = cachedImgObj.pending[i];
  6193. var cb = pendingWrap.cb;
  6194. cb && cb(this, pendingWrap.cbPayload);
  6195. pendingWrap.hostEl.dirty();
  6196. }
  6197. cachedImgObj.pending.length = 0;
  6198. }
  6199. function isImageReady(image) {
  6200. return image && image.width && image.height;
  6201. }
  6202. var textWidthCache = {};
  6203. var textWidthCacheCounter = 0;
  6204. var TEXT_CACHE_MAX = 5000;
  6205. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6206. var DEFAULT_FONT$1 = '12px sans-serif';
  6207. // Avoid assign to an exported variable, for transforming to cjs.
  6208. var methods$1 = {};
  6209. /**
  6210. * @public
  6211. * @param {string} text
  6212. * @param {string} font
  6213. * @return {number} width
  6214. */
  6215. function getWidth(text, font) {
  6216. font = font || DEFAULT_FONT$1;
  6217. var key = text + ':' + font;
  6218. if (textWidthCache[key]) {
  6219. return textWidthCache[key];
  6220. }
  6221. var textLines = (text + '').split('\n');
  6222. var width = 0;
  6223. for (var i = 0, l = textLines.length; i < l; i++) {
  6224. // textContain.measureText may be overrided in SVG or VML
  6225. width = Math.max(measureText(textLines[i], font).width, width);
  6226. }
  6227. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6228. textWidthCacheCounter = 0;
  6229. textWidthCache = {};
  6230. }
  6231. textWidthCacheCounter++;
  6232. textWidthCache[key] = width;
  6233. return width;
  6234. }
  6235. /**
  6236. * @public
  6237. * @param {string} text
  6238. * @param {string} font
  6239. * @param {string} [textAlign='left']
  6240. * @param {string} [textVerticalAlign='top']
  6241. * @param {Array.<number>} [textPadding]
  6242. * @param {Object} [rich]
  6243. * @param {Object} [truncate]
  6244. * @return {Object} {x, y, width, height, lineHeight}
  6245. */
  6246. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6247. return rich
  6248. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6249. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6250. }
  6251. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6252. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6253. var outerWidth = getWidth(text, font);
  6254. if (textPadding) {
  6255. outerWidth += textPadding[1] + textPadding[3];
  6256. }
  6257. var outerHeight = contentBlock.outerHeight;
  6258. var x = adjustTextX(0, outerWidth, textAlign);
  6259. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6260. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6261. rect.lineHeight = contentBlock.lineHeight;
  6262. return rect;
  6263. }
  6264. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6265. var contentBlock = parseRichText(text, {
  6266. rich: rich,
  6267. truncate: truncate,
  6268. font: font,
  6269. textAlign: textAlign,
  6270. textPadding: textPadding,
  6271. textLineHeight: textLineHeight
  6272. });
  6273. var outerWidth = contentBlock.outerWidth;
  6274. var outerHeight = contentBlock.outerHeight;
  6275. var x = adjustTextX(0, outerWidth, textAlign);
  6276. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6277. return new BoundingRect(x, y, outerWidth, outerHeight);
  6278. }
  6279. /**
  6280. * @public
  6281. * @param {number} x
  6282. * @param {number} width
  6283. * @param {string} [textAlign='left']
  6284. * @return {number} Adjusted x.
  6285. */
  6286. function adjustTextX(x, width, textAlign) {
  6287. // FIXME Right to left language
  6288. if (textAlign === 'right') {
  6289. x -= width;
  6290. }
  6291. else if (textAlign === 'center') {
  6292. x -= width / 2;
  6293. }
  6294. return x;
  6295. }
  6296. /**
  6297. * @public
  6298. * @param {number} y
  6299. * @param {number} height
  6300. * @param {string} [textVerticalAlign='top']
  6301. * @return {number} Adjusted y.
  6302. */
  6303. function adjustTextY(y, height, textVerticalAlign) {
  6304. if (textVerticalAlign === 'middle') {
  6305. y -= height / 2;
  6306. }
  6307. else if (textVerticalAlign === 'bottom') {
  6308. y -= height;
  6309. }
  6310. return y;
  6311. }
  6312. /**
  6313. * @public
  6314. * @param {stirng} textPosition
  6315. * @param {Object} rect {x, y, width, height}
  6316. * @param {number} distance
  6317. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6318. */
  6319. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6320. var x = rect.x;
  6321. var y = rect.y;
  6322. var height = rect.height;
  6323. var width = rect.width;
  6324. var halfHeight = height / 2;
  6325. var textAlign = 'left';
  6326. var textVerticalAlign = 'top';
  6327. switch (textPosition) {
  6328. case 'left':
  6329. x -= distance;
  6330. y += halfHeight;
  6331. textAlign = 'right';
  6332. textVerticalAlign = 'middle';
  6333. break;
  6334. case 'right':
  6335. x += distance + width;
  6336. y += halfHeight;
  6337. textVerticalAlign = 'middle';
  6338. break;
  6339. case 'top':
  6340. x += width / 2;
  6341. y -= distance;
  6342. textAlign = 'center';
  6343. textVerticalAlign = 'bottom';
  6344. break;
  6345. case 'bottom':
  6346. x += width / 2;
  6347. y += height + distance;
  6348. textAlign = 'center';
  6349. break;
  6350. case 'inside':
  6351. x += width / 2;
  6352. y += halfHeight;
  6353. textAlign = 'center';
  6354. textVerticalAlign = 'middle';
  6355. break;
  6356. case 'insideLeft':
  6357. x += distance;
  6358. y += halfHeight;
  6359. textVerticalAlign = 'middle';
  6360. break;
  6361. case 'insideRight':
  6362. x += width - distance;
  6363. y += halfHeight;
  6364. textAlign = 'right';
  6365. textVerticalAlign = 'middle';
  6366. break;
  6367. case 'insideTop':
  6368. x += width / 2;
  6369. y += distance;
  6370. textAlign = 'center';
  6371. break;
  6372. case 'insideBottom':
  6373. x += width / 2;
  6374. y += height - distance;
  6375. textAlign = 'center';
  6376. textVerticalAlign = 'bottom';
  6377. break;
  6378. case 'insideTopLeft':
  6379. x += distance;
  6380. y += distance;
  6381. break;
  6382. case 'insideTopRight':
  6383. x += width - distance;
  6384. y += distance;
  6385. textAlign = 'right';
  6386. break;
  6387. case 'insideBottomLeft':
  6388. x += distance;
  6389. y += height - distance;
  6390. textVerticalAlign = 'bottom';
  6391. break;
  6392. case 'insideBottomRight':
  6393. x += width - distance;
  6394. y += height - distance;
  6395. textAlign = 'right';
  6396. textVerticalAlign = 'bottom';
  6397. break;
  6398. }
  6399. return {
  6400. x: x,
  6401. y: y,
  6402. textAlign: textAlign,
  6403. textVerticalAlign: textVerticalAlign
  6404. };
  6405. }
  6406. /**
  6407. * Show ellipsis if overflow.
  6408. *
  6409. * @public
  6410. * @param {string} text
  6411. * @param {string} containerWidth
  6412. * @param {string} font
  6413. * @param {number} [ellipsis='...']
  6414. * @param {Object} [options]
  6415. * @param {number} [options.maxIterations=3]
  6416. * @param {number} [options.minChar=0] If truncate result are less
  6417. * then minChar, ellipsis will not show, which is
  6418. * better for user hint in some cases.
  6419. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6420. * @return {string}
  6421. */
  6422. function truncateText(text, containerWidth, font, ellipsis, options) {
  6423. if (!containerWidth) {
  6424. return '';
  6425. }
  6426. var textLines = (text + '').split('\n');
  6427. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6428. // FIXME
  6429. // It is not appropriate that every line has '...' when truncate multiple lines.
  6430. for (var i = 0, len = textLines.length; i < len; i++) {
  6431. textLines[i] = truncateSingleLine(textLines[i], options);
  6432. }
  6433. return textLines.join('\n');
  6434. }
  6435. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6436. options = extend({}, options);
  6437. options.font = font;
  6438. var ellipsis = retrieve2(ellipsis, '...');
  6439. options.maxIterations = retrieve2(options.maxIterations, 2);
  6440. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6441. // FIXME
  6442. // Other languages?
  6443. options.cnCharWidth = getWidth('国', font);
  6444. // FIXME
  6445. // Consider proportional font?
  6446. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6447. options.placeholder = retrieve2(options.placeholder, '');
  6448. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6449. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6450. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6451. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6452. contentWidth -= ascCharWidth;
  6453. }
  6454. var ellipsisWidth = getWidth(ellipsis, font);
  6455. if (ellipsisWidth > contentWidth) {
  6456. ellipsis = '';
  6457. ellipsisWidth = 0;
  6458. }
  6459. contentWidth = containerWidth - ellipsisWidth;
  6460. options.ellipsis = ellipsis;
  6461. options.ellipsisWidth = ellipsisWidth;
  6462. options.contentWidth = contentWidth;
  6463. options.containerWidth = containerWidth;
  6464. return options;
  6465. }
  6466. function truncateSingleLine(textLine, options) {
  6467. var containerWidth = options.containerWidth;
  6468. var font = options.font;
  6469. var contentWidth = options.contentWidth;
  6470. if (!containerWidth) {
  6471. return '';
  6472. }
  6473. var lineWidth = getWidth(textLine, font);
  6474. if (lineWidth <= containerWidth) {
  6475. return textLine;
  6476. }
  6477. for (var j = 0; ; j++) {
  6478. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6479. textLine += options.ellipsis;
  6480. break;
  6481. }
  6482. var subLength = j === 0
  6483. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6484. : lineWidth > 0
  6485. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6486. : 0;
  6487. textLine = textLine.substr(0, subLength);
  6488. lineWidth = getWidth(textLine, font);
  6489. }
  6490. if (textLine === '') {
  6491. textLine = options.placeholder;
  6492. }
  6493. return textLine;
  6494. }
  6495. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6496. var width = 0;
  6497. var i = 0;
  6498. for (var len = text.length; i < len && width < contentWidth; i++) {
  6499. var charCode = text.charCodeAt(i);
  6500. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6501. }
  6502. return i;
  6503. }
  6504. /**
  6505. * @public
  6506. * @param {string} font
  6507. * @return {number} line height
  6508. */
  6509. function getLineHeight(font) {
  6510. // FIXME A rough approach.
  6511. return getWidth('国', font);
  6512. }
  6513. /**
  6514. * @public
  6515. * @param {string} text
  6516. * @param {string} font
  6517. * @return {Object} width
  6518. */
  6519. function measureText(text, font) {
  6520. return methods$1.measureText(text, font);
  6521. }
  6522. // Avoid assign to an exported variable, for transforming to cjs.
  6523. methods$1.measureText = function (text, font) {
  6524. var ctx = getContext();
  6525. ctx.font = font || DEFAULT_FONT$1;
  6526. return ctx.measureText(text);
  6527. };
  6528. /**
  6529. * @public
  6530. * @param {string} text
  6531. * @param {string} font
  6532. * @param {Object} [truncate]
  6533. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6534. * Notice: for performance, do not calculate outerWidth util needed.
  6535. */
  6536. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6537. text != null && (text += '');
  6538. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6539. var lines = text ? text.split('\n') : [];
  6540. var height = lines.length * lineHeight;
  6541. var outerHeight = height;
  6542. if (padding) {
  6543. outerHeight += padding[0] + padding[2];
  6544. }
  6545. if (text && truncate) {
  6546. var truncOuterHeight = truncate.outerHeight;
  6547. var truncOuterWidth = truncate.outerWidth;
  6548. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6549. text = '';
  6550. lines = [];
  6551. }
  6552. else if (truncOuterWidth != null) {
  6553. var options = prepareTruncateOptions(
  6554. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6555. font,
  6556. truncate.ellipsis,
  6557. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6558. );
  6559. // FIXME
  6560. // It is not appropriate that every line has '...' when truncate multiple lines.
  6561. for (var i = 0, len = lines.length; i < len; i++) {
  6562. lines[i] = truncateSingleLine(lines[i], options);
  6563. }
  6564. }
  6565. }
  6566. return {
  6567. lines: lines,
  6568. height: height,
  6569. outerHeight: outerHeight,
  6570. lineHeight: lineHeight
  6571. };
  6572. }
  6573. /**
  6574. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6575. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6576. *
  6577. * @public
  6578. * @param {string} text
  6579. * @param {Object} style
  6580. * @return {Object} block
  6581. * {
  6582. * width,
  6583. * height,
  6584. * lines: [{
  6585. * lineHeight,
  6586. * width,
  6587. * tokens: [[{
  6588. * styleName,
  6589. * text,
  6590. * width, // include textPadding
  6591. * height, // include textPadding
  6592. * textWidth, // pure text width
  6593. * textHeight, // pure text height
  6594. * lineHeihgt,
  6595. * font,
  6596. * textAlign,
  6597. * textVerticalAlign
  6598. * }], [...], ...]
  6599. * }, ...]
  6600. * }
  6601. * If styleName is undefined, it is plain text.
  6602. */
  6603. function parseRichText(text, style) {
  6604. var contentBlock = {lines: [], width: 0, height: 0};
  6605. text != null && (text += '');
  6606. if (!text) {
  6607. return contentBlock;
  6608. }
  6609. var lastIndex = STYLE_REG.lastIndex = 0;
  6610. var result;
  6611. while ((result = STYLE_REG.exec(text)) != null) {
  6612. var matchedIndex = result.index;
  6613. if (matchedIndex > lastIndex) {
  6614. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6615. }
  6616. pushTokens(contentBlock, result[2], result[1]);
  6617. lastIndex = STYLE_REG.lastIndex;
  6618. }
  6619. if (lastIndex < text.length) {
  6620. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6621. }
  6622. var lines = contentBlock.lines;
  6623. var contentHeight = 0;
  6624. var contentWidth = 0;
  6625. // For `textWidth: 100%`
  6626. var pendingList = [];
  6627. var stlPadding = style.textPadding;
  6628. var truncate = style.truncate;
  6629. var truncateWidth = truncate && truncate.outerWidth;
  6630. var truncateHeight = truncate && truncate.outerHeight;
  6631. if (stlPadding) {
  6632. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6633. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6634. }
  6635. // Calculate layout info of tokens.
  6636. for (var i = 0; i < lines.length; i++) {
  6637. var line = lines[i];
  6638. var lineHeight = 0;
  6639. var lineWidth = 0;
  6640. for (var j = 0; j < line.tokens.length; j++) {
  6641. var token = line.tokens[j];
  6642. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6643. // textPadding should not inherit from style.
  6644. var textPadding = token.textPadding = tokenStyle.textPadding;
  6645. // textFont has been asigned to font by `normalizeStyle`.
  6646. var font = token.font = tokenStyle.font || style.font;
  6647. // textHeight can be used when textVerticalAlign is specified in token.
  6648. var tokenHeight = token.textHeight = retrieve2(
  6649. // textHeight should not be inherited, consider it can be specified
  6650. // as box height of the block.
  6651. tokenStyle.textHeight, getLineHeight(font)
  6652. );
  6653. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6654. token.height = tokenHeight;
  6655. token.lineHeight = retrieve3(
  6656. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6657. );
  6658. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6659. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6660. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6661. return {lines: [], width: 0, height: 0};
  6662. }
  6663. token.textWidth = getWidth(token.text, font);
  6664. var tokenWidth = tokenStyle.textWidth;
  6665. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6666. // Percent width, can be `100%`, can be used in drawing separate
  6667. // line when box width is needed to be auto.
  6668. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6669. token.percentWidth = tokenWidth;
  6670. pendingList.push(token);
  6671. tokenWidth = 0;
  6672. // Do not truncate in this case, because there is no user case
  6673. // and it is too complicated.
  6674. }
  6675. else {
  6676. if (tokenWidthNotSpecified) {
  6677. tokenWidth = token.textWidth;
  6678. // FIXME: If image is not loaded and textWidth is not specified, calling
  6679. // `getBoundingRect()` will not get correct result.
  6680. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6681. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6682. // Use cases:
  6683. // (1) If image is not loaded, it will be loaded at render phase and call
  6684. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6685. // image, and then the right size will be calculated here at the next tick.
  6686. // See `graphic/helper/text.js`.
  6687. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6688. // use `imageHelper.findExistImage` to find cached image.
  6689. // `imageHelper.findExistImage` will always be called here before
  6690. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6691. // which ensures that image will not be rendered before correct size calcualted.
  6692. if (bgImg) {
  6693. bgImg = findExistImage(bgImg);
  6694. if (isImageReady(bgImg)) {
  6695. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6696. }
  6697. }
  6698. }
  6699. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6700. tokenWidth += paddingW;
  6701. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6702. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6703. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6704. token.text = '';
  6705. token.textWidth = tokenWidth = 0;
  6706. }
  6707. else {
  6708. token.text = truncateText(
  6709. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6710. {minChar: truncate.minChar}
  6711. );
  6712. token.textWidth = getWidth(token.text, font);
  6713. tokenWidth = token.textWidth + paddingW;
  6714. }
  6715. }
  6716. }
  6717. lineWidth += (token.width = tokenWidth);
  6718. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6719. }
  6720. line.width = lineWidth;
  6721. line.lineHeight = lineHeight;
  6722. contentHeight += lineHeight;
  6723. contentWidth = Math.max(contentWidth, lineWidth);
  6724. }
  6725. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6726. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6727. if (stlPadding) {
  6728. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6729. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6730. }
  6731. for (var i = 0; i < pendingList.length; i++) {
  6732. var token = pendingList[i];
  6733. var percentWidth = token.percentWidth;
  6734. // Should not base on outerWidth, because token can not be placed out of padding.
  6735. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6736. }
  6737. return contentBlock;
  6738. }
  6739. function pushTokens(block, str, styleName) {
  6740. var isEmptyStr = str === '';
  6741. var strs = str.split('\n');
  6742. var lines = block.lines;
  6743. for (var i = 0; i < strs.length; i++) {
  6744. var text = strs[i];
  6745. var token = {
  6746. styleName: styleName,
  6747. text: text,
  6748. isLineHolder: !text && !isEmptyStr
  6749. };
  6750. // The first token should be appended to the last line.
  6751. if (!i) {
  6752. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6753. // Consider cases:
  6754. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6755. // (which is a placeholder) should be replaced by new token.
  6756. // (2) A image backage, where token likes {a|}.
  6757. // (3) A redundant '' will affect textAlign in line.
  6758. // (4) tokens with the same tplName should not be merged, because
  6759. // they should be displayed in different box (with border and padding).
  6760. var tokensLen = tokens.length;
  6761. (tokensLen === 1 && tokens[0].isLineHolder)
  6762. ? (tokens[0] = token)
  6763. // Consider text is '', only insert when it is the "lineHolder" or
  6764. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6765. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6766. }
  6767. // Other tokens always start a new line.
  6768. else {
  6769. // If there is '', insert it as a placeholder.
  6770. lines.push({tokens: [token]});
  6771. }
  6772. }
  6773. }
  6774. function makeFont(style) {
  6775. // FIXME in node-canvas fontWeight is before fontStyle
  6776. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6777. var font = (style.fontSize || style.fontFamily) && [
  6778. style.fontStyle,
  6779. style.fontWeight,
  6780. (style.fontSize || 12) + 'px',
  6781. // If font properties are defined, `fontFamily` should not be ignored.
  6782. style.fontFamily || 'sans-serif'
  6783. ].join(' ');
  6784. return font && trim(font) || style.textFont || style.font;
  6785. }
  6786. /**
  6787. * @param {Object} ctx
  6788. * @param {Object} shape
  6789. * @param {number} shape.x
  6790. * @param {number} shape.y
  6791. * @param {number} shape.width
  6792. * @param {number} shape.height
  6793. * @param {number} shape.r
  6794. */
  6795. function buildPath(ctx, shape) {
  6796. var x = shape.x;
  6797. var y = shape.y;
  6798. var width = shape.width;
  6799. var height = shape.height;
  6800. var r = shape.r;
  6801. var r1;
  6802. var r2;
  6803. var r3;
  6804. var r4;
  6805. // Convert width and height to positive for better borderRadius
  6806. if (width < 0) {
  6807. x = x + width;
  6808. width = -width;
  6809. }
  6810. if (height < 0) {
  6811. y = y + height;
  6812. height = -height;
  6813. }
  6814. if (typeof r === 'number') {
  6815. r1 = r2 = r3 = r4 = r;
  6816. }
  6817. else if (r instanceof Array) {
  6818. if (r.length === 1) {
  6819. r1 = r2 = r3 = r4 = r[0];
  6820. }
  6821. else if (r.length === 2) {
  6822. r1 = r3 = r[0];
  6823. r2 = r4 = r[1];
  6824. }
  6825. else if (r.length === 3) {
  6826. r1 = r[0];
  6827. r2 = r4 = r[1];
  6828. r3 = r[2];
  6829. }
  6830. else {
  6831. r1 = r[0];
  6832. r2 = r[1];
  6833. r3 = r[2];
  6834. r4 = r[3];
  6835. }
  6836. }
  6837. else {
  6838. r1 = r2 = r3 = r4 = 0;
  6839. }
  6840. var total;
  6841. if (r1 + r2 > width) {
  6842. total = r1 + r2;
  6843. r1 *= width / total;
  6844. r2 *= width / total;
  6845. }
  6846. if (r3 + r4 > width) {
  6847. total = r3 + r4;
  6848. r3 *= width / total;
  6849. r4 *= width / total;
  6850. }
  6851. if (r2 + r3 > height) {
  6852. total = r2 + r3;
  6853. r2 *= height / total;
  6854. r3 *= height / total;
  6855. }
  6856. if (r1 + r4 > height) {
  6857. total = r1 + r4;
  6858. r1 *= height / total;
  6859. r4 *= height / total;
  6860. }
  6861. ctx.moveTo(x + r1, y);
  6862. ctx.lineTo(x + width - r2, y);
  6863. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6864. ctx.lineTo(x + width, y + height - r3);
  6865. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6866. ctx.lineTo(x + r4, y + height);
  6867. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6868. ctx.lineTo(x, y + r1);
  6869. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6870. }
  6871. var DEFAULT_FONT = DEFAULT_FONT$1;
  6872. // TODO: Have not support 'start', 'end' yet.
  6873. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6874. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6875. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  6876. // the default value of shadowColor is `'transparent'`.
  6877. var SHADOW_STYLE_COMMON_PROPS = [
  6878. ['textShadowBlur', 'shadowBlur', 0],
  6879. ['textShadowOffsetX', 'shadowOffsetX', 0],
  6880. ['textShadowOffsetY', 'shadowOffsetY', 0],
  6881. ['textShadowColor', 'shadowColor', 'transparent']
  6882. ];
  6883. /**
  6884. * @param {module:zrender/graphic/Style} style
  6885. * @return {module:zrender/graphic/Style} The input style.
  6886. */
  6887. function normalizeTextStyle(style) {
  6888. normalizeStyle(style);
  6889. each$1(style.rich, normalizeStyle);
  6890. return style;
  6891. }
  6892. function normalizeStyle(style) {
  6893. if (style) {
  6894. style.font = makeFont(style);
  6895. var textAlign = style.textAlign;
  6896. textAlign === 'middle' && (textAlign = 'center');
  6897. style.textAlign = (
  6898. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6899. ) ? textAlign : 'left';
  6900. // Compatible with textBaseline.
  6901. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6902. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6903. style.textVerticalAlign = (
  6904. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6905. ) ? textVerticalAlign : 'top';
  6906. var textPadding = style.textPadding;
  6907. if (textPadding) {
  6908. style.textPadding = normalizeCssArray(style.textPadding);
  6909. }
  6910. }
  6911. }
  6912. /**
  6913. * @param {CanvasRenderingContext2D} ctx
  6914. * @param {string} text
  6915. * @param {module:zrender/graphic/Style} style
  6916. * @param {Object|boolean} [rect] {x, y, width, height}
  6917. * If set false, rect text is not used.
  6918. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  6919. */
  6920. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  6921. style.rich
  6922. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  6923. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  6924. }
  6925. // Avoid setting to ctx according to prevEl if possible for
  6926. // performance in scenarios of large amount text.
  6927. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  6928. 'use strict';
  6929. var needDrawBg = needDrawBackground(style);
  6930. var prevStyle;
  6931. var checkCache = false;
  6932. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  6933. // Only take and check cache for `Text` el, but not RectText.
  6934. if (prevEl !== WILL_BE_RESTORED) {
  6935. if (prevEl) {
  6936. prevStyle = prevEl.style;
  6937. checkCache = !needDrawBg && cachedByMe && prevStyle;
  6938. }
  6939. // Prevent from using cache in `Style::bind`, because of the case:
  6940. // ctx property is modified by other properties than `Style::bind`
  6941. // used, and Style::bind is called next.
  6942. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  6943. }
  6944. // Since this will be restored, prevent from using these props to check cache in the next
  6945. // entering of this method. But do not need to clear other cache like `Style::bind`.
  6946. else if (cachedByMe) {
  6947. ctx.__attrCachedBy = ContextCachedBy.NONE;
  6948. }
  6949. var styleFont = style.font || DEFAULT_FONT;
  6950. // PENDING
  6951. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  6952. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  6953. // But layer save/restore needed to be considered.
  6954. // if (styleFont !== ctx.__fontCache) {
  6955. // ctx.font = styleFont;
  6956. // if (prevEl !== WILL_BE_RESTORED) {
  6957. // ctx.__fontCache = styleFont;
  6958. // }
  6959. // }
  6960. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  6961. ctx.font = styleFont;
  6962. }
  6963. // Use the final font from context-2d, because the final
  6964. // font might not be the style.font when it is illegal.
  6965. // But get `ctx.font` might be time consuming.
  6966. var computedFont = hostEl.__computedFont;
  6967. if (hostEl.__styleFont !== styleFont) {
  6968. hostEl.__styleFont = styleFont;
  6969. computedFont = hostEl.__computedFont = ctx.font;
  6970. }
  6971. var textPadding = style.textPadding;
  6972. var textLineHeight = style.textLineHeight;
  6973. var contentBlock = hostEl.__textCotentBlock;
  6974. if (!contentBlock || hostEl.__dirtyText) {
  6975. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6976. text, computedFont, textPadding, textLineHeight, style.truncate
  6977. );
  6978. }
  6979. var outerHeight = contentBlock.outerHeight;
  6980. var textLines = contentBlock.lines;
  6981. var lineHeight = contentBlock.lineHeight;
  6982. var boxPos = getBoxPosition(outerHeight, style, rect);
  6983. var baseX = boxPos.baseX;
  6984. var baseY = boxPos.baseY;
  6985. var textAlign = boxPos.textAlign || 'left';
  6986. var textVerticalAlign = boxPos.textVerticalAlign;
  6987. // Origin of textRotation should be the base point of text drawing.
  6988. applyTextRotation(ctx, style, rect, baseX, baseY);
  6989. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6990. var textX = baseX;
  6991. var textY = boxY;
  6992. if (needDrawBg || textPadding) {
  6993. // Consider performance, do not call getTextWidth util necessary.
  6994. var textWidth = getWidth(text, computedFont);
  6995. var outerWidth = textWidth;
  6996. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6997. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6998. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6999. if (textPadding) {
  7000. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7001. textY += textPadding[0];
  7002. }
  7003. }
  7004. // Always set textAlign and textBase line, because it is difficute to calculate
  7005. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7006. // font set happened.
  7007. ctx.textAlign = textAlign;
  7008. // Force baseline to be "middle". Otherwise, if using "top", the
  7009. // text will offset downward a little bit in font "Microsoft YaHei".
  7010. ctx.textBaseline = 'middle';
  7011. // Set text opacity
  7012. ctx.globalAlpha = style.opacity || 1;
  7013. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7014. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7015. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7016. var styleProp = propItem[0];
  7017. var ctxProp = propItem[1];
  7018. var val = style[styleProp];
  7019. if (!checkCache || val !== prevStyle[styleProp]) {
  7020. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7021. }
  7022. }
  7023. // `textBaseline` is set as 'middle'.
  7024. textY += lineHeight / 2;
  7025. var textStrokeWidth = style.textStrokeWidth;
  7026. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7027. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7028. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7029. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7030. var textFill = getFill(style.textFill);
  7031. if (textStroke) {
  7032. if (strokeWidthChanged) {
  7033. ctx.lineWidth = textStrokeWidth;
  7034. }
  7035. if (strokeChanged) {
  7036. ctx.strokeStyle = textStroke;
  7037. }
  7038. }
  7039. if (textFill) {
  7040. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7041. ctx.fillStyle = textFill;
  7042. }
  7043. }
  7044. // Optimize simply, in most cases only one line exists.
  7045. if (textLines.length === 1) {
  7046. // Fill after stroke so the outline will not cover the main part.
  7047. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7048. textFill && ctx.fillText(textLines[0], textX, textY);
  7049. }
  7050. else {
  7051. for (var i = 0; i < textLines.length; i++) {
  7052. // Fill after stroke so the outline will not cover the main part.
  7053. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7054. textFill && ctx.fillText(textLines[i], textX, textY);
  7055. textY += lineHeight;
  7056. }
  7057. }
  7058. }
  7059. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7060. // Do not do cache for rich text because of the complexity.
  7061. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7062. if (prevEl !== WILL_BE_RESTORED) {
  7063. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7064. }
  7065. var contentBlock = hostEl.__textCotentBlock;
  7066. if (!contentBlock || hostEl.__dirtyText) {
  7067. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7068. }
  7069. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7070. }
  7071. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7072. var contentWidth = contentBlock.width;
  7073. var outerWidth = contentBlock.outerWidth;
  7074. var outerHeight = contentBlock.outerHeight;
  7075. var textPadding = style.textPadding;
  7076. var boxPos = getBoxPosition(outerHeight, style, rect);
  7077. var baseX = boxPos.baseX;
  7078. var baseY = boxPos.baseY;
  7079. var textAlign = boxPos.textAlign;
  7080. var textVerticalAlign = boxPos.textVerticalAlign;
  7081. // Origin of textRotation should be the base point of text drawing.
  7082. applyTextRotation(ctx, style, rect, baseX, baseY);
  7083. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7084. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7085. var xLeft = boxX;
  7086. var lineTop = boxY;
  7087. if (textPadding) {
  7088. xLeft += textPadding[3];
  7089. lineTop += textPadding[0];
  7090. }
  7091. var xRight = xLeft + contentWidth;
  7092. needDrawBackground(style) && drawBackground(
  7093. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7094. );
  7095. for (var i = 0; i < contentBlock.lines.length; i++) {
  7096. var line = contentBlock.lines[i];
  7097. var tokens = line.tokens;
  7098. var tokenCount = tokens.length;
  7099. var lineHeight = line.lineHeight;
  7100. var usedWidth = line.width;
  7101. var leftIndex = 0;
  7102. var lineXLeft = xLeft;
  7103. var lineXRight = xRight;
  7104. var rightIndex = tokenCount - 1;
  7105. var token;
  7106. while (
  7107. leftIndex < tokenCount
  7108. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7109. ) {
  7110. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7111. usedWidth -= token.width;
  7112. lineXLeft += token.width;
  7113. leftIndex++;
  7114. }
  7115. while (
  7116. rightIndex >= 0
  7117. && (token = tokens[rightIndex], token.textAlign === 'right')
  7118. ) {
  7119. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7120. usedWidth -= token.width;
  7121. lineXRight -= token.width;
  7122. rightIndex--;
  7123. }
  7124. // The other tokens are placed as textAlign 'center' if there is enough space.
  7125. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7126. while (leftIndex <= rightIndex) {
  7127. token = tokens[leftIndex];
  7128. // Consider width specified by user, use 'center' rather than 'left'.
  7129. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7130. lineXLeft += token.width;
  7131. leftIndex++;
  7132. }
  7133. lineTop += lineHeight;
  7134. }
  7135. }
  7136. function applyTextRotation(ctx, style, rect, x, y) {
  7137. // textRotation only apply in RectText.
  7138. if (rect && style.textRotation) {
  7139. var origin = style.textOrigin;
  7140. if (origin === 'center') {
  7141. x = rect.width / 2 + rect.x;
  7142. y = rect.height / 2 + rect.y;
  7143. }
  7144. else if (origin) {
  7145. x = origin[0] + rect.x;
  7146. y = origin[1] + rect.y;
  7147. }
  7148. ctx.translate(x, y);
  7149. // Positive: anticlockwise
  7150. ctx.rotate(-style.textRotation);
  7151. ctx.translate(-x, -y);
  7152. }
  7153. }
  7154. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7155. var tokenStyle = style.rich[token.styleName] || {};
  7156. tokenStyle.text = token.text;
  7157. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7158. // the bias of "Microsoft YaHei".
  7159. var textVerticalAlign = token.textVerticalAlign;
  7160. var y = lineTop + lineHeight / 2;
  7161. if (textVerticalAlign === 'top') {
  7162. y = lineTop + token.height / 2;
  7163. }
  7164. else if (textVerticalAlign === 'bottom') {
  7165. y = lineTop + lineHeight - token.height / 2;
  7166. }
  7167. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7168. hostEl,
  7169. ctx,
  7170. tokenStyle,
  7171. textAlign === 'right'
  7172. ? x - token.width
  7173. : textAlign === 'center'
  7174. ? x - token.width / 2
  7175. : x,
  7176. y - token.height / 2,
  7177. token.width,
  7178. token.height
  7179. );
  7180. var textPadding = token.textPadding;
  7181. if (textPadding) {
  7182. x = getTextXForPadding(x, textAlign, textPadding);
  7183. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7184. }
  7185. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7186. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7187. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7188. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7189. setCtx(ctx, 'textAlign', textAlign);
  7190. // Force baseline to be "middle". Otherwise, if using "top", the
  7191. // text will offset downward a little bit in font "Microsoft YaHei".
  7192. setCtx(ctx, 'textBaseline', 'middle');
  7193. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7194. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7195. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7196. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7197. // Fill after stroke so the outline will not cover the main part.
  7198. if (textStroke) {
  7199. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7200. setCtx(ctx, 'strokeStyle', textStroke);
  7201. ctx.strokeText(token.text, x, y);
  7202. }
  7203. if (textFill) {
  7204. setCtx(ctx, 'fillStyle', textFill);
  7205. ctx.fillText(token.text, x, y);
  7206. }
  7207. }
  7208. function needDrawBackground(style) {
  7209. return !!(
  7210. style.textBackgroundColor
  7211. || (style.textBorderWidth && style.textBorderColor)
  7212. );
  7213. }
  7214. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7215. // shape: {x, y, width, height}
  7216. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7217. var textBackgroundColor = style.textBackgroundColor;
  7218. var textBorderWidth = style.textBorderWidth;
  7219. var textBorderColor = style.textBorderColor;
  7220. var isPlainBg = isString(textBackgroundColor);
  7221. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7222. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7223. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7224. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7225. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7226. ctx.beginPath();
  7227. var textBorderRadius = style.textBorderRadius;
  7228. if (!textBorderRadius) {
  7229. ctx.rect(x, y, width, height);
  7230. }
  7231. else {
  7232. buildPath(ctx, {
  7233. x: x, y: y, width: width, height: height, r: textBorderRadius
  7234. });
  7235. }
  7236. ctx.closePath();
  7237. }
  7238. if (isPlainBg) {
  7239. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7240. if (style.fillOpacity != null) {
  7241. var originalGlobalAlpha = ctx.globalAlpha;
  7242. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7243. ctx.fill();
  7244. ctx.globalAlpha = originalGlobalAlpha;
  7245. }
  7246. else {
  7247. ctx.fill();
  7248. }
  7249. }
  7250. else if (isObject$1(textBackgroundColor)) {
  7251. var image = textBackgroundColor.image;
  7252. image = createOrUpdateImage(
  7253. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7254. );
  7255. if (image && isImageReady(image)) {
  7256. ctx.drawImage(image, x, y, width, height);
  7257. }
  7258. }
  7259. if (textBorderWidth && textBorderColor) {
  7260. setCtx(ctx, 'lineWidth', textBorderWidth);
  7261. setCtx(ctx, 'strokeStyle', textBorderColor);
  7262. if (style.strokeOpacity != null) {
  7263. var originalGlobalAlpha = ctx.globalAlpha;
  7264. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7265. ctx.stroke();
  7266. ctx.globalAlpha = originalGlobalAlpha;
  7267. }
  7268. else {
  7269. ctx.stroke();
  7270. }
  7271. }
  7272. }
  7273. function onBgImageLoaded(image, textBackgroundColor) {
  7274. // Replace image, so that `contain/text.js#parseRichText`
  7275. // will get correct result in next tick.
  7276. textBackgroundColor.image = image;
  7277. }
  7278. function getBoxPosition(blockHeiht, style, rect) {
  7279. var baseX = style.x || 0;
  7280. var baseY = style.y || 0;
  7281. var textAlign = style.textAlign;
  7282. var textVerticalAlign = style.textVerticalAlign;
  7283. // Text position represented by coord
  7284. if (rect) {
  7285. var textPosition = style.textPosition;
  7286. if (textPosition instanceof Array) {
  7287. // Percent
  7288. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7289. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7290. }
  7291. else {
  7292. var res = adjustTextPositionOnRect(
  7293. textPosition, rect, style.textDistance
  7294. );
  7295. baseX = res.x;
  7296. baseY = res.y;
  7297. // Default align and baseline when has textPosition
  7298. textAlign = textAlign || res.textAlign;
  7299. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7300. }
  7301. // textOffset is only support in RectText, otherwise
  7302. // we have to adjust boundingRect for textOffset.
  7303. var textOffset = style.textOffset;
  7304. if (textOffset) {
  7305. baseX += textOffset[0];
  7306. baseY += textOffset[1];
  7307. }
  7308. }
  7309. return {
  7310. baseX: baseX,
  7311. baseY: baseY,
  7312. textAlign: textAlign,
  7313. textVerticalAlign: textVerticalAlign
  7314. };
  7315. }
  7316. function setCtx(ctx, prop, value) {
  7317. ctx[prop] = fixShadow(ctx, prop, value);
  7318. return ctx[prop];
  7319. }
  7320. /**
  7321. * @param {string} [stroke] If specified, do not check style.textStroke.
  7322. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7323. * @param {number} style
  7324. */
  7325. function getStroke(stroke, lineWidth) {
  7326. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7327. ? null
  7328. // TODO pattern and gradient?
  7329. : (stroke.image || stroke.colorStops)
  7330. ? '#000'
  7331. : stroke;
  7332. }
  7333. function getFill(fill) {
  7334. return (fill == null || fill === 'none')
  7335. ? null
  7336. // TODO pattern and gradient?
  7337. : (fill.image || fill.colorStops)
  7338. ? '#000'
  7339. : fill;
  7340. }
  7341. function parsePercent(value, maxValue) {
  7342. if (typeof value === 'string') {
  7343. if (value.lastIndexOf('%') >= 0) {
  7344. return parseFloat(value) / 100 * maxValue;
  7345. }
  7346. return parseFloat(value);
  7347. }
  7348. return value;
  7349. }
  7350. function getTextXForPadding(x, textAlign, textPadding) {
  7351. return textAlign === 'right'
  7352. ? (x - textPadding[1])
  7353. : textAlign === 'center'
  7354. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7355. : (x + textPadding[3]);
  7356. }
  7357. /**
  7358. * @param {string} text
  7359. * @param {module:zrender/Style} style
  7360. * @return {boolean}
  7361. */
  7362. function needDrawText(text, style) {
  7363. return text != null
  7364. && (text
  7365. || style.textBackgroundColor
  7366. || (style.textBorderWidth && style.textBorderColor)
  7367. || style.textPadding
  7368. );
  7369. }
  7370. /**
  7371. * Mixin for drawing text in a element bounding rect
  7372. * @module zrender/mixin/RectText
  7373. */
  7374. var tmpRect$1 = new BoundingRect();
  7375. var RectText = function () {};
  7376. RectText.prototype = {
  7377. constructor: RectText,
  7378. /**
  7379. * Draw text in a rect with specified position.
  7380. * @param {CanvasRenderingContext2D} ctx
  7381. * @param {Object} rect Displayable rect
  7382. */
  7383. drawRectText: function (ctx, rect) {
  7384. var style = this.style;
  7385. rect = style.textRect || rect;
  7386. // Optimize, avoid normalize every time.
  7387. this.__dirty && normalizeTextStyle(style, true);
  7388. var text = style.text;
  7389. // Convert to string
  7390. text != null && (text += '');
  7391. if (!needDrawText(text, style)) {
  7392. return;
  7393. }
  7394. // FIXME
  7395. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7396. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7397. // text propably break the cache for its host elements.
  7398. ctx.save();
  7399. // Transform rect to view space
  7400. var transform = this.transform;
  7401. if (!style.transformText) {
  7402. if (transform) {
  7403. tmpRect$1.copy(rect);
  7404. tmpRect$1.applyTransform(transform);
  7405. rect = tmpRect$1;
  7406. }
  7407. }
  7408. else {
  7409. this.setTransform(ctx);
  7410. }
  7411. // transformText and textRotation can not be used at the same time.
  7412. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7413. ctx.restore();
  7414. }
  7415. };
  7416. /**
  7417. * 可绘制的图形基类
  7418. * Base class of all displayable graphic objects
  7419. * @module zrender/graphic/Displayable
  7420. */
  7421. /**
  7422. * @alias module:zrender/graphic/Displayable
  7423. * @extends module:zrender/Element
  7424. * @extends module:zrender/graphic/mixin/RectText
  7425. */
  7426. function Displayable(opts) {
  7427. opts = opts || {};
  7428. Element.call(this, opts);
  7429. // Extend properties
  7430. for (var name in opts) {
  7431. if (
  7432. opts.hasOwnProperty(name)
  7433. && name !== 'style'
  7434. ) {
  7435. this[name] = opts[name];
  7436. }
  7437. }
  7438. /**
  7439. * @type {module:zrender/graphic/Style}
  7440. */
  7441. this.style = new Style(opts.style, this);
  7442. this._rect = null;
  7443. // Shapes for cascade clipping.
  7444. this.__clipPaths = [];
  7445. // FIXME Stateful must be mixined after style is setted
  7446. // Stateful.call(this, opts);
  7447. }
  7448. Displayable.prototype = {
  7449. constructor: Displayable,
  7450. type: 'displayable',
  7451. /**
  7452. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7453. * Dirty flag. From which painter will determine if this displayable object needs brush
  7454. * @name module:zrender/graphic/Displayable#__dirty
  7455. * @type {boolean}
  7456. */
  7457. __dirty: true,
  7458. /**
  7459. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7460. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7461. * @name module:/zrender/graphic/Displayable#invisible
  7462. * @type {boolean}
  7463. * @default false
  7464. */
  7465. invisible: false,
  7466. /**
  7467. * @name module:/zrender/graphic/Displayable#z
  7468. * @type {number}
  7469. * @default 0
  7470. */
  7471. z: 0,
  7472. /**
  7473. * @name module:/zrender/graphic/Displayable#z
  7474. * @type {number}
  7475. * @default 0
  7476. */
  7477. z2: 0,
  7478. /**
  7479. * z层level,决定绘画在哪层canvas中
  7480. * @name module:/zrender/graphic/Displayable#zlevel
  7481. * @type {number}
  7482. * @default 0
  7483. */
  7484. zlevel: 0,
  7485. /**
  7486. * 是否可拖拽
  7487. * @name module:/zrender/graphic/Displayable#draggable
  7488. * @type {boolean}
  7489. * @default false
  7490. */
  7491. draggable: false,
  7492. /**
  7493. * 是否正在拖拽
  7494. * @name module:/zrender/graphic/Displayable#draggable
  7495. * @type {boolean}
  7496. * @default false
  7497. */
  7498. dragging: false,
  7499. /**
  7500. * 是否相应鼠标事件
  7501. * @name module:/zrender/graphic/Displayable#silent
  7502. * @type {boolean}
  7503. * @default false
  7504. */
  7505. silent: false,
  7506. /**
  7507. * If enable culling
  7508. * @type {boolean}
  7509. * @default false
  7510. */
  7511. culling: false,
  7512. /**
  7513. * Mouse cursor when hovered
  7514. * @name module:/zrender/graphic/Displayable#cursor
  7515. * @type {string}
  7516. */
  7517. cursor: 'pointer',
  7518. /**
  7519. * If hover area is bounding rect
  7520. * @name module:/zrender/graphic/Displayable#rectHover
  7521. * @type {string}
  7522. */
  7523. rectHover: false,
  7524. /**
  7525. * Render the element progressively when the value >= 0,
  7526. * usefull for large data.
  7527. * @type {boolean}
  7528. */
  7529. progressive: false,
  7530. /**
  7531. * @type {boolean}
  7532. */
  7533. incremental: false,
  7534. /**
  7535. * Scale ratio for global scale.
  7536. * @type {boolean}
  7537. */
  7538. globalScaleRatio: 1,
  7539. beforeBrush: function (ctx) {},
  7540. afterBrush: function (ctx) {},
  7541. /**
  7542. * 图形绘制方法
  7543. * @param {CanvasRenderingContext2D} ctx
  7544. */
  7545. // Interface
  7546. brush: function (ctx, prevEl) {},
  7547. /**
  7548. * 获取最小包围盒
  7549. * @return {module:zrender/core/BoundingRect}
  7550. */
  7551. // Interface
  7552. getBoundingRect: function () {},
  7553. /**
  7554. * 判断坐标 x, y 是否在图形上
  7555. * If displayable element contain coord x, y
  7556. * @param {number} x
  7557. * @param {number} y
  7558. * @return {boolean}
  7559. */
  7560. contain: function (x, y) {
  7561. return this.rectContain(x, y);
  7562. },
  7563. /**
  7564. * @param {Function} cb
  7565. * @param {} context
  7566. */
  7567. traverse: function (cb, context) {
  7568. cb.call(context, this);
  7569. },
  7570. /**
  7571. * 判断坐标 x, y 是否在图形的包围盒上
  7572. * If bounding rect of element contain coord x, y
  7573. * @param {number} x
  7574. * @param {number} y
  7575. * @return {boolean}
  7576. */
  7577. rectContain: function (x, y) {
  7578. var coord = this.transformCoordToLocal(x, y);
  7579. var rect = this.getBoundingRect();
  7580. return rect.contain(coord[0], coord[1]);
  7581. },
  7582. /**
  7583. * 标记图形元素为脏,并且在下一帧重绘
  7584. * Mark displayable element dirty and refresh next frame
  7585. */
  7586. dirty: function () {
  7587. this.__dirty = this.__dirtyText = true;
  7588. this._rect = null;
  7589. this.__zr && this.__zr.refresh();
  7590. },
  7591. /**
  7592. * 图形是否会触发事件
  7593. * If displayable object binded any event
  7594. * @return {boolean}
  7595. */
  7596. // TODO, 通过 bind 绑定的事件
  7597. // isSilent: function () {
  7598. // return !(
  7599. // this.hoverable || this.draggable
  7600. // || this.onmousemove || this.onmouseover || this.onmouseout
  7601. // || this.onmousedown || this.onmouseup || this.onclick
  7602. // || this.ondragenter || this.ondragover || this.ondragleave
  7603. // || this.ondrop
  7604. // );
  7605. // },
  7606. /**
  7607. * Alias for animate('style')
  7608. * @param {boolean} loop
  7609. */
  7610. animateStyle: function (loop) {
  7611. return this.animate('style', loop);
  7612. },
  7613. attrKV: function (key, value) {
  7614. if (key !== 'style') {
  7615. Element.prototype.attrKV.call(this, key, value);
  7616. }
  7617. else {
  7618. this.style.set(value);
  7619. }
  7620. },
  7621. /**
  7622. * @param {Object|string} key
  7623. * @param {*} value
  7624. */
  7625. setStyle: function (key, value) {
  7626. this.style.set(key, value);
  7627. this.dirty(false);
  7628. return this;
  7629. },
  7630. /**
  7631. * Use given style object
  7632. * @param {Object} obj
  7633. */
  7634. useStyle: function (obj) {
  7635. this.style = new Style(obj, this);
  7636. this.dirty(false);
  7637. return this;
  7638. }
  7639. };
  7640. inherits(Displayable, Element);
  7641. mixin(Displayable, RectText);
  7642. /**
  7643. * @alias zrender/graphic/Image
  7644. * @extends module:zrender/graphic/Displayable
  7645. * @constructor
  7646. * @param {Object} opts
  7647. */
  7648. function ZImage(opts) {
  7649. Displayable.call(this, opts);
  7650. }
  7651. ZImage.prototype = {
  7652. constructor: ZImage,
  7653. type: 'image',
  7654. brush: function (ctx, prevEl) {
  7655. var style = this.style;
  7656. var src = style.image;
  7657. // Must bind each time
  7658. style.bind(ctx, this, prevEl);
  7659. var image = this._image = createOrUpdateImage(
  7660. src,
  7661. this._image,
  7662. this,
  7663. this.onload
  7664. );
  7665. if (!image || !isImageReady(image)) {
  7666. return;
  7667. }
  7668. // 图片已经加载完成
  7669. // if (image.nodeName.toUpperCase() == 'IMG') {
  7670. // if (!image.complete) {
  7671. // return;
  7672. // }
  7673. // }
  7674. // Else is canvas
  7675. var x = style.x || 0;
  7676. var y = style.y || 0;
  7677. var width = style.width;
  7678. var height = style.height;
  7679. var aspect = image.width / image.height;
  7680. if (width == null && height != null) {
  7681. // Keep image/height ratio
  7682. width = height * aspect;
  7683. }
  7684. else if (height == null && width != null) {
  7685. height = width / aspect;
  7686. }
  7687. else if (width == null && height == null) {
  7688. width = image.width;
  7689. height = image.height;
  7690. }
  7691. // 设置transform
  7692. this.setTransform(ctx);
  7693. if (style.sWidth && style.sHeight) {
  7694. var sx = style.sx || 0;
  7695. var sy = style.sy || 0;
  7696. ctx.drawImage(
  7697. image,
  7698. sx, sy, style.sWidth, style.sHeight,
  7699. x, y, width, height
  7700. );
  7701. }
  7702. else if (style.sx && style.sy) {
  7703. var sx = style.sx;
  7704. var sy = style.sy;
  7705. var sWidth = width - sx;
  7706. var sHeight = height - sy;
  7707. ctx.drawImage(
  7708. image,
  7709. sx, sy, sWidth, sHeight,
  7710. x, y, width, height
  7711. );
  7712. }
  7713. else {
  7714. ctx.drawImage(image, x, y, width, height);
  7715. }
  7716. // Draw rect text
  7717. if (style.text != null) {
  7718. // Only restore transform when needs draw text.
  7719. this.restoreTransform(ctx);
  7720. this.drawRectText(ctx, this.getBoundingRect());
  7721. }
  7722. },
  7723. getBoundingRect: function () {
  7724. var style = this.style;
  7725. if (!this._rect) {
  7726. this._rect = new BoundingRect(
  7727. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7728. );
  7729. }
  7730. return this._rect;
  7731. }
  7732. };
  7733. inherits(ZImage, Displayable);
  7734. var HOVER_LAYER_ZLEVEL = 1e5;
  7735. var CANVAS_ZLEVEL = 314159;
  7736. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7737. var INCREMENTAL_INC = 0.001;
  7738. function parseInt10(val) {
  7739. return parseInt(val, 10);
  7740. }
  7741. function isLayerValid(layer) {
  7742. if (!layer) {
  7743. return false;
  7744. }
  7745. if (layer.__builtin__) {
  7746. return true;
  7747. }
  7748. if (typeof (layer.resize) !== 'function'
  7749. || typeof (layer.refresh) !== 'function'
  7750. ) {
  7751. return false;
  7752. }
  7753. return true;
  7754. }
  7755. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7756. var viewRect = new BoundingRect(0, 0, 0, 0);
  7757. function isDisplayableCulled(el, width, height) {
  7758. tmpRect.copy(el.getBoundingRect());
  7759. if (el.transform) {
  7760. tmpRect.applyTransform(el.transform);
  7761. }
  7762. viewRect.width = width;
  7763. viewRect.height = height;
  7764. return !tmpRect.intersect(viewRect);
  7765. }
  7766. function isClipPathChanged(clipPaths, prevClipPaths) {
  7767. if (clipPaths === prevClipPaths) { // Can both be null or undefined
  7768. return false;
  7769. }
  7770. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7771. return true;
  7772. }
  7773. for (var i = 0; i < clipPaths.length; i++) {
  7774. if (clipPaths[i] !== prevClipPaths[i]) {
  7775. return true;
  7776. }
  7777. }
  7778. }
  7779. function doClip(clipPaths, ctx) {
  7780. for (var i = 0; i < clipPaths.length; i++) {
  7781. var clipPath = clipPaths[i];
  7782. clipPath.setTransform(ctx);
  7783. ctx.beginPath();
  7784. clipPath.buildPath(ctx, clipPath.shape);
  7785. ctx.clip();
  7786. // Transform back
  7787. clipPath.restoreTransform(ctx);
  7788. }
  7789. }
  7790. function createRoot(width, height) {
  7791. var domRoot = document.createElement('div');
  7792. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7793. domRoot.style.cssText = [
  7794. 'position:relative',
  7795. 'overflow:hidden',
  7796. 'width:' + width + 'px',
  7797. 'height:' + height + 'px',
  7798. 'padding:0',
  7799. 'margin:0',
  7800. 'border-width:0'
  7801. ].join(';') + ';';
  7802. return domRoot;
  7803. }
  7804. /**
  7805. * @alias module:zrender/Painter
  7806. * @constructor
  7807. * @param {HTMLElement} root 绘图容器
  7808. * @param {module:zrender/Storage} storage
  7809. * @param {Object} opts
  7810. */
  7811. var Painter = function (root, storage, opts) {
  7812. this.type = 'canvas';
  7813. // In node environment using node-canvas
  7814. var singleCanvas = !root.nodeName // In node ?
  7815. || root.nodeName.toUpperCase() === 'CANVAS';
  7816. this._opts = opts = extend({}, opts || {});
  7817. /**
  7818. * @type {number}
  7819. */
  7820. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7821. /**
  7822. * @type {boolean}
  7823. * @private
  7824. */
  7825. this._singleCanvas = singleCanvas;
  7826. /**
  7827. * 绘图容器
  7828. * @type {HTMLElement}
  7829. */
  7830. this.root = root;
  7831. var rootStyle = root.style;
  7832. if (rootStyle) {
  7833. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7834. rootStyle['-webkit-user-select'] =
  7835. rootStyle['user-select'] =
  7836. rootStyle['-webkit-touch-callout'] = 'none';
  7837. root.innerHTML = '';
  7838. }
  7839. /**
  7840. * @type {module:zrender/Storage}
  7841. */
  7842. this.storage = storage;
  7843. /**
  7844. * @type {Array.<number>}
  7845. * @private
  7846. */
  7847. var zlevelList = this._zlevelList = [];
  7848. /**
  7849. * @type {Object.<string, module:zrender/Layer>}
  7850. * @private
  7851. */
  7852. var layers = this._layers = {};
  7853. /**
  7854. * @type {Object.<string, Object>}
  7855. * @private
  7856. */
  7857. this._layerConfig = {};
  7858. /**
  7859. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7860. */
  7861. this._needsManuallyCompositing = false;
  7862. if (!singleCanvas) {
  7863. this._width = this._getSize(0);
  7864. this._height = this._getSize(1);
  7865. var domRoot = this._domRoot = createRoot(
  7866. this._width, this._height
  7867. );
  7868. root.appendChild(domRoot);
  7869. }
  7870. else {
  7871. var width = root.width;
  7872. var height = root.height;
  7873. if (opts.width != null) {
  7874. width = opts.width;
  7875. }
  7876. if (opts.height != null) {
  7877. height = opts.height;
  7878. }
  7879. this.dpr = opts.devicePixelRatio || 1;
  7880. // Use canvas width and height directly
  7881. root.width = width * this.dpr;
  7882. root.height = height * this.dpr;
  7883. this._width = width;
  7884. this._height = height;
  7885. // Create layer if only one given canvas
  7886. // Device can be specified to create a high dpi image.
  7887. var mainLayer = new Layer(root, this, this.dpr);
  7888. mainLayer.__builtin__ = true;
  7889. mainLayer.initContext();
  7890. // FIXME Use canvas width and height
  7891. // mainLayer.resize(width, height);
  7892. layers[CANVAS_ZLEVEL] = mainLayer;
  7893. mainLayer.zlevel = CANVAS_ZLEVEL;
  7894. // Not use common zlevel.
  7895. zlevelList.push(CANVAS_ZLEVEL);
  7896. this._domRoot = root;
  7897. }
  7898. /**
  7899. * @type {module:zrender/Layer}
  7900. * @private
  7901. */
  7902. this._hoverlayer = null;
  7903. this._hoverElements = [];
  7904. };
  7905. Painter.prototype = {
  7906. constructor: Painter,
  7907. getType: function () {
  7908. return 'canvas';
  7909. },
  7910. /**
  7911. * If painter use a single canvas
  7912. * @return {boolean}
  7913. */
  7914. isSingleCanvas: function () {
  7915. return this._singleCanvas;
  7916. },
  7917. /**
  7918. * @return {HTMLDivElement}
  7919. */
  7920. getViewportRoot: function () {
  7921. return this._domRoot;
  7922. },
  7923. getViewportRootOffset: function () {
  7924. var viewportRoot = this.getViewportRoot();
  7925. if (viewportRoot) {
  7926. return {
  7927. offsetLeft: viewportRoot.offsetLeft || 0,
  7928. offsetTop: viewportRoot.offsetTop || 0
  7929. };
  7930. }
  7931. },
  7932. /**
  7933. * 刷新
  7934. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7935. */
  7936. refresh: function (paintAll) {
  7937. var list = this.storage.getDisplayList(true);
  7938. var zlevelList = this._zlevelList;
  7939. this._redrawId = Math.random();
  7940. this._paintList(list, paintAll, this._redrawId);
  7941. // Paint custum layers
  7942. for (var i = 0; i < zlevelList.length; i++) {
  7943. var z = zlevelList[i];
  7944. var layer = this._layers[z];
  7945. if (!layer.__builtin__ && layer.refresh) {
  7946. var clearColor = i === 0 ? this._backgroundColor : null;
  7947. layer.refresh(clearColor);
  7948. }
  7949. }
  7950. this.refreshHover();
  7951. return this;
  7952. },
  7953. addHover: function (el, hoverStyle) {
  7954. if (el.__hoverMir) {
  7955. return;
  7956. }
  7957. var elMirror = new el.constructor({
  7958. style: el.style,
  7959. shape: el.shape,
  7960. z: el.z,
  7961. z2: el.z2,
  7962. silent: el.silent
  7963. });
  7964. elMirror.__from = el;
  7965. el.__hoverMir = elMirror;
  7966. hoverStyle && elMirror.setStyle(hoverStyle);
  7967. this._hoverElements.push(elMirror);
  7968. return elMirror;
  7969. },
  7970. removeHover: function (el) {
  7971. var elMirror = el.__hoverMir;
  7972. var hoverElements = this._hoverElements;
  7973. var idx = indexOf(hoverElements, elMirror);
  7974. if (idx >= 0) {
  7975. hoverElements.splice(idx, 1);
  7976. }
  7977. el.__hoverMir = null;
  7978. },
  7979. clearHover: function (el) {
  7980. var hoverElements = this._hoverElements;
  7981. for (var i = 0; i < hoverElements.length; i++) {
  7982. var from = hoverElements[i].__from;
  7983. if (from) {
  7984. from.__hoverMir = null;
  7985. }
  7986. }
  7987. hoverElements.length = 0;
  7988. },
  7989. refreshHover: function () {
  7990. var hoverElements = this._hoverElements;
  7991. var len = hoverElements.length;
  7992. var hoverLayer = this._hoverlayer;
  7993. hoverLayer && hoverLayer.clear();
  7994. if (!len) {
  7995. return;
  7996. }
  7997. sort(hoverElements, this.storage.displayableSortFunc);
  7998. // Use a extream large zlevel
  7999. // FIXME?
  8000. if (!hoverLayer) {
  8001. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8002. }
  8003. var scope = {};
  8004. hoverLayer.ctx.save();
  8005. for (var i = 0; i < len;) {
  8006. var el = hoverElements[i];
  8007. var originalEl = el.__from;
  8008. // Original el is removed
  8009. // PENDING
  8010. if (!(originalEl && originalEl.__zr)) {
  8011. hoverElements.splice(i, 1);
  8012. originalEl.__hoverMir = null;
  8013. len--;
  8014. continue;
  8015. }
  8016. i++;
  8017. // Use transform
  8018. // FIXME style and shape ?
  8019. if (!originalEl.invisible) {
  8020. el.transform = originalEl.transform;
  8021. el.invTransform = originalEl.invTransform;
  8022. el.__clipPaths = originalEl.__clipPaths;
  8023. // el.
  8024. this._doPaintEl(el, hoverLayer, true, scope);
  8025. }
  8026. }
  8027. hoverLayer.ctx.restore();
  8028. },
  8029. getHoverLayer: function () {
  8030. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8031. },
  8032. _paintList: function (list, paintAll, redrawId) {
  8033. if (this._redrawId !== redrawId) {
  8034. return;
  8035. }
  8036. paintAll = paintAll || false;
  8037. this._updateLayerStatus(list);
  8038. var finished = this._doPaintList(list, paintAll);
  8039. if (this._needsManuallyCompositing) {
  8040. this._compositeManually();
  8041. }
  8042. if (!finished) {
  8043. var self = this;
  8044. requestAnimationFrame(function () {
  8045. self._paintList(list, paintAll, redrawId);
  8046. });
  8047. }
  8048. },
  8049. _compositeManually: function () {
  8050. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8051. var width = this._domRoot.width;
  8052. var height = this._domRoot.height;
  8053. ctx.clearRect(0, 0, width, height);
  8054. // PENDING, If only builtin layer?
  8055. this.eachBuiltinLayer(function (layer) {
  8056. if (layer.virtual) {
  8057. ctx.drawImage(layer.dom, 0, 0, width, height);
  8058. }
  8059. });
  8060. },
  8061. _doPaintList: function (list, paintAll) {
  8062. var layerList = [];
  8063. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8064. var zlevel = this._zlevelList[zi];
  8065. var layer = this._layers[zlevel];
  8066. if (layer.__builtin__
  8067. && layer !== this._hoverlayer
  8068. && (layer.__dirty || paintAll)
  8069. ) {
  8070. layerList.push(layer);
  8071. }
  8072. }
  8073. var finished = true;
  8074. for (var k = 0; k < layerList.length; k++) {
  8075. var layer = layerList[k];
  8076. var ctx = layer.ctx;
  8077. var scope = {};
  8078. ctx.save();
  8079. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8080. var useTimer = !paintAll && layer.incremental && Date.now;
  8081. var startTime = useTimer && Date.now();
  8082. var clearColor = layer.zlevel === this._zlevelList[0]
  8083. ? this._backgroundColor : null;
  8084. // All elements in this layer are cleared.
  8085. if (layer.__startIndex === layer.__endIndex) {
  8086. layer.clear(false, clearColor);
  8087. }
  8088. else if (start === layer.__startIndex) {
  8089. var firstEl = list[start];
  8090. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8091. layer.clear(false, clearColor);
  8092. }
  8093. }
  8094. if (start === -1) {
  8095. console.error('For some unknown reason. drawIndex is -1');
  8096. start = layer.__startIndex;
  8097. }
  8098. for (var i = start; i < layer.__endIndex; i++) {
  8099. var el = list[i];
  8100. this._doPaintEl(el, layer, paintAll, scope);
  8101. el.__dirty = el.__dirtyText = false;
  8102. if (useTimer) {
  8103. // Date.now can be executed in 13,025,305 ops/second.
  8104. var dTime = Date.now() - startTime;
  8105. // Give 15 millisecond to draw.
  8106. // The rest elements will be drawn in the next frame.
  8107. if (dTime > 15) {
  8108. break;
  8109. }
  8110. }
  8111. }
  8112. layer.__drawIndex = i;
  8113. if (layer.__drawIndex < layer.__endIndex) {
  8114. finished = false;
  8115. }
  8116. if (scope.prevElClipPaths) {
  8117. // Needs restore the state. If last drawn element is in the clipping area.
  8118. ctx.restore();
  8119. }
  8120. ctx.restore();
  8121. }
  8122. if (env$1.wxa) {
  8123. // Flush for weixin application
  8124. each$1(this._layers, function (layer) {
  8125. if (layer && layer.ctx && layer.ctx.draw) {
  8126. layer.ctx.draw();
  8127. }
  8128. });
  8129. }
  8130. return finished;
  8131. },
  8132. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8133. var ctx = currentLayer.ctx;
  8134. var m = el.transform;
  8135. if (
  8136. (currentLayer.__dirty || forcePaint)
  8137. // Ignore invisible element
  8138. && !el.invisible
  8139. // Ignore transparent element
  8140. && el.style.opacity !== 0
  8141. // Ignore scale 0 element, in some environment like node-canvas
  8142. // Draw a scale 0 element can cause all following draw wrong
  8143. // And setTransform with scale 0 will cause set back transform failed.
  8144. && !(m && !m[0] && !m[3])
  8145. // Ignore culled element
  8146. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8147. ) {
  8148. var clipPaths = el.__clipPaths;
  8149. // Optimize when clipping on group with several elements
  8150. if (!scope.prevElClipPaths
  8151. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  8152. ) {
  8153. // If has previous clipping state, restore from it
  8154. if (scope.prevElClipPaths) {
  8155. currentLayer.ctx.restore();
  8156. scope.prevElClipPaths = null;
  8157. // Reset prevEl since context has been restored
  8158. scope.prevEl = null;
  8159. }
  8160. // New clipping state
  8161. if (clipPaths) {
  8162. ctx.save();
  8163. doClip(clipPaths, ctx);
  8164. scope.prevElClipPaths = clipPaths;
  8165. }
  8166. }
  8167. el.beforeBrush && el.beforeBrush(ctx);
  8168. el.brush(ctx, scope.prevEl || null);
  8169. scope.prevEl = el;
  8170. el.afterBrush && el.afterBrush(ctx);
  8171. }
  8172. },
  8173. /**
  8174. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8175. * @param {number} zlevel
  8176. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8177. * @return {module:zrender/Layer}
  8178. */
  8179. getLayer: function (zlevel, virtual) {
  8180. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8181. zlevel = CANVAS_ZLEVEL;
  8182. }
  8183. var layer = this._layers[zlevel];
  8184. if (!layer) {
  8185. // Create a new layer
  8186. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8187. layer.zlevel = zlevel;
  8188. layer.__builtin__ = true;
  8189. if (this._layerConfig[zlevel]) {
  8190. merge(layer, this._layerConfig[zlevel], true);
  8191. }
  8192. if (virtual) {
  8193. layer.virtual = virtual;
  8194. }
  8195. this.insertLayer(zlevel, layer);
  8196. // Context is created after dom inserted to document
  8197. // Or excanvas will get 0px clientWidth and clientHeight
  8198. layer.initContext();
  8199. }
  8200. return layer;
  8201. },
  8202. insertLayer: function (zlevel, layer) {
  8203. var layersMap = this._layers;
  8204. var zlevelList = this._zlevelList;
  8205. var len = zlevelList.length;
  8206. var prevLayer = null;
  8207. var i = -1;
  8208. var domRoot = this._domRoot;
  8209. if (layersMap[zlevel]) {
  8210. log$1('ZLevel ' + zlevel + ' has been used already');
  8211. return;
  8212. }
  8213. // Check if is a valid layer
  8214. if (!isLayerValid(layer)) {
  8215. log$1('Layer of zlevel ' + zlevel + ' is not valid');
  8216. return;
  8217. }
  8218. if (len > 0 && zlevel > zlevelList[0]) {
  8219. for (i = 0; i < len - 1; i++) {
  8220. if (
  8221. zlevelList[i] < zlevel
  8222. && zlevelList[i + 1] > zlevel
  8223. ) {
  8224. break;
  8225. }
  8226. }
  8227. prevLayer = layersMap[zlevelList[i]];
  8228. }
  8229. zlevelList.splice(i + 1, 0, zlevel);
  8230. layersMap[zlevel] = layer;
  8231. // Vitual layer will not directly show on the screen.
  8232. // (It can be a WebGL layer and assigned to a ZImage element)
  8233. // But it still under management of zrender.
  8234. if (!layer.virtual) {
  8235. if (prevLayer) {
  8236. var prevDom = prevLayer.dom;
  8237. if (prevDom.nextSibling) {
  8238. domRoot.insertBefore(
  8239. layer.dom,
  8240. prevDom.nextSibling
  8241. );
  8242. }
  8243. else {
  8244. domRoot.appendChild(layer.dom);
  8245. }
  8246. }
  8247. else {
  8248. if (domRoot.firstChild) {
  8249. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8250. }
  8251. else {
  8252. domRoot.appendChild(layer.dom);
  8253. }
  8254. }
  8255. }
  8256. },
  8257. // Iterate each layer
  8258. eachLayer: function (cb, context) {
  8259. var zlevelList = this._zlevelList;
  8260. var z;
  8261. var i;
  8262. for (i = 0; i < zlevelList.length; i++) {
  8263. z = zlevelList[i];
  8264. cb.call(context, this._layers[z], z);
  8265. }
  8266. },
  8267. // Iterate each buildin layer
  8268. eachBuiltinLayer: function (cb, context) {
  8269. var zlevelList = this._zlevelList;
  8270. var layer;
  8271. var z;
  8272. var i;
  8273. for (i = 0; i < zlevelList.length; i++) {
  8274. z = zlevelList[i];
  8275. layer = this._layers[z];
  8276. if (layer.__builtin__) {
  8277. cb.call(context, layer, z);
  8278. }
  8279. }
  8280. },
  8281. // Iterate each other layer except buildin layer
  8282. eachOtherLayer: function (cb, context) {
  8283. var zlevelList = this._zlevelList;
  8284. var layer;
  8285. var z;
  8286. var i;
  8287. for (i = 0; i < zlevelList.length; i++) {
  8288. z = zlevelList[i];
  8289. layer = this._layers[z];
  8290. if (!layer.__builtin__) {
  8291. cb.call(context, layer, z);
  8292. }
  8293. }
  8294. },
  8295. /**
  8296. * 获取所有已创建的层
  8297. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8298. */
  8299. getLayers: function () {
  8300. return this._layers;
  8301. },
  8302. _updateLayerStatus: function (list) {
  8303. this.eachBuiltinLayer(function (layer, z) {
  8304. layer.__dirty = layer.__used = false;
  8305. });
  8306. function updatePrevLayer(idx) {
  8307. if (prevLayer) {
  8308. if (prevLayer.__endIndex !== idx) {
  8309. prevLayer.__dirty = true;
  8310. }
  8311. prevLayer.__endIndex = idx;
  8312. }
  8313. }
  8314. if (this._singleCanvas) {
  8315. for (var i = 1; i < list.length; i++) {
  8316. var el = list[i];
  8317. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8318. this._needsManuallyCompositing = true;
  8319. break;
  8320. }
  8321. }
  8322. }
  8323. var prevLayer = null;
  8324. var incrementalLayerCount = 0;
  8325. for (var i = 0; i < list.length; i++) {
  8326. var el = list[i];
  8327. var zlevel = el.zlevel;
  8328. var layer;
  8329. // PENDING If change one incremental element style ?
  8330. // TODO Where there are non-incremental elements between incremental elements.
  8331. if (el.incremental) {
  8332. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8333. layer.incremental = true;
  8334. incrementalLayerCount = 1;
  8335. }
  8336. else {
  8337. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8338. }
  8339. if (!layer.__builtin__) {
  8340. log$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8341. }
  8342. if (layer !== prevLayer) {
  8343. layer.__used = true;
  8344. if (layer.__startIndex !== i) {
  8345. layer.__dirty = true;
  8346. }
  8347. layer.__startIndex = i;
  8348. if (!layer.incremental) {
  8349. layer.__drawIndex = i;
  8350. }
  8351. else {
  8352. // Mark layer draw index needs to update.
  8353. layer.__drawIndex = -1;
  8354. }
  8355. updatePrevLayer(i);
  8356. prevLayer = layer;
  8357. }
  8358. if (el.__dirty) {
  8359. layer.__dirty = true;
  8360. if (layer.incremental && layer.__drawIndex < 0) {
  8361. // Start draw from the first dirty element.
  8362. layer.__drawIndex = i;
  8363. }
  8364. }
  8365. }
  8366. updatePrevLayer(i);
  8367. this.eachBuiltinLayer(function (layer, z) {
  8368. // Used in last frame but not in this frame. Needs clear
  8369. if (!layer.__used && layer.getElementCount() > 0) {
  8370. layer.__dirty = true;
  8371. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8372. }
  8373. // For incremental layer. In case start index changed and no elements are dirty.
  8374. if (layer.__dirty && layer.__drawIndex < 0) {
  8375. layer.__drawIndex = layer.__startIndex;
  8376. }
  8377. });
  8378. },
  8379. /**
  8380. * 清除hover层外所有内容
  8381. */
  8382. clear: function () {
  8383. this.eachBuiltinLayer(this._clearLayer);
  8384. return this;
  8385. },
  8386. _clearLayer: function (layer) {
  8387. layer.clear();
  8388. },
  8389. setBackgroundColor: function (backgroundColor) {
  8390. this._backgroundColor = backgroundColor;
  8391. },
  8392. /**
  8393. * 修改指定zlevel的绘制参数
  8394. *
  8395. * @param {string} zlevel
  8396. * @param {Object} config 配置对象
  8397. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8398. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8399. * @param {number} [config.lastFrameAlpha=0.7]
  8400. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8401. */
  8402. configLayer: function (zlevel, config) {
  8403. if (config) {
  8404. var layerConfig = this._layerConfig;
  8405. if (!layerConfig[zlevel]) {
  8406. layerConfig[zlevel] = config;
  8407. }
  8408. else {
  8409. merge(layerConfig[zlevel], config, true);
  8410. }
  8411. for (var i = 0; i < this._zlevelList.length; i++) {
  8412. var _zlevel = this._zlevelList[i];
  8413. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8414. var layer = this._layers[_zlevel];
  8415. merge(layer, layerConfig[zlevel], true);
  8416. }
  8417. }
  8418. }
  8419. },
  8420. /**
  8421. * 删除指定层
  8422. * @param {number} zlevel 层所在的zlevel
  8423. */
  8424. delLayer: function (zlevel) {
  8425. var layers = this._layers;
  8426. var zlevelList = this._zlevelList;
  8427. var layer = layers[zlevel];
  8428. if (!layer) {
  8429. return;
  8430. }
  8431. layer.dom.parentNode.removeChild(layer.dom);
  8432. delete layers[zlevel];
  8433. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8434. },
  8435. /**
  8436. * 区域大小变化后重绘
  8437. */
  8438. resize: function (width, height) {
  8439. if (!this._domRoot.style) { // Maybe in node or worker
  8440. if (width == null || height == null) {
  8441. return;
  8442. }
  8443. this._width = width;
  8444. this._height = height;
  8445. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8446. }
  8447. else {
  8448. var domRoot = this._domRoot;
  8449. // FIXME Why ?
  8450. domRoot.style.display = 'none';
  8451. // Save input w/h
  8452. var opts = this._opts;
  8453. width != null && (opts.width = width);
  8454. height != null && (opts.height = height);
  8455. width = this._getSize(0);
  8456. height = this._getSize(1);
  8457. domRoot.style.display = '';
  8458. // 优化没有实际改变的resize
  8459. if (this._width !== width || height !== this._height) {
  8460. domRoot.style.width = width + 'px';
  8461. domRoot.style.height = height + 'px';
  8462. for (var id in this._layers) {
  8463. if (this._layers.hasOwnProperty(id)) {
  8464. this._layers[id].resize(width, height);
  8465. }
  8466. }
  8467. each$1(this._progressiveLayers, function (layer) {
  8468. layer.resize(width, height);
  8469. });
  8470. this.refresh(true);
  8471. }
  8472. this._width = width;
  8473. this._height = height;
  8474. }
  8475. return this;
  8476. },
  8477. /**
  8478. * 清除单独的一个层
  8479. * @param {number} zlevel
  8480. */
  8481. clearLayer: function (zlevel) {
  8482. var layer = this._layers[zlevel];
  8483. if (layer) {
  8484. layer.clear();
  8485. }
  8486. },
  8487. /**
  8488. * 释放
  8489. */
  8490. dispose: function () {
  8491. this.root.innerHTML = '';
  8492. this.root =
  8493. this.storage =
  8494. this._domRoot =
  8495. this._layers = null;
  8496. },
  8497. /**
  8498. * Get canvas which has all thing rendered
  8499. * @param {Object} opts
  8500. * @param {string} [opts.backgroundColor]
  8501. * @param {number} [opts.pixelRatio]
  8502. */
  8503. getRenderedCanvas: function (opts) {
  8504. opts = opts || {};
  8505. if (this._singleCanvas && !this._compositeManually) {
  8506. return this._layers[CANVAS_ZLEVEL].dom;
  8507. }
  8508. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8509. imageLayer.initContext();
  8510. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8511. if (opts.pixelRatio <= this.dpr) {
  8512. this.refresh();
  8513. var width = imageLayer.dom.width;
  8514. var height = imageLayer.dom.height;
  8515. var ctx = imageLayer.ctx;
  8516. this.eachLayer(function (layer) {
  8517. if (layer.__builtin__) {
  8518. ctx.drawImage(layer.dom, 0, 0, width, height);
  8519. }
  8520. else if (layer.renderToCanvas) {
  8521. imageLayer.ctx.save();
  8522. layer.renderToCanvas(imageLayer.ctx);
  8523. imageLayer.ctx.restore();
  8524. }
  8525. });
  8526. }
  8527. else {
  8528. // PENDING, echarts-gl and incremental rendering.
  8529. var scope = {};
  8530. var displayList = this.storage.getDisplayList(true);
  8531. for (var i = 0; i < displayList.length; i++) {
  8532. var el = displayList[i];
  8533. this._doPaintEl(el, imageLayer, true, scope);
  8534. }
  8535. }
  8536. return imageLayer.dom;
  8537. },
  8538. /**
  8539. * 获取绘图区域宽度
  8540. */
  8541. getWidth: function () {
  8542. return this._width;
  8543. },
  8544. /**
  8545. * 获取绘图区域高度
  8546. */
  8547. getHeight: function () {
  8548. return this._height;
  8549. },
  8550. _getSize: function (whIdx) {
  8551. var opts = this._opts;
  8552. var wh = ['width', 'height'][whIdx];
  8553. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8554. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8555. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8556. if (opts[wh] != null && opts[wh] !== 'auto') {
  8557. return parseFloat(opts[wh]);
  8558. }
  8559. var root = this.root;
  8560. // IE8 does not support getComputedStyle, but it use VML.
  8561. var stl = document.defaultView.getComputedStyle(root);
  8562. return (
  8563. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8564. - (parseInt10(stl[plt]) || 0)
  8565. - (parseInt10(stl[prb]) || 0)
  8566. ) | 0;
  8567. },
  8568. pathToImage: function (path, dpr) {
  8569. dpr = dpr || this.dpr;
  8570. var canvas = document.createElement('canvas');
  8571. var ctx = canvas.getContext('2d');
  8572. var rect = path.getBoundingRect();
  8573. var style = path.style;
  8574. var shadowBlurSize = style.shadowBlur * dpr;
  8575. var shadowOffsetX = style.shadowOffsetX * dpr;
  8576. var shadowOffsetY = style.shadowOffsetY * dpr;
  8577. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8578. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8579. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8580. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8581. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8582. var width = rect.width + leftMargin + rightMargin;
  8583. var height = rect.height + topMargin + bottomMargin;
  8584. canvas.width = width * dpr;
  8585. canvas.height = height * dpr;
  8586. ctx.scale(dpr, dpr);
  8587. ctx.clearRect(0, 0, width, height);
  8588. ctx.dpr = dpr;
  8589. var pathTransform = {
  8590. position: path.position,
  8591. rotation: path.rotation,
  8592. scale: path.scale
  8593. };
  8594. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8595. path.rotation = 0;
  8596. path.scale = [1, 1];
  8597. path.updateTransform();
  8598. if (path) {
  8599. path.brush(ctx);
  8600. }
  8601. var ImageShape = ZImage;
  8602. var imgShape = new ImageShape({
  8603. style: {
  8604. x: 0,
  8605. y: 0,
  8606. image: canvas
  8607. }
  8608. });
  8609. if (pathTransform.position != null) {
  8610. imgShape.position = path.position = pathTransform.position;
  8611. }
  8612. if (pathTransform.rotation != null) {
  8613. imgShape.rotation = path.rotation = pathTransform.rotation;
  8614. }
  8615. if (pathTransform.scale != null) {
  8616. imgShape.scale = path.scale = pathTransform.scale;
  8617. }
  8618. return imgShape;
  8619. }
  8620. };
  8621. /**
  8622. * 动画主类, 调度和管理所有动画控制器
  8623. *
  8624. * @module zrender/animation/Animation
  8625. * @author pissang(https://github.com/pissang)
  8626. */
  8627. // TODO Additive animation
  8628. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8629. // https://developer.apple.com/videos/wwdc2014/#236
  8630. /**
  8631. * @typedef {Object} IZRenderStage
  8632. * @property {Function} update
  8633. */
  8634. /**
  8635. * @alias module:zrender/animation/Animation
  8636. * @constructor
  8637. * @param {Object} [options]
  8638. * @param {Function} [options.onframe]
  8639. * @param {IZRenderStage} [options.stage]
  8640. * @example
  8641. * var animation = new Animation();
  8642. * var obj = {
  8643. * x: 100,
  8644. * y: 100
  8645. * };
  8646. * animation.animate(node.position)
  8647. * .when(1000, {
  8648. * x: 500,
  8649. * y: 500
  8650. * })
  8651. * .when(2000, {
  8652. * x: 100,
  8653. * y: 100
  8654. * })
  8655. * .start('spline');
  8656. */
  8657. var Animation = function (options) {
  8658. options = options || {};
  8659. this.stage = options.stage || {};
  8660. this.onframe = options.onframe || function () {};
  8661. // private properties
  8662. this._clips = [];
  8663. this._running = false;
  8664. this._time;
  8665. this._pausedTime;
  8666. this._pauseStart;
  8667. this._paused = false;
  8668. Eventful.call(this);
  8669. };
  8670. Animation.prototype = {
  8671. constructor: Animation,
  8672. /**
  8673. * 添加 clip
  8674. * @param {module:zrender/animation/Clip} clip
  8675. */
  8676. addClip: function (clip) {
  8677. this._clips.push(clip);
  8678. },
  8679. /**
  8680. * 添加 animator
  8681. * @param {module:zrender/animation/Animator} animator
  8682. */
  8683. addAnimator: function (animator) {
  8684. animator.animation = this;
  8685. var clips = animator.getClips();
  8686. for (var i = 0; i < clips.length; i++) {
  8687. this.addClip(clips[i]);
  8688. }
  8689. },
  8690. /**
  8691. * 删除动画片段
  8692. * @param {module:zrender/animation/Clip} clip
  8693. */
  8694. removeClip: function (clip) {
  8695. var idx = indexOf(this._clips, clip);
  8696. if (idx >= 0) {
  8697. this._clips.splice(idx, 1);
  8698. }
  8699. },
  8700. /**
  8701. * 删除动画片段
  8702. * @param {module:zrender/animation/Animator} animator
  8703. */
  8704. removeAnimator: function (animator) {
  8705. var clips = animator.getClips();
  8706. for (var i = 0; i < clips.length; i++) {
  8707. this.removeClip(clips[i]);
  8708. }
  8709. animator.animation = null;
  8710. },
  8711. _update: function () {
  8712. var time = new Date().getTime() - this._pausedTime;
  8713. var delta = time - this._time;
  8714. var clips = this._clips;
  8715. var len = clips.length;
  8716. var deferredEvents = [];
  8717. var deferredClips = [];
  8718. for (var i = 0; i < len; i++) {
  8719. var clip = clips[i];
  8720. var e = clip.step(time, delta);
  8721. // Throw out the events need to be called after
  8722. // stage.update, like destroy
  8723. if (e) {
  8724. deferredEvents.push(e);
  8725. deferredClips.push(clip);
  8726. }
  8727. }
  8728. // Remove the finished clip
  8729. for (var i = 0; i < len;) {
  8730. if (clips[i]._needsRemove) {
  8731. clips[i] = clips[len - 1];
  8732. clips.pop();
  8733. len--;
  8734. }
  8735. else {
  8736. i++;
  8737. }
  8738. }
  8739. len = deferredEvents.length;
  8740. for (var i = 0; i < len; i++) {
  8741. deferredClips[i].fire(deferredEvents[i]);
  8742. }
  8743. this._time = time;
  8744. this.onframe(delta);
  8745. // 'frame' should be triggered before stage, because upper application
  8746. // depends on the sequence (e.g., echarts-stream and finish
  8747. // event judge)
  8748. this.trigger('frame', delta);
  8749. if (this.stage.update) {
  8750. this.stage.update();
  8751. }
  8752. },
  8753. _startLoop: function () {
  8754. var self = this;
  8755. this._running = true;
  8756. function step() {
  8757. if (self._running) {
  8758. requestAnimationFrame(step);
  8759. !self._paused && self._update();
  8760. }
  8761. }
  8762. requestAnimationFrame(step);
  8763. },
  8764. /**
  8765. * Start animation.
  8766. */
  8767. start: function () {
  8768. this._time = new Date().getTime();
  8769. this._pausedTime = 0;
  8770. this._startLoop();
  8771. },
  8772. /**
  8773. * Stop animation.
  8774. */
  8775. stop: function () {
  8776. this._running = false;
  8777. },
  8778. /**
  8779. * Pause animation.
  8780. */
  8781. pause: function () {
  8782. if (!this._paused) {
  8783. this._pauseStart = new Date().getTime();
  8784. this._paused = true;
  8785. }
  8786. },
  8787. /**
  8788. * Resume animation.
  8789. */
  8790. resume: function () {
  8791. if (this._paused) {
  8792. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8793. this._paused = false;
  8794. }
  8795. },
  8796. /**
  8797. * Clear animation.
  8798. */
  8799. clear: function () {
  8800. this._clips = [];
  8801. },
  8802. /**
  8803. * Whether animation finished.
  8804. */
  8805. isFinished: function () {
  8806. return !this._clips.length;
  8807. },
  8808. /**
  8809. * Creat animator for a target, whose props can be animated.
  8810. *
  8811. * @param {Object} target
  8812. * @param {Object} options
  8813. * @param {boolean} [options.loop=false] Whether loop animation.
  8814. * @param {Function} [options.getter=null] Get value from target.
  8815. * @param {Function} [options.setter=null] Set value to target.
  8816. * @return {module:zrender/animation/Animation~Animator}
  8817. */
  8818. // TODO Gap
  8819. animate: function (target, options) {
  8820. options = options || {};
  8821. var animator = new Animator(
  8822. target,
  8823. options.loop,
  8824. options.getter,
  8825. options.setter
  8826. );
  8827. this.addAnimator(animator);
  8828. return animator;
  8829. }
  8830. };
  8831. mixin(Animation, Eventful);
  8832. var TOUCH_CLICK_DELAY = 300;
  8833. var mouseHandlerNames = [
  8834. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8835. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8836. ];
  8837. var touchHandlerNames = [
  8838. 'touchstart', 'touchend', 'touchmove'
  8839. ];
  8840. var pointerEventNames = {
  8841. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8842. };
  8843. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8844. var nm = name.replace('mouse', 'pointer');
  8845. return pointerEventNames[nm] ? nm : name;
  8846. });
  8847. function eventNameFix(name) {
  8848. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8849. }
  8850. // function onMSGestureChange(proxy, event) {
  8851. // if (event.translationX || event.translationY) {
  8852. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8853. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8854. // }
  8855. // if (event.scale !== 1) {
  8856. // event.pinchX = event.offsetX;
  8857. // event.pinchY = event.offsetY;
  8858. // event.pinchScale = event.scale;
  8859. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8860. // }
  8861. // }
  8862. /**
  8863. * Prevent mouse event from being dispatched after Touch Events action
  8864. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8865. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8866. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8867. * Result: Blocking Mouse Events for 700ms.
  8868. */
  8869. function setTouchTimer(instance) {
  8870. instance._touching = true;
  8871. clearTimeout(instance._touchTimer);
  8872. instance._touchTimer = setTimeout(function () {
  8873. instance._touching = false;
  8874. }, 700);
  8875. }
  8876. var domHandlers = {
  8877. /**
  8878. * Mouse move handler
  8879. * @inner
  8880. * @param {Event} event
  8881. */
  8882. mousemove: function (event) {
  8883. event = normalizeEvent(this.dom, event);
  8884. this.trigger('mousemove', event);
  8885. },
  8886. /**
  8887. * Mouse out handler
  8888. * @inner
  8889. * @param {Event} event
  8890. */
  8891. mouseout: function (event) {
  8892. event = normalizeEvent(this.dom, event);
  8893. var element = event.toElement || event.relatedTarget;
  8894. if (element !== this.dom) {
  8895. while (element && element.nodeType !== 9) {
  8896. // 忽略包含在root中的dom引起的mouseOut
  8897. if (element === this.dom) {
  8898. return;
  8899. }
  8900. element = element.parentNode;
  8901. }
  8902. }
  8903. this.trigger('mouseout', event);
  8904. },
  8905. /**
  8906. * Touch开始响应函数
  8907. * @inner
  8908. * @param {Event} event
  8909. */
  8910. touchstart: function (event) {
  8911. // Default mouse behaviour should not be disabled here.
  8912. // For example, page may needs to be slided.
  8913. event = normalizeEvent(this.dom, event);
  8914. // Mark touch, which is useful in distinguish touch and
  8915. // mouse event in upper applicatoin.
  8916. event.zrByTouch = true;
  8917. this._lastTouchMoment = new Date();
  8918. this.handler.processGesture(this, event, 'start');
  8919. // In touch device, trigger `mousemove`(`mouseover`) should
  8920. // be triggered, and must before `mousedown` triggered.
  8921. domHandlers.mousemove.call(this, event);
  8922. domHandlers.mousedown.call(this, event);
  8923. setTouchTimer(this);
  8924. },
  8925. /**
  8926. * Touch移动响应函数
  8927. * @inner
  8928. * @param {Event} event
  8929. */
  8930. touchmove: function (event) {
  8931. event = normalizeEvent(this.dom, event);
  8932. // Mark touch, which is useful in distinguish touch and
  8933. // mouse event in upper applicatoin.
  8934. event.zrByTouch = true;
  8935. this.handler.processGesture(this, event, 'change');
  8936. // Mouse move should always be triggered no matter whether
  8937. // there is gestrue event, because mouse move and pinch may
  8938. // be used at the same time.
  8939. domHandlers.mousemove.call(this, event);
  8940. setTouchTimer(this);
  8941. },
  8942. /**
  8943. * Touch结束响应函数
  8944. * @inner
  8945. * @param {Event} event
  8946. */
  8947. touchend: function (event) {
  8948. event = normalizeEvent(this.dom, event);
  8949. // Mark touch, which is useful in distinguish touch and
  8950. // mouse event in upper applicatoin.
  8951. event.zrByTouch = true;
  8952. this.handler.processGesture(this, event, 'end');
  8953. domHandlers.mouseup.call(this, event);
  8954. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8955. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8956. // we can conveniently implement "hover style" in both PC and touch device just
  8957. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8958. // to remove "hover style" on an element, without any additional code for
  8959. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8960. // style" will remain for user view)
  8961. // click event should always be triggered no matter whether
  8962. // there is gestrue event. System click can not be prevented.
  8963. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8964. domHandlers.click.call(this, event);
  8965. }
  8966. setTouchTimer(this);
  8967. },
  8968. pointerdown: function (event) {
  8969. domHandlers.mousedown.call(this, event);
  8970. // if (useMSGuesture(this, event)) {
  8971. // this._msGesture.addPointer(event.pointerId);
  8972. // }
  8973. },
  8974. pointermove: function (event) {
  8975. // FIXME
  8976. // pointermove is so sensitive that it always triggered when
  8977. // tap(click) on touch screen, which affect some judgement in
  8978. // upper application. So, we dont support mousemove on MS touch
  8979. // device yet.
  8980. if (!isPointerFromTouch(event)) {
  8981. domHandlers.mousemove.call(this, event);
  8982. }
  8983. },
  8984. pointerup: function (event) {
  8985. domHandlers.mouseup.call(this, event);
  8986. },
  8987. pointerout: function (event) {
  8988. // pointerout will be triggered when tap on touch screen
  8989. // (IE11+/Edge on MS Surface) after click event triggered,
  8990. // which is inconsistent with the mousout behavior we defined
  8991. // in touchend. So we unify them.
  8992. // (check domHandlers.touchend for detailed explanation)
  8993. if (!isPointerFromTouch(event)) {
  8994. domHandlers.mouseout.call(this, event);
  8995. }
  8996. }
  8997. };
  8998. function isPointerFromTouch(event) {
  8999. var pointerType = event.pointerType;
  9000. return pointerType === 'pen' || pointerType === 'touch';
  9001. }
  9002. // function useMSGuesture(handlerProxy, event) {
  9003. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9004. // }
  9005. // Common handlers
  9006. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9007. domHandlers[name] = function (event) {
  9008. event = normalizeEvent(this.dom, event);
  9009. this.trigger(name, event);
  9010. };
  9011. });
  9012. /**
  9013. * 为控制类实例初始化dom 事件处理函数
  9014. *
  9015. * @inner
  9016. * @param {module:zrender/Handler} instance 控制类实例
  9017. */
  9018. function initDomHandler(instance) {
  9019. each$1(touchHandlerNames, function (name) {
  9020. instance._handlers[name] = bind(domHandlers[name], instance);
  9021. });
  9022. each$1(pointerHandlerNames, function (name) {
  9023. instance._handlers[name] = bind(domHandlers[name], instance);
  9024. });
  9025. each$1(mouseHandlerNames, function (name) {
  9026. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9027. });
  9028. function makeMouseHandler(fn, instance) {
  9029. return function () {
  9030. if (instance._touching) {
  9031. return;
  9032. }
  9033. return fn.apply(instance, arguments);
  9034. };
  9035. }
  9036. }
  9037. function HandlerDomProxy(dom) {
  9038. Eventful.call(this);
  9039. this.dom = dom;
  9040. /**
  9041. * @private
  9042. * @type {boolean}
  9043. */
  9044. this._touching = false;
  9045. /**
  9046. * @private
  9047. * @type {number}
  9048. */
  9049. this._touchTimer;
  9050. this._handlers = {};
  9051. initDomHandler(this);
  9052. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9053. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9054. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9055. // at the same time.
  9056. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9057. // screen, which do not occurs in pointer event.
  9058. // So we use pointer event to both detect touch gesture and mouse behavior.
  9059. mountHandlers(pointerHandlerNames, this);
  9060. // FIXME
  9061. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9062. // which does not prevent defuault behavior occasionally (which may cause view port
  9063. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9064. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9065. // touch screen. And we only support click behavior on MS touch screen now.
  9066. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9067. // We dont support touch on IE on win7.
  9068. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9069. // if (typeof MSGesture === 'function') {
  9070. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9071. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9072. // }
  9073. }
  9074. else {
  9075. if (env$1.touchEventsSupported) {
  9076. mountHandlers(touchHandlerNames, this);
  9077. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9078. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9079. }
  9080. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9081. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9082. // mouse event can not be handle in those devices.
  9083. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9084. // mouseevent after touch event triggered, see `setTouchTimer`.
  9085. mountHandlers(mouseHandlerNames, this);
  9086. }
  9087. function mountHandlers(handlerNames, instance) {
  9088. each$1(handlerNames, function (name) {
  9089. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9090. }, instance);
  9091. }
  9092. }
  9093. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9094. handlerDomProxyProto.dispose = function () {
  9095. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9096. for (var i = 0; i < handlerNames.length; i++) {
  9097. var name = handlerNames[i];
  9098. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9099. }
  9100. };
  9101. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9102. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9103. };
  9104. mixin(HandlerDomProxy, Eventful);
  9105. /*!
  9106. * ZRender, a high performance 2d drawing library.
  9107. *
  9108. * Copyright (c) 2013, Baidu Inc.
  9109. * All rights reserved.
  9110. *
  9111. * LICENSE
  9112. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9113. */
  9114. var useVML = !env$1.canvasSupported;
  9115. var painterCtors = {
  9116. canvas: Painter
  9117. };
  9118. /**
  9119. * @type {string}
  9120. */
  9121. var version$1 = '4.0.7';
  9122. /**
  9123. * Initializing a zrender instance
  9124. * @param {HTMLElement} dom
  9125. * @param {Object} [opts]
  9126. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9127. * @param {number} [opts.devicePixelRatio]
  9128. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9129. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9130. * @return {module:zrender/ZRender}
  9131. */
  9132. function init$1(dom, opts) {
  9133. var zr = new ZRender(guid(), dom, opts);
  9134. return zr;
  9135. }
  9136. /**
  9137. * Dispose zrender instance
  9138. * @param {module:zrender/ZRender} zr
  9139. */
  9140. /**
  9141. * Get zrender instance by id
  9142. * @param {string} id zrender instance id
  9143. * @return {module:zrender/ZRender}
  9144. */
  9145. /**
  9146. * @module zrender/ZRender
  9147. */
  9148. /**
  9149. * @constructor
  9150. * @alias module:zrender/ZRender
  9151. * @param {string} id
  9152. * @param {HTMLElement} dom
  9153. * @param {Object} opts
  9154. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9155. * @param {number} [opts.devicePixelRatio]
  9156. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9157. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9158. */
  9159. var ZRender = function (id, dom, opts) {
  9160. opts = opts || {};
  9161. /**
  9162. * @type {HTMLDomElement}
  9163. */
  9164. this.dom = dom;
  9165. /**
  9166. * @type {string}
  9167. */
  9168. this.id = id;
  9169. var self = this;
  9170. var storage = new Storage();
  9171. var rendererType = opts.renderer;
  9172. // TODO WebGL
  9173. if (useVML) {
  9174. if (!painterCtors.vml) {
  9175. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9176. }
  9177. rendererType = 'vml';
  9178. }
  9179. else if (!rendererType || !painterCtors[rendererType]) {
  9180. rendererType = 'canvas';
  9181. }
  9182. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9183. this.storage = storage;
  9184. this.painter = painter;
  9185. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9186. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9187. /**
  9188. * @type {module:zrender/animation/Animation}
  9189. */
  9190. this.animation = new Animation({
  9191. stage: {
  9192. update: bind(this.flush, this)
  9193. }
  9194. });
  9195. this.animation.start();
  9196. /**
  9197. * @type {boolean}
  9198. * @private
  9199. */
  9200. this._needsRefresh;
  9201. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9202. // FIXME 有点ugly
  9203. var oldDelFromStorage = storage.delFromStorage;
  9204. var oldAddToStorage = storage.addToStorage;
  9205. storage.delFromStorage = function (el) {
  9206. oldDelFromStorage.call(storage, el);
  9207. el && el.removeSelfFromZr(self);
  9208. };
  9209. storage.addToStorage = function (el) {
  9210. oldAddToStorage.call(storage, el);
  9211. el.addSelfToZr(self);
  9212. };
  9213. };
  9214. ZRender.prototype = {
  9215. constructor: ZRender,
  9216. /**
  9217. * 获取实例唯一标识
  9218. * @return {string}
  9219. */
  9220. getId: function () {
  9221. return this.id;
  9222. },
  9223. /**
  9224. * 添加元素
  9225. * @param {module:zrender/Element} el
  9226. */
  9227. add: function (el) {
  9228. this.storage.addRoot(el);
  9229. this._needsRefresh = true;
  9230. },
  9231. /**
  9232. * 删除元素
  9233. * @param {module:zrender/Element} el
  9234. */
  9235. remove: function (el) {
  9236. this.storage.delRoot(el);
  9237. this._needsRefresh = true;
  9238. },
  9239. /**
  9240. * Change configuration of layer
  9241. * @param {string} zLevel
  9242. * @param {Object} config
  9243. * @param {string} [config.clearColor=0] Clear color
  9244. * @param {string} [config.motionBlur=false] If enable motion blur
  9245. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9246. */
  9247. configLayer: function (zLevel, config) {
  9248. if (this.painter.configLayer) {
  9249. this.painter.configLayer(zLevel, config);
  9250. }
  9251. this._needsRefresh = true;
  9252. },
  9253. /**
  9254. * Set background color
  9255. * @param {string} backgroundColor
  9256. */
  9257. setBackgroundColor: function (backgroundColor) {
  9258. if (this.painter.setBackgroundColor) {
  9259. this.painter.setBackgroundColor(backgroundColor);
  9260. }
  9261. this._needsRefresh = true;
  9262. },
  9263. /**
  9264. * Repaint the canvas immediately
  9265. */
  9266. refreshImmediately: function () {
  9267. // var start = new Date();
  9268. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9269. // Or it will cause zrender refreshes again and again.
  9270. this._needsRefresh = false;
  9271. this.painter.refresh();
  9272. /**
  9273. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9274. */
  9275. this._needsRefresh = false;
  9276. // var end = new Date();
  9277. // var log = document.getElementById('log');
  9278. // if (log) {
  9279. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9280. // }
  9281. },
  9282. /**
  9283. * Mark and repaint the canvas in the next frame of browser
  9284. */
  9285. refresh: function () {
  9286. this._needsRefresh = true;
  9287. },
  9288. /**
  9289. * Perform all refresh
  9290. */
  9291. flush: function () {
  9292. var triggerRendered;
  9293. if (this._needsRefresh) {
  9294. triggerRendered = true;
  9295. this.refreshImmediately();
  9296. }
  9297. if (this._needsRefreshHover) {
  9298. triggerRendered = true;
  9299. this.refreshHoverImmediately();
  9300. }
  9301. triggerRendered && this.trigger('rendered');
  9302. },
  9303. /**
  9304. * Add element to hover layer
  9305. * @param {module:zrender/Element} el
  9306. * @param {Object} style
  9307. */
  9308. addHover: function (el, style) {
  9309. if (this.painter.addHover) {
  9310. var elMirror = this.painter.addHover(el, style);
  9311. this.refreshHover();
  9312. return elMirror;
  9313. }
  9314. },
  9315. /**
  9316. * Add element from hover layer
  9317. * @param {module:zrender/Element} el
  9318. */
  9319. removeHover: function (el) {
  9320. if (this.painter.removeHover) {
  9321. this.painter.removeHover(el);
  9322. this.refreshHover();
  9323. }
  9324. },
  9325. /**
  9326. * Clear all hover elements in hover layer
  9327. * @param {module:zrender/Element} el
  9328. */
  9329. clearHover: function () {
  9330. if (this.painter.clearHover) {
  9331. this.painter.clearHover();
  9332. this.refreshHover();
  9333. }
  9334. },
  9335. /**
  9336. * Refresh hover in next frame
  9337. */
  9338. refreshHover: function () {
  9339. this._needsRefreshHover = true;
  9340. },
  9341. /**
  9342. * Refresh hover immediately
  9343. */
  9344. refreshHoverImmediately: function () {
  9345. this._needsRefreshHover = false;
  9346. this.painter.refreshHover && this.painter.refreshHover();
  9347. },
  9348. /**
  9349. * Resize the canvas.
  9350. * Should be invoked when container size is changed
  9351. * @param {Object} [opts]
  9352. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9353. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9354. */
  9355. resize: function (opts) {
  9356. opts = opts || {};
  9357. this.painter.resize(opts.width, opts.height);
  9358. this.handler.resize();
  9359. },
  9360. /**
  9361. * Stop and clear all animation immediately
  9362. */
  9363. clearAnimation: function () {
  9364. this.animation.clear();
  9365. },
  9366. /**
  9367. * Get container width
  9368. */
  9369. getWidth: function () {
  9370. return this.painter.getWidth();
  9371. },
  9372. /**
  9373. * Get container height
  9374. */
  9375. getHeight: function () {
  9376. return this.painter.getHeight();
  9377. },
  9378. /**
  9379. * Export the canvas as Base64 URL
  9380. * @param {string} type
  9381. * @param {string} [backgroundColor='#fff']
  9382. * @return {string} Base64 URL
  9383. */
  9384. // toDataURL: function(type, backgroundColor) {
  9385. // return this.painter.getRenderedCanvas({
  9386. // backgroundColor: backgroundColor
  9387. // }).toDataURL(type);
  9388. // },
  9389. /**
  9390. * Converting a path to image.
  9391. * It has much better performance of drawing image rather than drawing a vector path.
  9392. * @param {module:zrender/graphic/Path} e
  9393. * @param {number} width
  9394. * @param {number} height
  9395. */
  9396. pathToImage: function (e, dpr) {
  9397. return this.painter.pathToImage(e, dpr);
  9398. },
  9399. /**
  9400. * Set default cursor
  9401. * @param {string} [cursorStyle='default'] 例如 crosshair
  9402. */
  9403. setCursorStyle: function (cursorStyle) {
  9404. this.handler.setCursorStyle(cursorStyle);
  9405. },
  9406. /**
  9407. * Find hovered element
  9408. * @param {number} x
  9409. * @param {number} y
  9410. * @return {Object} {target, topTarget}
  9411. */
  9412. findHover: function (x, y) {
  9413. return this.handler.findHover(x, y);
  9414. },
  9415. /**
  9416. * Bind event
  9417. *
  9418. * @param {string} eventName Event name
  9419. * @param {Function} eventHandler Handler function
  9420. * @param {Object} [context] Context object
  9421. */
  9422. on: function (eventName, eventHandler, context) {
  9423. this.handler.on(eventName, eventHandler, context);
  9424. },
  9425. /**
  9426. * Unbind event
  9427. * @param {string} eventName Event name
  9428. * @param {Function} [eventHandler] Handler function
  9429. */
  9430. off: function (eventName, eventHandler) {
  9431. this.handler.off(eventName, eventHandler);
  9432. },
  9433. /**
  9434. * Trigger event manually
  9435. *
  9436. * @param {string} eventName Event name
  9437. * @param {event=} event Event object
  9438. */
  9439. trigger: function (eventName, event) {
  9440. this.handler.trigger(eventName, event);
  9441. },
  9442. /**
  9443. * Clear all objects and the canvas.
  9444. */
  9445. clear: function () {
  9446. this.storage.delRoot();
  9447. this.painter.clear();
  9448. },
  9449. /**
  9450. * Dispose self.
  9451. */
  9452. dispose: function () {
  9453. this.animation.stop();
  9454. this.clear();
  9455. this.storage.dispose();
  9456. this.painter.dispose();
  9457. this.handler.dispose();
  9458. this.animation =
  9459. this.storage =
  9460. this.painter =
  9461. this.handler = null;
  9462. }
  9463. };
  9464. /*
  9465. * Licensed to the Apache Software Foundation (ASF) under one
  9466. * or more contributor license agreements. See the NOTICE file
  9467. * distributed with this work for additional information
  9468. * regarding copyright ownership. The ASF licenses this file
  9469. * to you under the Apache License, Version 2.0 (the
  9470. * "License"); you may not use this file except in compliance
  9471. * with the License. You may obtain a copy of the License at
  9472. *
  9473. * http://www.apache.org/licenses/LICENSE-2.0
  9474. *
  9475. * Unless required by applicable law or agreed to in writing,
  9476. * software distributed under the License is distributed on an
  9477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9478. * KIND, either express or implied. See the License for the
  9479. * specific language governing permissions and limitations
  9480. * under the License.
  9481. */
  9482. var each$2 = each$1;
  9483. var isObject$2 = isObject$1;
  9484. var isArray$1 = isArray;
  9485. /**
  9486. * Make the name displayable. But we should
  9487. * make sure it is not duplicated with user
  9488. * specified name, so use '\0';
  9489. */
  9490. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9491. /**
  9492. * If value is not array, then translate it to array.
  9493. * @param {*} value
  9494. * @return {Array} [value] or value
  9495. */
  9496. function normalizeToArray(value) {
  9497. return value instanceof Array
  9498. ? value
  9499. : value == null
  9500. ? []
  9501. : [value];
  9502. }
  9503. /**
  9504. * Sync default option between normal and emphasis like `position` and `show`
  9505. * In case some one will write code like
  9506. * label: {
  9507. * show: false,
  9508. * position: 'outside',
  9509. * fontSize: 18
  9510. * },
  9511. * emphasis: {
  9512. * label: { show: true }
  9513. * }
  9514. * @param {Object} opt
  9515. * @param {string} key
  9516. * @param {Array.<string>} subOpts
  9517. */
  9518. function defaultEmphasis(opt, key, subOpts) {
  9519. // Caution: performance sensitive.
  9520. if (opt) {
  9521. opt[key] = opt[key] || {};
  9522. opt.emphasis = opt.emphasis || {};
  9523. opt.emphasis[key] = opt.emphasis[key] || {};
  9524. // Default emphasis option from normal
  9525. for (var i = 0, len = subOpts.length; i < len; i++) {
  9526. var subOptName = subOpts[i];
  9527. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9528. && opt[key].hasOwnProperty(subOptName)
  9529. ) {
  9530. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9531. }
  9532. }
  9533. }
  9534. }
  9535. var TEXT_STYLE_OPTIONS = [
  9536. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9537. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9538. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9539. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9540. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9541. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9542. ];
  9543. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9544. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9545. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9546. // // FIXME: deprecated, check and remove it.
  9547. // 'textStyle'
  9548. // ]);
  9549. /**
  9550. * The method do not ensure performance.
  9551. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9552. * This helper method retieves value from data.
  9553. * @param {string|number|Date|Array|Object} dataItem
  9554. * @return {number|string|Date|Array.<number|string|Date>}
  9555. */
  9556. function getDataItemValue(dataItem) {
  9557. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9558. ? dataItem.value : dataItem;
  9559. }
  9560. /**
  9561. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9562. * This helper method determine if dataItem has extra option besides value
  9563. * @param {string|number|Date|Array|Object} dataItem
  9564. */
  9565. function isDataItemOption(dataItem) {
  9566. return isObject$2(dataItem)
  9567. && !(dataItem instanceof Array);
  9568. // // markLine data can be array
  9569. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9570. }
  9571. /**
  9572. * Mapping to exists for merge.
  9573. *
  9574. * @public
  9575. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9576. * @param {Object|Array.<Object>} newCptOptions
  9577. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9578. * index of which is the same as exists.
  9579. */
  9580. function mappingToExists(exists, newCptOptions) {
  9581. // Mapping by the order by original option (but not order of
  9582. // new option) in merge mode. Because we should ensure
  9583. // some specified index (like xAxisIndex) is consistent with
  9584. // original option, which is easy to understand, espatially in
  9585. // media query. And in most case, merge option is used to
  9586. // update partial option but not be expected to change order.
  9587. newCptOptions = (newCptOptions || []).slice();
  9588. var result = map(exists || [], function (obj, index) {
  9589. return {exist: obj};
  9590. });
  9591. // Mapping by id or name if specified.
  9592. each$2(newCptOptions, function (cptOption, index) {
  9593. if (!isObject$2(cptOption)) {
  9594. return;
  9595. }
  9596. // id has highest priority.
  9597. for (var i = 0; i < result.length; i++) {
  9598. if (!result[i].option // Consider name: two map to one.
  9599. && cptOption.id != null
  9600. && result[i].exist.id === cptOption.id + ''
  9601. ) {
  9602. result[i].option = cptOption;
  9603. newCptOptions[index] = null;
  9604. return;
  9605. }
  9606. }
  9607. for (var i = 0; i < result.length; i++) {
  9608. var exist = result[i].exist;
  9609. if (!result[i].option // Consider name: two map to one.
  9610. // Can not match when both ids exist but different.
  9611. && (exist.id == null || cptOption.id == null)
  9612. && cptOption.name != null
  9613. && !isIdInner(cptOption)
  9614. && !isIdInner(exist)
  9615. && exist.name === cptOption.name + ''
  9616. ) {
  9617. result[i].option = cptOption;
  9618. newCptOptions[index] = null;
  9619. return;
  9620. }
  9621. }
  9622. });
  9623. // Otherwise mapping by index.
  9624. each$2(newCptOptions, function (cptOption, index) {
  9625. if (!isObject$2(cptOption)) {
  9626. return;
  9627. }
  9628. var i = 0;
  9629. for (; i < result.length; i++) {
  9630. var exist = result[i].exist;
  9631. if (!result[i].option
  9632. // Existing model that already has id should be able to
  9633. // mapped to (because after mapping performed model may
  9634. // be assigned with a id, whish should not affect next
  9635. // mapping), except those has inner id.
  9636. && !isIdInner(exist)
  9637. // Caution:
  9638. // Do not overwrite id. But name can be overwritten,
  9639. // because axis use name as 'show label text'.
  9640. // 'exist' always has id and name and we dont
  9641. // need to check it.
  9642. && cptOption.id == null
  9643. ) {
  9644. result[i].option = cptOption;
  9645. break;
  9646. }
  9647. }
  9648. if (i >= result.length) {
  9649. result.push({option: cptOption});
  9650. }
  9651. });
  9652. return result;
  9653. }
  9654. /**
  9655. * Make id and name for mapping result (result of mappingToExists)
  9656. * into `keyInfo` field.
  9657. *
  9658. * @public
  9659. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9660. * which order is the same as exists.
  9661. * @return {Array.<Object>} The input.
  9662. */
  9663. function makeIdAndName(mapResult) {
  9664. // We use this id to hash component models and view instances
  9665. // in echarts. id can be specified by user, or auto generated.
  9666. // The id generation rule ensures new view instance are able
  9667. // to mapped to old instance when setOption are called in
  9668. // no-merge mode. So we generate model id by name and plus
  9669. // type in view id.
  9670. // name can be duplicated among components, which is convenient
  9671. // to specify multi components (like series) by one name.
  9672. // Ensure that each id is distinct.
  9673. var idMap = createHashMap();
  9674. each$2(mapResult, function (item, index) {
  9675. var existCpt = item.exist;
  9676. existCpt && idMap.set(existCpt.id, item);
  9677. });
  9678. each$2(mapResult, function (item, index) {
  9679. var opt = item.option;
  9680. assert$1(
  9681. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9682. 'id duplicates: ' + (opt && opt.id)
  9683. );
  9684. opt && opt.id != null && idMap.set(opt.id, item);
  9685. !item.keyInfo && (item.keyInfo = {});
  9686. });
  9687. // Make name and id.
  9688. each$2(mapResult, function (item, index) {
  9689. var existCpt = item.exist;
  9690. var opt = item.option;
  9691. var keyInfo = item.keyInfo;
  9692. if (!isObject$2(opt)) {
  9693. return;
  9694. }
  9695. // name can be overwitten. Consider case: axis.name = '20km'.
  9696. // But id generated by name will not be changed, which affect
  9697. // only in that case: setOption with 'not merge mode' and view
  9698. // instance will be recreated, which can be accepted.
  9699. keyInfo.name = opt.name != null
  9700. ? opt.name + ''
  9701. : existCpt
  9702. ? existCpt.name
  9703. // Avoid diffferent series has the same name,
  9704. // because name may be used like in color pallet.
  9705. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9706. if (existCpt) {
  9707. keyInfo.id = existCpt.id;
  9708. }
  9709. else if (opt.id != null) {
  9710. keyInfo.id = opt.id + '';
  9711. }
  9712. else {
  9713. // Consider this situatoin:
  9714. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9715. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9716. // Series with the same name between optionA and optionB
  9717. // should be mapped.
  9718. var idNum = 0;
  9719. do {
  9720. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9721. }
  9722. while (idMap.get(keyInfo.id));
  9723. }
  9724. idMap.set(keyInfo.id, item);
  9725. });
  9726. }
  9727. function isNameSpecified(componentModel) {
  9728. var name = componentModel.name;
  9729. // Is specified when `indexOf` get -1 or > 0.
  9730. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9731. }
  9732. /**
  9733. * @public
  9734. * @param {Object} cptOption
  9735. * @return {boolean}
  9736. */
  9737. function isIdInner(cptOption) {
  9738. return isObject$2(cptOption)
  9739. && cptOption.id
  9740. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9741. }
  9742. /**
  9743. * A helper for removing duplicate items between batchA and batchB,
  9744. * and in themselves, and categorize by series.
  9745. *
  9746. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9747. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9748. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9749. */
  9750. /**
  9751. * @param {module:echarts/data/List} data
  9752. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9753. * each of which can be Array or primary type.
  9754. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9755. */
  9756. function queryDataIndex(data, payload) {
  9757. if (payload.dataIndexInside != null) {
  9758. return payload.dataIndexInside;
  9759. }
  9760. else if (payload.dataIndex != null) {
  9761. return isArray(payload.dataIndex)
  9762. ? map(payload.dataIndex, function (value) {
  9763. return data.indexOfRawIndex(value);
  9764. })
  9765. : data.indexOfRawIndex(payload.dataIndex);
  9766. }
  9767. else if (payload.name != null) {
  9768. return isArray(payload.name)
  9769. ? map(payload.name, function (value) {
  9770. return data.indexOfName(value);
  9771. })
  9772. : data.indexOfName(payload.name);
  9773. }
  9774. }
  9775. /**
  9776. * Enable property storage to any host object.
  9777. * Notice: Serialization is not supported.
  9778. *
  9779. * For example:
  9780. * var inner = zrUitl.makeInner();
  9781. *
  9782. * function some1(hostObj) {
  9783. * inner(hostObj).someProperty = 1212;
  9784. * ...
  9785. * }
  9786. * function some2() {
  9787. * var fields = inner(this);
  9788. * fields.someProperty1 = 1212;
  9789. * fields.someProperty2 = 'xx';
  9790. * ...
  9791. * }
  9792. *
  9793. * @return {Function}
  9794. */
  9795. function makeInner() {
  9796. // Consider different scope by es module import.
  9797. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9798. return function (hostObj) {
  9799. return hostObj[key] || (hostObj[key] = {});
  9800. };
  9801. }
  9802. var innerUniqueIndex = 0;
  9803. /**
  9804. * @param {module:echarts/model/Global} ecModel
  9805. * @param {string|Object} finder
  9806. * If string, e.g., 'geo', means {geoIndex: 0}.
  9807. * If Object, could contain some of these properties below:
  9808. * {
  9809. * seriesIndex, seriesId, seriesName,
  9810. * geoIndex, geoId, geoName,
  9811. * bmapIndex, bmapId, bmapName,
  9812. * xAxisIndex, xAxisId, xAxisName,
  9813. * yAxisIndex, yAxisId, yAxisName,
  9814. * gridIndex, gridId, gridName,
  9815. * ... (can be extended)
  9816. * }
  9817. * Each properties can be number|string|Array.<number>|Array.<string>
  9818. * For example, a finder could be
  9819. * {
  9820. * seriesIndex: 3,
  9821. * geoId: ['aa', 'cc'],
  9822. * gridName: ['xx', 'rr']
  9823. * }
  9824. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9825. * If nothing or null/undefined specified, return nothing.
  9826. * @param {Object} [opt]
  9827. * @param {string} [opt.defaultMainType]
  9828. * @param {Array.<string>} [opt.includeMainTypes]
  9829. * @return {Object} result like:
  9830. * {
  9831. * seriesModels: [seriesModel1, seriesModel2],
  9832. * seriesModel: seriesModel1, // The first model
  9833. * geoModels: [geoModel1, geoModel2],
  9834. * geoModel: geoModel1, // The first model
  9835. * ...
  9836. * }
  9837. */
  9838. function parseFinder(ecModel, finder, opt) {
  9839. if (isString(finder)) {
  9840. var obj = {};
  9841. obj[finder + 'Index'] = 0;
  9842. finder = obj;
  9843. }
  9844. var defaultMainType = opt && opt.defaultMainType;
  9845. if (defaultMainType
  9846. && !has(finder, defaultMainType + 'Index')
  9847. && !has(finder, defaultMainType + 'Id')
  9848. && !has(finder, defaultMainType + 'Name')
  9849. ) {
  9850. finder[defaultMainType + 'Index'] = 0;
  9851. }
  9852. var result = {};
  9853. each$2(finder, function (value, key) {
  9854. var value = finder[key];
  9855. // Exclude 'dataIndex' and other illgal keys.
  9856. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9857. result[key] = value;
  9858. return;
  9859. }
  9860. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9861. var mainType = parsedKey[1];
  9862. var queryType = (parsedKey[2] || '').toLowerCase();
  9863. if (!mainType
  9864. || !queryType
  9865. || value == null
  9866. || (queryType === 'index' && value === 'none')
  9867. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9868. ) {
  9869. return;
  9870. }
  9871. var queryParam = {mainType: mainType};
  9872. if (queryType !== 'index' || value !== 'all') {
  9873. queryParam[queryType] = value;
  9874. }
  9875. var models = ecModel.queryComponents(queryParam);
  9876. result[mainType + 'Models'] = models;
  9877. result[mainType + 'Model'] = models[0];
  9878. });
  9879. return result;
  9880. }
  9881. function has(obj, prop) {
  9882. return obj && obj.hasOwnProperty(prop);
  9883. }
  9884. function setAttribute(dom, key, value) {
  9885. dom.setAttribute
  9886. ? dom.setAttribute(key, value)
  9887. : (dom[key] = value);
  9888. }
  9889. function getAttribute(dom, key) {
  9890. return dom.getAttribute
  9891. ? dom.getAttribute(key)
  9892. : dom[key];
  9893. }
  9894. function getTooltipRenderMode(renderModeOption) {
  9895. if (renderModeOption === 'auto') {
  9896. // Using html when `document` exists, use richText otherwise
  9897. return env$1.domSupported ? 'html' : 'richText';
  9898. }
  9899. else {
  9900. return renderModeOption || 'html';
  9901. }
  9902. }
  9903. /**
  9904. * Group a list by key.
  9905. *
  9906. * @param {Array} array
  9907. * @param {Function} getKey
  9908. * param {*} Array item
  9909. * return {string} key
  9910. * @return {Object} Result
  9911. * {Array}: keys,
  9912. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  9913. */
  9914. /*
  9915. * Licensed to the Apache Software Foundation (ASF) under one
  9916. * or more contributor license agreements. See the NOTICE file
  9917. * distributed with this work for additional information
  9918. * regarding copyright ownership. The ASF licenses this file
  9919. * to you under the Apache License, Version 2.0 (the
  9920. * "License"); you may not use this file except in compliance
  9921. * with the License. You may obtain a copy of the License at
  9922. *
  9923. * http://www.apache.org/licenses/LICENSE-2.0
  9924. *
  9925. * Unless required by applicable law or agreed to in writing,
  9926. * software distributed under the License is distributed on an
  9927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9928. * KIND, either express or implied. See the License for the
  9929. * specific language governing permissions and limitations
  9930. * under the License.
  9931. */
  9932. var TYPE_DELIMITER = '.';
  9933. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9934. /**
  9935. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9936. * @public
  9937. */
  9938. function parseClassType$1(componentType) {
  9939. var ret = {main: '', sub: ''};
  9940. if (componentType) {
  9941. componentType = componentType.split(TYPE_DELIMITER);
  9942. ret.main = componentType[0] || '';
  9943. ret.sub = componentType[1] || '';
  9944. }
  9945. return ret;
  9946. }
  9947. /**
  9948. * @public
  9949. */
  9950. function checkClassType(componentType) {
  9951. assert$1(
  9952. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  9953. 'componentType "' + componentType + '" illegal'
  9954. );
  9955. }
  9956. /**
  9957. * @public
  9958. */
  9959. function enableClassExtend(RootClass, mandatoryMethods) {
  9960. RootClass.$constructor = RootClass;
  9961. RootClass.extend = function (proto) {
  9962. if (__DEV__) {
  9963. each$1(mandatoryMethods, function (method) {
  9964. if (!proto[method]) {
  9965. console.warn(
  9966. 'Method `' + method + '` should be implemented'
  9967. + (proto.type ? ' in ' + proto.type : '') + '.'
  9968. );
  9969. }
  9970. });
  9971. }
  9972. var superClass = this;
  9973. var ExtendedClass = function () {
  9974. if (!proto.$constructor) {
  9975. superClass.apply(this, arguments);
  9976. }
  9977. else {
  9978. proto.$constructor.apply(this, arguments);
  9979. }
  9980. };
  9981. extend(ExtendedClass.prototype, proto);
  9982. ExtendedClass.extend = this.extend;
  9983. ExtendedClass.superCall = superCall;
  9984. ExtendedClass.superApply = superApply;
  9985. inherits(ExtendedClass, this);
  9986. ExtendedClass.superClass = superClass;
  9987. return ExtendedClass;
  9988. };
  9989. }
  9990. var classBase = 0;
  9991. /**
  9992. * Can not use instanceof, consider different scope by
  9993. * cross domain or es module import in ec extensions.
  9994. * Mount a method "isInstance()" to Clz.
  9995. */
  9996. function enableClassCheck(Clz) {
  9997. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  9998. Clz.prototype[classAttr] = true;
  9999. if (__DEV__) {
  10000. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10001. }
  10002. Clz.isInstance = function (obj) {
  10003. return !!(obj && obj[classAttr]);
  10004. };
  10005. }
  10006. // superCall should have class info, which can not be fetch from 'this'.
  10007. // Consider this case:
  10008. // class A has method f,
  10009. // class B inherits class A, overrides method f, f call superApply('f'),
  10010. // class C inherits class B, do not overrides method f,
  10011. // then when method of class C is called, dead loop occured.
  10012. function superCall(context, methodName) {
  10013. var args = slice(arguments, 2);
  10014. return this.superClass.prototype[methodName].apply(context, args);
  10015. }
  10016. function superApply(context, methodName, args) {
  10017. return this.superClass.prototype[methodName].apply(context, args);
  10018. }
  10019. /**
  10020. * @param {Object} entity
  10021. * @param {Object} options
  10022. * @param {boolean} [options.registerWhenExtend]
  10023. * @public
  10024. */
  10025. function enableClassManagement(entity, options) {
  10026. options = options || {};
  10027. /**
  10028. * Component model classes
  10029. * key: componentType,
  10030. * value:
  10031. * componentClass, when componentType is 'xxx'
  10032. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10033. * @type {Object}
  10034. */
  10035. var storage = {};
  10036. entity.registerClass = function (Clazz, componentType) {
  10037. if (componentType) {
  10038. checkClassType(componentType);
  10039. componentType = parseClassType$1(componentType);
  10040. if (!componentType.sub) {
  10041. if (__DEV__) {
  10042. if (storage[componentType.main]) {
  10043. console.warn(componentType.main + ' exists.');
  10044. }
  10045. }
  10046. storage[componentType.main] = Clazz;
  10047. }
  10048. else if (componentType.sub !== IS_CONTAINER) {
  10049. var container = makeContainer(componentType);
  10050. container[componentType.sub] = Clazz;
  10051. }
  10052. }
  10053. return Clazz;
  10054. };
  10055. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10056. var Clazz = storage[componentMainType];
  10057. if (Clazz && Clazz[IS_CONTAINER]) {
  10058. Clazz = subType ? Clazz[subType] : null;
  10059. }
  10060. if (throwWhenNotFound && !Clazz) {
  10061. throw new Error(
  10062. !subType
  10063. ? componentMainType + '.' + 'type should be specified.'
  10064. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10065. );
  10066. }
  10067. return Clazz;
  10068. };
  10069. entity.getClassesByMainType = function (componentType) {
  10070. componentType = parseClassType$1(componentType);
  10071. var result = [];
  10072. var obj = storage[componentType.main];
  10073. if (obj && obj[IS_CONTAINER]) {
  10074. each$1(obj, function (o, type) {
  10075. type !== IS_CONTAINER && result.push(o);
  10076. });
  10077. }
  10078. else {
  10079. result.push(obj);
  10080. }
  10081. return result;
  10082. };
  10083. entity.hasClass = function (componentType) {
  10084. // Just consider componentType.main.
  10085. componentType = parseClassType$1(componentType);
  10086. return !!storage[componentType.main];
  10087. };
  10088. /**
  10089. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10090. */
  10091. entity.getAllClassMainTypes = function () {
  10092. var types = [];
  10093. each$1(storage, function (obj, type) {
  10094. types.push(type);
  10095. });
  10096. return types;
  10097. };
  10098. /**
  10099. * If a main type is container and has sub types
  10100. * @param {string} mainType
  10101. * @return {boolean}
  10102. */
  10103. entity.hasSubTypes = function (componentType) {
  10104. componentType = parseClassType$1(componentType);
  10105. var obj = storage[componentType.main];
  10106. return obj && obj[IS_CONTAINER];
  10107. };
  10108. entity.parseClassType = parseClassType$1;
  10109. function makeContainer(componentType) {
  10110. var container = storage[componentType.main];
  10111. if (!container || !container[IS_CONTAINER]) {
  10112. container = storage[componentType.main] = {};
  10113. container[IS_CONTAINER] = true;
  10114. }
  10115. return container;
  10116. }
  10117. if (options.registerWhenExtend) {
  10118. var originalExtend = entity.extend;
  10119. if (originalExtend) {
  10120. entity.extend = function (proto) {
  10121. var ExtendedClass = originalExtend.call(this, proto);
  10122. return entity.registerClass(ExtendedClass, proto.type);
  10123. };
  10124. }
  10125. }
  10126. return entity;
  10127. }
  10128. /**
  10129. * @param {string|Array.<string>} properties
  10130. */
  10131. /*
  10132. * Licensed to the Apache Software Foundation (ASF) under one
  10133. * or more contributor license agreements. See the NOTICE file
  10134. * distributed with this work for additional information
  10135. * regarding copyright ownership. The ASF licenses this file
  10136. * to you under the Apache License, Version 2.0 (the
  10137. * "License"); you may not use this file except in compliance
  10138. * with the License. You may obtain a copy of the License at
  10139. *
  10140. * http://www.apache.org/licenses/LICENSE-2.0
  10141. *
  10142. * Unless required by applicable law or agreed to in writing,
  10143. * software distributed under the License is distributed on an
  10144. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10145. * KIND, either express or implied. See the License for the
  10146. * specific language governing permissions and limitations
  10147. * under the License.
  10148. */
  10149. // TODO Parse shadow style
  10150. // TODO Only shallow path support
  10151. var makeStyleMapper = function (properties) {
  10152. // Normalize
  10153. for (var i = 0; i < properties.length; i++) {
  10154. if (!properties[i][1]) {
  10155. properties[i][1] = properties[i][0];
  10156. }
  10157. }
  10158. return function (model, excludes, includes) {
  10159. var style = {};
  10160. for (var i = 0; i < properties.length; i++) {
  10161. var propName = properties[i][1];
  10162. if ((excludes && indexOf(excludes, propName) >= 0)
  10163. || (includes && indexOf(includes, propName) < 0)
  10164. ) {
  10165. continue;
  10166. }
  10167. var val = model.getShallow(propName);
  10168. if (val != null) {
  10169. style[properties[i][0]] = val;
  10170. }
  10171. }
  10172. return style;
  10173. };
  10174. };
  10175. /*
  10176. * Licensed to the Apache Software Foundation (ASF) under one
  10177. * or more contributor license agreements. See the NOTICE file
  10178. * distributed with this work for additional information
  10179. * regarding copyright ownership. The ASF licenses this file
  10180. * to you under the Apache License, Version 2.0 (the
  10181. * "License"); you may not use this file except in compliance
  10182. * with the License. You may obtain a copy of the License at
  10183. *
  10184. * http://www.apache.org/licenses/LICENSE-2.0
  10185. *
  10186. * Unless required by applicable law or agreed to in writing,
  10187. * software distributed under the License is distributed on an
  10188. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10189. * KIND, either express or implied. See the License for the
  10190. * specific language governing permissions and limitations
  10191. * under the License.
  10192. */
  10193. var getLineStyle = makeStyleMapper(
  10194. [
  10195. ['lineWidth', 'width'],
  10196. ['stroke', 'color'],
  10197. ['opacity'],
  10198. ['shadowBlur'],
  10199. ['shadowOffsetX'],
  10200. ['shadowOffsetY'],
  10201. ['shadowColor']
  10202. ]
  10203. );
  10204. var lineStyleMixin = {
  10205. getLineStyle: function (excludes) {
  10206. var style = getLineStyle(this, excludes);
  10207. var lineDash = this.getLineDash(style.lineWidth);
  10208. lineDash && (style.lineDash = lineDash);
  10209. return style;
  10210. },
  10211. getLineDash: function (lineWidth) {
  10212. if (lineWidth == null) {
  10213. lineWidth = 1;
  10214. }
  10215. var lineType = this.get('type');
  10216. var dotSize = Math.max(lineWidth, 2);
  10217. var dashSize = lineWidth * 4;
  10218. return (lineType === 'solid' || lineType == null) ? null
  10219. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10220. }
  10221. };
  10222. /*
  10223. * Licensed to the Apache Software Foundation (ASF) under one
  10224. * or more contributor license agreements. See the NOTICE file
  10225. * distributed with this work for additional information
  10226. * regarding copyright ownership. The ASF licenses this file
  10227. * to you under the Apache License, Version 2.0 (the
  10228. * "License"); you may not use this file except in compliance
  10229. * with the License. You may obtain a copy of the License at
  10230. *
  10231. * http://www.apache.org/licenses/LICENSE-2.0
  10232. *
  10233. * Unless required by applicable law or agreed to in writing,
  10234. * software distributed under the License is distributed on an
  10235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10236. * KIND, either express or implied. See the License for the
  10237. * specific language governing permissions and limitations
  10238. * under the License.
  10239. */
  10240. var getAreaStyle = makeStyleMapper(
  10241. [
  10242. ['fill', 'color'],
  10243. ['shadowBlur'],
  10244. ['shadowOffsetX'],
  10245. ['shadowOffsetY'],
  10246. ['opacity'],
  10247. ['shadowColor']
  10248. ]
  10249. );
  10250. var areaStyleMixin = {
  10251. getAreaStyle: function (excludes, includes) {
  10252. return getAreaStyle(this, excludes, includes);
  10253. }
  10254. };
  10255. /**
  10256. * 曲线辅助模块
  10257. * @module zrender/core/curve
  10258. * @author pissang(https://www.github.com/pissang)
  10259. */
  10260. var mathPow = Math.pow;
  10261. var mathSqrt$2 = Math.sqrt;
  10262. var EPSILON$1 = 1e-8;
  10263. var EPSILON_NUMERIC = 1e-4;
  10264. var THREE_SQRT = mathSqrt$2(3);
  10265. var ONE_THIRD = 1 / 3;
  10266. // 临时变量
  10267. var _v0 = create();
  10268. var _v1 = create();
  10269. var _v2 = create();
  10270. function isAroundZero(val) {
  10271. return val > -EPSILON$1 && val < EPSILON$1;
  10272. }
  10273. function isNotAroundZero$1(val) {
  10274. return val > EPSILON$1 || val < -EPSILON$1;
  10275. }
  10276. /**
  10277. * 计算三次贝塞尔值
  10278. * @memberOf module:zrender/core/curve
  10279. * @param {number} p0
  10280. * @param {number} p1
  10281. * @param {number} p2
  10282. * @param {number} p3
  10283. * @param {number} t
  10284. * @return {number}
  10285. */
  10286. function cubicAt(p0, p1, p2, p3, t) {
  10287. var onet = 1 - t;
  10288. return onet * onet * (onet * p0 + 3 * t * p1)
  10289. + t * t * (t * p3 + 3 * onet * p2);
  10290. }
  10291. /**
  10292. * 计算三次贝塞尔导数值
  10293. * @memberOf module:zrender/core/curve
  10294. * @param {number} p0
  10295. * @param {number} p1
  10296. * @param {number} p2
  10297. * @param {number} p3
  10298. * @param {number} t
  10299. * @return {number}
  10300. */
  10301. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10302. var onet = 1 - t;
  10303. return 3 * (
  10304. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10305. + (p3 - p2) * t * t
  10306. );
  10307. }
  10308. /**
  10309. * 计算三次贝塞尔方程根,使用盛金公式
  10310. * @memberOf module:zrender/core/curve
  10311. * @param {number} p0
  10312. * @param {number} p1
  10313. * @param {number} p2
  10314. * @param {number} p3
  10315. * @param {number} val
  10316. * @param {Array.<number>} roots
  10317. * @return {number} 有效根数目
  10318. */
  10319. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10320. // Evaluate roots of cubic functions
  10321. var a = p3 + 3 * (p1 - p2) - p0;
  10322. var b = 3 * (p2 - p1 * 2 + p0);
  10323. var c = 3 * (p1 - p0);
  10324. var d = p0 - val;
  10325. var A = b * b - 3 * a * c;
  10326. var B = b * c - 9 * a * d;
  10327. var C = c * c - 3 * b * d;
  10328. var n = 0;
  10329. if (isAroundZero(A) && isAroundZero(B)) {
  10330. if (isAroundZero(b)) {
  10331. roots[0] = 0;
  10332. }
  10333. else {
  10334. var t1 = -c / b; //t1, t2, t3, b is not zero
  10335. if (t1 >= 0 && t1 <= 1) {
  10336. roots[n++] = t1;
  10337. }
  10338. }
  10339. }
  10340. else {
  10341. var disc = B * B - 4 * A * C;
  10342. if (isAroundZero(disc)) {
  10343. var K = B / A;
  10344. var t1 = -b / a + K; // t1, a is not zero
  10345. var t2 = -K / 2; // t2, t3
  10346. if (t1 >= 0 && t1 <= 1) {
  10347. roots[n++] = t1;
  10348. }
  10349. if (t2 >= 0 && t2 <= 1) {
  10350. roots[n++] = t2;
  10351. }
  10352. }
  10353. else if (disc > 0) {
  10354. var discSqrt = mathSqrt$2(disc);
  10355. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10356. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10357. if (Y1 < 0) {
  10358. Y1 = -mathPow(-Y1, ONE_THIRD);
  10359. }
  10360. else {
  10361. Y1 = mathPow(Y1, ONE_THIRD);
  10362. }
  10363. if (Y2 < 0) {
  10364. Y2 = -mathPow(-Y2, ONE_THIRD);
  10365. }
  10366. else {
  10367. Y2 = mathPow(Y2, ONE_THIRD);
  10368. }
  10369. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10370. if (t1 >= 0 && t1 <= 1) {
  10371. roots[n++] = t1;
  10372. }
  10373. }
  10374. else {
  10375. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10376. var theta = Math.acos(T) / 3;
  10377. var ASqrt = mathSqrt$2(A);
  10378. var tmp = Math.cos(theta);
  10379. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10380. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10381. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10382. if (t1 >= 0 && t1 <= 1) {
  10383. roots[n++] = t1;
  10384. }
  10385. if (t2 >= 0 && t2 <= 1) {
  10386. roots[n++] = t2;
  10387. }
  10388. if (t3 >= 0 && t3 <= 1) {
  10389. roots[n++] = t3;
  10390. }
  10391. }
  10392. }
  10393. return n;
  10394. }
  10395. /**
  10396. * 计算三次贝塞尔方程极限值的位置
  10397. * @memberOf module:zrender/core/curve
  10398. * @param {number} p0
  10399. * @param {number} p1
  10400. * @param {number} p2
  10401. * @param {number} p3
  10402. * @param {Array.<number>} extrema
  10403. * @return {number} 有效数目
  10404. */
  10405. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10406. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10407. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10408. var c = 3 * p1 - 3 * p0;
  10409. var n = 0;
  10410. if (isAroundZero(a)) {
  10411. if (isNotAroundZero$1(b)) {
  10412. var t1 = -c / b;
  10413. if (t1 >= 0 && t1 <= 1) {
  10414. extrema[n++] = t1;
  10415. }
  10416. }
  10417. }
  10418. else {
  10419. var disc = b * b - 4 * a * c;
  10420. if (isAroundZero(disc)) {
  10421. extrema[0] = -b / (2 * a);
  10422. }
  10423. else if (disc > 0) {
  10424. var discSqrt = mathSqrt$2(disc);
  10425. var t1 = (-b + discSqrt) / (2 * a);
  10426. var t2 = (-b - discSqrt) / (2 * a);
  10427. if (t1 >= 0 && t1 <= 1) {
  10428. extrema[n++] = t1;
  10429. }
  10430. if (t2 >= 0 && t2 <= 1) {
  10431. extrema[n++] = t2;
  10432. }
  10433. }
  10434. }
  10435. return n;
  10436. }
  10437. /**
  10438. * 细分三次贝塞尔曲线
  10439. * @memberOf module:zrender/core/curve
  10440. * @param {number} p0
  10441. * @param {number} p1
  10442. * @param {number} p2
  10443. * @param {number} p3
  10444. * @param {number} t
  10445. * @param {Array.<number>} out
  10446. */
  10447. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10448. var p01 = (p1 - p0) * t + p0;
  10449. var p12 = (p2 - p1) * t + p1;
  10450. var p23 = (p3 - p2) * t + p2;
  10451. var p012 = (p12 - p01) * t + p01;
  10452. var p123 = (p23 - p12) * t + p12;
  10453. var p0123 = (p123 - p012) * t + p012;
  10454. // Seg0
  10455. out[0] = p0;
  10456. out[1] = p01;
  10457. out[2] = p012;
  10458. out[3] = p0123;
  10459. // Seg1
  10460. out[4] = p0123;
  10461. out[5] = p123;
  10462. out[6] = p23;
  10463. out[7] = p3;
  10464. }
  10465. /**
  10466. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10467. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10468. * @param {number} x0
  10469. * @param {number} y0
  10470. * @param {number} x1
  10471. * @param {number} y1
  10472. * @param {number} x2
  10473. * @param {number} y2
  10474. * @param {number} x3
  10475. * @param {number} y3
  10476. * @param {number} x
  10477. * @param {number} y
  10478. * @param {Array.<number>} [out] 投射点
  10479. * @return {number}
  10480. */
  10481. function cubicProjectPoint(
  10482. x0, y0, x1, y1, x2, y2, x3, y3,
  10483. x, y, out
  10484. ) {
  10485. // http://pomax.github.io/bezierinfo/#projections
  10486. var t;
  10487. var interval = 0.005;
  10488. var d = Infinity;
  10489. var prev;
  10490. var next;
  10491. var d1;
  10492. var d2;
  10493. _v0[0] = x;
  10494. _v0[1] = y;
  10495. // 先粗略估计一下可能的最小距离的 t 值
  10496. // PENDING
  10497. for (var _t = 0; _t < 1; _t += 0.05) {
  10498. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10499. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10500. d1 = distSquare(_v0, _v1);
  10501. if (d1 < d) {
  10502. t = _t;
  10503. d = d1;
  10504. }
  10505. }
  10506. d = Infinity;
  10507. // At most 32 iteration
  10508. for (var i = 0; i < 32; i++) {
  10509. if (interval < EPSILON_NUMERIC) {
  10510. break;
  10511. }
  10512. prev = t - interval;
  10513. next = t + interval;
  10514. // t - interval
  10515. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10516. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10517. d1 = distSquare(_v1, _v0);
  10518. if (prev >= 0 && d1 < d) {
  10519. t = prev;
  10520. d = d1;
  10521. }
  10522. else {
  10523. // t + interval
  10524. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10525. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10526. d2 = distSquare(_v2, _v0);
  10527. if (next <= 1 && d2 < d) {
  10528. t = next;
  10529. d = d2;
  10530. }
  10531. else {
  10532. interval *= 0.5;
  10533. }
  10534. }
  10535. }
  10536. // t
  10537. if (out) {
  10538. out[0] = cubicAt(x0, x1, x2, x3, t);
  10539. out[1] = cubicAt(y0, y1, y2, y3, t);
  10540. }
  10541. // console.log(interval, i);
  10542. return mathSqrt$2(d);
  10543. }
  10544. /**
  10545. * 计算二次方贝塞尔值
  10546. * @param {number} p0
  10547. * @param {number} p1
  10548. * @param {number} p2
  10549. * @param {number} t
  10550. * @return {number}
  10551. */
  10552. function quadraticAt(p0, p1, p2, t) {
  10553. var onet = 1 - t;
  10554. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10555. }
  10556. /**
  10557. * 计算二次方贝塞尔导数值
  10558. * @param {number} p0
  10559. * @param {number} p1
  10560. * @param {number} p2
  10561. * @param {number} t
  10562. * @return {number}
  10563. */
  10564. function quadraticDerivativeAt(p0, p1, p2, t) {
  10565. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10566. }
  10567. /**
  10568. * 计算二次方贝塞尔方程根
  10569. * @param {number} p0
  10570. * @param {number} p1
  10571. * @param {number} p2
  10572. * @param {number} t
  10573. * @param {Array.<number>} roots
  10574. * @return {number} 有效根数目
  10575. */
  10576. function quadraticRootAt(p0, p1, p2, val, roots) {
  10577. var a = p0 - 2 * p1 + p2;
  10578. var b = 2 * (p1 - p0);
  10579. var c = p0 - val;
  10580. var n = 0;
  10581. if (isAroundZero(a)) {
  10582. if (isNotAroundZero$1(b)) {
  10583. var t1 = -c / b;
  10584. if (t1 >= 0 && t1 <= 1) {
  10585. roots[n++] = t1;
  10586. }
  10587. }
  10588. }
  10589. else {
  10590. var disc = b * b - 4 * a * c;
  10591. if (isAroundZero(disc)) {
  10592. var t1 = -b / (2 * a);
  10593. if (t1 >= 0 && t1 <= 1) {
  10594. roots[n++] = t1;
  10595. }
  10596. }
  10597. else if (disc > 0) {
  10598. var discSqrt = mathSqrt$2(disc);
  10599. var t1 = (-b + discSqrt) / (2 * a);
  10600. var t2 = (-b - discSqrt) / (2 * a);
  10601. if (t1 >= 0 && t1 <= 1) {
  10602. roots[n++] = t1;
  10603. }
  10604. if (t2 >= 0 && t2 <= 1) {
  10605. roots[n++] = t2;
  10606. }
  10607. }
  10608. }
  10609. return n;
  10610. }
  10611. /**
  10612. * 计算二次贝塞尔方程极限值
  10613. * @memberOf module:zrender/core/curve
  10614. * @param {number} p0
  10615. * @param {number} p1
  10616. * @param {number} p2
  10617. * @return {number}
  10618. */
  10619. function quadraticExtremum(p0, p1, p2) {
  10620. var divider = p0 + p2 - 2 * p1;
  10621. if (divider === 0) {
  10622. // p1 is center of p0 and p2
  10623. return 0.5;
  10624. }
  10625. else {
  10626. return (p0 - p1) / divider;
  10627. }
  10628. }
  10629. /**
  10630. * 细分二次贝塞尔曲线
  10631. * @memberOf module:zrender/core/curve
  10632. * @param {number} p0
  10633. * @param {number} p1
  10634. * @param {number} p2
  10635. * @param {number} t
  10636. * @param {Array.<number>} out
  10637. */
  10638. function quadraticSubdivide(p0, p1, p2, t, out) {
  10639. var p01 = (p1 - p0) * t + p0;
  10640. var p12 = (p2 - p1) * t + p1;
  10641. var p012 = (p12 - p01) * t + p01;
  10642. // Seg0
  10643. out[0] = p0;
  10644. out[1] = p01;
  10645. out[2] = p012;
  10646. // Seg1
  10647. out[3] = p012;
  10648. out[4] = p12;
  10649. out[5] = p2;
  10650. }
  10651. /**
  10652. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10653. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10654. * @param {number} x0
  10655. * @param {number} y0
  10656. * @param {number} x1
  10657. * @param {number} y1
  10658. * @param {number} x2
  10659. * @param {number} y2
  10660. * @param {number} x
  10661. * @param {number} y
  10662. * @param {Array.<number>} out 投射点
  10663. * @return {number}
  10664. */
  10665. function quadraticProjectPoint(
  10666. x0, y0, x1, y1, x2, y2,
  10667. x, y, out
  10668. ) {
  10669. // http://pomax.github.io/bezierinfo/#projections
  10670. var t;
  10671. var interval = 0.005;
  10672. var d = Infinity;
  10673. _v0[0] = x;
  10674. _v0[1] = y;
  10675. // 先粗略估计一下可能的最小距离的 t 值
  10676. // PENDING
  10677. for (var _t = 0; _t < 1; _t += 0.05) {
  10678. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10679. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10680. var d1 = distSquare(_v0, _v1);
  10681. if (d1 < d) {
  10682. t = _t;
  10683. d = d1;
  10684. }
  10685. }
  10686. d = Infinity;
  10687. // At most 32 iteration
  10688. for (var i = 0; i < 32; i++) {
  10689. if (interval < EPSILON_NUMERIC) {
  10690. break;
  10691. }
  10692. var prev = t - interval;
  10693. var next = t + interval;
  10694. // t - interval
  10695. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10696. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10697. var d1 = distSquare(_v1, _v0);
  10698. if (prev >= 0 && d1 < d) {
  10699. t = prev;
  10700. d = d1;
  10701. }
  10702. else {
  10703. // t + interval
  10704. _v2[0] = quadraticAt(x0, x1, x2, next);
  10705. _v2[1] = quadraticAt(y0, y1, y2, next);
  10706. var d2 = distSquare(_v2, _v0);
  10707. if (next <= 1 && d2 < d) {
  10708. t = next;
  10709. d = d2;
  10710. }
  10711. else {
  10712. interval *= 0.5;
  10713. }
  10714. }
  10715. }
  10716. // t
  10717. if (out) {
  10718. out[0] = quadraticAt(x0, x1, x2, t);
  10719. out[1] = quadraticAt(y0, y1, y2, t);
  10720. }
  10721. // console.log(interval, i);
  10722. return mathSqrt$2(d);
  10723. }
  10724. /**
  10725. * @author Yi Shen(https://github.com/pissang)
  10726. */
  10727. var mathMin$3 = Math.min;
  10728. var mathMax$3 = Math.max;
  10729. var mathSin$2 = Math.sin;
  10730. var mathCos$2 = Math.cos;
  10731. var PI2 = Math.PI * 2;
  10732. var start = create();
  10733. var end = create();
  10734. var extremity = create();
  10735. /**
  10736. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10737. * @module zrender/core/bbox
  10738. * @param {Array<Object>} points 顶点数组
  10739. * @param {number} min
  10740. * @param {number} max
  10741. */
  10742. /**
  10743. * @memberOf module:zrender/core/bbox
  10744. * @param {number} x0
  10745. * @param {number} y0
  10746. * @param {number} x1
  10747. * @param {number} y1
  10748. * @param {Array.<number>} min
  10749. * @param {Array.<number>} max
  10750. */
  10751. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10752. min$$1[0] = mathMin$3(x0, x1);
  10753. min$$1[1] = mathMin$3(y0, y1);
  10754. max$$1[0] = mathMax$3(x0, x1);
  10755. max$$1[1] = mathMax$3(y0, y1);
  10756. }
  10757. var xDim = [];
  10758. var yDim = [];
  10759. /**
  10760. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10761. * @memberOf module:zrender/core/bbox
  10762. * @param {number} x0
  10763. * @param {number} y0
  10764. * @param {number} x1
  10765. * @param {number} y1
  10766. * @param {number} x2
  10767. * @param {number} y2
  10768. * @param {number} x3
  10769. * @param {number} y3
  10770. * @param {Array.<number>} min
  10771. * @param {Array.<number>} max
  10772. */
  10773. function fromCubic(
  10774. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10775. ) {
  10776. var cubicExtrema$$1 = cubicExtrema;
  10777. var cubicAt$$1 = cubicAt;
  10778. var i;
  10779. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10780. min$$1[0] = Infinity;
  10781. min$$1[1] = Infinity;
  10782. max$$1[0] = -Infinity;
  10783. max$$1[1] = -Infinity;
  10784. for (i = 0; i < n; i++) {
  10785. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10786. min$$1[0] = mathMin$3(x, min$$1[0]);
  10787. max$$1[0] = mathMax$3(x, max$$1[0]);
  10788. }
  10789. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10790. for (i = 0; i < n; i++) {
  10791. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10792. min$$1[1] = mathMin$3(y, min$$1[1]);
  10793. max$$1[1] = mathMax$3(y, max$$1[1]);
  10794. }
  10795. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10796. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10797. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10798. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10799. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10800. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10801. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10802. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10803. }
  10804. /**
  10805. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10806. * @memberOf module:zrender/core/bbox
  10807. * @param {number} x0
  10808. * @param {number} y0
  10809. * @param {number} x1
  10810. * @param {number} y1
  10811. * @param {number} x2
  10812. * @param {number} y2
  10813. * @param {Array.<number>} min
  10814. * @param {Array.<number>} max
  10815. */
  10816. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10817. var quadraticExtremum$$1 = quadraticExtremum;
  10818. var quadraticAt$$1 = quadraticAt;
  10819. // Find extremities, where derivative in x dim or y dim is zero
  10820. var tx =
  10821. mathMax$3(
  10822. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10823. );
  10824. var ty =
  10825. mathMax$3(
  10826. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10827. );
  10828. var x = quadraticAt$$1(x0, x1, x2, tx);
  10829. var y = quadraticAt$$1(y0, y1, y2, ty);
  10830. min$$1[0] = mathMin$3(x0, x2, x);
  10831. min$$1[1] = mathMin$3(y0, y2, y);
  10832. max$$1[0] = mathMax$3(x0, x2, x);
  10833. max$$1[1] = mathMax$3(y0, y2, y);
  10834. }
  10835. /**
  10836. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10837. * @method
  10838. * @memberOf module:zrender/core/bbox
  10839. * @param {number} x
  10840. * @param {number} y
  10841. * @param {number} rx
  10842. * @param {number} ry
  10843. * @param {number} startAngle
  10844. * @param {number} endAngle
  10845. * @param {number} anticlockwise
  10846. * @param {Array.<number>} min
  10847. * @param {Array.<number>} max
  10848. */
  10849. function fromArc(
  10850. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10851. ) {
  10852. var vec2Min = min;
  10853. var vec2Max = max;
  10854. var diff = Math.abs(startAngle - endAngle);
  10855. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10856. // Is a circle
  10857. min$$1[0] = x - rx;
  10858. min$$1[1] = y - ry;
  10859. max$$1[0] = x + rx;
  10860. max$$1[1] = y + ry;
  10861. return;
  10862. }
  10863. start[0] = mathCos$2(startAngle) * rx + x;
  10864. start[1] = mathSin$2(startAngle) * ry + y;
  10865. end[0] = mathCos$2(endAngle) * rx + x;
  10866. end[1] = mathSin$2(endAngle) * ry + y;
  10867. vec2Min(min$$1, start, end);
  10868. vec2Max(max$$1, start, end);
  10869. // Thresh to [0, Math.PI * 2]
  10870. startAngle = startAngle % (PI2);
  10871. if (startAngle < 0) {
  10872. startAngle = startAngle + PI2;
  10873. }
  10874. endAngle = endAngle % (PI2);
  10875. if (endAngle < 0) {
  10876. endAngle = endAngle + PI2;
  10877. }
  10878. if (startAngle > endAngle && !anticlockwise) {
  10879. endAngle += PI2;
  10880. }
  10881. else if (startAngle < endAngle && anticlockwise) {
  10882. startAngle += PI2;
  10883. }
  10884. if (anticlockwise) {
  10885. var tmp = endAngle;
  10886. endAngle = startAngle;
  10887. startAngle = tmp;
  10888. }
  10889. // var number = 0;
  10890. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10891. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10892. if (angle > startAngle) {
  10893. extremity[0] = mathCos$2(angle) * rx + x;
  10894. extremity[1] = mathSin$2(angle) * ry + y;
  10895. vec2Min(min$$1, extremity, min$$1);
  10896. vec2Max(max$$1, extremity, max$$1);
  10897. }
  10898. }
  10899. }
  10900. /**
  10901. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10902. * 可以用于 isInsidePath 判断以及获取boundingRect
  10903. *
  10904. * @module zrender/core/PathProxy
  10905. * @author Yi Shen (http://www.github.com/pissang)
  10906. */
  10907. // TODO getTotalLength, getPointAtLength
  10908. var CMD = {
  10909. M: 1,
  10910. L: 2,
  10911. C: 3,
  10912. Q: 4,
  10913. A: 5,
  10914. Z: 6,
  10915. // Rect
  10916. R: 7
  10917. };
  10918. // var CMD_MEM_SIZE = {
  10919. // M: 3,
  10920. // L: 3,
  10921. // C: 7,
  10922. // Q: 5,
  10923. // A: 9,
  10924. // R: 5,
  10925. // Z: 1
  10926. // };
  10927. var min$1 = [];
  10928. var max$1 = [];
  10929. var min2 = [];
  10930. var max2 = [];
  10931. var mathMin$2 = Math.min;
  10932. var mathMax$2 = Math.max;
  10933. var mathCos$1 = Math.cos;
  10934. var mathSin$1 = Math.sin;
  10935. var mathSqrt$1 = Math.sqrt;
  10936. var mathAbs = Math.abs;
  10937. var hasTypedArray = typeof Float32Array !== 'undefined';
  10938. /**
  10939. * @alias module:zrender/core/PathProxy
  10940. * @constructor
  10941. */
  10942. var PathProxy = function (notSaveData) {
  10943. this._saveData = !(notSaveData || false);
  10944. if (this._saveData) {
  10945. /**
  10946. * Path data. Stored as flat array
  10947. * @type {Array.<Object>}
  10948. */
  10949. this.data = [];
  10950. }
  10951. this._ctx = null;
  10952. };
  10953. /**
  10954. * 快速计算Path包围盒(并不是最小包围盒)
  10955. * @return {Object}
  10956. */
  10957. PathProxy.prototype = {
  10958. constructor: PathProxy,
  10959. _xi: 0,
  10960. _yi: 0,
  10961. _x0: 0,
  10962. _y0: 0,
  10963. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10964. _ux: 0,
  10965. _uy: 0,
  10966. _len: 0,
  10967. _lineDash: null,
  10968. _dashOffset: 0,
  10969. _dashIdx: 0,
  10970. _dashSum: 0,
  10971. /**
  10972. * @readOnly
  10973. */
  10974. setScale: function (sx, sy) {
  10975. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  10976. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  10977. },
  10978. getContext: function () {
  10979. return this._ctx;
  10980. },
  10981. /**
  10982. * @param {CanvasRenderingContext2D} ctx
  10983. * @return {module:zrender/core/PathProxy}
  10984. */
  10985. beginPath: function (ctx) {
  10986. this._ctx = ctx;
  10987. ctx && ctx.beginPath();
  10988. ctx && (this.dpr = ctx.dpr);
  10989. // Reset
  10990. if (this._saveData) {
  10991. this._len = 0;
  10992. }
  10993. if (this._lineDash) {
  10994. this._lineDash = null;
  10995. this._dashOffset = 0;
  10996. }
  10997. return this;
  10998. },
  10999. /**
  11000. * @param {number} x
  11001. * @param {number} y
  11002. * @return {module:zrender/core/PathProxy}
  11003. */
  11004. moveTo: function (x, y) {
  11005. this.addData(CMD.M, x, y);
  11006. this._ctx && this._ctx.moveTo(x, y);
  11007. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11008. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11009. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11010. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11011. this._x0 = x;
  11012. this._y0 = y;
  11013. this._xi = x;
  11014. this._yi = y;
  11015. return this;
  11016. },
  11017. /**
  11018. * @param {number} x
  11019. * @param {number} y
  11020. * @return {module:zrender/core/PathProxy}
  11021. */
  11022. lineTo: function (x, y) {
  11023. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11024. || mathAbs(y - this._yi) > this._uy
  11025. // Force draw the first segment
  11026. || this._len < 5;
  11027. this.addData(CMD.L, x, y);
  11028. if (this._ctx && exceedUnit) {
  11029. this._needsDash() ? this._dashedLineTo(x, y)
  11030. : this._ctx.lineTo(x, y);
  11031. }
  11032. if (exceedUnit) {
  11033. this._xi = x;
  11034. this._yi = y;
  11035. }
  11036. return this;
  11037. },
  11038. /**
  11039. * @param {number} x1
  11040. * @param {number} y1
  11041. * @param {number} x2
  11042. * @param {number} y2
  11043. * @param {number} x3
  11044. * @param {number} y3
  11045. * @return {module:zrender/core/PathProxy}
  11046. */
  11047. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11048. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11049. if (this._ctx) {
  11050. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11051. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11052. }
  11053. this._xi = x3;
  11054. this._yi = y3;
  11055. return this;
  11056. },
  11057. /**
  11058. * @param {number} x1
  11059. * @param {number} y1
  11060. * @param {number} x2
  11061. * @param {number} y2
  11062. * @return {module:zrender/core/PathProxy}
  11063. */
  11064. quadraticCurveTo: function (x1, y1, x2, y2) {
  11065. this.addData(CMD.Q, x1, y1, x2, y2);
  11066. if (this._ctx) {
  11067. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11068. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11069. }
  11070. this._xi = x2;
  11071. this._yi = y2;
  11072. return this;
  11073. },
  11074. /**
  11075. * @param {number} cx
  11076. * @param {number} cy
  11077. * @param {number} r
  11078. * @param {number} startAngle
  11079. * @param {number} endAngle
  11080. * @param {boolean} anticlockwise
  11081. * @return {module:zrender/core/PathProxy}
  11082. */
  11083. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11084. this.addData(
  11085. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11086. );
  11087. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11088. this._xi = mathCos$1(endAngle) * r + cx;
  11089. this._yi = mathSin$1(endAngle) * r + cy;
  11090. return this;
  11091. },
  11092. // TODO
  11093. arcTo: function (x1, y1, x2, y2, radius) {
  11094. if (this._ctx) {
  11095. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11096. }
  11097. return this;
  11098. },
  11099. // TODO
  11100. rect: function (x, y, w, h) {
  11101. this._ctx && this._ctx.rect(x, y, w, h);
  11102. this.addData(CMD.R, x, y, w, h);
  11103. return this;
  11104. },
  11105. /**
  11106. * @return {module:zrender/core/PathProxy}
  11107. */
  11108. closePath: function () {
  11109. this.addData(CMD.Z);
  11110. var ctx = this._ctx;
  11111. var x0 = this._x0;
  11112. var y0 = this._y0;
  11113. if (ctx) {
  11114. this._needsDash() && this._dashedLineTo(x0, y0);
  11115. ctx.closePath();
  11116. }
  11117. this._xi = x0;
  11118. this._yi = y0;
  11119. return this;
  11120. },
  11121. /**
  11122. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11123. * stroke 同样
  11124. * @param {CanvasRenderingContext2D} ctx
  11125. * @return {module:zrender/core/PathProxy}
  11126. */
  11127. fill: function (ctx) {
  11128. ctx && ctx.fill();
  11129. this.toStatic();
  11130. },
  11131. /**
  11132. * @param {CanvasRenderingContext2D} ctx
  11133. * @return {module:zrender/core/PathProxy}
  11134. */
  11135. stroke: function (ctx) {
  11136. ctx && ctx.stroke();
  11137. this.toStatic();
  11138. },
  11139. /**
  11140. * 必须在其它绘制命令前调用
  11141. * Must be invoked before all other path drawing methods
  11142. * @return {module:zrender/core/PathProxy}
  11143. */
  11144. setLineDash: function (lineDash) {
  11145. if (lineDash instanceof Array) {
  11146. this._lineDash = lineDash;
  11147. this._dashIdx = 0;
  11148. var lineDashSum = 0;
  11149. for (var i = 0; i < lineDash.length; i++) {
  11150. lineDashSum += lineDash[i];
  11151. }
  11152. this._dashSum = lineDashSum;
  11153. }
  11154. return this;
  11155. },
  11156. /**
  11157. * 必须在其它绘制命令前调用
  11158. * Must be invoked before all other path drawing methods
  11159. * @return {module:zrender/core/PathProxy}
  11160. */
  11161. setLineDashOffset: function (offset) {
  11162. this._dashOffset = offset;
  11163. return this;
  11164. },
  11165. /**
  11166. *
  11167. * @return {boolean}
  11168. */
  11169. len: function () {
  11170. return this._len;
  11171. },
  11172. /**
  11173. * 直接设置 Path 数据
  11174. */
  11175. setData: function (data) {
  11176. var len$$1 = data.length;
  11177. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11178. this.data = new Float32Array(len$$1);
  11179. }
  11180. for (var i = 0; i < len$$1; i++) {
  11181. this.data[i] = data[i];
  11182. }
  11183. this._len = len$$1;
  11184. },
  11185. /**
  11186. * 添加子路径
  11187. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11188. */
  11189. appendPath: function (path) {
  11190. if (!(path instanceof Array)) {
  11191. path = [path];
  11192. }
  11193. var len$$1 = path.length;
  11194. var appendSize = 0;
  11195. var offset = this._len;
  11196. for (var i = 0; i < len$$1; i++) {
  11197. appendSize += path[i].len();
  11198. }
  11199. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11200. this.data = new Float32Array(offset + appendSize);
  11201. }
  11202. for (var i = 0; i < len$$1; i++) {
  11203. var appendPathData = path[i].data;
  11204. for (var k = 0; k < appendPathData.length; k++) {
  11205. this.data[offset++] = appendPathData[k];
  11206. }
  11207. }
  11208. this._len = offset;
  11209. },
  11210. /**
  11211. * 填充 Path 数据。
  11212. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11213. */
  11214. addData: function (cmd) {
  11215. if (!this._saveData) {
  11216. return;
  11217. }
  11218. var data = this.data;
  11219. if (this._len + arguments.length > data.length) {
  11220. // 因为之前的数组已经转换成静态的 Float32Array
  11221. // 所以不够用时需要扩展一个新的动态数组
  11222. this._expandData();
  11223. data = this.data;
  11224. }
  11225. for (var i = 0; i < arguments.length; i++) {
  11226. data[this._len++] = arguments[i];
  11227. }
  11228. this._prevCmd = cmd;
  11229. },
  11230. _expandData: function () {
  11231. // Only if data is Float32Array
  11232. if (!(this.data instanceof Array)) {
  11233. var newData = [];
  11234. for (var i = 0; i < this._len; i++) {
  11235. newData[i] = this.data[i];
  11236. }
  11237. this.data = newData;
  11238. }
  11239. },
  11240. /**
  11241. * If needs js implemented dashed line
  11242. * @return {boolean}
  11243. * @private
  11244. */
  11245. _needsDash: function () {
  11246. return this._lineDash;
  11247. },
  11248. _dashedLineTo: function (x1, y1) {
  11249. var dashSum = this._dashSum;
  11250. var offset = this._dashOffset;
  11251. var lineDash = this._lineDash;
  11252. var ctx = this._ctx;
  11253. var x0 = this._xi;
  11254. var y0 = this._yi;
  11255. var dx = x1 - x0;
  11256. var dy = y1 - y0;
  11257. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11258. var x = x0;
  11259. var y = y0;
  11260. var dash;
  11261. var nDash = lineDash.length;
  11262. var idx;
  11263. dx /= dist$$1;
  11264. dy /= dist$$1;
  11265. if (offset < 0) {
  11266. // Convert to positive offset
  11267. offset = dashSum + offset;
  11268. }
  11269. offset %= dashSum;
  11270. x -= offset * dx;
  11271. y -= offset * dy;
  11272. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11273. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11274. idx = this._dashIdx;
  11275. dash = lineDash[idx];
  11276. x += dx * dash;
  11277. y += dy * dash;
  11278. this._dashIdx = (idx + 1) % nDash;
  11279. // Skip positive offset
  11280. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11281. continue;
  11282. }
  11283. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11284. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11285. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11286. );
  11287. }
  11288. // Offset for next lineTo
  11289. dx = x - x1;
  11290. dy = y - y1;
  11291. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11292. },
  11293. // Not accurate dashed line to
  11294. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11295. var dashSum = this._dashSum;
  11296. var offset = this._dashOffset;
  11297. var lineDash = this._lineDash;
  11298. var ctx = this._ctx;
  11299. var x0 = this._xi;
  11300. var y0 = this._yi;
  11301. var t;
  11302. var dx;
  11303. var dy;
  11304. var cubicAt$$1 = cubicAt;
  11305. var bezierLen = 0;
  11306. var idx = this._dashIdx;
  11307. var nDash = lineDash.length;
  11308. var x;
  11309. var y;
  11310. var tmpLen = 0;
  11311. if (offset < 0) {
  11312. // Convert to positive offset
  11313. offset = dashSum + offset;
  11314. }
  11315. offset %= dashSum;
  11316. // Bezier approx length
  11317. for (t = 0; t < 1; t += 0.1) {
  11318. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11319. - cubicAt$$1(x0, x1, x2, x3, t);
  11320. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11321. - cubicAt$$1(y0, y1, y2, y3, t);
  11322. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11323. }
  11324. // Find idx after add offset
  11325. for (; idx < nDash; idx++) {
  11326. tmpLen += lineDash[idx];
  11327. if (tmpLen > offset) {
  11328. break;
  11329. }
  11330. }
  11331. t = (tmpLen - offset) / bezierLen;
  11332. while (t <= 1) {
  11333. x = cubicAt$$1(x0, x1, x2, x3, t);
  11334. y = cubicAt$$1(y0, y1, y2, y3, t);
  11335. // Use line to approximate dashed bezier
  11336. // Bad result if dash is long
  11337. idx % 2 ? ctx.moveTo(x, y)
  11338. : ctx.lineTo(x, y);
  11339. t += lineDash[idx] / bezierLen;
  11340. idx = (idx + 1) % nDash;
  11341. }
  11342. // Finish the last segment and calculate the new offset
  11343. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11344. dx = x3 - x;
  11345. dy = y3 - y;
  11346. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11347. },
  11348. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11349. // Convert quadratic to cubic using degree elevation
  11350. var x3 = x2;
  11351. var y3 = y2;
  11352. x2 = (x2 + 2 * x1) / 3;
  11353. y2 = (y2 + 2 * y1) / 3;
  11354. x1 = (this._xi + 2 * x1) / 3;
  11355. y1 = (this._yi + 2 * y1) / 3;
  11356. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11357. },
  11358. /**
  11359. * 转成静态的 Float32Array 减少堆内存占用
  11360. * Convert dynamic array to static Float32Array
  11361. */
  11362. toStatic: function () {
  11363. var data = this.data;
  11364. if (data instanceof Array) {
  11365. data.length = this._len;
  11366. if (hasTypedArray) {
  11367. this.data = new Float32Array(data);
  11368. }
  11369. }
  11370. },
  11371. /**
  11372. * @return {module:zrender/core/BoundingRect}
  11373. */
  11374. getBoundingRect: function () {
  11375. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11376. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11377. var data = this.data;
  11378. var xi = 0;
  11379. var yi = 0;
  11380. var x0 = 0;
  11381. var y0 = 0;
  11382. for (var i = 0; i < data.length;) {
  11383. var cmd = data[i++];
  11384. if (i === 1) {
  11385. // 如果第一个命令是 L, C, Q
  11386. // 则 previous point 同绘制命令的第一个 point
  11387. //
  11388. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11389. xi = data[i];
  11390. yi = data[i + 1];
  11391. x0 = xi;
  11392. y0 = yi;
  11393. }
  11394. switch (cmd) {
  11395. case CMD.M:
  11396. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11397. // 在 closePath 的时候使用
  11398. x0 = data[i++];
  11399. y0 = data[i++];
  11400. xi = x0;
  11401. yi = y0;
  11402. min2[0] = x0;
  11403. min2[1] = y0;
  11404. max2[0] = x0;
  11405. max2[1] = y0;
  11406. break;
  11407. case CMD.L:
  11408. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11409. xi = data[i++];
  11410. yi = data[i++];
  11411. break;
  11412. case CMD.C:
  11413. fromCubic(
  11414. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11415. min2, max2
  11416. );
  11417. xi = data[i++];
  11418. yi = data[i++];
  11419. break;
  11420. case CMD.Q:
  11421. fromQuadratic(
  11422. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11423. min2, max2
  11424. );
  11425. xi = data[i++];
  11426. yi = data[i++];
  11427. break;
  11428. case CMD.A:
  11429. // TODO Arc 判断的开销比较大
  11430. var cx = data[i++];
  11431. var cy = data[i++];
  11432. var rx = data[i++];
  11433. var ry = data[i++];
  11434. var startAngle = data[i++];
  11435. var endAngle = data[i++] + startAngle;
  11436. // TODO Arc 旋转
  11437. i += 1;
  11438. var anticlockwise = 1 - data[i++];
  11439. if (i === 1) {
  11440. // 直接使用 arc 命令
  11441. // 第一个命令起点还未定义
  11442. x0 = mathCos$1(startAngle) * rx + cx;
  11443. y0 = mathSin$1(startAngle) * ry + cy;
  11444. }
  11445. fromArc(
  11446. cx, cy, rx, ry, startAngle, endAngle,
  11447. anticlockwise, min2, max2
  11448. );
  11449. xi = mathCos$1(endAngle) * rx + cx;
  11450. yi = mathSin$1(endAngle) * ry + cy;
  11451. break;
  11452. case CMD.R:
  11453. x0 = xi = data[i++];
  11454. y0 = yi = data[i++];
  11455. var width = data[i++];
  11456. var height = data[i++];
  11457. // Use fromLine
  11458. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11459. break;
  11460. case CMD.Z:
  11461. xi = x0;
  11462. yi = y0;
  11463. break;
  11464. }
  11465. // Union
  11466. min(min$1, min$1, min2);
  11467. max(max$1, max$1, max2);
  11468. }
  11469. // No data
  11470. if (i === 0) {
  11471. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11472. }
  11473. return new BoundingRect(
  11474. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11475. );
  11476. },
  11477. /**
  11478. * Rebuild path from current data
  11479. * Rebuild path will not consider javascript implemented line dash.
  11480. * @param {CanvasRenderingContext2D} ctx
  11481. */
  11482. rebuildPath: function (ctx) {
  11483. var d = this.data;
  11484. var x0, y0;
  11485. var xi, yi;
  11486. var x, y;
  11487. var ux = this._ux;
  11488. var uy = this._uy;
  11489. var len$$1 = this._len;
  11490. for (var i = 0; i < len$$1;) {
  11491. var cmd = d[i++];
  11492. if (i === 1) {
  11493. // 如果第一个命令是 L, C, Q
  11494. // 则 previous point 同绘制命令的第一个 point
  11495. //
  11496. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11497. xi = d[i];
  11498. yi = d[i + 1];
  11499. x0 = xi;
  11500. y0 = yi;
  11501. }
  11502. switch (cmd) {
  11503. case CMD.M:
  11504. x0 = xi = d[i++];
  11505. y0 = yi = d[i++];
  11506. ctx.moveTo(xi, yi);
  11507. break;
  11508. case CMD.L:
  11509. x = d[i++];
  11510. y = d[i++];
  11511. // Not draw too small seg between
  11512. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11513. ctx.lineTo(x, y);
  11514. xi = x;
  11515. yi = y;
  11516. }
  11517. break;
  11518. case CMD.C:
  11519. ctx.bezierCurveTo(
  11520. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11521. );
  11522. xi = d[i - 2];
  11523. yi = d[i - 1];
  11524. break;
  11525. case CMD.Q:
  11526. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11527. xi = d[i - 2];
  11528. yi = d[i - 1];
  11529. break;
  11530. case CMD.A:
  11531. var cx = d[i++];
  11532. var cy = d[i++];
  11533. var rx = d[i++];
  11534. var ry = d[i++];
  11535. var theta = d[i++];
  11536. var dTheta = d[i++];
  11537. var psi = d[i++];
  11538. var fs = d[i++];
  11539. var r = (rx > ry) ? rx : ry;
  11540. var scaleX = (rx > ry) ? 1 : rx / ry;
  11541. var scaleY = (rx > ry) ? ry / rx : 1;
  11542. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11543. var endAngle = theta + dTheta;
  11544. if (isEllipse) {
  11545. ctx.translate(cx, cy);
  11546. ctx.rotate(psi);
  11547. ctx.scale(scaleX, scaleY);
  11548. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11549. ctx.scale(1 / scaleX, 1 / scaleY);
  11550. ctx.rotate(-psi);
  11551. ctx.translate(-cx, -cy);
  11552. }
  11553. else {
  11554. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11555. }
  11556. if (i === 1) {
  11557. // 直接使用 arc 命令
  11558. // 第一个命令起点还未定义
  11559. x0 = mathCos$1(theta) * rx + cx;
  11560. y0 = mathSin$1(theta) * ry + cy;
  11561. }
  11562. xi = mathCos$1(endAngle) * rx + cx;
  11563. yi = mathSin$1(endAngle) * ry + cy;
  11564. break;
  11565. case CMD.R:
  11566. x0 = xi = d[i];
  11567. y0 = yi = d[i + 1];
  11568. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11569. break;
  11570. case CMD.Z:
  11571. ctx.closePath();
  11572. xi = x0;
  11573. yi = y0;
  11574. }
  11575. }
  11576. }
  11577. };
  11578. PathProxy.CMD = CMD;
  11579. /**
  11580. * 线段包含判断
  11581. * @param {number} x0
  11582. * @param {number} y0
  11583. * @param {number} x1
  11584. * @param {number} y1
  11585. * @param {number} lineWidth
  11586. * @param {number} x
  11587. * @param {number} y
  11588. * @return {boolean}
  11589. */
  11590. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11591. if (lineWidth === 0) {
  11592. return false;
  11593. }
  11594. var _l = lineWidth;
  11595. var _a = 0;
  11596. var _b = x0;
  11597. // Quick reject
  11598. if (
  11599. (y > y0 + _l && y > y1 + _l)
  11600. || (y < y0 - _l && y < y1 - _l)
  11601. || (x > x0 + _l && x > x1 + _l)
  11602. || (x < x0 - _l && x < x1 - _l)
  11603. ) {
  11604. return false;
  11605. }
  11606. if (x0 !== x1) {
  11607. _a = (y0 - y1) / (x0 - x1);
  11608. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11609. }
  11610. else {
  11611. return Math.abs(x - x0) <= _l / 2;
  11612. }
  11613. var tmp = _a * x - y + _b;
  11614. var _s = tmp * tmp / (_a * _a + 1);
  11615. return _s <= _l / 2 * _l / 2;
  11616. }
  11617. /**
  11618. * 三次贝塞尔曲线描边包含判断
  11619. * @param {number} x0
  11620. * @param {number} y0
  11621. * @param {number} x1
  11622. * @param {number} y1
  11623. * @param {number} x2
  11624. * @param {number} y2
  11625. * @param {number} x3
  11626. * @param {number} y3
  11627. * @param {number} lineWidth
  11628. * @param {number} x
  11629. * @param {number} y
  11630. * @return {boolean}
  11631. */
  11632. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11633. if (lineWidth === 0) {
  11634. return false;
  11635. }
  11636. var _l = lineWidth;
  11637. // Quick reject
  11638. if (
  11639. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11640. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11641. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11642. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11643. ) {
  11644. return false;
  11645. }
  11646. var d = cubicProjectPoint(
  11647. x0, y0, x1, y1, x2, y2, x3, y3,
  11648. x, y, null
  11649. );
  11650. return d <= _l / 2;
  11651. }
  11652. /**
  11653. * 二次贝塞尔曲线描边包含判断
  11654. * @param {number} x0
  11655. * @param {number} y0
  11656. * @param {number} x1
  11657. * @param {number} y1
  11658. * @param {number} x2
  11659. * @param {number} y2
  11660. * @param {number} lineWidth
  11661. * @param {number} x
  11662. * @param {number} y
  11663. * @return {boolean}
  11664. */
  11665. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11666. if (lineWidth === 0) {
  11667. return false;
  11668. }
  11669. var _l = lineWidth;
  11670. // Quick reject
  11671. if (
  11672. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11673. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11674. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11675. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11676. ) {
  11677. return false;
  11678. }
  11679. var d = quadraticProjectPoint(
  11680. x0, y0, x1, y1, x2, y2,
  11681. x, y, null
  11682. );
  11683. return d <= _l / 2;
  11684. }
  11685. var PI2$3 = Math.PI * 2;
  11686. function normalizeRadian(angle) {
  11687. angle %= PI2$3;
  11688. if (angle < 0) {
  11689. angle += PI2$3;
  11690. }
  11691. return angle;
  11692. }
  11693. var PI2$2 = Math.PI * 2;
  11694. /**
  11695. * 圆弧描边包含判断
  11696. * @param {number} cx
  11697. * @param {number} cy
  11698. * @param {number} r
  11699. * @param {number} startAngle
  11700. * @param {number} endAngle
  11701. * @param {boolean} anticlockwise
  11702. * @param {number} lineWidth
  11703. * @param {number} x
  11704. * @param {number} y
  11705. * @return {Boolean}
  11706. */
  11707. function containStroke$4(
  11708. cx, cy, r, startAngle, endAngle, anticlockwise,
  11709. lineWidth, x, y
  11710. ) {
  11711. if (lineWidth === 0) {
  11712. return false;
  11713. }
  11714. var _l = lineWidth;
  11715. x -= cx;
  11716. y -= cy;
  11717. var d = Math.sqrt(x * x + y * y);
  11718. if ((d - _l > r) || (d + _l < r)) {
  11719. return false;
  11720. }
  11721. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11722. // Is a circle
  11723. return true;
  11724. }
  11725. if (anticlockwise) {
  11726. var tmp = startAngle;
  11727. startAngle = normalizeRadian(endAngle);
  11728. endAngle = normalizeRadian(tmp);
  11729. }
  11730. else {
  11731. startAngle = normalizeRadian(startAngle);
  11732. endAngle = normalizeRadian(endAngle);
  11733. }
  11734. if (startAngle > endAngle) {
  11735. endAngle += PI2$2;
  11736. }
  11737. var angle = Math.atan2(y, x);
  11738. if (angle < 0) {
  11739. angle += PI2$2;
  11740. }
  11741. return (angle >= startAngle && angle <= endAngle)
  11742. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11743. }
  11744. function windingLine(x0, y0, x1, y1, x, y) {
  11745. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11746. return 0;
  11747. }
  11748. // Ignore horizontal line
  11749. if (y1 === y0) {
  11750. return 0;
  11751. }
  11752. var dir = y1 < y0 ? 1 : -1;
  11753. var t = (y - y0) / (y1 - y0);
  11754. // Avoid winding error when intersection point is the connect point of two line of polygon
  11755. if (t === 1 || t === 0) {
  11756. dir = y1 < y0 ? 0.5 : -0.5;
  11757. }
  11758. var x_ = t * (x1 - x0) + x0;
  11759. // If (x, y) on the line, considered as "contain".
  11760. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11761. }
  11762. var CMD$1 = PathProxy.CMD;
  11763. var PI2$1 = Math.PI * 2;
  11764. var EPSILON$2 = 1e-4;
  11765. function isAroundEqual(a, b) {
  11766. return Math.abs(a - b) < EPSILON$2;
  11767. }
  11768. // 临时数组
  11769. var roots = [-1, -1, -1];
  11770. var extrema = [-1, -1];
  11771. function swapExtrema() {
  11772. var tmp = extrema[0];
  11773. extrema[0] = extrema[1];
  11774. extrema[1] = tmp;
  11775. }
  11776. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11777. // Quick reject
  11778. if (
  11779. (y > y0 && y > y1 && y > y2 && y > y3)
  11780. || (y < y0 && y < y1 && y < y2 && y < y3)
  11781. ) {
  11782. return 0;
  11783. }
  11784. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11785. if (nRoots === 0) {
  11786. return 0;
  11787. }
  11788. else {
  11789. var w = 0;
  11790. var nExtrema = -1;
  11791. var y0_;
  11792. var y1_;
  11793. for (var i = 0; i < nRoots; i++) {
  11794. var t = roots[i];
  11795. // Avoid winding error when intersection point is the connect point of two line of polygon
  11796. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11797. var x_ = cubicAt(x0, x1, x2, x3, t);
  11798. if (x_ < x) { // Quick reject
  11799. continue;
  11800. }
  11801. if (nExtrema < 0) {
  11802. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11803. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11804. swapExtrema();
  11805. }
  11806. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11807. if (nExtrema > 1) {
  11808. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11809. }
  11810. }
  11811. if (nExtrema === 2) {
  11812. // 分成三段单调函数
  11813. if (t < extrema[0]) {
  11814. w += y0_ < y0 ? unit : -unit;
  11815. }
  11816. else if (t < extrema[1]) {
  11817. w += y1_ < y0_ ? unit : -unit;
  11818. }
  11819. else {
  11820. w += y3 < y1_ ? unit : -unit;
  11821. }
  11822. }
  11823. else {
  11824. // 分成两段单调函数
  11825. if (t < extrema[0]) {
  11826. w += y0_ < y0 ? unit : -unit;
  11827. }
  11828. else {
  11829. w += y3 < y0_ ? unit : -unit;
  11830. }
  11831. }
  11832. }
  11833. return w;
  11834. }
  11835. }
  11836. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11837. // Quick reject
  11838. if (
  11839. (y > y0 && y > y1 && y > y2)
  11840. || (y < y0 && y < y1 && y < y2)
  11841. ) {
  11842. return 0;
  11843. }
  11844. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11845. if (nRoots === 0) {
  11846. return 0;
  11847. }
  11848. else {
  11849. var t = quadraticExtremum(y0, y1, y2);
  11850. if (t >= 0 && t <= 1) {
  11851. var w = 0;
  11852. var y_ = quadraticAt(y0, y1, y2, t);
  11853. for (var i = 0; i < nRoots; i++) {
  11854. // Remove one endpoint.
  11855. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11856. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11857. if (x_ < x) { // Quick reject
  11858. continue;
  11859. }
  11860. if (roots[i] < t) {
  11861. w += y_ < y0 ? unit : -unit;
  11862. }
  11863. else {
  11864. w += y2 < y_ ? unit : -unit;
  11865. }
  11866. }
  11867. return w;
  11868. }
  11869. else {
  11870. // Remove one endpoint.
  11871. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11872. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11873. if (x_ < x) { // Quick reject
  11874. return 0;
  11875. }
  11876. return y2 < y0 ? unit : -unit;
  11877. }
  11878. }
  11879. }
  11880. // TODO
  11881. // Arc 旋转
  11882. function windingArc(
  11883. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11884. ) {
  11885. y -= cy;
  11886. if (y > r || y < -r) {
  11887. return 0;
  11888. }
  11889. var tmp = Math.sqrt(r * r - y * y);
  11890. roots[0] = -tmp;
  11891. roots[1] = tmp;
  11892. var diff = Math.abs(startAngle - endAngle);
  11893. if (diff < 1e-4) {
  11894. return 0;
  11895. }
  11896. if (diff % PI2$1 < 1e-4) {
  11897. // Is a circle
  11898. startAngle = 0;
  11899. endAngle = PI2$1;
  11900. var dir = anticlockwise ? 1 : -1;
  11901. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11902. return dir;
  11903. }
  11904. else {
  11905. return 0;
  11906. }
  11907. }
  11908. if (anticlockwise) {
  11909. var tmp = startAngle;
  11910. startAngle = normalizeRadian(endAngle);
  11911. endAngle = normalizeRadian(tmp);
  11912. }
  11913. else {
  11914. startAngle = normalizeRadian(startAngle);
  11915. endAngle = normalizeRadian(endAngle);
  11916. }
  11917. if (startAngle > endAngle) {
  11918. endAngle += PI2$1;
  11919. }
  11920. var w = 0;
  11921. for (var i = 0; i < 2; i++) {
  11922. var x_ = roots[i];
  11923. if (x_ + cx > x) {
  11924. var angle = Math.atan2(y, x_);
  11925. var dir = anticlockwise ? 1 : -1;
  11926. if (angle < 0) {
  11927. angle = PI2$1 + angle;
  11928. }
  11929. if (
  11930. (angle >= startAngle && angle <= endAngle)
  11931. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11932. ) {
  11933. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11934. dir = -dir;
  11935. }
  11936. w += dir;
  11937. }
  11938. }
  11939. }
  11940. return w;
  11941. }
  11942. function containPath(data, lineWidth, isStroke, x, y) {
  11943. var w = 0;
  11944. var xi = 0;
  11945. var yi = 0;
  11946. var x0 = 0;
  11947. var y0 = 0;
  11948. for (var i = 0; i < data.length;) {
  11949. var cmd = data[i++];
  11950. // Begin a new subpath
  11951. if (cmd === CMD$1.M && i > 1) {
  11952. // Close previous subpath
  11953. if (!isStroke) {
  11954. w += windingLine(xi, yi, x0, y0, x, y);
  11955. }
  11956. // 如果被任何一个 subpath 包含
  11957. // if (w !== 0) {
  11958. // return true;
  11959. // }
  11960. }
  11961. if (i === 1) {
  11962. // 如果第一个命令是 L, C, Q
  11963. // 则 previous point 同绘制命令的第一个 point
  11964. //
  11965. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11966. xi = data[i];
  11967. yi = data[i + 1];
  11968. x0 = xi;
  11969. y0 = yi;
  11970. }
  11971. switch (cmd) {
  11972. case CMD$1.M:
  11973. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11974. // 在 closePath 的时候使用
  11975. x0 = data[i++];
  11976. y0 = data[i++];
  11977. xi = x0;
  11978. yi = y0;
  11979. break;
  11980. case CMD$1.L:
  11981. if (isStroke) {
  11982. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  11983. return true;
  11984. }
  11985. }
  11986. else {
  11987. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  11988. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  11989. }
  11990. xi = data[i++];
  11991. yi = data[i++];
  11992. break;
  11993. case CMD$1.C:
  11994. if (isStroke) {
  11995. if (containStroke$2(xi, yi,
  11996. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11997. lineWidth, x, y
  11998. )) {
  11999. return true;
  12000. }
  12001. }
  12002. else {
  12003. w += windingCubic(
  12004. xi, yi,
  12005. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12006. x, y
  12007. ) || 0;
  12008. }
  12009. xi = data[i++];
  12010. yi = data[i++];
  12011. break;
  12012. case CMD$1.Q:
  12013. if (isStroke) {
  12014. if (containStroke$3(xi, yi,
  12015. data[i++], data[i++], data[i], data[i + 1],
  12016. lineWidth, x, y
  12017. )) {
  12018. return true;
  12019. }
  12020. }
  12021. else {
  12022. w += windingQuadratic(
  12023. xi, yi,
  12024. data[i++], data[i++], data[i], data[i + 1],
  12025. x, y
  12026. ) || 0;
  12027. }
  12028. xi = data[i++];
  12029. yi = data[i++];
  12030. break;
  12031. case CMD$1.A:
  12032. // TODO Arc 判断的开销比较大
  12033. var cx = data[i++];
  12034. var cy = data[i++];
  12035. var rx = data[i++];
  12036. var ry = data[i++];
  12037. var theta = data[i++];
  12038. var dTheta = data[i++];
  12039. // TODO Arc 旋转
  12040. i += 1;
  12041. var anticlockwise = 1 - data[i++];
  12042. var x1 = Math.cos(theta) * rx + cx;
  12043. var y1 = Math.sin(theta) * ry + cy;
  12044. // 不是直接使用 arc 命令
  12045. if (i > 1) {
  12046. w += windingLine(xi, yi, x1, y1, x, y);
  12047. }
  12048. else {
  12049. // 第一个命令起点还未定义
  12050. x0 = x1;
  12051. y0 = y1;
  12052. }
  12053. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12054. var _x = (x - cx) * ry / rx + cx;
  12055. if (isStroke) {
  12056. if (containStroke$4(
  12057. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12058. lineWidth, _x, y
  12059. )) {
  12060. return true;
  12061. }
  12062. }
  12063. else {
  12064. w += windingArc(
  12065. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12066. _x, y
  12067. );
  12068. }
  12069. xi = Math.cos(theta + dTheta) * rx + cx;
  12070. yi = Math.sin(theta + dTheta) * ry + cy;
  12071. break;
  12072. case CMD$1.R:
  12073. x0 = xi = data[i++];
  12074. y0 = yi = data[i++];
  12075. var width = data[i++];
  12076. var height = data[i++];
  12077. var x1 = x0 + width;
  12078. var y1 = y0 + height;
  12079. if (isStroke) {
  12080. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12081. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12082. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12083. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12084. ) {
  12085. return true;
  12086. }
  12087. }
  12088. else {
  12089. // FIXME Clockwise ?
  12090. w += windingLine(x1, y0, x1, y1, x, y);
  12091. w += windingLine(x0, y1, x0, y0, x, y);
  12092. }
  12093. break;
  12094. case CMD$1.Z:
  12095. if (isStroke) {
  12096. if (containStroke$1(
  12097. xi, yi, x0, y0, lineWidth, x, y
  12098. )) {
  12099. return true;
  12100. }
  12101. }
  12102. else {
  12103. // Close a subpath
  12104. w += windingLine(xi, yi, x0, y0, x, y);
  12105. // 如果被任何一个 subpath 包含
  12106. // FIXME subpaths may overlap
  12107. // if (w !== 0) {
  12108. // return true;
  12109. // }
  12110. }
  12111. xi = x0;
  12112. yi = y0;
  12113. break;
  12114. }
  12115. }
  12116. if (!isStroke && !isAroundEqual(yi, y0)) {
  12117. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12118. }
  12119. return w !== 0;
  12120. }
  12121. function contain(pathData, x, y) {
  12122. return containPath(pathData, 0, false, x, y);
  12123. }
  12124. function containStroke(pathData, lineWidth, x, y) {
  12125. return containPath(pathData, lineWidth, true, x, y);
  12126. }
  12127. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12128. var abs = Math.abs;
  12129. var pathProxyForDraw = new PathProxy(true);
  12130. /**
  12131. * @alias module:zrender/graphic/Path
  12132. * @extends module:zrender/graphic/Displayable
  12133. * @constructor
  12134. * @param {Object} opts
  12135. */
  12136. function Path(opts) {
  12137. Displayable.call(this, opts);
  12138. /**
  12139. * @type {module:zrender/core/PathProxy}
  12140. * @readOnly
  12141. */
  12142. this.path = null;
  12143. }
  12144. Path.prototype = {
  12145. constructor: Path,
  12146. type: 'path',
  12147. __dirtyPath: true,
  12148. strokeContainThreshold: 5,
  12149. /**
  12150. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12151. * @type {boolean}
  12152. */
  12153. subPixelOptimize: false,
  12154. brush: function (ctx, prevEl) {
  12155. var style = this.style;
  12156. var path = this.path || pathProxyForDraw;
  12157. var hasStroke = style.hasStroke();
  12158. var hasFill = style.hasFill();
  12159. var fill = style.fill;
  12160. var stroke = style.stroke;
  12161. var hasFillGradient = hasFill && !!(fill.colorStops);
  12162. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12163. var hasFillPattern = hasFill && !!(fill.image);
  12164. var hasStrokePattern = hasStroke && !!(stroke.image);
  12165. style.bind(ctx, this, prevEl);
  12166. this.setTransform(ctx);
  12167. if (this.__dirty) {
  12168. var rect;
  12169. // Update gradient because bounding rect may changed
  12170. if (hasFillGradient) {
  12171. rect = rect || this.getBoundingRect();
  12172. this._fillGradient = style.getGradient(ctx, fill, rect);
  12173. }
  12174. if (hasStrokeGradient) {
  12175. rect = rect || this.getBoundingRect();
  12176. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12177. }
  12178. }
  12179. // Use the gradient or pattern
  12180. if (hasFillGradient) {
  12181. // PENDING If may have affect the state
  12182. ctx.fillStyle = this._fillGradient;
  12183. }
  12184. else if (hasFillPattern) {
  12185. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12186. }
  12187. if (hasStrokeGradient) {
  12188. ctx.strokeStyle = this._strokeGradient;
  12189. }
  12190. else if (hasStrokePattern) {
  12191. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12192. }
  12193. var lineDash = style.lineDash;
  12194. var lineDashOffset = style.lineDashOffset;
  12195. var ctxLineDash = !!ctx.setLineDash;
  12196. // Update path sx, sy
  12197. var scale = this.getGlobalScale();
  12198. path.setScale(scale[0], scale[1]);
  12199. // Proxy context
  12200. // Rebuild path in following 2 cases
  12201. // 1. Path is dirty
  12202. // 2. Path needs javascript implemented lineDash stroking.
  12203. // In this case, lineDash information will not be saved in PathProxy
  12204. if (this.__dirtyPath
  12205. || (lineDash && !ctxLineDash && hasStroke)
  12206. ) {
  12207. path.beginPath(ctx);
  12208. // Setting line dash before build path
  12209. if (lineDash && !ctxLineDash) {
  12210. path.setLineDash(lineDash);
  12211. path.setLineDashOffset(lineDashOffset);
  12212. }
  12213. this.buildPath(path, this.shape, false);
  12214. // Clear path dirty flag
  12215. if (this.path) {
  12216. this.__dirtyPath = false;
  12217. }
  12218. }
  12219. else {
  12220. // Replay path building
  12221. ctx.beginPath();
  12222. this.path.rebuildPath(ctx);
  12223. }
  12224. if (hasFill) {
  12225. if (style.fillOpacity != null) {
  12226. var originalGlobalAlpha = ctx.globalAlpha;
  12227. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12228. path.fill(ctx);
  12229. ctx.globalAlpha = originalGlobalAlpha;
  12230. }
  12231. else {
  12232. path.fill(ctx);
  12233. }
  12234. }
  12235. if (lineDash && ctxLineDash) {
  12236. ctx.setLineDash(lineDash);
  12237. ctx.lineDashOffset = lineDashOffset;
  12238. }
  12239. if (hasStroke) {
  12240. if (style.strokeOpacity != null) {
  12241. var originalGlobalAlpha = ctx.globalAlpha;
  12242. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12243. path.stroke(ctx);
  12244. ctx.globalAlpha = originalGlobalAlpha;
  12245. }
  12246. else {
  12247. path.stroke(ctx);
  12248. }
  12249. }
  12250. if (lineDash && ctxLineDash) {
  12251. // PENDING
  12252. // Remove lineDash
  12253. ctx.setLineDash([]);
  12254. }
  12255. // Draw rect text
  12256. if (style.text != null) {
  12257. // Only restore transform when needs draw text.
  12258. this.restoreTransform(ctx);
  12259. this.drawRectText(ctx, this.getBoundingRect());
  12260. }
  12261. },
  12262. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12263. // Like in circle
  12264. buildPath: function (ctx, shapeCfg, inBundle) {},
  12265. createPathProxy: function () {
  12266. this.path = new PathProxy();
  12267. },
  12268. getBoundingRect: function () {
  12269. var rect = this._rect;
  12270. var style = this.style;
  12271. var needsUpdateRect = !rect;
  12272. if (needsUpdateRect) {
  12273. var path = this.path;
  12274. if (!path) {
  12275. // Create path on demand.
  12276. path = this.path = new PathProxy();
  12277. }
  12278. if (this.__dirtyPath) {
  12279. path.beginPath();
  12280. this.buildPath(path, this.shape, false);
  12281. }
  12282. rect = path.getBoundingRect();
  12283. }
  12284. this._rect = rect;
  12285. if (style.hasStroke()) {
  12286. // Needs update rect with stroke lineWidth when
  12287. // 1. Element changes scale or lineWidth
  12288. // 2. Shape is changed
  12289. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12290. if (this.__dirty || needsUpdateRect) {
  12291. rectWithStroke.copy(rect);
  12292. // FIXME Must after updateTransform
  12293. var w = style.lineWidth;
  12294. // PENDING, Min line width is needed when line is horizontal or vertical
  12295. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12296. // Only add extra hover lineWidth when there are no fill
  12297. if (!style.hasFill()) {
  12298. w = Math.max(w, this.strokeContainThreshold || 4);
  12299. }
  12300. // Consider line width
  12301. // Line scale can't be 0;
  12302. if (lineScale > 1e-10) {
  12303. rectWithStroke.width += w / lineScale;
  12304. rectWithStroke.height += w / lineScale;
  12305. rectWithStroke.x -= w / lineScale / 2;
  12306. rectWithStroke.y -= w / lineScale / 2;
  12307. }
  12308. }
  12309. // Return rect with stroke
  12310. return rectWithStroke;
  12311. }
  12312. return rect;
  12313. },
  12314. contain: function (x, y) {
  12315. var localPos = this.transformCoordToLocal(x, y);
  12316. var rect = this.getBoundingRect();
  12317. var style = this.style;
  12318. x = localPos[0];
  12319. y = localPos[1];
  12320. if (rect.contain(x, y)) {
  12321. var pathData = this.path.data;
  12322. if (style.hasStroke()) {
  12323. var lineWidth = style.lineWidth;
  12324. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12325. // Line scale can't be 0;
  12326. if (lineScale > 1e-10) {
  12327. // Only add extra hover lineWidth when there are no fill
  12328. if (!style.hasFill()) {
  12329. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12330. }
  12331. if (containStroke(
  12332. pathData, lineWidth / lineScale, x, y
  12333. )) {
  12334. return true;
  12335. }
  12336. }
  12337. }
  12338. if (style.hasFill()) {
  12339. return contain(pathData, x, y);
  12340. }
  12341. }
  12342. return false;
  12343. },
  12344. /**
  12345. * @param {boolean} dirtyPath
  12346. */
  12347. dirty: function (dirtyPath) {
  12348. if (dirtyPath == null) {
  12349. dirtyPath = true;
  12350. }
  12351. // Only mark dirty, not mark clean
  12352. if (dirtyPath) {
  12353. this.__dirtyPath = dirtyPath;
  12354. this._rect = null;
  12355. }
  12356. this.__dirty = this.__dirtyText = true;
  12357. this.__zr && this.__zr.refresh();
  12358. // Used as a clipping path
  12359. if (this.__clipTarget) {
  12360. this.__clipTarget.dirty();
  12361. }
  12362. },
  12363. /**
  12364. * Alias for animate('shape')
  12365. * @param {boolean} loop
  12366. */
  12367. animateShape: function (loop) {
  12368. return this.animate('shape', loop);
  12369. },
  12370. // Overwrite attrKV
  12371. attrKV: function (key, value) {
  12372. // FIXME
  12373. if (key === 'shape') {
  12374. this.setShape(value);
  12375. this.__dirtyPath = true;
  12376. this._rect = null;
  12377. }
  12378. else {
  12379. Displayable.prototype.attrKV.call(this, key, value);
  12380. }
  12381. },
  12382. /**
  12383. * @param {Object|string} key
  12384. * @param {*} value
  12385. */
  12386. setShape: function (key, value) {
  12387. var shape = this.shape;
  12388. // Path from string may not have shape
  12389. if (shape) {
  12390. if (isObject$1(key)) {
  12391. for (var name in key) {
  12392. if (key.hasOwnProperty(name)) {
  12393. shape[name] = key[name];
  12394. }
  12395. }
  12396. }
  12397. else {
  12398. shape[key] = value;
  12399. }
  12400. this.dirty(true);
  12401. }
  12402. return this;
  12403. },
  12404. getLineScale: function () {
  12405. var m = this.transform;
  12406. // Get the line scale.
  12407. // Determinant of `m` means how much the area is enlarged by the
  12408. // transformation. So its square root can be used as a scale factor
  12409. // for width.
  12410. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12411. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12412. : 1;
  12413. }
  12414. };
  12415. /**
  12416. * 扩展一个 Path element, 比如星形,圆等。
  12417. * Extend a path element
  12418. * @param {Object} props
  12419. * @param {string} props.type Path type
  12420. * @param {Function} props.init Initialize
  12421. * @param {Function} props.buildPath Overwrite buildPath method
  12422. * @param {Object} [props.style] Extended default style config
  12423. * @param {Object} [props.shape] Extended default shape config
  12424. */
  12425. Path.extend = function (defaults$$1) {
  12426. var Sub = function (opts) {
  12427. Path.call(this, opts);
  12428. if (defaults$$1.style) {
  12429. // Extend default style
  12430. this.style.extendFrom(defaults$$1.style, false);
  12431. }
  12432. // Extend default shape
  12433. var defaultShape = defaults$$1.shape;
  12434. if (defaultShape) {
  12435. this.shape = this.shape || {};
  12436. var thisShape = this.shape;
  12437. for (var name in defaultShape) {
  12438. if (
  12439. !thisShape.hasOwnProperty(name)
  12440. && defaultShape.hasOwnProperty(name)
  12441. ) {
  12442. thisShape[name] = defaultShape[name];
  12443. }
  12444. }
  12445. }
  12446. defaults$$1.init && defaults$$1.init.call(this, opts);
  12447. };
  12448. inherits(Sub, Path);
  12449. // FIXME 不能 extend position, rotation 等引用对象
  12450. for (var name in defaults$$1) {
  12451. // Extending prototype values and methods
  12452. if (name !== 'style' && name !== 'shape') {
  12453. Sub.prototype[name] = defaults$$1[name];
  12454. }
  12455. }
  12456. return Sub;
  12457. };
  12458. inherits(Path, Displayable);
  12459. var CMD$2 = PathProxy.CMD;
  12460. var points = [[], [], []];
  12461. var mathSqrt$3 = Math.sqrt;
  12462. var mathAtan2 = Math.atan2;
  12463. var transformPath = function (path, m) {
  12464. var data = path.data;
  12465. var cmd;
  12466. var nPoint;
  12467. var i;
  12468. var j;
  12469. var k;
  12470. var p;
  12471. var M = CMD$2.M;
  12472. var C = CMD$2.C;
  12473. var L = CMD$2.L;
  12474. var R = CMD$2.R;
  12475. var A = CMD$2.A;
  12476. var Q = CMD$2.Q;
  12477. for (i = 0, j = 0; i < data.length;) {
  12478. cmd = data[i++];
  12479. j = i;
  12480. nPoint = 0;
  12481. switch (cmd) {
  12482. case M:
  12483. nPoint = 1;
  12484. break;
  12485. case L:
  12486. nPoint = 1;
  12487. break;
  12488. case C:
  12489. nPoint = 3;
  12490. break;
  12491. case Q:
  12492. nPoint = 2;
  12493. break;
  12494. case A:
  12495. var x = m[4];
  12496. var y = m[5];
  12497. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12498. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12499. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12500. // cx
  12501. data[i] *= sx;
  12502. data[i++] += x;
  12503. // cy
  12504. data[i] *= sy;
  12505. data[i++] += y;
  12506. // Scale rx and ry
  12507. // FIXME Assume psi is 0 here
  12508. data[i++] *= sx;
  12509. data[i++] *= sy;
  12510. // Start angle
  12511. data[i++] += angle;
  12512. // end angle
  12513. data[i++] += angle;
  12514. // FIXME psi
  12515. i += 2;
  12516. j = i;
  12517. break;
  12518. case R:
  12519. // x0, y0
  12520. p[0] = data[i++];
  12521. p[1] = data[i++];
  12522. applyTransform(p, p, m);
  12523. data[j++] = p[0];
  12524. data[j++] = p[1];
  12525. // x1, y1
  12526. p[0] += data[i++];
  12527. p[1] += data[i++];
  12528. applyTransform(p, p, m);
  12529. data[j++] = p[0];
  12530. data[j++] = p[1];
  12531. }
  12532. for (k = 0; k < nPoint; k++) {
  12533. var p = points[k];
  12534. p[0] = data[i++];
  12535. p[1] = data[i++];
  12536. applyTransform(p, p, m);
  12537. // Write back
  12538. data[j++] = p[0];
  12539. data[j++] = p[1];
  12540. }
  12541. }
  12542. };
  12543. // command chars
  12544. // var cc = [
  12545. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12546. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12547. // ];
  12548. var mathSqrt = Math.sqrt;
  12549. var mathSin = Math.sin;
  12550. var mathCos = Math.cos;
  12551. var PI = Math.PI;
  12552. var vMag = function (v) {
  12553. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12554. };
  12555. var vRatio = function (u, v) {
  12556. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12557. };
  12558. var vAngle = function (u, v) {
  12559. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12560. * Math.acos(vRatio(u, v));
  12561. };
  12562. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12563. var psi = psiDeg * (PI / 180.0);
  12564. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12565. + mathSin(psi) * (y1 - y2) / 2.0;
  12566. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12567. + mathCos(psi) * (y1 - y2) / 2.0;
  12568. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12569. if (lambda > 1) {
  12570. rx *= mathSqrt(lambda);
  12571. ry *= mathSqrt(lambda);
  12572. }
  12573. var f = (fa === fs ? -1 : 1)
  12574. * mathSqrt((((rx * rx) * (ry * ry))
  12575. - ((rx * rx) * (yp * yp))
  12576. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12577. + (ry * ry) * (xp * xp))
  12578. ) || 0;
  12579. var cxp = f * rx * yp / ry;
  12580. var cyp = f * -ry * xp / rx;
  12581. var cx = (x1 + x2) / 2.0
  12582. + mathCos(psi) * cxp
  12583. - mathSin(psi) * cyp;
  12584. var cy = (y1 + y2) / 2.0
  12585. + mathSin(psi) * cxp
  12586. + mathCos(psi) * cyp;
  12587. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12588. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12589. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12590. var dTheta = vAngle(u, v);
  12591. if (vRatio(u, v) <= -1) {
  12592. dTheta = PI;
  12593. }
  12594. if (vRatio(u, v) >= 1) {
  12595. dTheta = 0;
  12596. }
  12597. if (fs === 0 && dTheta > 0) {
  12598. dTheta = dTheta - 2 * PI;
  12599. }
  12600. if (fs === 1 && dTheta < 0) {
  12601. dTheta = dTheta + 2 * PI;
  12602. }
  12603. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12604. }
  12605. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12606. // Consider case:
  12607. // (1) delimiter can be comma or space, where continuous commas
  12608. // or spaces should be seen as one comma.
  12609. // (2) value can be like:
  12610. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12611. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12612. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12613. // var valueSplitReg = /[\s,]+/;
  12614. function createPathProxyFromString(data) {
  12615. if (!data) {
  12616. return new PathProxy();
  12617. }
  12618. // var data = data.replace(/-/g, ' -')
  12619. // .replace(/ /g, ' ')
  12620. // .replace(/ /g, ',')
  12621. // .replace(/,,/g, ',');
  12622. // var n;
  12623. // create pipes so that we can split the data
  12624. // for (n = 0; n < cc.length; n++) {
  12625. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12626. // }
  12627. // data = data.replace(/-/g, ',-');
  12628. // create array
  12629. // var arr = cs.split('|');
  12630. // init context point
  12631. var cpx = 0;
  12632. var cpy = 0;
  12633. var subpathX = cpx;
  12634. var subpathY = cpy;
  12635. var prevCmd;
  12636. var path = new PathProxy();
  12637. var CMD = PathProxy.CMD;
  12638. // commandReg.lastIndex = 0;
  12639. // var cmdResult;
  12640. // while ((cmdResult = commandReg.exec(data)) != null) {
  12641. // var cmdStr = cmdResult[1];
  12642. // var cmdContent = cmdResult[2];
  12643. var cmdList = data.match(commandReg);
  12644. for (var l = 0; l < cmdList.length; l++) {
  12645. var cmdText = cmdList[l];
  12646. var cmdStr = cmdText.charAt(0);
  12647. var cmd;
  12648. // String#split is faster a little bit than String#replace or RegExp#exec.
  12649. // var p = cmdContent.split(valueSplitReg);
  12650. // var pLen = 0;
  12651. // for (var i = 0; i < p.length; i++) {
  12652. // // '' and other invalid str => NaN
  12653. // var val = parseFloat(p[i]);
  12654. // !isNaN(val) && (p[pLen++] = val);
  12655. // }
  12656. var p = cmdText.match(numberReg) || [];
  12657. var pLen = p.length;
  12658. for (var i = 0; i < pLen; i++) {
  12659. p[i] = parseFloat(p[i]);
  12660. }
  12661. var off = 0;
  12662. while (off < pLen) {
  12663. var ctlPtx;
  12664. var ctlPty;
  12665. var rx;
  12666. var ry;
  12667. var psi;
  12668. var fa;
  12669. var fs;
  12670. var x1 = cpx;
  12671. var y1 = cpy;
  12672. // convert l, H, h, V, and v to L
  12673. switch (cmdStr) {
  12674. case 'l':
  12675. cpx += p[off++];
  12676. cpy += p[off++];
  12677. cmd = CMD.L;
  12678. path.addData(cmd, cpx, cpy);
  12679. break;
  12680. case 'L':
  12681. cpx = p[off++];
  12682. cpy = p[off++];
  12683. cmd = CMD.L;
  12684. path.addData(cmd, cpx, cpy);
  12685. break;
  12686. case 'm':
  12687. cpx += p[off++];
  12688. cpy += p[off++];
  12689. cmd = CMD.M;
  12690. path.addData(cmd, cpx, cpy);
  12691. subpathX = cpx;
  12692. subpathY = cpy;
  12693. cmdStr = 'l';
  12694. break;
  12695. case 'M':
  12696. cpx = p[off++];
  12697. cpy = p[off++];
  12698. cmd = CMD.M;
  12699. path.addData(cmd, cpx, cpy);
  12700. subpathX = cpx;
  12701. subpathY = cpy;
  12702. cmdStr = 'L';
  12703. break;
  12704. case 'h':
  12705. cpx += p[off++];
  12706. cmd = CMD.L;
  12707. path.addData(cmd, cpx, cpy);
  12708. break;
  12709. case 'H':
  12710. cpx = p[off++];
  12711. cmd = CMD.L;
  12712. path.addData(cmd, cpx, cpy);
  12713. break;
  12714. case 'v':
  12715. cpy += p[off++];
  12716. cmd = CMD.L;
  12717. path.addData(cmd, cpx, cpy);
  12718. break;
  12719. case 'V':
  12720. cpy = p[off++];
  12721. cmd = CMD.L;
  12722. path.addData(cmd, cpx, cpy);
  12723. break;
  12724. case 'C':
  12725. cmd = CMD.C;
  12726. path.addData(
  12727. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12728. );
  12729. cpx = p[off - 2];
  12730. cpy = p[off - 1];
  12731. break;
  12732. case 'c':
  12733. cmd = CMD.C;
  12734. path.addData(
  12735. cmd,
  12736. p[off++] + cpx, p[off++] + cpy,
  12737. p[off++] + cpx, p[off++] + cpy,
  12738. p[off++] + cpx, p[off++] + cpy
  12739. );
  12740. cpx += p[off - 2];
  12741. cpy += p[off - 1];
  12742. break;
  12743. case 'S':
  12744. ctlPtx = cpx;
  12745. ctlPty = cpy;
  12746. var len = path.len();
  12747. var pathData = path.data;
  12748. if (prevCmd === CMD.C) {
  12749. ctlPtx += cpx - pathData[len - 4];
  12750. ctlPty += cpy - pathData[len - 3];
  12751. }
  12752. cmd = CMD.C;
  12753. x1 = p[off++];
  12754. y1 = p[off++];
  12755. cpx = p[off++];
  12756. cpy = p[off++];
  12757. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12758. break;
  12759. case 's':
  12760. ctlPtx = cpx;
  12761. ctlPty = cpy;
  12762. var len = path.len();
  12763. var pathData = path.data;
  12764. if (prevCmd === CMD.C) {
  12765. ctlPtx += cpx - pathData[len - 4];
  12766. ctlPty += cpy - pathData[len - 3];
  12767. }
  12768. cmd = CMD.C;
  12769. x1 = cpx + p[off++];
  12770. y1 = cpy + p[off++];
  12771. cpx += p[off++];
  12772. cpy += p[off++];
  12773. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12774. break;
  12775. case 'Q':
  12776. x1 = p[off++];
  12777. y1 = p[off++];
  12778. cpx = p[off++];
  12779. cpy = p[off++];
  12780. cmd = CMD.Q;
  12781. path.addData(cmd, x1, y1, cpx, cpy);
  12782. break;
  12783. case 'q':
  12784. x1 = p[off++] + cpx;
  12785. y1 = p[off++] + cpy;
  12786. cpx += p[off++];
  12787. cpy += p[off++];
  12788. cmd = CMD.Q;
  12789. path.addData(cmd, x1, y1, cpx, cpy);
  12790. break;
  12791. case 'T':
  12792. ctlPtx = cpx;
  12793. ctlPty = cpy;
  12794. var len = path.len();
  12795. var pathData = path.data;
  12796. if (prevCmd === CMD.Q) {
  12797. ctlPtx += cpx - pathData[len - 4];
  12798. ctlPty += cpy - pathData[len - 3];
  12799. }
  12800. cpx = p[off++];
  12801. cpy = p[off++];
  12802. cmd = CMD.Q;
  12803. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12804. break;
  12805. case 't':
  12806. ctlPtx = cpx;
  12807. ctlPty = cpy;
  12808. var len = path.len();
  12809. var pathData = path.data;
  12810. if (prevCmd === CMD.Q) {
  12811. ctlPtx += cpx - pathData[len - 4];
  12812. ctlPty += cpy - pathData[len - 3];
  12813. }
  12814. cpx += p[off++];
  12815. cpy += p[off++];
  12816. cmd = CMD.Q;
  12817. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12818. break;
  12819. case 'A':
  12820. rx = p[off++];
  12821. ry = p[off++];
  12822. psi = p[off++];
  12823. fa = p[off++];
  12824. fs = p[off++];
  12825. x1 = cpx, y1 = cpy;
  12826. cpx = p[off++];
  12827. cpy = p[off++];
  12828. cmd = CMD.A;
  12829. processArc(
  12830. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12831. );
  12832. break;
  12833. case 'a':
  12834. rx = p[off++];
  12835. ry = p[off++];
  12836. psi = p[off++];
  12837. fa = p[off++];
  12838. fs = p[off++];
  12839. x1 = cpx, y1 = cpy;
  12840. cpx += p[off++];
  12841. cpy += p[off++];
  12842. cmd = CMD.A;
  12843. processArc(
  12844. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12845. );
  12846. break;
  12847. }
  12848. }
  12849. if (cmdStr === 'z' || cmdStr === 'Z') {
  12850. cmd = CMD.Z;
  12851. path.addData(cmd);
  12852. // z may be in the middle of the path.
  12853. cpx = subpathX;
  12854. cpy = subpathY;
  12855. }
  12856. prevCmd = cmd;
  12857. }
  12858. path.toStatic();
  12859. return path;
  12860. }
  12861. // TODO Optimize double memory cost problem
  12862. function createPathOptions(str, opts) {
  12863. var pathProxy = createPathProxyFromString(str);
  12864. opts = opts || {};
  12865. opts.buildPath = function (path) {
  12866. if (path.setData) {
  12867. path.setData(pathProxy.data);
  12868. // Svg and vml renderer don't have context
  12869. var ctx = path.getContext();
  12870. if (ctx) {
  12871. path.rebuildPath(ctx);
  12872. }
  12873. }
  12874. else {
  12875. var ctx = path;
  12876. pathProxy.rebuildPath(ctx);
  12877. }
  12878. };
  12879. opts.applyTransform = function (m) {
  12880. transformPath(pathProxy, m);
  12881. this.dirty(true);
  12882. };
  12883. return opts;
  12884. }
  12885. /**
  12886. * Create a Path object from path string data
  12887. * http://www.w3.org/TR/SVG/paths.html#PathData
  12888. * @param {Object} opts Other options
  12889. */
  12890. function createFromString(str, opts) {
  12891. return new Path(createPathOptions(str, opts));
  12892. }
  12893. /**
  12894. * Create a Path class from path string data
  12895. * @param {string} str
  12896. * @param {Object} opts Other options
  12897. */
  12898. function extendFromString(str, opts) {
  12899. return Path.extend(createPathOptions(str, opts));
  12900. }
  12901. /**
  12902. * Merge multiple paths
  12903. */
  12904. // TODO Apply transform
  12905. // TODO stroke dash
  12906. // TODO Optimize double memory cost problem
  12907. function mergePath$1(pathEls, opts) {
  12908. var pathList = [];
  12909. var len = pathEls.length;
  12910. for (var i = 0; i < len; i++) {
  12911. var pathEl = pathEls[i];
  12912. if (!pathEl.path) {
  12913. pathEl.createPathProxy();
  12914. }
  12915. if (pathEl.__dirtyPath) {
  12916. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12917. }
  12918. pathList.push(pathEl.path);
  12919. }
  12920. var pathBundle = new Path(opts);
  12921. // Need path proxy.
  12922. pathBundle.createPathProxy();
  12923. pathBundle.buildPath = function (path) {
  12924. path.appendPath(pathList);
  12925. // Svg and vml renderer don't have context
  12926. var ctx = path.getContext();
  12927. if (ctx) {
  12928. path.rebuildPath(ctx);
  12929. }
  12930. };
  12931. return pathBundle;
  12932. }
  12933. /**
  12934. * @alias zrender/graphic/Text
  12935. * @extends module:zrender/graphic/Displayable
  12936. * @constructor
  12937. * @param {Object} opts
  12938. */
  12939. var Text = function (opts) { // jshint ignore:line
  12940. Displayable.call(this, opts);
  12941. };
  12942. Text.prototype = {
  12943. constructor: Text,
  12944. type: 'text',
  12945. brush: function (ctx, prevEl) {
  12946. var style = this.style;
  12947. // Optimize, avoid normalize every time.
  12948. this.__dirty && normalizeTextStyle(style, true);
  12949. // Use props with prefix 'text'.
  12950. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12951. style.shadowOffsetX = style.shadowOffsetY = null;
  12952. var text = style.text;
  12953. // Convert to string
  12954. text != null && (text += '');
  12955. // Do not apply style.bind in Text node. Because the real bind job
  12956. // is in textHelper.renderText, and performance of text render should
  12957. // be considered.
  12958. // style.bind(ctx, this, prevEl);
  12959. if (!needDrawText(text, style)) {
  12960. // The current el.style is not applied
  12961. // and should not be used as cache.
  12962. ctx.__attrCachedBy = ContextCachedBy.NONE;
  12963. return;
  12964. }
  12965. this.setTransform(ctx);
  12966. renderText(this, ctx, text, style, null, prevEl);
  12967. this.restoreTransform(ctx);
  12968. },
  12969. getBoundingRect: function () {
  12970. var style = this.style;
  12971. // Optimize, avoid normalize every time.
  12972. this.__dirty && normalizeTextStyle(style, true);
  12973. if (!this._rect) {
  12974. var text = style.text;
  12975. text != null ? (text += '') : (text = '');
  12976. var rect = getBoundingRect(
  12977. style.text + '',
  12978. style.font,
  12979. style.textAlign,
  12980. style.textVerticalAlign,
  12981. style.textPadding,
  12982. style.textLineHeight,
  12983. style.rich
  12984. );
  12985. rect.x += style.x || 0;
  12986. rect.y += style.y || 0;
  12987. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12988. var w = style.textStrokeWidth;
  12989. rect.x -= w / 2;
  12990. rect.y -= w / 2;
  12991. rect.width += w;
  12992. rect.height += w;
  12993. }
  12994. this._rect = rect;
  12995. }
  12996. return this._rect;
  12997. }
  12998. };
  12999. inherits(Text, Displayable);
  13000. /**
  13001. * 圆形
  13002. * @module zrender/shape/Circle
  13003. */
  13004. var Circle = Path.extend({
  13005. type: 'circle',
  13006. shape: {
  13007. cx: 0,
  13008. cy: 0,
  13009. r: 0
  13010. },
  13011. buildPath: function (ctx, shape, inBundle) {
  13012. // Better stroking in ShapeBundle
  13013. // Always do it may have performence issue ( fill may be 2x more cost)
  13014. if (inBundle) {
  13015. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13016. }
  13017. // else {
  13018. // if (ctx.allocate && !ctx.data.length) {
  13019. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13020. // }
  13021. // }
  13022. // Better stroking in ShapeBundle
  13023. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13024. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13025. }
  13026. });
  13027. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13028. // where exception "unexpected call to method or property access"
  13029. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13030. // whose area size is zero is drawn and ctx.clip() is called and
  13031. // shadowBlur is set. See #4572, #3112, #5777.
  13032. // (e.g.,
  13033. // ctx.moveTo(10, 10);
  13034. // ctx.lineTo(20, 10);
  13035. // ctx.closePath();
  13036. // ctx.clip();
  13037. // ctx.shadowBlur = 10;
  13038. // ...
  13039. // ctx.fill();
  13040. // )
  13041. var shadowTemp = [
  13042. ['shadowBlur', 0],
  13043. ['shadowColor', '#000'],
  13044. ['shadowOffsetX', 0],
  13045. ['shadowOffsetY', 0]
  13046. ];
  13047. var fixClipWithShadow = function (orignalBrush) {
  13048. // version string can be: '11.0'
  13049. return (env$1.browser.ie && env$1.browser.version >= 11)
  13050. ? function () {
  13051. var clipPaths = this.__clipPaths;
  13052. var style = this.style;
  13053. var modified;
  13054. if (clipPaths) {
  13055. for (var i = 0; i < clipPaths.length; i++) {
  13056. var clipPath = clipPaths[i];
  13057. var shape = clipPath && clipPath.shape;
  13058. var type = clipPath && clipPath.type;
  13059. if (shape && (
  13060. (type === 'sector' && shape.startAngle === shape.endAngle)
  13061. || (type === 'rect' && (!shape.width || !shape.height))
  13062. )) {
  13063. for (var j = 0; j < shadowTemp.length; j++) {
  13064. // It is save to put shadowTemp static, because shadowTemp
  13065. // will be all modified each item brush called.
  13066. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13067. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13068. }
  13069. modified = true;
  13070. break;
  13071. }
  13072. }
  13073. }
  13074. orignalBrush.apply(this, arguments);
  13075. if (modified) {
  13076. for (var j = 0; j < shadowTemp.length; j++) {
  13077. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13078. }
  13079. }
  13080. }
  13081. : orignalBrush;
  13082. };
  13083. /**
  13084. * 扇形
  13085. * @module zrender/graphic/shape/Sector
  13086. */
  13087. var Sector = Path.extend({
  13088. type: 'sector',
  13089. shape: {
  13090. cx: 0,
  13091. cy: 0,
  13092. r0: 0,
  13093. r: 0,
  13094. startAngle: 0,
  13095. endAngle: Math.PI * 2,
  13096. clockwise: true
  13097. },
  13098. brush: fixClipWithShadow(Path.prototype.brush),
  13099. buildPath: function (ctx, shape) {
  13100. var x = shape.cx;
  13101. var y = shape.cy;
  13102. var r0 = Math.max(shape.r0 || 0, 0);
  13103. var r = Math.max(shape.r, 0);
  13104. var startAngle = shape.startAngle;
  13105. var endAngle = shape.endAngle;
  13106. var clockwise = shape.clockwise;
  13107. var unitX = Math.cos(startAngle);
  13108. var unitY = Math.sin(startAngle);
  13109. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13110. ctx.lineTo(unitX * r + x, unitY * r + y);
  13111. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13112. ctx.lineTo(
  13113. Math.cos(endAngle) * r0 + x,
  13114. Math.sin(endAngle) * r0 + y
  13115. );
  13116. if (r0 !== 0) {
  13117. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13118. }
  13119. ctx.closePath();
  13120. }
  13121. });
  13122. /**
  13123. * 圆环
  13124. * @module zrender/graphic/shape/Ring
  13125. */
  13126. var Ring = Path.extend({
  13127. type: 'ring',
  13128. shape: {
  13129. cx: 0,
  13130. cy: 0,
  13131. r: 0,
  13132. r0: 0
  13133. },
  13134. buildPath: function (ctx, shape) {
  13135. var x = shape.cx;
  13136. var y = shape.cy;
  13137. var PI2 = Math.PI * 2;
  13138. ctx.moveTo(x + shape.r, y);
  13139. ctx.arc(x, y, shape.r, 0, PI2, false);
  13140. ctx.moveTo(x + shape.r0, y);
  13141. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13142. }
  13143. });
  13144. /**
  13145. * Catmull-Rom spline 插值折线
  13146. * @module zrender/shape/util/smoothSpline
  13147. * @author pissang (https://www.github.com/pissang)
  13148. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13149. * errorrik (errorrik@gmail.com)
  13150. */
  13151. /**
  13152. * @inner
  13153. */
  13154. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13155. var v0 = (p2 - p0) * 0.5;
  13156. var v1 = (p3 - p1) * 0.5;
  13157. return (2 * (p1 - p2) + v0 + v1) * t3
  13158. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13159. + v0 * t + p1;
  13160. }
  13161. /**
  13162. * @alias module:zrender/shape/util/smoothSpline
  13163. * @param {Array} points 线段顶点数组
  13164. * @param {boolean} isLoop
  13165. * @return {Array}
  13166. */
  13167. var smoothSpline = function (points, isLoop) {
  13168. var len$$1 = points.length;
  13169. var ret = [];
  13170. var distance$$1 = 0;
  13171. for (var i = 1; i < len$$1; i++) {
  13172. distance$$1 += distance(points[i - 1], points[i]);
  13173. }
  13174. var segs = distance$$1 / 2;
  13175. segs = segs < len$$1 ? len$$1 : segs;
  13176. for (var i = 0; i < segs; i++) {
  13177. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13178. var idx = Math.floor(pos);
  13179. var w = pos - idx;
  13180. var p0;
  13181. var p1 = points[idx % len$$1];
  13182. var p2;
  13183. var p3;
  13184. if (!isLoop) {
  13185. p0 = points[idx === 0 ? idx : idx - 1];
  13186. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13187. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13188. }
  13189. else {
  13190. p0 = points[(idx - 1 + len$$1) % len$$1];
  13191. p2 = points[(idx + 1) % len$$1];
  13192. p3 = points[(idx + 2) % len$$1];
  13193. }
  13194. var w2 = w * w;
  13195. var w3 = w * w2;
  13196. ret.push([
  13197. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13198. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13199. ]);
  13200. }
  13201. return ret;
  13202. };
  13203. /**
  13204. * 贝塞尔平滑曲线
  13205. * @module zrender/shape/util/smoothBezier
  13206. * @author pissang (https://www.github.com/pissang)
  13207. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13208. * errorrik (errorrik@gmail.com)
  13209. */
  13210. /**
  13211. * 贝塞尔平滑曲线
  13212. * @alias module:zrender/shape/util/smoothBezier
  13213. * @param {Array} points 线段顶点数组
  13214. * @param {number} smooth 平滑等级, 0-1
  13215. * @param {boolean} isLoop
  13216. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13217. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13218. * 整个折线的包围盒做一个并集用来约束控制点。
  13219. * @param {Array} 计算出来的控制点数组
  13220. */
  13221. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13222. var cps = [];
  13223. var v = [];
  13224. var v1 = [];
  13225. var v2 = [];
  13226. var prevPoint;
  13227. var nextPoint;
  13228. var min$$1;
  13229. var max$$1;
  13230. if (constraint) {
  13231. min$$1 = [Infinity, Infinity];
  13232. max$$1 = [-Infinity, -Infinity];
  13233. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13234. min(min$$1, min$$1, points[i]);
  13235. max(max$$1, max$$1, points[i]);
  13236. }
  13237. // 与指定的包围盒做并集
  13238. min(min$$1, min$$1, constraint[0]);
  13239. max(max$$1, max$$1, constraint[1]);
  13240. }
  13241. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13242. var point = points[i];
  13243. if (isLoop) {
  13244. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13245. nextPoint = points[(i + 1) % len$$1];
  13246. }
  13247. else {
  13248. if (i === 0 || i === len$$1 - 1) {
  13249. cps.push(clone$1(points[i]));
  13250. continue;
  13251. }
  13252. else {
  13253. prevPoint = points[i - 1];
  13254. nextPoint = points[i + 1];
  13255. }
  13256. }
  13257. sub(v, nextPoint, prevPoint);
  13258. // use degree to scale the handle length
  13259. scale(v, v, smooth);
  13260. var d0 = distance(point, prevPoint);
  13261. var d1 = distance(point, nextPoint);
  13262. var sum = d0 + d1;
  13263. if (sum !== 0) {
  13264. d0 /= sum;
  13265. d1 /= sum;
  13266. }
  13267. scale(v1, v, -d0);
  13268. scale(v2, v, d1);
  13269. var cp0 = add([], point, v1);
  13270. var cp1 = add([], point, v2);
  13271. if (constraint) {
  13272. max(cp0, cp0, min$$1);
  13273. min(cp0, cp0, max$$1);
  13274. max(cp1, cp1, min$$1);
  13275. min(cp1, cp1, max$$1);
  13276. }
  13277. cps.push(cp0);
  13278. cps.push(cp1);
  13279. }
  13280. if (isLoop) {
  13281. cps.push(cps.shift());
  13282. }
  13283. return cps;
  13284. };
  13285. function buildPath$1(ctx, shape, closePath) {
  13286. var points = shape.points;
  13287. var smooth = shape.smooth;
  13288. if (points && points.length >= 2) {
  13289. if (smooth && smooth !== 'spline') {
  13290. var controlPoints = smoothBezier(
  13291. points, smooth, closePath, shape.smoothConstraint
  13292. );
  13293. ctx.moveTo(points[0][0], points[0][1]);
  13294. var len = points.length;
  13295. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13296. var cp1 = controlPoints[i * 2];
  13297. var cp2 = controlPoints[i * 2 + 1];
  13298. var p = points[(i + 1) % len];
  13299. ctx.bezierCurveTo(
  13300. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13301. );
  13302. }
  13303. }
  13304. else {
  13305. if (smooth === 'spline') {
  13306. points = smoothSpline(points, closePath);
  13307. }
  13308. ctx.moveTo(points[0][0], points[0][1]);
  13309. for (var i = 1, l = points.length; i < l; i++) {
  13310. ctx.lineTo(points[i][0], points[i][1]);
  13311. }
  13312. }
  13313. closePath && ctx.closePath();
  13314. }
  13315. }
  13316. /**
  13317. * 多边形
  13318. * @module zrender/shape/Polygon
  13319. */
  13320. var Polygon = Path.extend({
  13321. type: 'polygon',
  13322. shape: {
  13323. points: null,
  13324. smooth: false,
  13325. smoothConstraint: null
  13326. },
  13327. buildPath: function (ctx, shape) {
  13328. buildPath$1(ctx, shape, true);
  13329. }
  13330. });
  13331. /**
  13332. * @module zrender/graphic/shape/Polyline
  13333. */
  13334. var Polyline = Path.extend({
  13335. type: 'polyline',
  13336. shape: {
  13337. points: null,
  13338. smooth: false,
  13339. smoothConstraint: null
  13340. },
  13341. style: {
  13342. stroke: '#000',
  13343. fill: null
  13344. },
  13345. buildPath: function (ctx, shape) {
  13346. buildPath$1(ctx, shape, false);
  13347. }
  13348. });
  13349. /**
  13350. * Sub-pixel optimize for canvas rendering, prevent from blur
  13351. * when rendering a thin vertical/horizontal line.
  13352. */
  13353. var round$1 = Math.round;
  13354. /**
  13355. * Sub pixel optimize line for canvas
  13356. *
  13357. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13358. * `outputShape` and `inputShape` can be the same object.
  13359. * `outputShape` object can be used repeatly, because all of
  13360. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13361. * @param {Object} [inputShape]
  13362. * @param {number} [inputShape.x1]
  13363. * @param {number} [inputShape.y1]
  13364. * @param {number} [inputShape.x2]
  13365. * @param {number} [inputShape.y2]
  13366. * @param {Object} [style]
  13367. * @param {number} [style.lineWidth]
  13368. */
  13369. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13370. var lineWidth = style && style.lineWidth;
  13371. if (!inputShape || !lineWidth) {
  13372. return;
  13373. }
  13374. var x1 = inputShape.x1;
  13375. var x2 = inputShape.x2;
  13376. var y1 = inputShape.y1;
  13377. var y2 = inputShape.y2;
  13378. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  13379. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13380. }
  13381. else {
  13382. outputShape.x1 = x1;
  13383. outputShape.x2 = x2;
  13384. }
  13385. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  13386. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13387. }
  13388. else {
  13389. outputShape.y1 = y1;
  13390. outputShape.y2 = y2;
  13391. }
  13392. }
  13393. /**
  13394. * Sub pixel optimize rect for canvas
  13395. *
  13396. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13397. * `outputShape` and `inputShape` can be the same object.
  13398. * `outputShape` object can be used repeatly, because all of
  13399. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13400. * @param {Object} [inputShape]
  13401. * @param {number} [inputShape.x]
  13402. * @param {number} [inputShape.y]
  13403. * @param {number} [inputShape.width]
  13404. * @param {number} [inputShape.height]
  13405. * @param {Object} [style]
  13406. * @param {number} [style.lineWidth]
  13407. */
  13408. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13409. var lineWidth = style && style.lineWidth;
  13410. if (!inputShape || !lineWidth) {
  13411. return;
  13412. }
  13413. var originX = inputShape.x;
  13414. var originY = inputShape.y;
  13415. var originWidth = inputShape.width;
  13416. var originHeight = inputShape.height;
  13417. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13418. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13419. outputShape.width = Math.max(
  13420. subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x,
  13421. originWidth === 0 ? 0 : 1
  13422. );
  13423. outputShape.height = Math.max(
  13424. subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y,
  13425. originHeight === 0 ? 0 : 1
  13426. );
  13427. }
  13428. /**
  13429. * Sub pixel optimize for canvas
  13430. *
  13431. * @param {number} position Coordinate, such as x, y
  13432. * @param {number} lineWidth Should be nonnegative integer.
  13433. * @param {boolean=} positiveOrNegative Default false (negative).
  13434. * @return {number} Optimized position.
  13435. */
  13436. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13437. // Assure that (position + lineWidth / 2) is near integer edge,
  13438. // otherwise line will be fuzzy in canvas.
  13439. var doubledPosition = round$1(position * 2);
  13440. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  13441. ? doubledPosition / 2
  13442. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13443. }
  13444. /**
  13445. * 矩形
  13446. * @module zrender/graphic/shape/Rect
  13447. */
  13448. // Avoid create repeatly.
  13449. var subPixelOptimizeOutputShape = {};
  13450. var Rect = Path.extend({
  13451. type: 'rect',
  13452. shape: {
  13453. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13454. // r缩写为1 相当于 [1, 1, 1, 1]
  13455. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13456. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13457. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13458. r: 0,
  13459. x: 0,
  13460. y: 0,
  13461. width: 0,
  13462. height: 0
  13463. },
  13464. buildPath: function (ctx, shape) {
  13465. var x;
  13466. var y;
  13467. var width;
  13468. var height;
  13469. if (this.subPixelOptimize) {
  13470. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13471. x = subPixelOptimizeOutputShape.x;
  13472. y = subPixelOptimizeOutputShape.y;
  13473. width = subPixelOptimizeOutputShape.width;
  13474. height = subPixelOptimizeOutputShape.height;
  13475. subPixelOptimizeOutputShape.r = shape.r;
  13476. shape = subPixelOptimizeOutputShape;
  13477. }
  13478. else {
  13479. x = shape.x;
  13480. y = shape.y;
  13481. width = shape.width;
  13482. height = shape.height;
  13483. }
  13484. if (!shape.r) {
  13485. ctx.rect(x, y, width, height);
  13486. }
  13487. else {
  13488. buildPath(ctx, shape);
  13489. }
  13490. ctx.closePath();
  13491. return;
  13492. }
  13493. });
  13494. /**
  13495. * 直线
  13496. * @module zrender/graphic/shape/Line
  13497. */
  13498. // Avoid create repeatly.
  13499. var subPixelOptimizeOutputShape$1 = {};
  13500. var Line = Path.extend({
  13501. type: 'line',
  13502. shape: {
  13503. // Start point
  13504. x1: 0,
  13505. y1: 0,
  13506. // End point
  13507. x2: 0,
  13508. y2: 0,
  13509. percent: 1
  13510. },
  13511. style: {
  13512. stroke: '#000',
  13513. fill: null
  13514. },
  13515. buildPath: function (ctx, shape) {
  13516. var x1;
  13517. var y1;
  13518. var x2;
  13519. var y2;
  13520. if (this.subPixelOptimize) {
  13521. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13522. x1 = subPixelOptimizeOutputShape$1.x1;
  13523. y1 = subPixelOptimizeOutputShape$1.y1;
  13524. x2 = subPixelOptimizeOutputShape$1.x2;
  13525. y2 = subPixelOptimizeOutputShape$1.y2;
  13526. }
  13527. else {
  13528. x1 = shape.x1;
  13529. y1 = shape.y1;
  13530. x2 = shape.x2;
  13531. y2 = shape.y2;
  13532. }
  13533. var percent = shape.percent;
  13534. if (percent === 0) {
  13535. return;
  13536. }
  13537. ctx.moveTo(x1, y1);
  13538. if (percent < 1) {
  13539. x2 = x1 * (1 - percent) + x2 * percent;
  13540. y2 = y1 * (1 - percent) + y2 * percent;
  13541. }
  13542. ctx.lineTo(x2, y2);
  13543. },
  13544. /**
  13545. * Get point at percent
  13546. * @param {number} percent
  13547. * @return {Array.<number>}
  13548. */
  13549. pointAt: function (p) {
  13550. var shape = this.shape;
  13551. return [
  13552. shape.x1 * (1 - p) + shape.x2 * p,
  13553. shape.y1 * (1 - p) + shape.y2 * p
  13554. ];
  13555. }
  13556. });
  13557. /**
  13558. * 贝塞尔曲线
  13559. * @module zrender/shape/BezierCurve
  13560. */
  13561. var out = [];
  13562. function someVectorAt(shape, t, isTangent) {
  13563. var cpx2 = shape.cpx2;
  13564. var cpy2 = shape.cpy2;
  13565. if (cpx2 === null || cpy2 === null) {
  13566. return [
  13567. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13568. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13569. ];
  13570. }
  13571. else {
  13572. return [
  13573. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13574. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13575. ];
  13576. }
  13577. }
  13578. var BezierCurve = Path.extend({
  13579. type: 'bezier-curve',
  13580. shape: {
  13581. x1: 0,
  13582. y1: 0,
  13583. x2: 0,
  13584. y2: 0,
  13585. cpx1: 0,
  13586. cpy1: 0,
  13587. // cpx2: 0,
  13588. // cpy2: 0
  13589. // Curve show percent, for animating
  13590. percent: 1
  13591. },
  13592. style: {
  13593. stroke: '#000',
  13594. fill: null
  13595. },
  13596. buildPath: function (ctx, shape) {
  13597. var x1 = shape.x1;
  13598. var y1 = shape.y1;
  13599. var x2 = shape.x2;
  13600. var y2 = shape.y2;
  13601. var cpx1 = shape.cpx1;
  13602. var cpy1 = shape.cpy1;
  13603. var cpx2 = shape.cpx2;
  13604. var cpy2 = shape.cpy2;
  13605. var percent = shape.percent;
  13606. if (percent === 0) {
  13607. return;
  13608. }
  13609. ctx.moveTo(x1, y1);
  13610. if (cpx2 == null || cpy2 == null) {
  13611. if (percent < 1) {
  13612. quadraticSubdivide(
  13613. x1, cpx1, x2, percent, out
  13614. );
  13615. cpx1 = out[1];
  13616. x2 = out[2];
  13617. quadraticSubdivide(
  13618. y1, cpy1, y2, percent, out
  13619. );
  13620. cpy1 = out[1];
  13621. y2 = out[2];
  13622. }
  13623. ctx.quadraticCurveTo(
  13624. cpx1, cpy1,
  13625. x2, y2
  13626. );
  13627. }
  13628. else {
  13629. if (percent < 1) {
  13630. cubicSubdivide(
  13631. x1, cpx1, cpx2, x2, percent, out
  13632. );
  13633. cpx1 = out[1];
  13634. cpx2 = out[2];
  13635. x2 = out[3];
  13636. cubicSubdivide(
  13637. y1, cpy1, cpy2, y2, percent, out
  13638. );
  13639. cpy1 = out[1];
  13640. cpy2 = out[2];
  13641. y2 = out[3];
  13642. }
  13643. ctx.bezierCurveTo(
  13644. cpx1, cpy1,
  13645. cpx2, cpy2,
  13646. x2, y2
  13647. );
  13648. }
  13649. },
  13650. /**
  13651. * Get point at percent
  13652. * @param {number} t
  13653. * @return {Array.<number>}
  13654. */
  13655. pointAt: function (t) {
  13656. return someVectorAt(this.shape, t, false);
  13657. },
  13658. /**
  13659. * Get tangent at percent
  13660. * @param {number} t
  13661. * @return {Array.<number>}
  13662. */
  13663. tangentAt: function (t) {
  13664. var p = someVectorAt(this.shape, t, true);
  13665. return normalize(p, p);
  13666. }
  13667. });
  13668. /**
  13669. * 圆弧
  13670. * @module zrender/graphic/shape/Arc
  13671. */
  13672. var Arc = Path.extend({
  13673. type: 'arc',
  13674. shape: {
  13675. cx: 0,
  13676. cy: 0,
  13677. r: 0,
  13678. startAngle: 0,
  13679. endAngle: Math.PI * 2,
  13680. clockwise: true
  13681. },
  13682. style: {
  13683. stroke: '#000',
  13684. fill: null
  13685. },
  13686. buildPath: function (ctx, shape) {
  13687. var x = shape.cx;
  13688. var y = shape.cy;
  13689. var r = Math.max(shape.r, 0);
  13690. var startAngle = shape.startAngle;
  13691. var endAngle = shape.endAngle;
  13692. var clockwise = shape.clockwise;
  13693. var unitX = Math.cos(startAngle);
  13694. var unitY = Math.sin(startAngle);
  13695. ctx.moveTo(unitX * r + x, unitY * r + y);
  13696. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13697. }
  13698. });
  13699. // CompoundPath to improve performance
  13700. var CompoundPath = Path.extend({
  13701. type: 'compound',
  13702. shape: {
  13703. paths: null
  13704. },
  13705. _updatePathDirty: function () {
  13706. var dirtyPath = this.__dirtyPath;
  13707. var paths = this.shape.paths;
  13708. for (var i = 0; i < paths.length; i++) {
  13709. // Mark as dirty if any subpath is dirty
  13710. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13711. }
  13712. this.__dirtyPath = dirtyPath;
  13713. this.__dirty = this.__dirty || dirtyPath;
  13714. },
  13715. beforeBrush: function () {
  13716. this._updatePathDirty();
  13717. var paths = this.shape.paths || [];
  13718. var scale = this.getGlobalScale();
  13719. // Update path scale
  13720. for (var i = 0; i < paths.length; i++) {
  13721. if (!paths[i].path) {
  13722. paths[i].createPathProxy();
  13723. }
  13724. paths[i].path.setScale(scale[0], scale[1]);
  13725. }
  13726. },
  13727. buildPath: function (ctx, shape) {
  13728. var paths = shape.paths || [];
  13729. for (var i = 0; i < paths.length; i++) {
  13730. paths[i].buildPath(ctx, paths[i].shape, true);
  13731. }
  13732. },
  13733. afterBrush: function () {
  13734. var paths = this.shape.paths || [];
  13735. for (var i = 0; i < paths.length; i++) {
  13736. paths[i].__dirtyPath = false;
  13737. }
  13738. },
  13739. getBoundingRect: function () {
  13740. this._updatePathDirty();
  13741. return Path.prototype.getBoundingRect.call(this);
  13742. }
  13743. });
  13744. /**
  13745. * @param {Array.<Object>} colorStops
  13746. */
  13747. var Gradient = function (colorStops) {
  13748. this.colorStops = colorStops || [];
  13749. };
  13750. Gradient.prototype = {
  13751. constructor: Gradient,
  13752. addColorStop: function (offset, color) {
  13753. this.colorStops.push({
  13754. offset: offset,
  13755. color: color
  13756. });
  13757. }
  13758. };
  13759. /**
  13760. * x, y, x2, y2 are all percent from 0 to 1
  13761. * @param {number} [x=0]
  13762. * @param {number} [y=0]
  13763. * @param {number} [x2=1]
  13764. * @param {number} [y2=0]
  13765. * @param {Array.<Object>} colorStops
  13766. * @param {boolean} [globalCoord=false]
  13767. */
  13768. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13769. // Should do nothing more in this constructor. Because gradient can be
  13770. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13771. // this constructor will not be called.
  13772. this.x = x == null ? 0 : x;
  13773. this.y = y == null ? 0 : y;
  13774. this.x2 = x2 == null ? 1 : x2;
  13775. this.y2 = y2 == null ? 0 : y2;
  13776. // Can be cloned
  13777. this.type = 'linear';
  13778. // If use global coord
  13779. this.global = globalCoord || false;
  13780. Gradient.call(this, colorStops);
  13781. };
  13782. LinearGradient.prototype = {
  13783. constructor: LinearGradient
  13784. };
  13785. inherits(LinearGradient, Gradient);
  13786. /**
  13787. * x, y, r are all percent from 0 to 1
  13788. * @param {number} [x=0.5]
  13789. * @param {number} [y=0.5]
  13790. * @param {number} [r=0.5]
  13791. * @param {Array.<Object>} [colorStops]
  13792. * @param {boolean} [globalCoord=false]
  13793. */
  13794. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13795. // Should do nothing more in this constructor. Because gradient can be
  13796. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13797. // this constructor will not be called.
  13798. this.x = x == null ? 0.5 : x;
  13799. this.y = y == null ? 0.5 : y;
  13800. this.r = r == null ? 0.5 : r;
  13801. // Can be cloned
  13802. this.type = 'radial';
  13803. // If use global coord
  13804. this.global = globalCoord || false;
  13805. Gradient.call(this, colorStops);
  13806. };
  13807. RadialGradient.prototype = {
  13808. constructor: RadialGradient
  13809. };
  13810. inherits(RadialGradient, Gradient);
  13811. /**
  13812. * Displayable for incremental rendering. It will be rendered in a separate layer
  13813. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  13814. * addDisplayables will render the added displayables incremetally.
  13815. *
  13816. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13817. */
  13818. // TODO Style override ?
  13819. function IncrementalDisplayble(opts) {
  13820. Displayable.call(this, opts);
  13821. this._displayables = [];
  13822. this._temporaryDisplayables = [];
  13823. this._cursor = 0;
  13824. this.notClear = true;
  13825. }
  13826. IncrementalDisplayble.prototype.incremental = true;
  13827. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13828. this._displayables = [];
  13829. this._temporaryDisplayables = [];
  13830. this._cursor = 0;
  13831. this.dirty();
  13832. this.notClear = false;
  13833. };
  13834. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13835. if (notPersistent) {
  13836. this._temporaryDisplayables.push(displayable);
  13837. }
  13838. else {
  13839. this._displayables.push(displayable);
  13840. }
  13841. this.dirty();
  13842. };
  13843. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13844. notPersistent = notPersistent || false;
  13845. for (var i = 0; i < displayables.length; i++) {
  13846. this.addDisplayable(displayables[i], notPersistent);
  13847. }
  13848. };
  13849. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13850. for (var i = this._cursor; i < this._displayables.length; i++) {
  13851. cb && cb(this._displayables[i]);
  13852. }
  13853. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13854. cb && cb(this._temporaryDisplayables[i]);
  13855. }
  13856. };
  13857. IncrementalDisplayble.prototype.update = function () {
  13858. this.updateTransform();
  13859. for (var i = this._cursor; i < this._displayables.length; i++) {
  13860. var displayable = this._displayables[i];
  13861. // PENDING
  13862. displayable.parent = this;
  13863. displayable.update();
  13864. displayable.parent = null;
  13865. }
  13866. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13867. var displayable = this._temporaryDisplayables[i];
  13868. // PENDING
  13869. displayable.parent = this;
  13870. displayable.update();
  13871. displayable.parent = null;
  13872. }
  13873. };
  13874. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13875. // Render persistant displayables.
  13876. for (var i = this._cursor; i < this._displayables.length; i++) {
  13877. var displayable = this._displayables[i];
  13878. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13879. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13880. displayable.afterBrush && displayable.afterBrush(ctx);
  13881. }
  13882. this._cursor = i;
  13883. // Render temporary displayables.
  13884. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13885. var displayable = this._temporaryDisplayables[i];
  13886. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13887. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13888. displayable.afterBrush && displayable.afterBrush(ctx);
  13889. }
  13890. this._temporaryDisplayables = [];
  13891. this.notClear = true;
  13892. };
  13893. var m = [];
  13894. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13895. if (!this._rect) {
  13896. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13897. for (var i = 0; i < this._displayables.length; i++) {
  13898. var displayable = this._displayables[i];
  13899. var childRect = displayable.getBoundingRect().clone();
  13900. if (displayable.needLocalTransform()) {
  13901. childRect.applyTransform(displayable.getLocalTransform(m));
  13902. }
  13903. rect.union(childRect);
  13904. }
  13905. this._rect = rect;
  13906. }
  13907. return this._rect;
  13908. };
  13909. IncrementalDisplayble.prototype.contain = function (x, y) {
  13910. var localPos = this.transformCoordToLocal(x, y);
  13911. var rect = this.getBoundingRect();
  13912. if (rect.contain(localPos[0], localPos[1])) {
  13913. for (var i = 0; i < this._displayables.length; i++) {
  13914. var displayable = this._displayables[i];
  13915. if (displayable.contain(x, y)) {
  13916. return true;
  13917. }
  13918. }
  13919. }
  13920. return false;
  13921. };
  13922. inherits(IncrementalDisplayble, Displayable);
  13923. /*
  13924. * Licensed to the Apache Software Foundation (ASF) under one
  13925. * or more contributor license agreements. See the NOTICE file
  13926. * distributed with this work for additional information
  13927. * regarding copyright ownership. The ASF licenses this file
  13928. * to you under the Apache License, Version 2.0 (the
  13929. * "License"); you may not use this file except in compliance
  13930. * with the License. You may obtain a copy of the License at
  13931. *
  13932. * http://www.apache.org/licenses/LICENSE-2.0
  13933. *
  13934. * Unless required by applicable law or agreed to in writing,
  13935. * software distributed under the License is distributed on an
  13936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13937. * KIND, either express or implied. See the License for the
  13938. * specific language governing permissions and limitations
  13939. * under the License.
  13940. */
  13941. var round = Math.round;
  13942. var mathMax$1 = Math.max;
  13943. var mathMin$1 = Math.min;
  13944. var EMPTY_OBJ = {};
  13945. var Z2_EMPHASIS_LIFT = 1;
  13946. /**
  13947. * Extend shape with parameters
  13948. */
  13949. function extendShape(opts) {
  13950. return Path.extend(opts);
  13951. }
  13952. /**
  13953. * Extend path
  13954. */
  13955. function extendPath(pathData, opts) {
  13956. return extendFromString(pathData, opts);
  13957. }
  13958. /**
  13959. * Create a path element from path data string
  13960. * @param {string} pathData
  13961. * @param {Object} opts
  13962. * @param {module:zrender/core/BoundingRect} rect
  13963. * @param {string} [layout=cover] 'center' or 'cover'
  13964. */
  13965. function makePath(pathData, opts, rect, layout) {
  13966. var path = createFromString(pathData, opts);
  13967. if (rect) {
  13968. if (layout === 'center') {
  13969. rect = centerGraphic(rect, path.getBoundingRect());
  13970. }
  13971. resizePath(path, rect);
  13972. }
  13973. return path;
  13974. }
  13975. /**
  13976. * Create a image element from image url
  13977. * @param {string} imageUrl image url
  13978. * @param {Object} opts options
  13979. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13980. * @param {string} [layout=cover] 'center' or 'cover'
  13981. */
  13982. function makeImage(imageUrl, rect, layout) {
  13983. var path = new ZImage({
  13984. style: {
  13985. image: imageUrl,
  13986. x: rect.x,
  13987. y: rect.y,
  13988. width: rect.width,
  13989. height: rect.height
  13990. },
  13991. onload: function (img) {
  13992. if (layout === 'center') {
  13993. var boundingRect = {
  13994. width: img.width,
  13995. height: img.height
  13996. };
  13997. path.setStyle(centerGraphic(rect, boundingRect));
  13998. }
  13999. }
  14000. });
  14001. return path;
  14002. }
  14003. /**
  14004. * Get position of centered element in bounding box.
  14005. *
  14006. * @param {Object} rect element local bounding box
  14007. * @param {Object} boundingRect constraint bounding box
  14008. * @return {Object} element position containing x, y, width, and height
  14009. */
  14010. function centerGraphic(rect, boundingRect) {
  14011. // Set rect to center, keep width / height ratio.
  14012. var aspect = boundingRect.width / boundingRect.height;
  14013. var width = rect.height * aspect;
  14014. var height;
  14015. if (width <= rect.width) {
  14016. height = rect.height;
  14017. }
  14018. else {
  14019. width = rect.width;
  14020. height = width / aspect;
  14021. }
  14022. var cx = rect.x + rect.width / 2;
  14023. var cy = rect.y + rect.height / 2;
  14024. return {
  14025. x: cx - width / 2,
  14026. y: cy - height / 2,
  14027. width: width,
  14028. height: height
  14029. };
  14030. }
  14031. var mergePath = mergePath$1;
  14032. /**
  14033. * Resize a path to fit the rect
  14034. * @param {module:zrender/graphic/Path} path
  14035. * @param {Object} rect
  14036. */
  14037. function resizePath(path, rect) {
  14038. if (!path.applyTransform) {
  14039. return;
  14040. }
  14041. var pathRect = path.getBoundingRect();
  14042. var m = pathRect.calculateTransform(rect);
  14043. path.applyTransform(m);
  14044. }
  14045. /**
  14046. * Sub pixel optimize line for canvas
  14047. *
  14048. * @param {Object} param
  14049. * @param {Object} [param.shape]
  14050. * @param {number} [param.shape.x1]
  14051. * @param {number} [param.shape.y1]
  14052. * @param {number} [param.shape.x2]
  14053. * @param {number} [param.shape.y2]
  14054. * @param {Object} [param.style]
  14055. * @param {number} [param.style.lineWidth]
  14056. * @return {Object} Modified param
  14057. */
  14058. function subPixelOptimizeLine(param) {
  14059. var shape = param.shape;
  14060. var lineWidth = param.style.lineWidth;
  14061. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  14062. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  14063. }
  14064. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  14065. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  14066. }
  14067. return param;
  14068. }
  14069. /**
  14070. * Sub pixel optimize rect for canvas
  14071. *
  14072. * @param {Object} param
  14073. * @param {Object} [param.shape]
  14074. * @param {number} [param.shape.x]
  14075. * @param {number} [param.shape.y]
  14076. * @param {number} [param.shape.width]
  14077. * @param {number} [param.shape.height]
  14078. * @param {Object} [param.style]
  14079. * @param {number} [param.style.lineWidth]
  14080. * @return {Object} Modified param
  14081. */
  14082. function subPixelOptimizeRect(param) {
  14083. var shape = param.shape;
  14084. var lineWidth = param.style.lineWidth;
  14085. var originX = shape.x;
  14086. var originY = shape.y;
  14087. var originWidth = shape.width;
  14088. var originHeight = shape.height;
  14089. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  14090. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  14091. shape.width = Math.max(
  14092. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  14093. originWidth === 0 ? 0 : 1
  14094. );
  14095. shape.height = Math.max(
  14096. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  14097. originHeight === 0 ? 0 : 1
  14098. );
  14099. return param;
  14100. }
  14101. /**
  14102. * Sub pixel optimize for canvas
  14103. *
  14104. * @param {number} position Coordinate, such as x, y
  14105. * @param {number} lineWidth Should be nonnegative integer.
  14106. * @param {boolean=} positiveOrNegative Default false (negative).
  14107. * @return {number} Optimized position.
  14108. */
  14109. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14110. // Assure that (position + lineWidth / 2) is near integer edge,
  14111. // otherwise line will be fuzzy in canvas.
  14112. var doubledPosition = round(position * 2);
  14113. return (doubledPosition + round(lineWidth)) % 2 === 0
  14114. ? doubledPosition / 2
  14115. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14116. }
  14117. function hasFillOrStroke(fillOrStroke) {
  14118. return fillOrStroke != null && fillOrStroke !== 'none';
  14119. }
  14120. // Most lifted color are duplicated.
  14121. var liftedColorMap = createHashMap();
  14122. var liftedColorCount = 0;
  14123. function liftColor(color) {
  14124. if (typeof color !== 'string') {
  14125. return color;
  14126. }
  14127. var liftedColor = liftedColorMap.get(color);
  14128. if (!liftedColor) {
  14129. liftedColor = lift(color, -0.1);
  14130. if (liftedColorCount < 10000) {
  14131. liftedColorMap.set(color, liftedColor);
  14132. liftedColorCount++;
  14133. }
  14134. }
  14135. return liftedColor;
  14136. }
  14137. function cacheElementStl(el) {
  14138. if (!el.__hoverStlDirty) {
  14139. return;
  14140. }
  14141. el.__hoverStlDirty = false;
  14142. var hoverStyle = el.__hoverStl;
  14143. if (!hoverStyle) {
  14144. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14145. return;
  14146. }
  14147. var normalStyle = el.__cachedNormalStl = {};
  14148. el.__cachedNormalZ2 = el.z2;
  14149. var elStyle = el.style;
  14150. for (var name in hoverStyle) {
  14151. // See comment in `doSingleEnterHover`.
  14152. if (hoverStyle[name] != null) {
  14153. normalStyle[name] = elStyle[name];
  14154. }
  14155. }
  14156. // Always cache fill and stroke to normalStyle for lifting color.
  14157. normalStyle.fill = elStyle.fill;
  14158. normalStyle.stroke = elStyle.stroke;
  14159. }
  14160. function doSingleEnterHover(el) {
  14161. var hoverStl = el.__hoverStl;
  14162. if (!hoverStl || el.__highlighted) {
  14163. return;
  14164. }
  14165. var useHoverLayer = el.useHoverLayer;
  14166. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14167. var zr = el.__zr;
  14168. if (!zr && useHoverLayer) {
  14169. return;
  14170. }
  14171. var elTarget = el;
  14172. var targetStyle = el.style;
  14173. if (useHoverLayer) {
  14174. elTarget = zr.addHover(el);
  14175. targetStyle = elTarget.style;
  14176. }
  14177. rollbackDefaultTextStyle(targetStyle);
  14178. if (!useHoverLayer) {
  14179. cacheElementStl(elTarget);
  14180. }
  14181. // styles can be:
  14182. // {
  14183. // label: {
  14184. // show: false,
  14185. // position: 'outside',
  14186. // fontSize: 18
  14187. // },
  14188. // emphasis: {
  14189. // label: {
  14190. // show: true
  14191. // }
  14192. // }
  14193. // },
  14194. // where properties of `emphasis` may not appear in `normal`. We previously use
  14195. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14196. // But consider rich text and setOption in merge mode, it is impossible to cover
  14197. // all properties in merge. So we use merge mode when setting style here, where
  14198. // only properties that is not `null/undefined` can be set. The disadventage:
  14199. // null/undefined can not be used to remove style any more in `emphasis`.
  14200. targetStyle.extendFrom(hoverStl);
  14201. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14202. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14203. applyDefaultTextStyle(targetStyle);
  14204. if (!useHoverLayer) {
  14205. el.dirty(false);
  14206. el.z2 += Z2_EMPHASIS_LIFT;
  14207. }
  14208. }
  14209. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14210. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14211. targetStyle[prop] = liftColor(targetStyle[prop]);
  14212. }
  14213. }
  14214. function doSingleLeaveHover(el) {
  14215. var highlighted = el.__highlighted;
  14216. if (!highlighted) {
  14217. return;
  14218. }
  14219. el.__highlighted = false;
  14220. if (highlighted === 'layer') {
  14221. el.__zr && el.__zr.removeHover(el);
  14222. }
  14223. else if (highlighted) {
  14224. var style = el.style;
  14225. var normalStl = el.__cachedNormalStl;
  14226. if (normalStl) {
  14227. rollbackDefaultTextStyle(style);
  14228. // Consider null/undefined value, should use
  14229. // `setStyle` but not `extendFrom(stl, true)`.
  14230. el.setStyle(normalStl);
  14231. applyDefaultTextStyle(style);
  14232. }
  14233. // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14234. // when `el` is on emphasis state. So here by comparing with 1, we try
  14235. // hard to make the bug case rare.
  14236. var normalZ2 = el.__cachedNormalZ2;
  14237. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14238. el.z2 = normalZ2;
  14239. }
  14240. }
  14241. }
  14242. function traverseCall(el, method) {
  14243. el.isGroup
  14244. ? el.traverse(function (child) {
  14245. !child.isGroup && method(child);
  14246. })
  14247. : method(el);
  14248. }
  14249. /**
  14250. * Set hover style (namely "emphasis style") of element, based on the current
  14251. * style of the given `el`.
  14252. * This method should be called after all of the normal styles have been adopted
  14253. * to the `el`. See the reason on `setHoverStyle`.
  14254. *
  14255. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14256. * @param {Object|boolean} [hoverStl] The specified hover style.
  14257. * If set as `false`, disable the hover style.
  14258. * Similarly, The `el.hoverStyle` can alse be set
  14259. * as `false` to disable the hover style.
  14260. * Otherwise, use the default hover style if not provided.
  14261. * @param {Object} [opt]
  14262. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`
  14263. */
  14264. function setElementHoverStyle(el, hoverStl) {
  14265. // For performance consideration, it might be better to make the "hover style" only the
  14266. // difference properties from the "normal style", but not a entire copy of all styles.
  14267. hoverStl = el.__hoverStl = hoverStl !== false && (hoverStl || {});
  14268. el.__hoverStlDirty = true;
  14269. // FIXME
  14270. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14271. // It probably should be saved on `data` of series. Consider the cases:
  14272. // (1) A highlighted elements are moved out of the view port and re-enter
  14273. // again by dataZoom.
  14274. // (2) call `setOption` and replace elements totally when they are highlighted.
  14275. if (el.__highlighted) {
  14276. // Consider the case:
  14277. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14278. // should be adapted to the `el`. Notice here new "normal styles" should have
  14279. // been set outside and the cached "normal style" is out of date.
  14280. el.__cachedNormalStl = null;
  14281. // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14282. // of this method. In most cases, `z2` is not set and hover style should be able
  14283. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14284. // `doSingleLeaveHover` for details.
  14285. doSingleLeaveHover(el);
  14286. doSingleEnterHover(el);
  14287. }
  14288. }
  14289. /**
  14290. * Emphasis (called by API) has higher priority than `mouseover`.
  14291. * When element has been called to be entered emphasis, mouse over
  14292. * should not trigger the highlight effect (for example, animation
  14293. * scale) again, and `mouseout` should not downplay the highlight
  14294. * effect. So the listener of `mouseover` and `mouseout` should
  14295. * check `isInEmphasis`.
  14296. *
  14297. * @param {module:zrender/Element} el
  14298. * @return {boolean}
  14299. */
  14300. function isInEmphasis(el) {
  14301. return el && el.__isEmphasisEntered;
  14302. }
  14303. function onElementMouseOver(e) {
  14304. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14305. return;
  14306. }
  14307. // Only if element is not in emphasis status
  14308. !this.__isEmphasisEntered && traverseCall(this, doSingleEnterHover);
  14309. }
  14310. function onElementMouseOut(e) {
  14311. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14312. return;
  14313. }
  14314. // Only if element is not in emphasis status
  14315. !this.__isEmphasisEntered && traverseCall(this, doSingleLeaveHover);
  14316. }
  14317. function enterEmphasis() {
  14318. this.__isEmphasisEntered = true;
  14319. traverseCall(this, doSingleEnterHover);
  14320. }
  14321. function leaveEmphasis() {
  14322. this.__isEmphasisEntered = false;
  14323. traverseCall(this, doSingleLeaveHover);
  14324. }
  14325. /**
  14326. * Set hover style (namely "emphasis style") of element,
  14327. * based on the current style of the given `el`.
  14328. *
  14329. * (1)
  14330. * **CONSTRAINTS** for this method:
  14331. * <A> This method MUST be called after all of the normal styles having been adopted
  14332. * to the `el`.
  14333. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14334. * "normal style" having been set to the el.
  14335. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14336. * a default hover style).
  14337. *
  14338. * The reason: this method treat the current style of the `el` as the "normal style"
  14339. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14340. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14341. * logic, where the el should shift from the original emphasis style to the new
  14342. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14343. *
  14344. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14345. * not found a better solution yet to fit the backward compatibility, performance and
  14346. * the current programming style.
  14347. *
  14348. * (2)
  14349. * Call the method for a "root" element once. Do not call it for each descendants.
  14350. * If the descendants elemenets of a group has itself hover style different from the
  14351. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14352. * not call this method for them.
  14353. *
  14354. * @param {module:zrender/Element} el
  14355. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14356. * @param {Object} [opt]
  14357. * @param {boolean} [opt.hoverSilentOnTouch=false] See `graphic.setAsHoverStyleTrigger`.
  14358. */
  14359. function setHoverStyle(el, hoverStyle, opt) {
  14360. el.isGroup
  14361. ? el.traverse(function (child) {
  14362. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14363. // Often used when item group has a label element and it's hoverStyle is different
  14364. !child.isGroup && setElementHoverStyle(child, child.hoverStyle || hoverStyle);
  14365. })
  14366. : setElementHoverStyle(el, el.hoverStyle || hoverStyle);
  14367. setAsHoverStyleTrigger(el, opt);
  14368. }
  14369. /**
  14370. * @param {Object|boolean} [opt] If `false`, means disable trigger.
  14371. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14372. * In touch device, mouseover event will be trigger on touchstart event
  14373. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14374. * conveniently use hoverStyle when tap on touch screen without additional
  14375. * code for compatibility.
  14376. * But if the chart/component has select feature, which usually also use
  14377. * hoverStyle, there might be conflict between 'select-highlight' and
  14378. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14379. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14380. * on touch device.
  14381. */
  14382. function setAsHoverStyleTrigger(el, opt) {
  14383. var disable = opt === false;
  14384. el.__hoverSilentOnTouch = opt != null && opt.hoverSilentOnTouch;
  14385. // Simple optimize, since this method might be
  14386. // called for each elements of a group in some cases.
  14387. if (!disable || el.__hoverStyleTrigger) {
  14388. var method = disable ? 'off' : 'on';
  14389. // Duplicated function will be auto-ignored, see Eventful.js.
  14390. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut);
  14391. // Emphasis, normal can be triggered manually
  14392. el[method]('emphasis', enterEmphasis)[method]('normal', leaveEmphasis);
  14393. el.__hoverStyleTrigger = !disable;
  14394. }
  14395. }
  14396. /**
  14397. * See more info in `setTextStyleCommon`.
  14398. * @param {Object|module:zrender/graphic/Style} normalStyle
  14399. * @param {Object} emphasisStyle
  14400. * @param {module:echarts/model/Model} normalModel
  14401. * @param {module:echarts/model/Model} emphasisModel
  14402. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14403. * @param {string|Function} [opt.defaultText]
  14404. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14405. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14406. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14407. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14408. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14409. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14410. * @param {Object} [normalSpecified]
  14411. * @param {Object} [emphasisSpecified]
  14412. */
  14413. function setLabelStyle(
  14414. normalStyle, emphasisStyle,
  14415. normalModel, emphasisModel,
  14416. opt,
  14417. normalSpecified, emphasisSpecified
  14418. ) {
  14419. opt = opt || EMPTY_OBJ;
  14420. var labelFetcher = opt.labelFetcher;
  14421. var labelDataIndex = opt.labelDataIndex;
  14422. var labelDimIndex = opt.labelDimIndex;
  14423. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14424. // is not supported util someone requests.
  14425. var showNormal = normalModel.getShallow('show');
  14426. var showEmphasis = emphasisModel.getShallow('show');
  14427. // Consider performance, only fetch label when necessary.
  14428. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14429. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14430. var baseText;
  14431. if (showNormal || showEmphasis) {
  14432. if (labelFetcher) {
  14433. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14434. }
  14435. if (baseText == null) {
  14436. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14437. }
  14438. }
  14439. var normalStyleText = showNormal ? baseText : null;
  14440. var emphasisStyleText = showEmphasis
  14441. ? retrieve2(
  14442. labelFetcher
  14443. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14444. : null,
  14445. baseText
  14446. )
  14447. : null;
  14448. // Optimize: If style.text is null, text will not be drawn.
  14449. if (normalStyleText != null || emphasisStyleText != null) {
  14450. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14451. // values have to be set on `normalStyle`.
  14452. // If we set default values on `emphasisStyle`, consider case:
  14453. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14454. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14455. // Then the 'red' will not work on emphasis.
  14456. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14457. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14458. }
  14459. normalStyle.text = normalStyleText;
  14460. emphasisStyle.text = emphasisStyleText;
  14461. }
  14462. /**
  14463. * Set basic textStyle properties.
  14464. * See more info in `setTextStyleCommon`.
  14465. * @param {Object|module:zrender/graphic/Style} textStyle
  14466. * @param {module:echarts/model/Model} model
  14467. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14468. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14469. * @param {boolean} [isEmphasis]
  14470. */
  14471. function setTextStyle(
  14472. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14473. ) {
  14474. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14475. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14476. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14477. return textStyle;
  14478. }
  14479. /**
  14480. * Set text option in the style.
  14481. * See more info in `setTextStyleCommon`.
  14482. * @deprecated
  14483. * @param {Object} textStyle
  14484. * @param {module:echarts/model/Model} labelModel
  14485. * @param {string|boolean} defaultColor Default text color.
  14486. * If set as false, it will be processed as a emphasis style.
  14487. */
  14488. function setText(textStyle, labelModel, defaultColor) {
  14489. var opt = {isRectText: true};
  14490. var isEmphasis;
  14491. if (defaultColor === false) {
  14492. isEmphasis = true;
  14493. }
  14494. else {
  14495. // Support setting color as 'auto' to get visual color.
  14496. opt.autoColor = defaultColor;
  14497. }
  14498. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14499. // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14500. }
  14501. /**
  14502. * The uniform entry of set text style, that is, retrieve style definitions
  14503. * from `model` and set to `textStyle` object.
  14504. *
  14505. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14506. * properties will be set. (Consider the states of normal and emphasis and
  14507. * default value can be adopted, merge would make the logic too complicated
  14508. * to manage.)
  14509. *
  14510. * The `textStyle` object can either be a plain object or an instance of
  14511. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14512. * After this mothod called, the `textStyle` object can then be used in
  14513. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14514. *
  14515. * Default value will be adopted and `insideRollbackOpt` will be created.
  14516. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14517. *
  14518. * opt: {
  14519. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14520. * isRectText: boolean,
  14521. * autoColor: string, specify a color when color is 'auto',
  14522. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14523. * If autoColor specified, it is used as default textFill.
  14524. * useInsideStyle:
  14525. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14526. * if `textFill` is not specified.
  14527. * `false`: Do not use inside style.
  14528. * `null/undefined`: use inside style if `isRectText` is true and
  14529. * `textFill` is not specified and textPosition contains `'inside'`.
  14530. * forceRich: boolean
  14531. * }
  14532. */
  14533. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14534. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14535. opt = opt || EMPTY_OBJ;
  14536. if (opt.isRectText) {
  14537. var textPosition = textStyleModel.getShallow('position')
  14538. || (isEmphasis ? null : 'inside');
  14539. // 'outside' is not a valid zr textPostion value, but used
  14540. // in bar series, and magric type should be considered.
  14541. textPosition === 'outside' && (textPosition = 'top');
  14542. textStyle.textPosition = textPosition;
  14543. textStyle.textOffset = textStyleModel.getShallow('offset');
  14544. var labelRotate = textStyleModel.getShallow('rotate');
  14545. labelRotate != null && (labelRotate *= Math.PI / 180);
  14546. textStyle.textRotation = labelRotate;
  14547. textStyle.textDistance = retrieve2(
  14548. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14549. );
  14550. }
  14551. var ecModel = textStyleModel.ecModel;
  14552. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14553. // Consider case:
  14554. // {
  14555. // data: [{
  14556. // value: 12,
  14557. // label: {
  14558. // rich: {
  14559. // // no 'a' here but using parent 'a'.
  14560. // }
  14561. // }
  14562. // }],
  14563. // rich: {
  14564. // a: { ... }
  14565. // }
  14566. // }
  14567. var richItemNames = getRichItemNames(textStyleModel);
  14568. var richResult;
  14569. if (richItemNames) {
  14570. richResult = {};
  14571. for (var name in richItemNames) {
  14572. if (richItemNames.hasOwnProperty(name)) {
  14573. // Cascade is supported in rich.
  14574. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14575. // In rich, never `disableBox`.
  14576. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14577. }
  14578. }
  14579. }
  14580. textStyle.rich = richResult;
  14581. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14582. if (opt.forceRich && !opt.textStyle) {
  14583. opt.textStyle = {};
  14584. }
  14585. return textStyle;
  14586. }
  14587. // Consider case:
  14588. // {
  14589. // data: [{
  14590. // value: 12,
  14591. // label: {
  14592. // rich: {
  14593. // // no 'a' here but using parent 'a'.
  14594. // }
  14595. // }
  14596. // }],
  14597. // rich: {
  14598. // a: { ... }
  14599. // }
  14600. // }
  14601. function getRichItemNames(textStyleModel) {
  14602. // Use object to remove duplicated names.
  14603. var richItemNameMap;
  14604. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14605. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14606. if (rich) {
  14607. richItemNameMap = richItemNameMap || {};
  14608. for (var name in rich) {
  14609. if (rich.hasOwnProperty(name)) {
  14610. richItemNameMap[name] = 1;
  14611. }
  14612. }
  14613. }
  14614. textStyleModel = textStyleModel.parentModel;
  14615. }
  14616. return richItemNameMap;
  14617. }
  14618. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14619. // In merge mode, default value should not be given.
  14620. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14621. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14622. || globalTextStyle.color;
  14623. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14624. || globalTextStyle.textBorderColor;
  14625. textStyle.textStrokeWidth = retrieve2(
  14626. textStyleModel.getShallow('textBorderWidth'),
  14627. globalTextStyle.textBorderWidth
  14628. );
  14629. // Save original textPosition, because style.textPosition will be repalced by
  14630. // real location (like [10, 30]) in zrender.
  14631. textStyle.insideRawTextPosition = textStyle.textPosition;
  14632. if (!isEmphasis) {
  14633. if (isBlock) {
  14634. textStyle.insideRollbackOpt = opt;
  14635. applyDefaultTextStyle(textStyle);
  14636. }
  14637. // Set default finally.
  14638. if (textStyle.textFill == null) {
  14639. textStyle.textFill = opt.autoColor;
  14640. }
  14641. }
  14642. // Do not use `getFont` here, because merge should be supported, where
  14643. // part of these properties may be changed in emphasis style, and the
  14644. // others should remain their original value got from normal style.
  14645. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14646. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14647. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14648. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14649. textStyle.textAlign = textStyleModel.getShallow('align');
  14650. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14651. || textStyleModel.getShallow('baseline');
  14652. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14653. textStyle.textWidth = textStyleModel.getShallow('width');
  14654. textStyle.textHeight = textStyleModel.getShallow('height');
  14655. textStyle.textTag = textStyleModel.getShallow('tag');
  14656. if (!isBlock || !opt.disableBox) {
  14657. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14658. textStyle.textPadding = textStyleModel.getShallow('padding');
  14659. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14660. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14661. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14662. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14663. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14664. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14665. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14666. }
  14667. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14668. || globalTextStyle.textShadowColor;
  14669. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14670. || globalTextStyle.textShadowBlur;
  14671. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14672. || globalTextStyle.textShadowOffsetX;
  14673. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14674. || globalTextStyle.textShadowOffsetY;
  14675. }
  14676. function getAutoColor(color, opt) {
  14677. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14678. }
  14679. /**
  14680. * Give some default value to the input `textStyle` object, based on the current settings
  14681. * in this `textStyle` object.
  14682. *
  14683. * The Scenario:
  14684. * when text position is `inside` and `textFill` is not specified, we show
  14685. * text border by default for better view. But it should be considered that text position
  14686. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  14687. * restore the style.
  14688. *
  14689. * Usage (& NOTICE):
  14690. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  14691. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  14692. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  14693. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  14694. * does, `rollbackDefaultTextStyle` is not needed to be called).
  14695. */
  14696. function applyDefaultTextStyle(textStyle) {
  14697. var opt = textStyle.insideRollbackOpt;
  14698. // Only `insideRollbackOpt` created (in `setTextStyleCommon`),
  14699. // applyDefaultTextStyle works.
  14700. if (!opt || textStyle.textFill != null) {
  14701. return;
  14702. }
  14703. var useInsideStyle = opt.useInsideStyle;
  14704. var textPosition = textStyle.insideRawTextPosition;
  14705. var insideRollback;
  14706. var autoColor = opt.autoColor;
  14707. if (useInsideStyle !== false
  14708. && (useInsideStyle === true
  14709. || (opt.isRectText
  14710. && textPosition
  14711. // textPosition can be [10, 30]
  14712. && typeof textPosition === 'string'
  14713. && textPosition.indexOf('inside') >= 0
  14714. )
  14715. )
  14716. ) {
  14717. insideRollback = {
  14718. textFill: null,
  14719. textStroke: textStyle.textStroke,
  14720. textStrokeWidth: textStyle.textStrokeWidth
  14721. };
  14722. textStyle.textFill = '#fff';
  14723. // Consider text with #fff overflow its container.
  14724. if (textStyle.textStroke == null) {
  14725. textStyle.textStroke = autoColor;
  14726. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14727. }
  14728. }
  14729. else if (autoColor != null) {
  14730. insideRollback = {textFill: null};
  14731. textStyle.textFill = autoColor;
  14732. }
  14733. // Always set `insideRollback`, for clearing previous.
  14734. if (insideRollback) {
  14735. textStyle.insideRollback = insideRollback;
  14736. }
  14737. }
  14738. /**
  14739. * Consider the case: in a scatter,
  14740. * label: {
  14741. * normal: {position: 'inside'},
  14742. * emphasis: {position: 'top'}
  14743. * }
  14744. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  14745. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  14746. * should be retured to 'autoColor', but not keep '#fff'.
  14747. */
  14748. function rollbackDefaultTextStyle(style) {
  14749. var insideRollback = style.insideRollback;
  14750. if (insideRollback) {
  14751. style.textFill = insideRollback.textFill;
  14752. style.textStroke = insideRollback.textStroke;
  14753. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14754. style.insideRollback = null;
  14755. }
  14756. }
  14757. function getFont(opt, ecModel) {
  14758. // ecModel or default text style model.
  14759. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14760. return trim([
  14761. // FIXME in node-canvas fontWeight is before fontStyle
  14762. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14763. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14764. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14765. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14766. ].join(' '));
  14767. }
  14768. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14769. if (typeof dataIndex === 'function') {
  14770. cb = dataIndex;
  14771. dataIndex = null;
  14772. }
  14773. // Do not check 'animation' property directly here. Consider this case:
  14774. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14775. // but its parent model (`seriesModel`) does.
  14776. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14777. if (animationEnabled) {
  14778. var postfix = isUpdate ? 'Update' : '';
  14779. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14780. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14781. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14782. if (typeof animationDelay === 'function') {
  14783. animationDelay = animationDelay(
  14784. dataIndex,
  14785. animatableModel.getAnimationDelayParams
  14786. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14787. : null
  14788. );
  14789. }
  14790. if (typeof duration === 'function') {
  14791. duration = duration(dataIndex);
  14792. }
  14793. duration > 0
  14794. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14795. : (el.stopAnimation(), el.attr(props), cb && cb());
  14796. }
  14797. else {
  14798. el.stopAnimation();
  14799. el.attr(props);
  14800. cb && cb();
  14801. }
  14802. }
  14803. /**
  14804. * Update graphic element properties with or without animation according to the
  14805. * configuration in series.
  14806. *
  14807. * Caution: this method will stop previous animation.
  14808. * So if do not use this method to one element twice before
  14809. * animation starts, unless you know what you are doing.
  14810. *
  14811. * @param {module:zrender/Element} el
  14812. * @param {Object} props
  14813. * @param {module:echarts/model/Model} [animatableModel]
  14814. * @param {number} [dataIndex]
  14815. * @param {Function} [cb]
  14816. * @example
  14817. * graphic.updateProps(el, {
  14818. * position: [100, 100]
  14819. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14820. * // Or
  14821. * graphic.updateProps(el, {
  14822. * position: [100, 100]
  14823. * }, seriesModel, function () { console.log('Animation done!'); });
  14824. */
  14825. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14826. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14827. }
  14828. /**
  14829. * Init graphic element properties with or without animation according to the
  14830. * configuration in series.
  14831. *
  14832. * Caution: this method will stop previous animation.
  14833. * So if do not use this method to one element twice before
  14834. * animation starts, unless you know what you are doing.
  14835. *
  14836. * @param {module:zrender/Element} el
  14837. * @param {Object} props
  14838. * @param {module:echarts/model/Model} [animatableModel]
  14839. * @param {number} [dataIndex]
  14840. * @param {Function} cb
  14841. */
  14842. function initProps(el, props, animatableModel, dataIndex, cb) {
  14843. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14844. }
  14845. /**
  14846. * Get transform matrix of target (param target),
  14847. * in coordinate of its ancestor (param ancestor)
  14848. *
  14849. * @param {module:zrender/mixin/Transformable} target
  14850. * @param {module:zrender/mixin/Transformable} [ancestor]
  14851. */
  14852. function getTransform(target, ancestor) {
  14853. var mat = identity([]);
  14854. while (target && target !== ancestor) {
  14855. mul$1(mat, target.getLocalTransform(), mat);
  14856. target = target.parent;
  14857. }
  14858. return mat;
  14859. }
  14860. /**
  14861. * Apply transform to an vertex.
  14862. * @param {Array.<number>} target [x, y]
  14863. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14864. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14865. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14866. * @param {boolean=} invert Whether use invert matrix.
  14867. * @return {Array.<number>} [x, y]
  14868. */
  14869. function applyTransform$1(target, transform, invert$$1) {
  14870. if (transform && !isArrayLike(transform)) {
  14871. transform = Transformable.getLocalTransform(transform);
  14872. }
  14873. if (invert$$1) {
  14874. transform = invert([], transform);
  14875. }
  14876. return applyTransform([], target, transform);
  14877. }
  14878. /**
  14879. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14880. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14881. * @param {boolean=} invert Whether use invert matrix.
  14882. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14883. */
  14884. function transformDirection(direction, transform, invert$$1) {
  14885. // Pick a base, ensure that transform result will not be (0, 0).
  14886. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14887. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14888. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14889. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14890. var vertex = [
  14891. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14892. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14893. ];
  14894. vertex = applyTransform$1(vertex, transform, invert$$1);
  14895. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14896. ? (vertex[0] > 0 ? 'right' : 'left')
  14897. : (vertex[1] > 0 ? 'bottom' : 'top');
  14898. }
  14899. /**
  14900. * Apply group transition animation from g1 to g2.
  14901. * If no animatableModel, no animation.
  14902. */
  14903. function groupTransition(g1, g2, animatableModel, cb) {
  14904. if (!g1 || !g2) {
  14905. return;
  14906. }
  14907. function getElMap(g) {
  14908. var elMap = {};
  14909. g.traverse(function (el) {
  14910. if (!el.isGroup && el.anid) {
  14911. elMap[el.anid] = el;
  14912. }
  14913. });
  14914. return elMap;
  14915. }
  14916. function getAnimatableProps(el) {
  14917. var obj = {
  14918. position: clone$1(el.position),
  14919. rotation: el.rotation
  14920. };
  14921. if (el.shape) {
  14922. obj.shape = extend({}, el.shape);
  14923. }
  14924. return obj;
  14925. }
  14926. var elMap1 = getElMap(g1);
  14927. g2.traverse(function (el) {
  14928. if (!el.isGroup && el.anid) {
  14929. var oldEl = elMap1[el.anid];
  14930. if (oldEl) {
  14931. var newProp = getAnimatableProps(el);
  14932. el.attr(getAnimatableProps(oldEl));
  14933. updateProps(el, newProp, animatableModel, el.dataIndex);
  14934. }
  14935. // else {
  14936. // if (el.previousProps) {
  14937. // graphic.updateProps
  14938. // }
  14939. // }
  14940. }
  14941. });
  14942. }
  14943. /**
  14944. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14945. * @param {Object} rect {x, y, width, height}
  14946. * @return {Array.<Array.<number>>} A new clipped points.
  14947. */
  14948. function clipPointsByRect(points, rect) {
  14949. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14950. // and when element have border.
  14951. return map(points, function (point) {
  14952. var x = point[0];
  14953. x = mathMax$1(x, rect.x);
  14954. x = mathMin$1(x, rect.x + rect.width);
  14955. var y = point[1];
  14956. y = mathMax$1(y, rect.y);
  14957. y = mathMin$1(y, rect.y + rect.height);
  14958. return [x, y];
  14959. });
  14960. }
  14961. /**
  14962. * @param {Object} targetRect {x, y, width, height}
  14963. * @param {Object} rect {x, y, width, height}
  14964. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14965. */
  14966. function clipRectByRect(targetRect, rect) {
  14967. var x = mathMax$1(targetRect.x, rect.x);
  14968. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14969. var y = mathMax$1(targetRect.y, rect.y);
  14970. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14971. // If the total rect is cliped, nothing, including the border,
  14972. // should be painted. So return undefined.
  14973. if (x2 >= x && y2 >= y) {
  14974. return {
  14975. x: x,
  14976. y: y,
  14977. width: x2 - x,
  14978. height: y2 - y
  14979. };
  14980. }
  14981. }
  14982. /**
  14983. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14984. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14985. * @param {Object} [rect] {x, y, width, height}
  14986. * @return {module:zrender/Element} Icon path or image element.
  14987. */
  14988. function createIcon(iconStr, opt, rect) {
  14989. opt = extend({rectHover: true}, opt);
  14990. var style = opt.style = {strokeNoScale: true};
  14991. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14992. if (iconStr) {
  14993. return iconStr.indexOf('image://') === 0
  14994. ? (
  14995. style.image = iconStr.slice(8),
  14996. defaults(style, rect),
  14997. new ZImage(opt)
  14998. )
  14999. : (
  15000. makePath(
  15001. iconStr.replace('path://', ''),
  15002. opt,
  15003. rect,
  15004. 'center'
  15005. )
  15006. );
  15007. }
  15008. }
  15009. var graphic = (Object.freeze || Object)({
  15010. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15011. extendShape: extendShape,
  15012. extendPath: extendPath,
  15013. makePath: makePath,
  15014. makeImage: makeImage,
  15015. mergePath: mergePath,
  15016. resizePath: resizePath,
  15017. subPixelOptimizeLine: subPixelOptimizeLine,
  15018. subPixelOptimizeRect: subPixelOptimizeRect,
  15019. subPixelOptimize: subPixelOptimize,
  15020. setElementHoverStyle: setElementHoverStyle,
  15021. isInEmphasis: isInEmphasis,
  15022. setHoverStyle: setHoverStyle,
  15023. setAsHoverStyleTrigger: setAsHoverStyleTrigger,
  15024. setLabelStyle: setLabelStyle,
  15025. setTextStyle: setTextStyle,
  15026. setText: setText,
  15027. getFont: getFont,
  15028. updateProps: updateProps,
  15029. initProps: initProps,
  15030. getTransform: getTransform,
  15031. applyTransform: applyTransform$1,
  15032. transformDirection: transformDirection,
  15033. groupTransition: groupTransition,
  15034. clipPointsByRect: clipPointsByRect,
  15035. clipRectByRect: clipRectByRect,
  15036. createIcon: createIcon,
  15037. Group: Group,
  15038. Image: ZImage,
  15039. Text: Text,
  15040. Circle: Circle,
  15041. Sector: Sector,
  15042. Ring: Ring,
  15043. Polygon: Polygon,
  15044. Polyline: Polyline,
  15045. Rect: Rect,
  15046. Line: Line,
  15047. BezierCurve: BezierCurve,
  15048. Arc: Arc,
  15049. IncrementalDisplayable: IncrementalDisplayble,
  15050. CompoundPath: CompoundPath,
  15051. LinearGradient: LinearGradient,
  15052. RadialGradient: RadialGradient,
  15053. BoundingRect: BoundingRect
  15054. });
  15055. /*
  15056. * Licensed to the Apache Software Foundation (ASF) under one
  15057. * or more contributor license agreements. See the NOTICE file
  15058. * distributed with this work for additional information
  15059. * regarding copyright ownership. The ASF licenses this file
  15060. * to you under the Apache License, Version 2.0 (the
  15061. * "License"); you may not use this file except in compliance
  15062. * with the License. You may obtain a copy of the License at
  15063. *
  15064. * http://www.apache.org/licenses/LICENSE-2.0
  15065. *
  15066. * Unless required by applicable law or agreed to in writing,
  15067. * software distributed under the License is distributed on an
  15068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15069. * KIND, either express or implied. See the License for the
  15070. * specific language governing permissions and limitations
  15071. * under the License.
  15072. */
  15073. var PATH_COLOR = ['textStyle', 'color'];
  15074. var textStyleMixin = {
  15075. /**
  15076. * Get color property or get color from option.textStyle.color
  15077. * @param {boolean} [isEmphasis]
  15078. * @return {string}
  15079. */
  15080. getTextColor: function (isEmphasis) {
  15081. var ecModel = this.ecModel;
  15082. return this.getShallow('color')
  15083. || (
  15084. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  15085. );
  15086. },
  15087. /**
  15088. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15089. * @return {string}
  15090. */
  15091. getFont: function () {
  15092. return getFont({
  15093. fontStyle: this.getShallow('fontStyle'),
  15094. fontWeight: this.getShallow('fontWeight'),
  15095. fontSize: this.getShallow('fontSize'),
  15096. fontFamily: this.getShallow('fontFamily')
  15097. }, this.ecModel);
  15098. },
  15099. getTextRect: function (text) {
  15100. return getBoundingRect(
  15101. text,
  15102. this.getFont(),
  15103. this.getShallow('align'),
  15104. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  15105. this.getShallow('padding'),
  15106. this.getShallow('lineHeight'),
  15107. this.getShallow('rich'),
  15108. this.getShallow('truncateText')
  15109. );
  15110. }
  15111. };
  15112. /*
  15113. * Licensed to the Apache Software Foundation (ASF) under one
  15114. * or more contributor license agreements. See the NOTICE file
  15115. * distributed with this work for additional information
  15116. * regarding copyright ownership. The ASF licenses this file
  15117. * to you under the Apache License, Version 2.0 (the
  15118. * "License"); you may not use this file except in compliance
  15119. * with the License. You may obtain a copy of the License at
  15120. *
  15121. * http://www.apache.org/licenses/LICENSE-2.0
  15122. *
  15123. * Unless required by applicable law or agreed to in writing,
  15124. * software distributed under the License is distributed on an
  15125. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15126. * KIND, either express or implied. See the License for the
  15127. * specific language governing permissions and limitations
  15128. * under the License.
  15129. */
  15130. var getItemStyle = makeStyleMapper(
  15131. [
  15132. ['fill', 'color'],
  15133. ['stroke', 'borderColor'],
  15134. ['lineWidth', 'borderWidth'],
  15135. ['opacity'],
  15136. ['shadowBlur'],
  15137. ['shadowOffsetX'],
  15138. ['shadowOffsetY'],
  15139. ['shadowColor'],
  15140. ['textPosition'],
  15141. ['textAlign']
  15142. ]
  15143. );
  15144. var itemStyleMixin = {
  15145. getItemStyle: function (excludes, includes) {
  15146. var style = getItemStyle(this, excludes, includes);
  15147. var lineDash = this.getBorderLineDash();
  15148. lineDash && (style.lineDash = lineDash);
  15149. return style;
  15150. },
  15151. getBorderLineDash: function () {
  15152. var lineType = this.get('borderType');
  15153. return (lineType === 'solid' || lineType == null) ? null
  15154. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  15155. }
  15156. };
  15157. /*
  15158. * Licensed to the Apache Software Foundation (ASF) under one
  15159. * or more contributor license agreements. See the NOTICE file
  15160. * distributed with this work for additional information
  15161. * regarding copyright ownership. The ASF licenses this file
  15162. * to you under the Apache License, Version 2.0 (the
  15163. * "License"); you may not use this file except in compliance
  15164. * with the License. You may obtain a copy of the License at
  15165. *
  15166. * http://www.apache.org/licenses/LICENSE-2.0
  15167. *
  15168. * Unless required by applicable law or agreed to in writing,
  15169. * software distributed under the License is distributed on an
  15170. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15171. * KIND, either express or implied. See the License for the
  15172. * specific language governing permissions and limitations
  15173. * under the License.
  15174. */
  15175. /**
  15176. * @module echarts/model/Model
  15177. */
  15178. var mixin$1 = mixin;
  15179. var inner = makeInner();
  15180. /**
  15181. * @alias module:echarts/model/Model
  15182. * @constructor
  15183. * @param {Object} [option]
  15184. * @param {module:echarts/model/Model} [parentModel]
  15185. * @param {module:echarts/model/Global} [ecModel]
  15186. */
  15187. function Model(option, parentModel, ecModel) {
  15188. /**
  15189. * @type {module:echarts/model/Model}
  15190. * @readOnly
  15191. */
  15192. this.parentModel = parentModel;
  15193. /**
  15194. * @type {module:echarts/model/Global}
  15195. * @readOnly
  15196. */
  15197. this.ecModel = ecModel;
  15198. /**
  15199. * @type {Object}
  15200. * @protected
  15201. */
  15202. this.option = option;
  15203. // Simple optimization
  15204. // if (this.init) {
  15205. // if (arguments.length <= 4) {
  15206. // this.init(option, parentModel, ecModel, extraOpt);
  15207. // }
  15208. // else {
  15209. // this.init.apply(this, arguments);
  15210. // }
  15211. // }
  15212. }
  15213. Model.prototype = {
  15214. constructor: Model,
  15215. /**
  15216. * Model 的初始化函数
  15217. * @param {Object} option
  15218. */
  15219. init: null,
  15220. /**
  15221. * 从新的 Option merge
  15222. */
  15223. mergeOption: function (option) {
  15224. merge(this.option, option, true);
  15225. },
  15226. /**
  15227. * @param {string|Array.<string>} path
  15228. * @param {boolean} [ignoreParent=false]
  15229. * @return {*}
  15230. */
  15231. get: function (path, ignoreParent) {
  15232. if (path == null) {
  15233. return this.option;
  15234. }
  15235. return doGet(
  15236. this.option,
  15237. this.parsePath(path),
  15238. !ignoreParent && getParent(this, path)
  15239. );
  15240. },
  15241. /**
  15242. * @param {string} key
  15243. * @param {boolean} [ignoreParent=false]
  15244. * @return {*}
  15245. */
  15246. getShallow: function (key, ignoreParent) {
  15247. var option = this.option;
  15248. var val = option == null ? option : option[key];
  15249. var parentModel = !ignoreParent && getParent(this, key);
  15250. if (val == null && parentModel) {
  15251. val = parentModel.getShallow(key);
  15252. }
  15253. return val;
  15254. },
  15255. /**
  15256. * @param {string|Array.<string>} [path]
  15257. * @param {module:echarts/model/Model} [parentModel]
  15258. * @return {module:echarts/model/Model}
  15259. */
  15260. getModel: function (path, parentModel) {
  15261. var obj = path == null
  15262. ? this.option
  15263. : doGet(this.option, path = this.parsePath(path));
  15264. var thisParentModel;
  15265. parentModel = parentModel || (
  15266. (thisParentModel = getParent(this, path))
  15267. && thisParentModel.getModel(path)
  15268. );
  15269. return new Model(obj, parentModel, this.ecModel);
  15270. },
  15271. /**
  15272. * If model has option
  15273. */
  15274. isEmpty: function () {
  15275. return this.option == null;
  15276. },
  15277. restoreData: function () {},
  15278. // Pending
  15279. clone: function () {
  15280. var Ctor = this.constructor;
  15281. return new Ctor(clone(this.option));
  15282. },
  15283. setReadOnly: function (properties) {
  15284. // clazzUtil.setReadOnly(this, properties);
  15285. },
  15286. // If path is null/undefined, return null/undefined.
  15287. parsePath: function (path) {
  15288. if (typeof path === 'string') {
  15289. path = path.split('.');
  15290. }
  15291. return path;
  15292. },
  15293. /**
  15294. * @param {Function} getParentMethod
  15295. * param {Array.<string>|string} path
  15296. * return {module:echarts/model/Model}
  15297. */
  15298. customizeGetParent: function (getParentMethod) {
  15299. inner(this).getParent = getParentMethod;
  15300. },
  15301. isAnimationEnabled: function () {
  15302. if (!env$1.node) {
  15303. if (this.option.animation != null) {
  15304. return !!this.option.animation;
  15305. }
  15306. else if (this.parentModel) {
  15307. return this.parentModel.isAnimationEnabled();
  15308. }
  15309. }
  15310. }
  15311. };
  15312. function doGet(obj, pathArr, parentModel) {
  15313. for (var i = 0; i < pathArr.length; i++) {
  15314. // Ignore empty
  15315. if (!pathArr[i]) {
  15316. continue;
  15317. }
  15318. // obj could be number/string/... (like 0)
  15319. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15320. if (obj == null) {
  15321. break;
  15322. }
  15323. }
  15324. if (obj == null && parentModel) {
  15325. obj = parentModel.get(pathArr);
  15326. }
  15327. return obj;
  15328. }
  15329. // `path` can be null/undefined
  15330. function getParent(model, path) {
  15331. var getParentMethod = inner(model).getParent;
  15332. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15333. }
  15334. // Enable Model.extend.
  15335. enableClassExtend(Model);
  15336. enableClassCheck(Model);
  15337. mixin$1(Model, lineStyleMixin);
  15338. mixin$1(Model, areaStyleMixin);
  15339. mixin$1(Model, textStyleMixin);
  15340. mixin$1(Model, itemStyleMixin);
  15341. /*
  15342. * Licensed to the Apache Software Foundation (ASF) under one
  15343. * or more contributor license agreements. See the NOTICE file
  15344. * distributed with this work for additional information
  15345. * regarding copyright ownership. The ASF licenses this file
  15346. * to you under the Apache License, Version 2.0 (the
  15347. * "License"); you may not use this file except in compliance
  15348. * with the License. You may obtain a copy of the License at
  15349. *
  15350. * http://www.apache.org/licenses/LICENSE-2.0
  15351. *
  15352. * Unless required by applicable law or agreed to in writing,
  15353. * software distributed under the License is distributed on an
  15354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15355. * KIND, either express or implied. See the License for the
  15356. * specific language governing permissions and limitations
  15357. * under the License.
  15358. */
  15359. var base = 0;
  15360. /**
  15361. * @public
  15362. * @param {string} type
  15363. * @return {string}
  15364. */
  15365. function getUID(type) {
  15366. // Considering the case of crossing js context,
  15367. // use Math.random to make id as unique as possible.
  15368. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15369. }
  15370. /**
  15371. * @inner
  15372. */
  15373. function enableSubTypeDefaulter(entity) {
  15374. var subTypeDefaulters = {};
  15375. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15376. componentType = parseClassType$1(componentType);
  15377. subTypeDefaulters[componentType.main] = defaulter;
  15378. };
  15379. entity.determineSubType = function (componentType, option) {
  15380. var type = option.type;
  15381. if (!type) {
  15382. var componentTypeMain = parseClassType$1(componentType).main;
  15383. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15384. type = subTypeDefaulters[componentTypeMain](option);
  15385. }
  15386. }
  15387. return type;
  15388. };
  15389. return entity;
  15390. }
  15391. /**
  15392. * Topological travel on Activity Network (Activity On Vertices).
  15393. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15394. *
  15395. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15396. *
  15397. * If there is circle dependencey, Error will be thrown.
  15398. *
  15399. */
  15400. function enableTopologicalTravel(entity, dependencyGetter) {
  15401. /**
  15402. * @public
  15403. * @param {Array.<string>} targetNameList Target Component type list.
  15404. * Can be ['aa', 'bb', 'aa.xx']
  15405. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15406. * @param {Function} callback Params: componentType, dependencies.
  15407. * @param {Object} context Scope of callback.
  15408. */
  15409. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15410. if (!targetNameList.length) {
  15411. return;
  15412. }
  15413. var result = makeDepndencyGraph(fullNameList);
  15414. var graph = result.graph;
  15415. var stack = result.noEntryList;
  15416. var targetNameSet = {};
  15417. each$1(targetNameList, function (name) {
  15418. targetNameSet[name] = true;
  15419. });
  15420. while (stack.length) {
  15421. var currComponentType = stack.pop();
  15422. var currVertex = graph[currComponentType];
  15423. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15424. if (isInTargetNameSet) {
  15425. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15426. delete targetNameSet[currComponentType];
  15427. }
  15428. each$1(
  15429. currVertex.successor,
  15430. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15431. );
  15432. }
  15433. each$1(targetNameSet, function () {
  15434. throw new Error('Circle dependency may exists');
  15435. });
  15436. function removeEdge(succComponentType) {
  15437. graph[succComponentType].entryCount--;
  15438. if (graph[succComponentType].entryCount === 0) {
  15439. stack.push(succComponentType);
  15440. }
  15441. }
  15442. // Consider this case: legend depends on series, and we call
  15443. // chart.setOption({series: [...]}), where only series is in option.
  15444. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15445. // not be called, but only sereis.mergeOption is called. Thus legend
  15446. // have no chance to update its local record about series (like which
  15447. // name of series is available in legend).
  15448. function removeEdgeAndAdd(succComponentType) {
  15449. targetNameSet[succComponentType] = true;
  15450. removeEdge(succComponentType);
  15451. }
  15452. };
  15453. /**
  15454. * DepndencyGraph: {Object}
  15455. * key: conponentType,
  15456. * value: {
  15457. * successor: [conponentTypes...],
  15458. * originalDeps: [conponentTypes...],
  15459. * entryCount: {number}
  15460. * }
  15461. */
  15462. function makeDepndencyGraph(fullNameList) {
  15463. var graph = {};
  15464. var noEntryList = [];
  15465. each$1(fullNameList, function (name) {
  15466. var thisItem = createDependencyGraphItem(graph, name);
  15467. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15468. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15469. thisItem.entryCount = availableDeps.length;
  15470. if (thisItem.entryCount === 0) {
  15471. noEntryList.push(name);
  15472. }
  15473. each$1(availableDeps, function (dependentName) {
  15474. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15475. thisItem.predecessor.push(dependentName);
  15476. }
  15477. var thatItem = createDependencyGraphItem(graph, dependentName);
  15478. if (indexOf(thatItem.successor, dependentName) < 0) {
  15479. thatItem.successor.push(name);
  15480. }
  15481. });
  15482. });
  15483. return {graph: graph, noEntryList: noEntryList};
  15484. }
  15485. function createDependencyGraphItem(graph, name) {
  15486. if (!graph[name]) {
  15487. graph[name] = {predecessor: [], successor: []};
  15488. }
  15489. return graph[name];
  15490. }
  15491. function getAvailableDependencies(originalDeps, fullNameList) {
  15492. var availableDeps = [];
  15493. each$1(originalDeps, function (dep) {
  15494. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15495. });
  15496. return availableDeps;
  15497. }
  15498. }
  15499. /*
  15500. * Licensed to the Apache Software Foundation (ASF) under one
  15501. * or more contributor license agreements. See the NOTICE file
  15502. * distributed with this work for additional information
  15503. * regarding copyright ownership. The ASF licenses this file
  15504. * to you under the Apache License, Version 2.0 (the
  15505. * "License"); you may not use this file except in compliance
  15506. * with the License. You may obtain a copy of the License at
  15507. *
  15508. * http://www.apache.org/licenses/LICENSE-2.0
  15509. *
  15510. * Unless required by applicable law or agreed to in writing,
  15511. * software distributed under the License is distributed on an
  15512. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15513. * KIND, either express or implied. See the License for the
  15514. * specific language governing permissions and limitations
  15515. * under the License.
  15516. */
  15517. /*
  15518. * A third-party license is embeded for some of the code in this file:
  15519. * The method "quantile" was copied from "d3.js".
  15520. * (See more details in the comment of the method below.)
  15521. * The use of the source code of this file is also subject to the terms
  15522. * and consitions of the license of "d3.js" (BSD-3Clause, see
  15523. * </licenses/LICENSE-d3>).
  15524. */
  15525. var RADIAN_EPSILON = 1e-4;
  15526. function _trim(str) {
  15527. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15528. }
  15529. /**
  15530. * Linear mapping a value from domain to range
  15531. * @memberOf module:echarts/util/number
  15532. * @param {(number|Array.<number>)} val
  15533. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15534. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15535. * @param {boolean} clamp
  15536. * @return {(number|Array.<number>}
  15537. */
  15538. function linearMap(val, domain, range, clamp) {
  15539. var subDomain = domain[1] - domain[0];
  15540. var subRange = range[1] - range[0];
  15541. if (subDomain === 0) {
  15542. return subRange === 0
  15543. ? range[0]
  15544. : (range[0] + range[1]) / 2;
  15545. }
  15546. // Avoid accuracy problem in edge, such as
  15547. // 146.39 - 62.83 === 83.55999999999999.
  15548. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15549. // It is a little verbose for efficiency considering this method
  15550. // is a hotspot.
  15551. if (clamp) {
  15552. if (subDomain > 0) {
  15553. if (val <= domain[0]) {
  15554. return range[0];
  15555. }
  15556. else if (val >= domain[1]) {
  15557. return range[1];
  15558. }
  15559. }
  15560. else {
  15561. if (val >= domain[0]) {
  15562. return range[0];
  15563. }
  15564. else if (val <= domain[1]) {
  15565. return range[1];
  15566. }
  15567. }
  15568. }
  15569. else {
  15570. if (val === domain[0]) {
  15571. return range[0];
  15572. }
  15573. if (val === domain[1]) {
  15574. return range[1];
  15575. }
  15576. }
  15577. return (val - domain[0]) / subDomain * subRange + range[0];
  15578. }
  15579. /**
  15580. * Convert a percent string to absolute number.
  15581. * Returns NaN if percent is not a valid string or number
  15582. * @memberOf module:echarts/util/number
  15583. * @param {string|number} percent
  15584. * @param {number} all
  15585. * @return {number}
  15586. */
  15587. function parsePercent$1(percent, all) {
  15588. switch (percent) {
  15589. case 'center':
  15590. case 'middle':
  15591. percent = '50%';
  15592. break;
  15593. case 'left':
  15594. case 'top':
  15595. percent = '0%';
  15596. break;
  15597. case 'right':
  15598. case 'bottom':
  15599. percent = '100%';
  15600. break;
  15601. }
  15602. if (typeof percent === 'string') {
  15603. if (_trim(percent).match(/%$/)) {
  15604. return parseFloat(percent) / 100 * all;
  15605. }
  15606. return parseFloat(percent);
  15607. }
  15608. return percent == null ? NaN : +percent;
  15609. }
  15610. /**
  15611. * (1) Fix rounding error of float numbers.
  15612. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15613. *
  15614. * @param {number} x
  15615. * @param {number} [precision]
  15616. * @param {boolean} [returnStr]
  15617. * @return {number|string}
  15618. */
  15619. function round$2(x, precision, returnStr) {
  15620. if (precision == null) {
  15621. precision = 10;
  15622. }
  15623. // Avoid range error
  15624. precision = Math.min(Math.max(0, precision), 20);
  15625. x = (+x).toFixed(precision);
  15626. return returnStr ? x : +x;
  15627. }
  15628. /**
  15629. * Get precision
  15630. * @param {number} val
  15631. */
  15632. /**
  15633. * @param {string|number} val
  15634. * @return {number}
  15635. */
  15636. function getPrecisionSafe(val) {
  15637. var str = val.toString();
  15638. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15639. var eIndex = str.indexOf('e');
  15640. if (eIndex > 0) {
  15641. var precision = +str.slice(eIndex + 1);
  15642. return precision < 0 ? -precision : 0;
  15643. }
  15644. else {
  15645. var dotIndex = str.indexOf('.');
  15646. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15647. }
  15648. }
  15649. /**
  15650. * Minimal dicernible data precisioin according to a single pixel.
  15651. *
  15652. * @param {Array.<number>} dataExtent
  15653. * @param {Array.<number>} pixelExtent
  15654. * @return {number} precision
  15655. */
  15656. function getPixelPrecision(dataExtent, pixelExtent) {
  15657. var log = Math.log;
  15658. var LN10 = Math.LN10;
  15659. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15660. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15661. // toFixed() digits argument must be between 0 and 20.
  15662. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15663. return !isFinite(precision) ? 20 : precision;
  15664. }
  15665. /**
  15666. * Get a data of given precision, assuring the sum of percentages
  15667. * in valueList is 1.
  15668. * The largest remainer method is used.
  15669. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15670. *
  15671. * @param {Array.<number>} valueList a list of all data
  15672. * @param {number} idx index of the data to be processed in valueList
  15673. * @param {number} precision integer number showing digits of precision
  15674. * @return {number} percent ranging from 0 to 100
  15675. */
  15676. function getPercentWithPrecision(valueList, idx, precision) {
  15677. if (!valueList[idx]) {
  15678. return 0;
  15679. }
  15680. var sum = reduce(valueList, function (acc, val) {
  15681. return acc + (isNaN(val) ? 0 : val);
  15682. }, 0);
  15683. if (sum === 0) {
  15684. return 0;
  15685. }
  15686. var digits = Math.pow(10, precision);
  15687. var votesPerQuota = map(valueList, function (val) {
  15688. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15689. });
  15690. var targetSeats = digits * 100;
  15691. var seats = map(votesPerQuota, function (votes) {
  15692. // Assign automatic seats.
  15693. return Math.floor(votes);
  15694. });
  15695. var currentSum = reduce(seats, function (acc, val) {
  15696. return acc + val;
  15697. }, 0);
  15698. var remainder = map(votesPerQuota, function (votes, idx) {
  15699. return votes - seats[idx];
  15700. });
  15701. // Has remainding votes.
  15702. while (currentSum < targetSeats) {
  15703. // Find next largest remainder.
  15704. var max = Number.NEGATIVE_INFINITY;
  15705. var maxId = null;
  15706. for (var i = 0, len = remainder.length; i < len; ++i) {
  15707. if (remainder[i] > max) {
  15708. max = remainder[i];
  15709. maxId = i;
  15710. }
  15711. }
  15712. // Add a vote to max remainder.
  15713. ++seats[maxId];
  15714. remainder[maxId] = 0;
  15715. ++currentSum;
  15716. }
  15717. return seats[idx] / digits;
  15718. }
  15719. // Number.MAX_SAFE_INTEGER, ie do not support.
  15720. /**
  15721. * To 0 - 2 * PI, considering negative radian.
  15722. * @param {number} radian
  15723. * @return {number}
  15724. */
  15725. function remRadian(radian) {
  15726. var pi2 = Math.PI * 2;
  15727. return (radian % pi2 + pi2) % pi2;
  15728. }
  15729. /**
  15730. * @param {type} radian
  15731. * @return {boolean}
  15732. */
  15733. function isRadianAroundZero(val) {
  15734. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15735. }
  15736. /* eslint-disable */
  15737. 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
  15738. /* eslint-enable */
  15739. /**
  15740. * @param {string|Date|number} value These values can be accepted:
  15741. * + An instance of Date, represent a time in its own time zone.
  15742. * + Or string in a subset of ISO 8601, only including:
  15743. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15744. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15745. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15746. * all of which will be treated as local time if time zone is not specified
  15747. * (see <https://momentjs.com/>).
  15748. * + Or other string format, including (all of which will be treated as loacal time):
  15749. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15750. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15751. * + a timestamp, which represent a time in UTC.
  15752. * @return {Date} date
  15753. */
  15754. function parseDate(value) {
  15755. if (value instanceof Date) {
  15756. return value;
  15757. }
  15758. else if (typeof value === 'string') {
  15759. // Different browsers parse date in different way, so we parse it manually.
  15760. // Some other issues:
  15761. // new Date('1970-01-01') is UTC,
  15762. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15763. // See issue #3623
  15764. var match = TIME_REG.exec(value);
  15765. if (!match) {
  15766. // return Invalid Date.
  15767. return new Date(NaN);
  15768. }
  15769. // Use local time when no timezone offset specifed.
  15770. if (!match[8]) {
  15771. // match[n] can only be string or undefined.
  15772. // But take care of '12' + 1 => '121'.
  15773. return new Date(
  15774. +match[1],
  15775. +(match[2] || 1) - 1,
  15776. +match[3] || 1,
  15777. +match[4] || 0,
  15778. +(match[5] || 0),
  15779. +match[6] || 0,
  15780. +match[7] || 0
  15781. );
  15782. }
  15783. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15784. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15785. // For example, system timezone is set as "Time Zone: America/Toronto",
  15786. // then these code will get different result:
  15787. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15788. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15789. // So we should not use `new Date`, but use `Date.UTC`.
  15790. else {
  15791. var hour = +match[4] || 0;
  15792. if (match[8].toUpperCase() !== 'Z') {
  15793. hour -= match[8].slice(0, 3);
  15794. }
  15795. return new Date(Date.UTC(
  15796. +match[1],
  15797. +(match[2] || 1) - 1,
  15798. +match[3] || 1,
  15799. hour,
  15800. +(match[5] || 0),
  15801. +match[6] || 0,
  15802. +match[7] || 0
  15803. ));
  15804. }
  15805. }
  15806. else if (value == null) {
  15807. return new Date(NaN);
  15808. }
  15809. return new Date(Math.round(value));
  15810. }
  15811. /**
  15812. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15813. *
  15814. * @param {number} val
  15815. * @return {number}
  15816. */
  15817. function quantity(val) {
  15818. return Math.pow(10, quantityExponent(val));
  15819. }
  15820. function quantityExponent(val) {
  15821. return Math.floor(Math.log(val) / Math.LN10);
  15822. }
  15823. /**
  15824. * find a “nice” number approximately equal to x. Round the number if round = true,
  15825. * take ceiling if round = false. The primary observation is that the “nicest”
  15826. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15827. *
  15828. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15829. *
  15830. * @param {number} val Non-negative value.
  15831. * @param {boolean} round
  15832. * @return {number}
  15833. */
  15834. function nice(val, round) {
  15835. var exponent = quantityExponent(val);
  15836. var exp10 = Math.pow(10, exponent);
  15837. var f = val / exp10; // 1 <= f < 10
  15838. var nf;
  15839. if (round) {
  15840. if (f < 1.5) {
  15841. nf = 1;
  15842. }
  15843. else if (f < 2.5) {
  15844. nf = 2;
  15845. }
  15846. else if (f < 4) {
  15847. nf = 3;
  15848. }
  15849. else if (f < 7) {
  15850. nf = 5;
  15851. }
  15852. else {
  15853. nf = 10;
  15854. }
  15855. }
  15856. else {
  15857. if (f < 1) {
  15858. nf = 1;
  15859. }
  15860. else if (f < 2) {
  15861. nf = 2;
  15862. }
  15863. else if (f < 3) {
  15864. nf = 3;
  15865. }
  15866. else if (f < 5) {
  15867. nf = 5;
  15868. }
  15869. else {
  15870. nf = 10;
  15871. }
  15872. }
  15873. val = nf * exp10;
  15874. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15875. // 20 is the uppper bound of toFixed.
  15876. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15877. }
  15878. /**
  15879. * This code was copied from "d3.js"
  15880. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  15881. * See the license statement at the head of this file.
  15882. * @param {Array.<number>} ascArr
  15883. */
  15884. /**
  15885. * Order intervals asc, and split them when overlap.
  15886. * expect(numberUtil.reformIntervals([
  15887. * {interval: [18, 62], close: [1, 1]},
  15888. * {interval: [-Infinity, -70], close: [0, 0]},
  15889. * {interval: [-70, -26], close: [1, 1]},
  15890. * {interval: [-26, 18], close: [1, 1]},
  15891. * {interval: [62, 150], close: [1, 1]},
  15892. * {interval: [106, 150], close: [1, 1]},
  15893. * {interval: [150, Infinity], close: [0, 0]}
  15894. * ])).toEqual([
  15895. * {interval: [-Infinity, -70], close: [0, 0]},
  15896. * {interval: [-70, -26], close: [1, 1]},
  15897. * {interval: [-26, 18], close: [0, 1]},
  15898. * {interval: [18, 62], close: [0, 1]},
  15899. * {interval: [62, 150], close: [0, 1]},
  15900. * {interval: [150, Infinity], close: [0, 0]}
  15901. * ]);
  15902. * @param {Array.<Object>} list, where `close` mean open or close
  15903. * of the interval, and Infinity can be used.
  15904. * @return {Array.<Object>} The origin list, which has been reformed.
  15905. */
  15906. /**
  15907. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15908. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15909. * subtraction forces infinities to NaN
  15910. *
  15911. * @param {*} v
  15912. * @return {boolean}
  15913. */
  15914. /*
  15915. * Licensed to the Apache Software Foundation (ASF) under one
  15916. * or more contributor license agreements. See the NOTICE file
  15917. * distributed with this work for additional information
  15918. * regarding copyright ownership. The ASF licenses this file
  15919. * to you under the Apache License, Version 2.0 (the
  15920. * "License"); you may not use this file except in compliance
  15921. * with the License. You may obtain a copy of the License at
  15922. *
  15923. * http://www.apache.org/licenses/LICENSE-2.0
  15924. *
  15925. * Unless required by applicable law or agreed to in writing,
  15926. * software distributed under the License is distributed on an
  15927. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15928. * KIND, either express or implied. See the License for the
  15929. * specific language governing permissions and limitations
  15930. * under the License.
  15931. */
  15932. // import Text from 'zrender/src/graphic/Text';
  15933. /**
  15934. * 每三位默认加,格式化
  15935. * @param {string|number} x
  15936. * @return {string}
  15937. */
  15938. function addCommas(x) {
  15939. if (isNaN(x)) {
  15940. return '-';
  15941. }
  15942. x = (x + '').split('.');
  15943. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,')
  15944. + (x.length > 1 ? ('.' + x[1]) : '');
  15945. }
  15946. /**
  15947. * @param {string} str
  15948. * @param {boolean} [upperCaseFirst=false]
  15949. * @return {string} str
  15950. */
  15951. var normalizeCssArray$1 = normalizeCssArray;
  15952. var replaceReg = /([&<>"'])/g;
  15953. var replaceMap = {
  15954. '&': '&amp;',
  15955. '<': '&lt;',
  15956. '>': '&gt;',
  15957. '"': '&quot;',
  15958. '\'': '&#39;'
  15959. };
  15960. function encodeHTML(source) {
  15961. return source == null
  15962. ? ''
  15963. : (source + '').replace(replaceReg, function (str, c) {
  15964. return replaceMap[c];
  15965. });
  15966. }
  15967. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15968. var wrapVar = function (varName, seriesIdx) {
  15969. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15970. };
  15971. /**
  15972. * Template formatter
  15973. * @param {string} tpl
  15974. * @param {Array.<Object>|Object} paramsList
  15975. * @param {boolean} [encode=false]
  15976. * @return {string}
  15977. */
  15978. function formatTpl(tpl, paramsList, encode) {
  15979. if (!isArray(paramsList)) {
  15980. paramsList = [paramsList];
  15981. }
  15982. var seriesLen = paramsList.length;
  15983. if (!seriesLen) {
  15984. return '';
  15985. }
  15986. var $vars = paramsList[0].$vars || [];
  15987. for (var i = 0; i < $vars.length; i++) {
  15988. var alias = TPL_VAR_ALIAS[i];
  15989. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15990. }
  15991. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15992. for (var k = 0; k < $vars.length; k++) {
  15993. var val = paramsList[seriesIdx][$vars[k]];
  15994. tpl = tpl.replace(
  15995. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15996. encode ? encodeHTML(val) : val
  15997. );
  15998. }
  15999. }
  16000. return tpl;
  16001. }
  16002. /**
  16003. * simple Template formatter
  16004. *
  16005. * @param {string} tpl
  16006. * @param {Object} param
  16007. * @param {boolean} [encode=false]
  16008. * @return {string}
  16009. */
  16010. /**
  16011. * @param {Object|string} [opt] If string, means color.
  16012. * @param {string} [opt.color]
  16013. * @param {string} [opt.extraCssText]
  16014. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16015. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16016. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16017. * @return {string}
  16018. */
  16019. function getTooltipMarker(opt, extraCssText) {
  16020. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  16021. var color = opt.color;
  16022. var type = opt.type;
  16023. var extraCssText = opt.extraCssText;
  16024. var renderMode = opt.renderMode || 'html';
  16025. var markerId = opt.markerId || 'X';
  16026. if (!color) {
  16027. return '';
  16028. }
  16029. if (renderMode === 'html') {
  16030. return type === 'subItem'
  16031. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  16032. + 'border-radius:4px;width:4px;height:4px;background-color:'
  16033. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  16034. : '<span style="display:inline-block;margin-right:5px;'
  16035. + 'border-radius:10px;width:10px;height:10px;background-color:'
  16036. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16037. }
  16038. else {
  16039. // Space for rich element marker
  16040. return {
  16041. renderMode: renderMode,
  16042. content: '{marker' + markerId + '|} ',
  16043. style: {
  16044. color: color
  16045. }
  16046. };
  16047. }
  16048. }
  16049. function pad(str, len) {
  16050. str += '';
  16051. return '0000'.substr(0, len - str.length) + str;
  16052. }
  16053. /**
  16054. * ISO Date format
  16055. * @param {string} tpl
  16056. * @param {number} value
  16057. * @param {boolean} [isUTC=false] Default in local time.
  16058. * see `module:echarts/scale/Time`
  16059. * and `module:echarts/util/number#parseDate`.
  16060. * @inner
  16061. */
  16062. function formatTime(tpl, value, isUTC) {
  16063. if (tpl === 'week'
  16064. || tpl === 'month'
  16065. || tpl === 'quarter'
  16066. || tpl === 'half-year'
  16067. || tpl === 'year'
  16068. ) {
  16069. tpl = 'MM-dd\nyyyy';
  16070. }
  16071. var date = parseDate(value);
  16072. var utc = isUTC ? 'UTC' : '';
  16073. var y = date['get' + utc + 'FullYear']();
  16074. var M = date['get' + utc + 'Month']() + 1;
  16075. var d = date['get' + utc + 'Date']();
  16076. var h = date['get' + utc + 'Hours']();
  16077. var m = date['get' + utc + 'Minutes']();
  16078. var s = date['get' + utc + 'Seconds']();
  16079. var S = date['get' + utc + 'Milliseconds']();
  16080. tpl = tpl.replace('MM', pad(M, 2))
  16081. .replace('M', M)
  16082. .replace('yyyy', y)
  16083. .replace('yy', y % 100)
  16084. .replace('dd', pad(d, 2))
  16085. .replace('d', d)
  16086. .replace('hh', pad(h, 2))
  16087. .replace('h', h)
  16088. .replace('mm', pad(m, 2))
  16089. .replace('m', m)
  16090. .replace('ss', pad(s, 2))
  16091. .replace('s', s)
  16092. .replace('SSS', pad(S, 3));
  16093. return tpl;
  16094. }
  16095. /**
  16096. * Capital first
  16097. * @param {string} str
  16098. * @return {string}
  16099. */
  16100. var truncateText$1 = truncateText;
  16101. /**
  16102. * @public
  16103. * @param {Object} opt
  16104. * @param {string} opt.text
  16105. * @param {string} opt.font
  16106. * @param {string} [opt.textAlign='left']
  16107. * @param {string} [opt.textVerticalAlign='top']
  16108. * @param {Array.<number>} [opt.textPadding]
  16109. * @param {number} [opt.textLineHeight]
  16110. * @param {Object} [opt.rich]
  16111. * @param {Object} [opt.truncate]
  16112. * @return {Object} {x, y, width, height, lineHeight}
  16113. */
  16114. /**
  16115. * @deprecated
  16116. * the `textLineHeight` was added later.
  16117. * For backward compatiblility, put it as the last parameter.
  16118. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16119. */
  16120. /*
  16121. * Licensed to the Apache Software Foundation (ASF) under one
  16122. * or more contributor license agreements. See the NOTICE file
  16123. * distributed with this work for additional information
  16124. * regarding copyright ownership. The ASF licenses this file
  16125. * to you under the Apache License, Version 2.0 (the
  16126. * "License"); you may not use this file except in compliance
  16127. * with the License. You may obtain a copy of the License at
  16128. *
  16129. * http://www.apache.org/licenses/LICENSE-2.0
  16130. *
  16131. * Unless required by applicable law or agreed to in writing,
  16132. * software distributed under the License is distributed on an
  16133. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16134. * KIND, either express or implied. See the License for the
  16135. * specific language governing permissions and limitations
  16136. * under the License.
  16137. */
  16138. // Layout helpers for each component positioning
  16139. var each$3 = each$1;
  16140. /**
  16141. * @public
  16142. */
  16143. var LOCATION_PARAMS = [
  16144. 'left', 'right', 'top', 'bottom', 'width', 'height'
  16145. ];
  16146. /**
  16147. * @public
  16148. */
  16149. var HV_NAMES = [
  16150. ['width', 'left', 'right'],
  16151. ['height', 'top', 'bottom']
  16152. ];
  16153. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16154. var x = 0;
  16155. var y = 0;
  16156. if (maxWidth == null) {
  16157. maxWidth = Infinity;
  16158. }
  16159. if (maxHeight == null) {
  16160. maxHeight = Infinity;
  16161. }
  16162. var currentLineMaxSize = 0;
  16163. group.eachChild(function (child, idx) {
  16164. var position = child.position;
  16165. var rect = child.getBoundingRect();
  16166. var nextChild = group.childAt(idx + 1);
  16167. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16168. var nextX;
  16169. var nextY;
  16170. if (orient === 'horizontal') {
  16171. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16172. nextX = x + moveX;
  16173. // Wrap when width exceeds maxWidth or meet a `newline` group
  16174. // FIXME compare before adding gap?
  16175. if (nextX > maxWidth || child.newline) {
  16176. x = 0;
  16177. nextX = moveX;
  16178. y += currentLineMaxSize + gap;
  16179. currentLineMaxSize = rect.height;
  16180. }
  16181. else {
  16182. // FIXME: consider rect.y is not `0`?
  16183. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16184. }
  16185. }
  16186. else {
  16187. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16188. nextY = y + moveY;
  16189. // Wrap when width exceeds maxHeight or meet a `newline` group
  16190. if (nextY > maxHeight || child.newline) {
  16191. x += currentLineMaxSize + gap;
  16192. y = 0;
  16193. nextY = moveY;
  16194. currentLineMaxSize = rect.width;
  16195. }
  16196. else {
  16197. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16198. }
  16199. }
  16200. if (child.newline) {
  16201. return;
  16202. }
  16203. position[0] = x;
  16204. position[1] = y;
  16205. orient === 'horizontal'
  16206. ? (x = nextX + gap)
  16207. : (y = nextY + gap);
  16208. });
  16209. }
  16210. /**
  16211. * VBox or HBox layouting
  16212. * @param {string} orient
  16213. * @param {module:zrender/container/Group} group
  16214. * @param {number} gap
  16215. * @param {number} [width=Infinity]
  16216. * @param {number} [height=Infinity]
  16217. */
  16218. /**
  16219. * VBox layouting
  16220. * @param {module:zrender/container/Group} group
  16221. * @param {number} gap
  16222. * @param {number} [width=Infinity]
  16223. * @param {number} [height=Infinity]
  16224. */
  16225. var vbox = curry(boxLayout, 'vertical');
  16226. /**
  16227. * HBox layouting
  16228. * @param {module:zrender/container/Group} group
  16229. * @param {number} gap
  16230. * @param {number} [width=Infinity]
  16231. * @param {number} [height=Infinity]
  16232. */
  16233. var hbox = curry(boxLayout, 'horizontal');
  16234. /**
  16235. * If x or x2 is not specified or 'center' 'left' 'right',
  16236. * the width would be as long as possible.
  16237. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16238. * the height would be as long as possible.
  16239. *
  16240. * @param {Object} positionInfo
  16241. * @param {number|string} [positionInfo.x]
  16242. * @param {number|string} [positionInfo.y]
  16243. * @param {number|string} [positionInfo.x2]
  16244. * @param {number|string} [positionInfo.y2]
  16245. * @param {Object} containerRect {width, height}
  16246. * @param {string|number} margin
  16247. * @return {Object} {width, height}
  16248. */
  16249. /**
  16250. * Parse position info.
  16251. *
  16252. * @param {Object} positionInfo
  16253. * @param {number|string} [positionInfo.left]
  16254. * @param {number|string} [positionInfo.top]
  16255. * @param {number|string} [positionInfo.right]
  16256. * @param {number|string} [positionInfo.bottom]
  16257. * @param {number|string} [positionInfo.width]
  16258. * @param {number|string} [positionInfo.height]
  16259. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16260. * @param {Object} containerRect
  16261. * @param {string|number} [margin]
  16262. *
  16263. * @return {module:zrender/core/BoundingRect}
  16264. */
  16265. function getLayoutRect(
  16266. positionInfo, containerRect, margin
  16267. ) {
  16268. margin = normalizeCssArray$1(margin || 0);
  16269. var containerWidth = containerRect.width;
  16270. var containerHeight = containerRect.height;
  16271. var left = parsePercent$1(positionInfo.left, containerWidth);
  16272. var top = parsePercent$1(positionInfo.top, containerHeight);
  16273. var right = parsePercent$1(positionInfo.right, containerWidth);
  16274. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16275. var width = parsePercent$1(positionInfo.width, containerWidth);
  16276. var height = parsePercent$1(positionInfo.height, containerHeight);
  16277. var verticalMargin = margin[2] + margin[0];
  16278. var horizontalMargin = margin[1] + margin[3];
  16279. var aspect = positionInfo.aspect;
  16280. // If width is not specified, calculate width from left and right
  16281. if (isNaN(width)) {
  16282. width = containerWidth - right - horizontalMargin - left;
  16283. }
  16284. if (isNaN(height)) {
  16285. height = containerHeight - bottom - verticalMargin - top;
  16286. }
  16287. if (aspect != null) {
  16288. // If width and height are not given
  16289. // 1. Graph should not exceeds the container
  16290. // 2. Aspect must be keeped
  16291. // 3. Graph should take the space as more as possible
  16292. // FIXME
  16293. // Margin is not considered, because there is no case that both
  16294. // using margin and aspect so far.
  16295. if (isNaN(width) && isNaN(height)) {
  16296. if (aspect > containerWidth / containerHeight) {
  16297. width = containerWidth * 0.8;
  16298. }
  16299. else {
  16300. height = containerHeight * 0.8;
  16301. }
  16302. }
  16303. // Calculate width or height with given aspect
  16304. if (isNaN(width)) {
  16305. width = aspect * height;
  16306. }
  16307. if (isNaN(height)) {
  16308. height = width / aspect;
  16309. }
  16310. }
  16311. // If left is not specified, calculate left from right and width
  16312. if (isNaN(left)) {
  16313. left = containerWidth - right - width - horizontalMargin;
  16314. }
  16315. if (isNaN(top)) {
  16316. top = containerHeight - bottom - height - verticalMargin;
  16317. }
  16318. // Align left and top
  16319. switch (positionInfo.left || positionInfo.right) {
  16320. case 'center':
  16321. left = containerWidth / 2 - width / 2 - margin[3];
  16322. break;
  16323. case 'right':
  16324. left = containerWidth - width - horizontalMargin;
  16325. break;
  16326. }
  16327. switch (positionInfo.top || positionInfo.bottom) {
  16328. case 'middle':
  16329. case 'center':
  16330. top = containerHeight / 2 - height / 2 - margin[0];
  16331. break;
  16332. case 'bottom':
  16333. top = containerHeight - height - verticalMargin;
  16334. break;
  16335. }
  16336. // If something is wrong and left, top, width, height are calculated as NaN
  16337. left = left || 0;
  16338. top = top || 0;
  16339. if (isNaN(width)) {
  16340. // Width may be NaN if only one value is given except width
  16341. width = containerWidth - horizontalMargin - left - (right || 0);
  16342. }
  16343. if (isNaN(height)) {
  16344. // Height may be NaN if only one value is given except height
  16345. height = containerHeight - verticalMargin - top - (bottom || 0);
  16346. }
  16347. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16348. rect.margin = margin;
  16349. return rect;
  16350. }
  16351. /**
  16352. * Position a zr element in viewport
  16353. * Group position is specified by either
  16354. * {left, top}, {right, bottom}
  16355. * If all properties exists, right and bottom will be igonred.
  16356. *
  16357. * Logic:
  16358. * 1. Scale (against origin point in parent coord)
  16359. * 2. Rotate (against origin point in parent coord)
  16360. * 3. Traslate (with el.position by this method)
  16361. * So this method only fixes the last step 'Traslate', which does not affect
  16362. * scaling and rotating.
  16363. *
  16364. * If be called repeatly with the same input el, the same result will be gotten.
  16365. *
  16366. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16367. * @param {Object} positionInfo
  16368. * @param {number|string} [positionInfo.left]
  16369. * @param {number|string} [positionInfo.top]
  16370. * @param {number|string} [positionInfo.right]
  16371. * @param {number|string} [positionInfo.bottom]
  16372. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16373. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16374. * @param {Object} containerRect
  16375. * @param {string|number} margin
  16376. * @param {Object} [opt]
  16377. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16378. * @param {Array.<number>} [opt.boundingMode='all']
  16379. * Specify how to calculate boundingRect when locating.
  16380. * 'all': Position the boundingRect that is transformed and uioned
  16381. * both itself and its descendants.
  16382. * This mode simplies confine the elements in the bounding
  16383. * of their container (e.g., using 'right: 0').
  16384. * 'raw': Position the boundingRect that is not transformed and only itself.
  16385. * This mode is useful when you want a element can overflow its
  16386. * container. (Consider a rotated circle needs to be located in a corner.)
  16387. * In this mode positionInfo.width/height can only be number.
  16388. */
  16389. /**
  16390. * @param {Object} option Contains some of the properties in HV_NAMES.
  16391. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16392. */
  16393. /**
  16394. * Consider Case:
  16395. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16396. * through setOption or media query, using normal zrUtil.merge will cause
  16397. * {right: 0} does not take effect.
  16398. *
  16399. * @example
  16400. * ComponentModel.extend({
  16401. * init: function () {
  16402. * ...
  16403. * var inputPositionParams = layout.getLayoutParams(option);
  16404. * this.mergeOption(inputPositionParams);
  16405. * },
  16406. * mergeOption: function (newOption) {
  16407. * newOption && zrUtil.merge(thisOption, newOption, true);
  16408. * layout.mergeLayoutParam(thisOption, newOption);
  16409. * }
  16410. * });
  16411. *
  16412. * @param {Object} targetOption
  16413. * @param {Object} newOption
  16414. * @param {Object|string} [opt]
  16415. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16416. * that width (or height) should not be calculated by left and right (or top and bottom).
  16417. */
  16418. function mergeLayoutParam(targetOption, newOption, opt) {
  16419. !isObject$1(opt) && (opt = {});
  16420. var ignoreSize = opt.ignoreSize;
  16421. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16422. var hResult = merge$$1(HV_NAMES[0], 0);
  16423. var vResult = merge$$1(HV_NAMES[1], 1);
  16424. copy(HV_NAMES[0], targetOption, hResult);
  16425. copy(HV_NAMES[1], targetOption, vResult);
  16426. function merge$$1(names, hvIdx) {
  16427. var newParams = {};
  16428. var newValueCount = 0;
  16429. var merged = {};
  16430. var mergedValueCount = 0;
  16431. var enoughParamNumber = 2;
  16432. each$3(names, function (name) {
  16433. merged[name] = targetOption[name];
  16434. });
  16435. each$3(names, function (name) {
  16436. // Consider case: newOption.width is null, which is
  16437. // set by user for removing width setting.
  16438. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16439. hasValue(newParams, name) && newValueCount++;
  16440. hasValue(merged, name) && mergedValueCount++;
  16441. });
  16442. if (ignoreSize[hvIdx]) {
  16443. // Only one of left/right is premitted to exist.
  16444. if (hasValue(newOption, names[1])) {
  16445. merged[names[2]] = null;
  16446. }
  16447. else if (hasValue(newOption, names[2])) {
  16448. merged[names[1]] = null;
  16449. }
  16450. return merged;
  16451. }
  16452. // Case: newOption: {width: ..., right: ...},
  16453. // or targetOption: {right: ...} and newOption: {width: ...},
  16454. // There is no conflict when merged only has params count
  16455. // little than enoughParamNumber.
  16456. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16457. return merged;
  16458. }
  16459. // Case: newOption: {width: ..., right: ...},
  16460. // Than we can make sure user only want those two, and ignore
  16461. // all origin params in targetOption.
  16462. else if (newValueCount >= enoughParamNumber) {
  16463. return newParams;
  16464. }
  16465. else {
  16466. // Chose another param from targetOption by priority.
  16467. for (var i = 0; i < names.length; i++) {
  16468. var name = names[i];
  16469. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16470. newParams[name] = targetOption[name];
  16471. break;
  16472. }
  16473. }
  16474. return newParams;
  16475. }
  16476. }
  16477. function hasProp(obj, name) {
  16478. return obj.hasOwnProperty(name);
  16479. }
  16480. function hasValue(obj, name) {
  16481. return obj[name] != null && obj[name] !== 'auto';
  16482. }
  16483. function copy(names, target, source) {
  16484. each$3(names, function (name) {
  16485. target[name] = source[name];
  16486. });
  16487. }
  16488. }
  16489. /**
  16490. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16491. * @param {Object} source
  16492. * @return {Object} Result contains those props.
  16493. */
  16494. function getLayoutParams(source) {
  16495. return copyLayoutParams({}, source);
  16496. }
  16497. /**
  16498. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16499. * @param {Object} source
  16500. * @return {Object} Result contains those props.
  16501. */
  16502. function copyLayoutParams(target, source) {
  16503. source && target && each$3(LOCATION_PARAMS, function (name) {
  16504. source.hasOwnProperty(name) && (target[name] = source[name]);
  16505. });
  16506. return target;
  16507. }
  16508. /*
  16509. * Licensed to the Apache Software Foundation (ASF) under one
  16510. * or more contributor license agreements. See the NOTICE file
  16511. * distributed with this work for additional information
  16512. * regarding copyright ownership. The ASF licenses this file
  16513. * to you under the Apache License, Version 2.0 (the
  16514. * "License"); you may not use this file except in compliance
  16515. * with the License. You may obtain a copy of the License at
  16516. *
  16517. * http://www.apache.org/licenses/LICENSE-2.0
  16518. *
  16519. * Unless required by applicable law or agreed to in writing,
  16520. * software distributed under the License is distributed on an
  16521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16522. * KIND, either express or implied. See the License for the
  16523. * specific language governing permissions and limitations
  16524. * under the License.
  16525. */
  16526. var boxLayoutMixin = {
  16527. getBoxLayoutParams: function () {
  16528. return {
  16529. left: this.get('left'),
  16530. top: this.get('top'),
  16531. right: this.get('right'),
  16532. bottom: this.get('bottom'),
  16533. width: this.get('width'),
  16534. height: this.get('height')
  16535. };
  16536. }
  16537. };
  16538. /*
  16539. * Licensed to the Apache Software Foundation (ASF) under one
  16540. * or more contributor license agreements. See the NOTICE file
  16541. * distributed with this work for additional information
  16542. * regarding copyright ownership. The ASF licenses this file
  16543. * to you under the Apache License, Version 2.0 (the
  16544. * "License"); you may not use this file except in compliance
  16545. * with the License. You may obtain a copy of the License at
  16546. *
  16547. * http://www.apache.org/licenses/LICENSE-2.0
  16548. *
  16549. * Unless required by applicable law or agreed to in writing,
  16550. * software distributed under the License is distributed on an
  16551. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16552. * KIND, either express or implied. See the License for the
  16553. * specific language governing permissions and limitations
  16554. * under the License.
  16555. */
  16556. /**
  16557. * Component model
  16558. *
  16559. * @module echarts/model/Component
  16560. */
  16561. var inner$1 = makeInner();
  16562. /**
  16563. * @alias module:echarts/model/Component
  16564. * @constructor
  16565. * @param {Object} option
  16566. * @param {module:echarts/model/Model} parentModel
  16567. * @param {module:echarts/model/Model} ecModel
  16568. */
  16569. var ComponentModel = Model.extend({
  16570. type: 'component',
  16571. /**
  16572. * @readOnly
  16573. * @type {string}
  16574. */
  16575. id: '',
  16576. /**
  16577. * Because simplified concept is probably better, series.name (or component.name)
  16578. * has been having too many resposibilities:
  16579. * (1) Generating id (which requires name in option should not be modified).
  16580. * (2) As an index to mapping series when merging option or calling API (a name
  16581. * can refer to more then one components, which is convinient is some case).
  16582. * (3) Display.
  16583. * @readOnly
  16584. */
  16585. name: '',
  16586. /**
  16587. * @readOnly
  16588. * @type {string}
  16589. */
  16590. mainType: '',
  16591. /**
  16592. * @readOnly
  16593. * @type {string}
  16594. */
  16595. subType: '',
  16596. /**
  16597. * @readOnly
  16598. * @type {number}
  16599. */
  16600. componentIndex: 0,
  16601. /**
  16602. * @type {Object}
  16603. * @protected
  16604. */
  16605. defaultOption: null,
  16606. /**
  16607. * @type {module:echarts/model/Global}
  16608. * @readOnly
  16609. */
  16610. ecModel: null,
  16611. /**
  16612. * key: componentType
  16613. * value: Component model list, can not be null.
  16614. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16615. * @readOnly
  16616. */
  16617. dependentModels: [],
  16618. /**
  16619. * @type {string}
  16620. * @readOnly
  16621. */
  16622. uid: null,
  16623. /**
  16624. * Support merge layout params.
  16625. * Only support 'box' now (left/right/top/bottom/width/height).
  16626. * @type {string|Object} Object can be {ignoreSize: true}
  16627. * @readOnly
  16628. */
  16629. layoutMode: null,
  16630. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16631. Model.call(this, option, parentModel, ecModel, extraOpt);
  16632. this.uid = getUID('ec_cpt_model');
  16633. },
  16634. init: function (option, parentModel, ecModel, extraOpt) {
  16635. this.mergeDefaultAndTheme(option, ecModel);
  16636. },
  16637. mergeDefaultAndTheme: function (option, ecModel) {
  16638. var layoutMode = this.layoutMode;
  16639. var inputPositionParams = layoutMode
  16640. ? getLayoutParams(option) : {};
  16641. var themeModel = ecModel.getTheme();
  16642. merge(option, themeModel.get(this.mainType));
  16643. merge(option, this.getDefaultOption());
  16644. if (layoutMode) {
  16645. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16646. }
  16647. },
  16648. mergeOption: function (option, extraOpt) {
  16649. merge(this.option, option, true);
  16650. var layoutMode = this.layoutMode;
  16651. if (layoutMode) {
  16652. mergeLayoutParam(this.option, option, layoutMode);
  16653. }
  16654. },
  16655. // Hooker after init or mergeOption
  16656. optionUpdated: function (newCptOption, isInit) {},
  16657. getDefaultOption: function () {
  16658. var fields = inner$1(this);
  16659. if (!fields.defaultOption) {
  16660. var optList = [];
  16661. var Class = this.constructor;
  16662. while (Class) {
  16663. var opt = Class.prototype.defaultOption;
  16664. opt && optList.push(opt);
  16665. Class = Class.superClass;
  16666. }
  16667. var defaultOption = {};
  16668. for (var i = optList.length - 1; i >= 0; i--) {
  16669. defaultOption = merge(defaultOption, optList[i], true);
  16670. }
  16671. fields.defaultOption = defaultOption;
  16672. }
  16673. return fields.defaultOption;
  16674. },
  16675. getReferringComponents: function (mainType) {
  16676. return this.ecModel.queryComponents({
  16677. mainType: mainType,
  16678. index: this.get(mainType + 'Index', true),
  16679. id: this.get(mainType + 'Id', true)
  16680. });
  16681. }
  16682. });
  16683. // Reset ComponentModel.extend, add preConstruct.
  16684. // clazzUtil.enableClassExtend(
  16685. // ComponentModel,
  16686. // function (option, parentModel, ecModel, extraOpt) {
  16687. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16688. // zrUtil.extend(this, extraOpt);
  16689. // this.uid = componentUtil.getUID('componentModel');
  16690. // // this.setReadOnly([
  16691. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16692. // // 'dependentModels', 'componentIndex'
  16693. // // ]);
  16694. // }
  16695. // );
  16696. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16697. enableClassManagement(
  16698. ComponentModel, {registerWhenExtend: true}
  16699. );
  16700. enableSubTypeDefaulter(ComponentModel);
  16701. // Add capability of ComponentModel.topologicalTravel.
  16702. enableTopologicalTravel(ComponentModel, getDependencies);
  16703. function getDependencies(componentType) {
  16704. var deps = [];
  16705. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16706. deps = deps.concat(Clazz.prototype.dependencies || []);
  16707. });
  16708. // Ensure main type.
  16709. deps = map(deps, function (type) {
  16710. return parseClassType$1(type).main;
  16711. });
  16712. // Hack dataset for convenience.
  16713. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16714. deps.unshift('dataset');
  16715. }
  16716. return deps;
  16717. }
  16718. mixin(ComponentModel, boxLayoutMixin);
  16719. /*
  16720. * Licensed to the Apache Software Foundation (ASF) under one
  16721. * or more contributor license agreements. See the NOTICE file
  16722. * distributed with this work for additional information
  16723. * regarding copyright ownership. The ASF licenses this file
  16724. * to you under the Apache License, Version 2.0 (the
  16725. * "License"); you may not use this file except in compliance
  16726. * with the License. You may obtain a copy of the License at
  16727. *
  16728. * http://www.apache.org/licenses/LICENSE-2.0
  16729. *
  16730. * Unless required by applicable law or agreed to in writing,
  16731. * software distributed under the License is distributed on an
  16732. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16733. * KIND, either express or implied. See the License for the
  16734. * specific language governing permissions and limitations
  16735. * under the License.
  16736. */
  16737. var platform = '';
  16738. // Navigator not exists in node
  16739. if (typeof navigator !== 'undefined') {
  16740. platform = navigator.platform || '';
  16741. }
  16742. var globalDefault = {
  16743. // backgroundColor: 'rgba(0,0,0,0)',
  16744. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16745. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16746. // Light colors:
  16747. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16748. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16749. // Dark colors:
  16750. color: [
  16751. '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  16752. '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  16753. ],
  16754. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16755. // If xAxis and yAxis declared, grid is created by default.
  16756. // grid: {},
  16757. textStyle: {
  16758. // color: '#000',
  16759. // decoration: 'none',
  16760. // PENDING
  16761. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16762. // fontFamily: 'Arial, Verdana, sans-serif',
  16763. fontSize: 12,
  16764. fontStyle: 'normal',
  16765. fontWeight: 'normal'
  16766. },
  16767. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16768. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16769. // Default is source-over
  16770. blendMode: null,
  16771. animation: 'auto',
  16772. animationDuration: 1000,
  16773. animationDurationUpdate: 300,
  16774. animationEasing: 'exponentialOut',
  16775. animationEasingUpdate: 'cubicOut',
  16776. animationThreshold: 2000,
  16777. // Configuration for progressive/incremental rendering
  16778. progressiveThreshold: 3000,
  16779. progressive: 400,
  16780. // Threshold of if use single hover layer to optimize.
  16781. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16782. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16783. // which is unexpected.
  16784. // see example <echarts/test/heatmap-large.html>.
  16785. hoverLayerThreshold: 3000,
  16786. // See: module:echarts/scale/Time
  16787. useUTC: false
  16788. };
  16789. /*
  16790. * Licensed to the Apache Software Foundation (ASF) under one
  16791. * or more contributor license agreements. See the NOTICE file
  16792. * distributed with this work for additional information
  16793. * regarding copyright ownership. The ASF licenses this file
  16794. * to you under the Apache License, Version 2.0 (the
  16795. * "License"); you may not use this file except in compliance
  16796. * with the License. You may obtain a copy of the License at
  16797. *
  16798. * http://www.apache.org/licenses/LICENSE-2.0
  16799. *
  16800. * Unless required by applicable law or agreed to in writing,
  16801. * software distributed under the License is distributed on an
  16802. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16803. * KIND, either express or implied. See the License for the
  16804. * specific language governing permissions and limitations
  16805. * under the License.
  16806. */
  16807. var inner$2 = makeInner();
  16808. function getNearestColorPalette(colors, requestColorNum) {
  16809. var paletteNum = colors.length;
  16810. // TODO colors must be in order
  16811. for (var i = 0; i < paletteNum; i++) {
  16812. if (colors[i].length > requestColorNum) {
  16813. return colors[i];
  16814. }
  16815. }
  16816. return colors[paletteNum - 1];
  16817. }
  16818. var colorPaletteMixin = {
  16819. clearColorPalette: function () {
  16820. inner$2(this).colorIdx = 0;
  16821. inner$2(this).colorNameMap = {};
  16822. },
  16823. /**
  16824. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16825. * twise with the same parameters will get different result.
  16826. * @param {Object} [scope=this]
  16827. * @param {Object} [requestColorNum]
  16828. * @return {string} color string.
  16829. */
  16830. getColorFromPalette: function (name, scope, requestColorNum) {
  16831. scope = scope || this;
  16832. var scopeFields = inner$2(scope);
  16833. var colorIdx = scopeFields.colorIdx || 0;
  16834. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16835. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16836. if (colorNameMap.hasOwnProperty(name)) {
  16837. return colorNameMap[name];
  16838. }
  16839. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16840. var layeredColorPalette = this.get('colorLayer', true);
  16841. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16842. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16843. // In case can't find in layered color palette.
  16844. colorPalette = colorPalette || defaultColorPalette;
  16845. if (!colorPalette || !colorPalette.length) {
  16846. return;
  16847. }
  16848. var color = colorPalette[colorIdx];
  16849. if (name) {
  16850. colorNameMap[name] = color;
  16851. }
  16852. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16853. return color;
  16854. }
  16855. };
  16856. /*
  16857. * Licensed to the Apache Software Foundation (ASF) under one
  16858. * or more contributor license agreements. See the NOTICE file
  16859. * distributed with this work for additional information
  16860. * regarding copyright ownership. The ASF licenses this file
  16861. * to you under the Apache License, Version 2.0 (the
  16862. * "License"); you may not use this file except in compliance
  16863. * with the License. You may obtain a copy of the License at
  16864. *
  16865. * http://www.apache.org/licenses/LICENSE-2.0
  16866. *
  16867. * Unless required by applicable law or agreed to in writing,
  16868. * software distributed under the License is distributed on an
  16869. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16870. * KIND, either express or implied. See the License for the
  16871. * specific language governing permissions and limitations
  16872. * under the License.
  16873. */
  16874. /**
  16875. * Helper for model references.
  16876. * There are many manners to refer axis/coordSys.
  16877. */
  16878. // TODO
  16879. // merge relevant logic to this file?
  16880. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16881. /**
  16882. * @return {Object} For example:
  16883. * {
  16884. * coordSysName: 'cartesian2d',
  16885. * coordSysDims: ['x', 'y', ...],
  16886. * axisMap: HashMap({
  16887. * x: xAxisModel,
  16888. * y: yAxisModel
  16889. * }),
  16890. * categoryAxisMap: HashMap({
  16891. * x: xAxisModel,
  16892. * y: undefined
  16893. * }),
  16894. * // It also indicate that whether there is category axis.
  16895. * firstCategoryDimIndex: 1,
  16896. * // To replace user specified encode.
  16897. * }
  16898. */
  16899. function getCoordSysDefineBySeries(seriesModel) {
  16900. var coordSysName = seriesModel.get('coordinateSystem');
  16901. var result = {
  16902. coordSysName: coordSysName,
  16903. coordSysDims: [],
  16904. axisMap: createHashMap(),
  16905. categoryAxisMap: createHashMap()
  16906. };
  16907. var fetch = fetchers[coordSysName];
  16908. if (fetch) {
  16909. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16910. return result;
  16911. }
  16912. }
  16913. var fetchers = {
  16914. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16915. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16916. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16917. if (__DEV__) {
  16918. if (!xAxisModel) {
  16919. throw new Error('xAxis "' + retrieve(
  16920. seriesModel.get('xAxisIndex'),
  16921. seriesModel.get('xAxisId'),
  16922. 0
  16923. ) + '" not found');
  16924. }
  16925. if (!yAxisModel) {
  16926. throw new Error('yAxis "' + retrieve(
  16927. seriesModel.get('xAxisIndex'),
  16928. seriesModel.get('yAxisId'),
  16929. 0
  16930. ) + '" not found');
  16931. }
  16932. }
  16933. result.coordSysDims = ['x', 'y'];
  16934. axisMap.set('x', xAxisModel);
  16935. axisMap.set('y', yAxisModel);
  16936. if (isCategory(xAxisModel)) {
  16937. categoryAxisMap.set('x', xAxisModel);
  16938. result.firstCategoryDimIndex = 0;
  16939. }
  16940. if (isCategory(yAxisModel)) {
  16941. categoryAxisMap.set('y', yAxisModel);
  16942. result.firstCategoryDimIndex = 1;
  16943. }
  16944. },
  16945. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16946. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16947. if (__DEV__) {
  16948. if (!singleAxisModel) {
  16949. throw new Error('singleAxis should be specified.');
  16950. }
  16951. }
  16952. result.coordSysDims = ['single'];
  16953. axisMap.set('single', singleAxisModel);
  16954. if (isCategory(singleAxisModel)) {
  16955. categoryAxisMap.set('single', singleAxisModel);
  16956. result.firstCategoryDimIndex = 0;
  16957. }
  16958. },
  16959. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16960. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16961. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16962. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16963. if (__DEV__) {
  16964. if (!angleAxisModel) {
  16965. throw new Error('angleAxis option not found');
  16966. }
  16967. if (!radiusAxisModel) {
  16968. throw new Error('radiusAxis option not found');
  16969. }
  16970. }
  16971. result.coordSysDims = ['radius', 'angle'];
  16972. axisMap.set('radius', radiusAxisModel);
  16973. axisMap.set('angle', angleAxisModel);
  16974. if (isCategory(radiusAxisModel)) {
  16975. categoryAxisMap.set('radius', radiusAxisModel);
  16976. result.firstCategoryDimIndex = 0;
  16977. }
  16978. if (isCategory(angleAxisModel)) {
  16979. categoryAxisMap.set('angle', angleAxisModel);
  16980. result.firstCategoryDimIndex = 1;
  16981. }
  16982. },
  16983. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16984. result.coordSysDims = ['lng', 'lat'];
  16985. },
  16986. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16987. var ecModel = seriesModel.ecModel;
  16988. var parallelModel = ecModel.getComponent(
  16989. 'parallel', seriesModel.get('parallelIndex')
  16990. );
  16991. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16992. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16993. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16994. var axisDim = coordSysDims[index];
  16995. axisMap.set(axisDim, axisModel);
  16996. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16997. categoryAxisMap.set(axisDim, axisModel);
  16998. result.firstCategoryDimIndex = index;
  16999. }
  17000. });
  17001. }
  17002. };
  17003. function isCategory(axisModel) {
  17004. return axisModel.get('type') === 'category';
  17005. }
  17006. /*
  17007. * Licensed to the Apache Software Foundation (ASF) under one
  17008. * or more contributor license agreements. See the NOTICE file
  17009. * distributed with this work for additional information
  17010. * regarding copyright ownership. The ASF licenses this file
  17011. * to you under the Apache License, Version 2.0 (the
  17012. * "License"); you may not use this file except in compliance
  17013. * with the License. You may obtain a copy of the License at
  17014. *
  17015. * http://www.apache.org/licenses/LICENSE-2.0
  17016. *
  17017. * Unless required by applicable law or agreed to in writing,
  17018. * software distributed under the License is distributed on an
  17019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17020. * KIND, either express or implied. See the License for the
  17021. * specific language governing permissions and limitations
  17022. * under the License.
  17023. */
  17024. // Avoid typo.
  17025. var SOURCE_FORMAT_ORIGINAL = 'original';
  17026. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  17027. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  17028. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  17029. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  17030. // ??? CHANGE A NAME
  17031. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  17032. var SERIES_LAYOUT_BY_COLUMN = 'column';
  17033. var SERIES_LAYOUT_BY_ROW = 'row';
  17034. /*
  17035. * Licensed to the Apache Software Foundation (ASF) under one
  17036. * or more contributor license agreements. See the NOTICE file
  17037. * distributed with this work for additional information
  17038. * regarding copyright ownership. The ASF licenses this file
  17039. * to you under the Apache License, Version 2.0 (the
  17040. * "License"); you may not use this file except in compliance
  17041. * with the License. You may obtain a copy of the License at
  17042. *
  17043. * http://www.apache.org/licenses/LICENSE-2.0
  17044. *
  17045. * Unless required by applicable law or agreed to in writing,
  17046. * software distributed under the License is distributed on an
  17047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17048. * KIND, either express or implied. See the License for the
  17049. * specific language governing permissions and limitations
  17050. * under the License.
  17051. */
  17052. /**
  17053. * [sourceFormat]
  17054. *
  17055. * + "original":
  17056. * This format is only used in series.data, where
  17057. * itemStyle can be specified in data item.
  17058. *
  17059. * + "arrayRows":
  17060. * [
  17061. * ['product', 'score', 'amount'],
  17062. * ['Matcha Latte', 89.3, 95.8],
  17063. * ['Milk Tea', 92.1, 89.4],
  17064. * ['Cheese Cocoa', 94.4, 91.2],
  17065. * ['Walnut Brownie', 85.4, 76.9]
  17066. * ]
  17067. *
  17068. * + "objectRows":
  17069. * [
  17070. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17071. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17072. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17073. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17074. * ]
  17075. *
  17076. * + "keyedColumns":
  17077. * {
  17078. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17079. * 'count': [823, 235, 1042, 988],
  17080. * 'score': [95.8, 81.4, 91.2, 76.9]
  17081. * }
  17082. *
  17083. * + "typedArray"
  17084. *
  17085. * + "unknown"
  17086. */
  17087. /**
  17088. * @constructor
  17089. * @param {Object} fields
  17090. * @param {string} fields.sourceFormat
  17091. * @param {Array|Object} fields.fromDataset
  17092. * @param {Array|Object} [fields.data]
  17093. * @param {string} [seriesLayoutBy='column']
  17094. * @param {Array.<Object|string>} [dimensionsDefine]
  17095. * @param {Objet|HashMap} [encodeDefine]
  17096. * @param {number} [startIndex=0]
  17097. * @param {number} [dimensionsDetectCount]
  17098. */
  17099. function Source(fields) {
  17100. /**
  17101. * @type {boolean}
  17102. */
  17103. this.fromDataset = fields.fromDataset;
  17104. /**
  17105. * Not null/undefined.
  17106. * @type {Array|Object}
  17107. */
  17108. this.data = fields.data || (
  17109. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17110. );
  17111. /**
  17112. * See also "detectSourceFormat".
  17113. * Not null/undefined.
  17114. * @type {string}
  17115. */
  17116. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17117. /**
  17118. * 'row' or 'column'
  17119. * Not null/undefined.
  17120. * @type {string} seriesLayoutBy
  17121. */
  17122. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17123. /**
  17124. * dimensions definition in option.
  17125. * can be null/undefined.
  17126. * @type {Array.<Object|string>}
  17127. */
  17128. this.dimensionsDefine = fields.dimensionsDefine;
  17129. /**
  17130. * encode definition in option.
  17131. * can be null/undefined.
  17132. * @type {Objet|HashMap}
  17133. */
  17134. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17135. /**
  17136. * Not null/undefined, uint.
  17137. * @type {number}
  17138. */
  17139. this.startIndex = fields.startIndex || 0;
  17140. /**
  17141. * Can be null/undefined (when unknown), uint.
  17142. * @type {number}
  17143. */
  17144. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17145. }
  17146. /**
  17147. * Wrap original series data for some compatibility cases.
  17148. */
  17149. Source.seriesDataToSource = function (data) {
  17150. return new Source({
  17151. data: data,
  17152. sourceFormat: isTypedArray(data)
  17153. ? SOURCE_FORMAT_TYPED_ARRAY
  17154. : SOURCE_FORMAT_ORIGINAL,
  17155. fromDataset: false
  17156. });
  17157. };
  17158. enableClassCheck(Source);
  17159. /*
  17160. * Licensed to the Apache Software Foundation (ASF) under one
  17161. * or more contributor license agreements. See the NOTICE file
  17162. * distributed with this work for additional information
  17163. * regarding copyright ownership. The ASF licenses this file
  17164. * to you under the Apache License, Version 2.0 (the
  17165. * "License"); you may not use this file except in compliance
  17166. * with the License. You may obtain a copy of the License at
  17167. *
  17168. * http://www.apache.org/licenses/LICENSE-2.0
  17169. *
  17170. * Unless required by applicable law or agreed to in writing,
  17171. * software distributed under the License is distributed on an
  17172. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17173. * KIND, either express or implied. See the License for the
  17174. * specific language governing permissions and limitations
  17175. * under the License.
  17176. */
  17177. var inner$3 = makeInner();
  17178. /**
  17179. * @see {module:echarts/data/Source}
  17180. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17181. * @return {string} sourceFormat
  17182. */
  17183. function detectSourceFormat(datasetModel) {
  17184. var data = datasetModel.option.source;
  17185. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17186. if (isTypedArray(data)) {
  17187. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17188. }
  17189. else if (isArray(data)) {
  17190. // FIXME Whether tolerate null in top level array?
  17191. if (data.length === 0) {
  17192. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17193. }
  17194. for (var i = 0, len = data.length; i < len; i++) {
  17195. var item = data[i];
  17196. if (item == null) {
  17197. continue;
  17198. }
  17199. else if (isArray(item)) {
  17200. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17201. break;
  17202. }
  17203. else if (isObject$1(item)) {
  17204. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17205. break;
  17206. }
  17207. }
  17208. }
  17209. else if (isObject$1(data)) {
  17210. for (var key in data) {
  17211. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17212. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17213. break;
  17214. }
  17215. }
  17216. }
  17217. else if (data != null) {
  17218. throw new Error('Invalid data');
  17219. }
  17220. inner$3(datasetModel).sourceFormat = sourceFormat;
  17221. }
  17222. /**
  17223. * [Scenarios]:
  17224. * (1) Provide source data directly:
  17225. * series: {
  17226. * encode: {...},
  17227. * dimensions: [...]
  17228. * seriesLayoutBy: 'row',
  17229. * data: [[...]]
  17230. * }
  17231. * (2) Refer to datasetModel.
  17232. * series: [{
  17233. * encode: {...}
  17234. * // Ignore datasetIndex means `datasetIndex: 0`
  17235. * // and the dimensions defination in dataset is used
  17236. * }, {
  17237. * encode: {...},
  17238. * seriesLayoutBy: 'column',
  17239. * datasetIndex: 1
  17240. * }]
  17241. *
  17242. * Get data from series itself or datset.
  17243. * @return {module:echarts/data/Source} source
  17244. */
  17245. function getSource(seriesModel) {
  17246. return inner$3(seriesModel).source;
  17247. }
  17248. /**
  17249. * MUST be called before mergeOption of all series.
  17250. * @param {module:echarts/model/Global} ecModel
  17251. */
  17252. function resetSourceDefaulter(ecModel) {
  17253. // `datasetMap` is used to make default encode.
  17254. inner$3(ecModel).datasetMap = createHashMap();
  17255. }
  17256. /**
  17257. * [Caution]:
  17258. * MUST be called after series option merged and
  17259. * before "series.getInitailData()" called.
  17260. *
  17261. * [The rule of making default encode]:
  17262. * Category axis (if exists) alway map to the first dimension.
  17263. * Each other axis occupies a subsequent dimension.
  17264. *
  17265. * [Why make default encode]:
  17266. * Simplify the typing of encode in option, avoiding the case like that:
  17267. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17268. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17269. *
  17270. * @param {module:echarts/model/Series} seriesModel
  17271. */
  17272. function prepareSource(seriesModel) {
  17273. var seriesOption = seriesModel.option;
  17274. var data = seriesOption.data;
  17275. var sourceFormat = isTypedArray(data)
  17276. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17277. var fromDataset = false;
  17278. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17279. var sourceHeader = seriesOption.sourceHeader;
  17280. var dimensionsDefine = seriesOption.dimensions;
  17281. var datasetModel = getDatasetModel(seriesModel);
  17282. if (datasetModel) {
  17283. var datasetOption = datasetModel.option;
  17284. data = datasetOption.source;
  17285. sourceFormat = inner$3(datasetModel).sourceFormat;
  17286. fromDataset = true;
  17287. // These settings from series has higher priority.
  17288. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17289. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17290. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17291. }
  17292. var completeResult = completeBySourceData(
  17293. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17294. );
  17295. // Note: dataset option does not have `encode`.
  17296. var encodeDefine = seriesOption.encode;
  17297. if (!encodeDefine && datasetModel) {
  17298. encodeDefine = makeDefaultEncode(
  17299. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17300. );
  17301. }
  17302. inner$3(seriesModel).source = new Source({
  17303. data: data,
  17304. fromDataset: fromDataset,
  17305. seriesLayoutBy: seriesLayoutBy,
  17306. sourceFormat: sourceFormat,
  17307. dimensionsDefine: completeResult.dimensionsDefine,
  17308. startIndex: completeResult.startIndex,
  17309. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17310. encodeDefine: encodeDefine
  17311. });
  17312. }
  17313. // return {startIndex, dimensionsDefine, dimensionsCount}
  17314. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17315. if (!data) {
  17316. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17317. }
  17318. var dimensionsDetectCount;
  17319. var startIndex;
  17320. var findPotentialName;
  17321. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17322. // Rule: Most of the first line are string: it is header.
  17323. // Caution: consider a line with 5 string and 1 number,
  17324. // it still can not be sure it is a head, because the
  17325. // 5 string may be 5 values of category columns.
  17326. if (sourceHeader === 'auto' || sourceHeader == null) {
  17327. arrayRowsTravelFirst(function (val) {
  17328. // '-' is regarded as null/undefined.
  17329. if (val != null && val !== '-') {
  17330. if (isString(val)) {
  17331. startIndex == null && (startIndex = 1);
  17332. }
  17333. else {
  17334. startIndex = 0;
  17335. }
  17336. }
  17337. // 10 is an experience number, avoid long loop.
  17338. }, seriesLayoutBy, data, 10);
  17339. }
  17340. else {
  17341. startIndex = sourceHeader ? 1 : 0;
  17342. }
  17343. if (!dimensionsDefine && startIndex === 1) {
  17344. dimensionsDefine = [];
  17345. arrayRowsTravelFirst(function (val, index) {
  17346. dimensionsDefine[index] = val != null ? val : '';
  17347. }, seriesLayoutBy, data);
  17348. }
  17349. dimensionsDetectCount = dimensionsDefine
  17350. ? dimensionsDefine.length
  17351. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17352. ? data.length
  17353. : data[0]
  17354. ? data[0].length
  17355. : null;
  17356. }
  17357. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17358. if (!dimensionsDefine) {
  17359. dimensionsDefine = objectRowsCollectDimensions(data);
  17360. findPotentialName = true;
  17361. }
  17362. }
  17363. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17364. if (!dimensionsDefine) {
  17365. dimensionsDefine = [];
  17366. findPotentialName = true;
  17367. each$1(data, function (colArr, key) {
  17368. dimensionsDefine.push(key);
  17369. });
  17370. }
  17371. }
  17372. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17373. var value0 = getDataItemValue(data[0]);
  17374. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17375. }
  17376. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17377. if (__DEV__) {
  17378. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17379. }
  17380. }
  17381. var potentialNameDimIndex;
  17382. if (findPotentialName) {
  17383. each$1(dimensionsDefine, function (dim, idx) {
  17384. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17385. potentialNameDimIndex = idx;
  17386. }
  17387. });
  17388. }
  17389. return {
  17390. startIndex: startIndex,
  17391. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17392. dimensionsDetectCount: dimensionsDetectCount,
  17393. potentialNameDimIndex: potentialNameDimIndex
  17394. // TODO: potentialIdDimIdx
  17395. };
  17396. }
  17397. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17398. // which is reasonable. But dimension name is duplicated.
  17399. // Returns undefined or an array contains only object without null/undefiend or string.
  17400. function normalizeDimensionsDefine(dimensionsDefine) {
  17401. if (!dimensionsDefine) {
  17402. // The meaning of null/undefined is different from empty array.
  17403. return;
  17404. }
  17405. var nameMap = createHashMap();
  17406. return map(dimensionsDefine, function (item, index) {
  17407. item = extend({}, isObject$1(item) ? item : {name: item});
  17408. // User can set null in dimensions.
  17409. // We dont auto specify name, othewise a given name may
  17410. // cause it be refered unexpectedly.
  17411. if (item.name == null) {
  17412. return item;
  17413. }
  17414. // Also consider number form like 2012.
  17415. item.name += '';
  17416. // User may also specify displayName.
  17417. // displayName will always exists except user not
  17418. // specified or dim name is not specified or detected.
  17419. // (A auto generated dim name will not be used as
  17420. // displayName).
  17421. if (item.displayName == null) {
  17422. item.displayName = item.name;
  17423. }
  17424. var exist = nameMap.get(item.name);
  17425. if (!exist) {
  17426. nameMap.set(item.name, {count: 1});
  17427. }
  17428. else {
  17429. item.name += '-' + exist.count++;
  17430. }
  17431. return item;
  17432. });
  17433. }
  17434. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17435. maxLoop == null && (maxLoop = Infinity);
  17436. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17437. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17438. cb(data[i] ? data[i][0] : null, i);
  17439. }
  17440. }
  17441. else {
  17442. var value0 = data[0] || [];
  17443. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17444. cb(value0[i], i);
  17445. }
  17446. }
  17447. }
  17448. function objectRowsCollectDimensions(data) {
  17449. var firstIndex = 0;
  17450. var obj;
  17451. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17452. if (obj) {
  17453. var dimensions = [];
  17454. each$1(obj, function (value, key) {
  17455. dimensions.push(key);
  17456. });
  17457. return dimensions;
  17458. }
  17459. }
  17460. // ??? TODO merge to completedimensions, where also has
  17461. // default encode making logic. And the default rule
  17462. // should depends on series? consider 'map'.
  17463. function makeDefaultEncode(
  17464. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17465. ) {
  17466. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17467. var encode = {};
  17468. // var encodeTooltip = [];
  17469. // var encodeLabel = [];
  17470. var encodeItemName = [];
  17471. var encodeSeriesName = [];
  17472. var seriesType = seriesModel.subType;
  17473. // ??? TODO refactor: provide by series itself.
  17474. // Consider the case: 'map' series is based on geo coordSys,
  17475. // 'graph', 'heatmap' can be based on cartesian. But can not
  17476. // give default rule simply here.
  17477. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  17478. var cSeriesMap = createHashMap([
  17479. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  17480. ]);
  17481. // Usually in this case series will use the first data
  17482. // dimension as the "value" dimension, or other default
  17483. // processes respectively.
  17484. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  17485. var ecModel = seriesModel.ecModel;
  17486. var datasetMap = inner$3(ecModel).datasetMap;
  17487. var key = datasetModel.uid + '_' + seriesLayoutBy;
  17488. var datasetRecord = datasetMap.get(key)
  17489. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  17490. // TODO
  17491. // Auto detect first time axis and do arrangement.
  17492. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  17493. // In value way.
  17494. if (coordSysDefine.firstCategoryDimIndex == null) {
  17495. var dataDim = datasetRecord.valueWayDim++;
  17496. encode[coordDim] = dataDim;
  17497. // ??? TODO give a better default series name rule?
  17498. // especially when encode x y specified.
  17499. // consider: when mutiple series share one dimension
  17500. // category axis, series name should better use
  17501. // the other dimsion name. On the other hand, use
  17502. // both dimensions name.
  17503. encodeSeriesName.push(dataDim);
  17504. // encodeTooltip.push(dataDim);
  17505. // encodeLabel.push(dataDim);
  17506. }
  17507. // In category way, category axis.
  17508. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  17509. encode[coordDim] = 0;
  17510. encodeItemName.push(0);
  17511. }
  17512. // In category way, non-category axis.
  17513. else {
  17514. var dataDim = datasetRecord.categoryWayDim++;
  17515. encode[coordDim] = dataDim;
  17516. // encodeTooltip.push(dataDim);
  17517. // encodeLabel.push(dataDim);
  17518. encodeSeriesName.push(dataDim);
  17519. }
  17520. });
  17521. }
  17522. // Do not make a complex rule! Hard to code maintain and not necessary.
  17523. // ??? TODO refactor: provide by series itself.
  17524. // [{name: ..., value: ...}, ...] like:
  17525. else if (nSeriesMap.get(seriesType) != null) {
  17526. // Find the first not ordinal. (5 is an experience value)
  17527. var firstNotOrdinal;
  17528. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  17529. if (!doGuessOrdinal(
  17530. data, sourceFormat, seriesLayoutBy,
  17531. completeResult.dimensionsDefine, completeResult.startIndex, i
  17532. )) {
  17533. firstNotOrdinal = i;
  17534. }
  17535. }
  17536. if (firstNotOrdinal != null) {
  17537. encode.value = firstNotOrdinal;
  17538. var nameDimIndex = completeResult.potentialNameDimIndex
  17539. || Math.max(firstNotOrdinal - 1, 0);
  17540. // By default, label use itemName in charts.
  17541. // So we dont set encodeLabel here.
  17542. encodeSeriesName.push(nameDimIndex);
  17543. encodeItemName.push(nameDimIndex);
  17544. // encodeTooltip.push(firstNotOrdinal);
  17545. }
  17546. }
  17547. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  17548. // encodeLabel.length && (encode.label = encodeLabel);
  17549. encodeItemName.length && (encode.itemName = encodeItemName);
  17550. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17551. return encode;
  17552. }
  17553. /**
  17554. * If return null/undefined, indicate that should not use datasetModel.
  17555. */
  17556. function getDatasetModel(seriesModel) {
  17557. var option = seriesModel.option;
  17558. // Caution: consider the scenario:
  17559. // A dataset is declared and a series is not expected to use the dataset,
  17560. // and at the beginning `setOption({series: { noData })` (just prepare other
  17561. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17562. // the user should set an empty array to avoid that dataset is used by default.
  17563. var thisData = option.data;
  17564. if (!thisData) {
  17565. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17566. }
  17567. }
  17568. /**
  17569. * The rule should not be complex, otherwise user might not
  17570. * be able to known where the data is wrong.
  17571. * The code is ugly, but how to make it neat?
  17572. *
  17573. * @param {module:echars/data/Source} source
  17574. * @param {number} dimIndex
  17575. * @return {boolean} Whether ordinal.
  17576. */
  17577. function guessOrdinal(source, dimIndex) {
  17578. return doGuessOrdinal(
  17579. source.data,
  17580. source.sourceFormat,
  17581. source.seriesLayoutBy,
  17582. source.dimensionsDefine,
  17583. source.startIndex,
  17584. dimIndex
  17585. );
  17586. }
  17587. // dimIndex may be overflow source data.
  17588. function doGuessOrdinal(
  17589. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17590. ) {
  17591. var result;
  17592. // Experience value.
  17593. var maxLoop = 5;
  17594. if (isTypedArray(data)) {
  17595. return false;
  17596. }
  17597. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17598. // always exists in source.
  17599. var dimName;
  17600. if (dimensionsDefine) {
  17601. dimName = dimensionsDefine[dimIndex];
  17602. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17603. }
  17604. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17605. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17606. var sample = data[dimIndex];
  17607. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17608. if ((result = detectValue(sample[startIndex + i])) != null) {
  17609. return result;
  17610. }
  17611. }
  17612. }
  17613. else {
  17614. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17615. var row = data[startIndex + i];
  17616. if (row && (result = detectValue(row[dimIndex])) != null) {
  17617. return result;
  17618. }
  17619. }
  17620. }
  17621. }
  17622. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17623. if (!dimName) {
  17624. return;
  17625. }
  17626. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17627. var item = data[i];
  17628. if (item && (result = detectValue(item[dimName])) != null) {
  17629. return result;
  17630. }
  17631. }
  17632. }
  17633. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17634. if (!dimName) {
  17635. return;
  17636. }
  17637. var sample = data[dimName];
  17638. if (!sample || isTypedArray(sample)) {
  17639. return false;
  17640. }
  17641. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17642. if ((result = detectValue(sample[i])) != null) {
  17643. return result;
  17644. }
  17645. }
  17646. }
  17647. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17648. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17649. var item = data[i];
  17650. var val = getDataItemValue(item);
  17651. if (!isArray(val)) {
  17652. return false;
  17653. }
  17654. if ((result = detectValue(val[dimIndex])) != null) {
  17655. return result;
  17656. }
  17657. }
  17658. }
  17659. function detectValue(val) {
  17660. // Consider usage convenience, '1', '2' will be treated as "number".
  17661. // `isFinit('')` get `true`.
  17662. if (val != null && isFinite(val) && val !== '') {
  17663. return false;
  17664. }
  17665. else if (isString(val) && val !== '-') {
  17666. return true;
  17667. }
  17668. }
  17669. return false;
  17670. }
  17671. /*
  17672. * Licensed to the Apache Software Foundation (ASF) under one
  17673. * or more contributor license agreements. See the NOTICE file
  17674. * distributed with this work for additional information
  17675. * regarding copyright ownership. The ASF licenses this file
  17676. * to you under the Apache License, Version 2.0 (the
  17677. * "License"); you may not use this file except in compliance
  17678. * with the License. You may obtain a copy of the License at
  17679. *
  17680. * http://www.apache.org/licenses/LICENSE-2.0
  17681. *
  17682. * Unless required by applicable law or agreed to in writing,
  17683. * software distributed under the License is distributed on an
  17684. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17685. * KIND, either express or implied. See the License for the
  17686. * specific language governing permissions and limitations
  17687. * under the License.
  17688. */
  17689. /**
  17690. * ECharts global model
  17691. *
  17692. * @module {echarts/model/Global}
  17693. */
  17694. /**
  17695. * Caution: If the mechanism should be changed some day, these cases
  17696. * should be considered:
  17697. *
  17698. * (1) In `merge option` mode, if using the same option to call `setOption`
  17699. * many times, the result should be the same (try our best to ensure that).
  17700. * (2) In `merge option` mode, if a component has no id/name specified, it
  17701. * will be merged by index, and the result sequence of the components is
  17702. * consistent to the original sequence.
  17703. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17704. * `mergeOption` in module:echarts/model/OptionManager.
  17705. */
  17706. var OPTION_INNER_KEY = '\0_ec_inner';
  17707. /**
  17708. * @alias module:echarts/model/Global
  17709. *
  17710. * @param {Object} option
  17711. * @param {module:echarts/model/Model} parentModel
  17712. * @param {Object} theme
  17713. */
  17714. var GlobalModel = Model.extend({
  17715. init: function (option, parentModel, theme, optionManager) {
  17716. theme = theme || {};
  17717. this.option = null; // Mark as not initialized.
  17718. /**
  17719. * @type {module:echarts/model/Model}
  17720. * @private
  17721. */
  17722. this._theme = new Model(theme);
  17723. /**
  17724. * @type {module:echarts/model/OptionManager}
  17725. */
  17726. this._optionManager = optionManager;
  17727. },
  17728. setOption: function (option, optionPreprocessorFuncs) {
  17729. assert$1(
  17730. !(OPTION_INNER_KEY in option),
  17731. 'please use chart.getOption()'
  17732. );
  17733. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17734. this.resetOption(null);
  17735. },
  17736. /**
  17737. * @param {string} type null/undefined: reset all.
  17738. * 'recreate': force recreate all.
  17739. * 'timeline': only reset timeline option
  17740. * 'media': only reset media query option
  17741. * @return {boolean} Whether option changed.
  17742. */
  17743. resetOption: function (type) {
  17744. var optionChanged = false;
  17745. var optionManager = this._optionManager;
  17746. if (!type || type === 'recreate') {
  17747. var baseOption = optionManager.mountOption(type === 'recreate');
  17748. if (!this.option || type === 'recreate') {
  17749. initBase.call(this, baseOption);
  17750. }
  17751. else {
  17752. this.restoreData();
  17753. this.mergeOption(baseOption);
  17754. }
  17755. optionChanged = true;
  17756. }
  17757. if (type === 'timeline' || type === 'media') {
  17758. this.restoreData();
  17759. }
  17760. if (!type || type === 'recreate' || type === 'timeline') {
  17761. var timelineOption = optionManager.getTimelineOption(this);
  17762. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17763. }
  17764. if (!type || type === 'recreate' || type === 'media') {
  17765. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17766. if (mediaOptions.length) {
  17767. each$1(mediaOptions, function (mediaOption) {
  17768. this.mergeOption(mediaOption, optionChanged = true);
  17769. }, this);
  17770. }
  17771. }
  17772. return optionChanged;
  17773. },
  17774. /**
  17775. * @protected
  17776. */
  17777. mergeOption: function (newOption) {
  17778. var option = this.option;
  17779. var componentsMap = this._componentsMap;
  17780. var newCptTypes = [];
  17781. resetSourceDefaulter(this);
  17782. // If no component class, merge directly.
  17783. // For example: color, animaiton options, etc.
  17784. each$1(newOption, function (componentOption, mainType) {
  17785. if (componentOption == null) {
  17786. return;
  17787. }
  17788. if (!ComponentModel.hasClass(mainType)) {
  17789. // globalSettingTask.dirty();
  17790. option[mainType] = option[mainType] == null
  17791. ? clone(componentOption)
  17792. : merge(option[mainType], componentOption, true);
  17793. }
  17794. else if (mainType) {
  17795. newCptTypes.push(mainType);
  17796. }
  17797. });
  17798. ComponentModel.topologicalTravel(
  17799. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17800. );
  17801. function visitComponent(mainType, dependencies) {
  17802. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17803. var mapResult = mappingToExists(
  17804. componentsMap.get(mainType), newCptOptionList
  17805. );
  17806. makeIdAndName(mapResult);
  17807. // Set mainType and complete subType.
  17808. each$1(mapResult, function (item, index) {
  17809. var opt = item.option;
  17810. if (isObject$1(opt)) {
  17811. item.keyInfo.mainType = mainType;
  17812. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17813. }
  17814. });
  17815. var dependentModels = getComponentsByTypes(
  17816. componentsMap, dependencies
  17817. );
  17818. option[mainType] = [];
  17819. componentsMap.set(mainType, []);
  17820. each$1(mapResult, function (resultItem, index) {
  17821. var componentModel = resultItem.exist;
  17822. var newCptOption = resultItem.option;
  17823. assert$1(
  17824. isObject$1(newCptOption) || componentModel,
  17825. 'Empty component definition'
  17826. );
  17827. // Consider where is no new option and should be merged using {},
  17828. // see removeEdgeAndAdd in topologicalTravel and
  17829. // ComponentModel.getAllClassMainTypes.
  17830. if (!newCptOption) {
  17831. componentModel.mergeOption({}, this);
  17832. componentModel.optionUpdated({}, false);
  17833. }
  17834. else {
  17835. var ComponentModelClass = ComponentModel.getClass(
  17836. mainType, resultItem.keyInfo.subType, true
  17837. );
  17838. if (componentModel && componentModel instanceof ComponentModelClass) {
  17839. componentModel.name = resultItem.keyInfo.name;
  17840. // componentModel.settingTask && componentModel.settingTask.dirty();
  17841. componentModel.mergeOption(newCptOption, this);
  17842. componentModel.optionUpdated(newCptOption, false);
  17843. }
  17844. else {
  17845. // PENDING Global as parent ?
  17846. var extraOpt = extend(
  17847. {
  17848. dependentModels: dependentModels,
  17849. componentIndex: index
  17850. },
  17851. resultItem.keyInfo
  17852. );
  17853. componentModel = new ComponentModelClass(
  17854. newCptOption, this, this, extraOpt
  17855. );
  17856. extend(componentModel, extraOpt);
  17857. componentModel.init(newCptOption, this, this, extraOpt);
  17858. // Call optionUpdated after init.
  17859. // newCptOption has been used as componentModel.option
  17860. // and may be merged with theme and default, so pass null
  17861. // to avoid confusion.
  17862. componentModel.optionUpdated(null, true);
  17863. }
  17864. }
  17865. componentsMap.get(mainType)[index] = componentModel;
  17866. option[mainType][index] = componentModel.option;
  17867. }, this);
  17868. // Backup series for filtering.
  17869. if (mainType === 'series') {
  17870. createSeriesIndices(this, componentsMap.get('series'));
  17871. }
  17872. }
  17873. this._seriesIndicesMap = createHashMap(
  17874. this._seriesIndices = this._seriesIndices || []
  17875. );
  17876. },
  17877. /**
  17878. * Get option for output (cloned option and inner info removed)
  17879. * @public
  17880. * @return {Object}
  17881. */
  17882. getOption: function () {
  17883. var option = clone(this.option);
  17884. each$1(option, function (opts, mainType) {
  17885. if (ComponentModel.hasClass(mainType)) {
  17886. var opts = normalizeToArray(opts);
  17887. for (var i = opts.length - 1; i >= 0; i--) {
  17888. // Remove options with inner id.
  17889. if (isIdInner(opts[i])) {
  17890. opts.splice(i, 1);
  17891. }
  17892. }
  17893. option[mainType] = opts;
  17894. }
  17895. });
  17896. delete option[OPTION_INNER_KEY];
  17897. return option;
  17898. },
  17899. /**
  17900. * @return {module:echarts/model/Model}
  17901. */
  17902. getTheme: function () {
  17903. return this._theme;
  17904. },
  17905. /**
  17906. * @param {string} mainType
  17907. * @param {number} [idx=0]
  17908. * @return {module:echarts/model/Component}
  17909. */
  17910. getComponent: function (mainType, idx) {
  17911. var list = this._componentsMap.get(mainType);
  17912. if (list) {
  17913. return list[idx || 0];
  17914. }
  17915. },
  17916. /**
  17917. * If none of index and id and name used, return all components with mainType.
  17918. * @param {Object} condition
  17919. * @param {string} condition.mainType
  17920. * @param {string} [condition.subType] If ignore, only query by mainType
  17921. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17922. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17923. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17924. * @return {Array.<module:echarts/model/Component>}
  17925. */
  17926. queryComponents: function (condition) {
  17927. var mainType = condition.mainType;
  17928. if (!mainType) {
  17929. return [];
  17930. }
  17931. var index = condition.index;
  17932. var id = condition.id;
  17933. var name = condition.name;
  17934. var cpts = this._componentsMap.get(mainType);
  17935. if (!cpts || !cpts.length) {
  17936. return [];
  17937. }
  17938. var result;
  17939. if (index != null) {
  17940. if (!isArray(index)) {
  17941. index = [index];
  17942. }
  17943. result = filter(map(index, function (idx) {
  17944. return cpts[idx];
  17945. }), function (val) {
  17946. return !!val;
  17947. });
  17948. }
  17949. else if (id != null) {
  17950. var isIdArray = isArray(id);
  17951. result = filter(cpts, function (cpt) {
  17952. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17953. || (!isIdArray && cpt.id === id);
  17954. });
  17955. }
  17956. else if (name != null) {
  17957. var isNameArray = isArray(name);
  17958. result = filter(cpts, function (cpt) {
  17959. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17960. || (!isNameArray && cpt.name === name);
  17961. });
  17962. }
  17963. else {
  17964. // Return all components with mainType
  17965. result = cpts.slice();
  17966. }
  17967. return filterBySubType(result, condition);
  17968. },
  17969. /**
  17970. * The interface is different from queryComponents,
  17971. * which is convenient for inner usage.
  17972. *
  17973. * @usage
  17974. * var result = findComponents(
  17975. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17976. * );
  17977. * var result = findComponents(
  17978. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17979. * );
  17980. * var result = findComponents(
  17981. * {mainType: 'series'},
  17982. * function (model, index) {...}
  17983. * );
  17984. * // result like [component0, componnet1, ...]
  17985. *
  17986. * @param {Object} condition
  17987. * @param {string} condition.mainType Mandatory.
  17988. * @param {string} [condition.subType] Optional.
  17989. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17990. * where xxx is mainType.
  17991. * If query attribute is null/undefined or has no index/id/name,
  17992. * do not filtering by query conditions, which is convenient for
  17993. * no-payload situations or when target of action is global.
  17994. * @param {Function} [condition.filter] parameter: component, return boolean.
  17995. * @return {Array.<module:echarts/model/Component>}
  17996. */
  17997. findComponents: function (condition) {
  17998. var query = condition.query;
  17999. var mainType = condition.mainType;
  18000. var queryCond = getQueryCond(query);
  18001. var result = queryCond
  18002. ? this.queryComponents(queryCond)
  18003. : this._componentsMap.get(mainType);
  18004. return doFilter(filterBySubType(result, condition));
  18005. function getQueryCond(q) {
  18006. var indexAttr = mainType + 'Index';
  18007. var idAttr = mainType + 'Id';
  18008. var nameAttr = mainType + 'Name';
  18009. return q && (
  18010. q[indexAttr] != null
  18011. || q[idAttr] != null
  18012. || q[nameAttr] != null
  18013. )
  18014. ? {
  18015. mainType: mainType,
  18016. // subType will be filtered finally.
  18017. index: q[indexAttr],
  18018. id: q[idAttr],
  18019. name: q[nameAttr]
  18020. }
  18021. : null;
  18022. }
  18023. function doFilter(res) {
  18024. return condition.filter
  18025. ? filter(res, condition.filter)
  18026. : res;
  18027. }
  18028. },
  18029. /**
  18030. * @usage
  18031. * eachComponent('legend', function (legendModel, index) {
  18032. * ...
  18033. * });
  18034. * eachComponent(function (componentType, model, index) {
  18035. * // componentType does not include subType
  18036. * // (componentType is 'xxx' but not 'xxx.aa')
  18037. * });
  18038. * eachComponent(
  18039. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  18040. * function (model, index) {...}
  18041. * );
  18042. * eachComponent(
  18043. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  18044. * function (model, index) {...}
  18045. * );
  18046. *
  18047. * @param {string|Object=} mainType When mainType is object, the definition
  18048. * is the same as the method 'findComponents'.
  18049. * @param {Function} cb
  18050. * @param {*} context
  18051. */
  18052. eachComponent: function (mainType, cb, context) {
  18053. var componentsMap = this._componentsMap;
  18054. if (typeof mainType === 'function') {
  18055. context = cb;
  18056. cb = mainType;
  18057. componentsMap.each(function (components, componentType) {
  18058. each$1(components, function (component, index) {
  18059. cb.call(context, componentType, component, index);
  18060. });
  18061. });
  18062. }
  18063. else if (isString(mainType)) {
  18064. each$1(componentsMap.get(mainType), cb, context);
  18065. }
  18066. else if (isObject$1(mainType)) {
  18067. var queryResult = this.findComponents(mainType);
  18068. each$1(queryResult, cb, context);
  18069. }
  18070. },
  18071. /**
  18072. * @param {string} name
  18073. * @return {Array.<module:echarts/model/Series>}
  18074. */
  18075. getSeriesByName: function (name) {
  18076. var series = this._componentsMap.get('series');
  18077. return filter(series, function (oneSeries) {
  18078. return oneSeries.name === name;
  18079. });
  18080. },
  18081. /**
  18082. * @param {number} seriesIndex
  18083. * @return {module:echarts/model/Series}
  18084. */
  18085. getSeriesByIndex: function (seriesIndex) {
  18086. return this._componentsMap.get('series')[seriesIndex];
  18087. },
  18088. /**
  18089. * Get series list before filtered by type.
  18090. * FIXME: rename to getRawSeriesByType?
  18091. *
  18092. * @param {string} subType
  18093. * @return {Array.<module:echarts/model/Series>}
  18094. */
  18095. getSeriesByType: function (subType) {
  18096. var series = this._componentsMap.get('series');
  18097. return filter(series, function (oneSeries) {
  18098. return oneSeries.subType === subType;
  18099. });
  18100. },
  18101. /**
  18102. * @return {Array.<module:echarts/model/Series>}
  18103. */
  18104. getSeries: function () {
  18105. return this._componentsMap.get('series').slice();
  18106. },
  18107. /**
  18108. * @return {number}
  18109. */
  18110. getSeriesCount: function () {
  18111. return this._componentsMap.get('series').length;
  18112. },
  18113. /**
  18114. * After filtering, series may be different
  18115. * frome raw series.
  18116. *
  18117. * @param {Function} cb
  18118. * @param {*} context
  18119. */
  18120. eachSeries: function (cb, context) {
  18121. assertSeriesInitialized(this);
  18122. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18123. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18124. cb.call(context, series, rawSeriesIndex);
  18125. }, this);
  18126. },
  18127. /**
  18128. * Iterate raw series before filtered.
  18129. *
  18130. * @param {Function} cb
  18131. * @param {*} context
  18132. */
  18133. eachRawSeries: function (cb, context) {
  18134. each$1(this._componentsMap.get('series'), cb, context);
  18135. },
  18136. /**
  18137. * After filtering, series may be different.
  18138. * frome raw series.
  18139. *
  18140. * @parma {string} subType
  18141. * @param {Function} cb
  18142. * @param {*} context
  18143. */
  18144. eachSeriesByType: function (subType, cb, context) {
  18145. assertSeriesInitialized(this);
  18146. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18147. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18148. if (series.subType === subType) {
  18149. cb.call(context, series, rawSeriesIndex);
  18150. }
  18151. }, this);
  18152. },
  18153. /**
  18154. * Iterate raw series before filtered of given type.
  18155. *
  18156. * @parma {string} subType
  18157. * @param {Function} cb
  18158. * @param {*} context
  18159. */
  18160. eachRawSeriesByType: function (subType, cb, context) {
  18161. return each$1(this.getSeriesByType(subType), cb, context);
  18162. },
  18163. /**
  18164. * @param {module:echarts/model/Series} seriesModel
  18165. */
  18166. isSeriesFiltered: function (seriesModel) {
  18167. assertSeriesInitialized(this);
  18168. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18169. },
  18170. /**
  18171. * @return {Array.<number>}
  18172. */
  18173. getCurrentSeriesIndices: function () {
  18174. return (this._seriesIndices || []).slice();
  18175. },
  18176. /**
  18177. * @param {Function} cb
  18178. * @param {*} context
  18179. */
  18180. filterSeries: function (cb, context) {
  18181. assertSeriesInitialized(this);
  18182. var filteredSeries = filter(
  18183. this._componentsMap.get('series'), cb, context
  18184. );
  18185. createSeriesIndices(this, filteredSeries);
  18186. },
  18187. restoreData: function (payload) {
  18188. var componentsMap = this._componentsMap;
  18189. createSeriesIndices(this, componentsMap.get('series'));
  18190. var componentTypes = [];
  18191. componentsMap.each(function (components, componentType) {
  18192. componentTypes.push(componentType);
  18193. });
  18194. ComponentModel.topologicalTravel(
  18195. componentTypes,
  18196. ComponentModel.getAllClassMainTypes(),
  18197. function (componentType, dependencies) {
  18198. each$1(componentsMap.get(componentType), function (component) {
  18199. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18200. && component.restoreData();
  18201. });
  18202. }
  18203. );
  18204. }
  18205. });
  18206. function isNotTargetSeries(seriesModel, payload) {
  18207. if (payload) {
  18208. var index = payload.seiresIndex;
  18209. var id = payload.seriesId;
  18210. var name = payload.seriesName;
  18211. return (index != null && seriesModel.componentIndex !== index)
  18212. || (id != null && seriesModel.id !== id)
  18213. || (name != null && seriesModel.name !== name);
  18214. }
  18215. }
  18216. /**
  18217. * @inner
  18218. */
  18219. function mergeTheme(option, theme) {
  18220. // PENDING
  18221. // NOT use `colorLayer` in theme if option has `color`
  18222. var notMergeColorLayer = option.color && !option.colorLayer;
  18223. each$1(theme, function (themeItem, name) {
  18224. if (name === 'colorLayer' && notMergeColorLayer) {
  18225. return;
  18226. }
  18227. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18228. if (!ComponentModel.hasClass(name)) {
  18229. if (typeof themeItem === 'object') {
  18230. option[name] = !option[name]
  18231. ? clone(themeItem)
  18232. : merge(option[name], themeItem, false);
  18233. }
  18234. else {
  18235. if (option[name] == null) {
  18236. option[name] = themeItem;
  18237. }
  18238. }
  18239. }
  18240. });
  18241. }
  18242. function initBase(baseOption) {
  18243. baseOption = baseOption;
  18244. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18245. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18246. this.option = {};
  18247. this.option[OPTION_INNER_KEY] = 1;
  18248. /**
  18249. * Init with series: [], in case of calling findSeries method
  18250. * before series initialized.
  18251. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18252. * @private
  18253. */
  18254. this._componentsMap = createHashMap({series: []});
  18255. /**
  18256. * Mapping between filtered series list and raw series list.
  18257. * key: filtered series indices, value: raw series indices.
  18258. * @type {Array.<nubmer>}
  18259. * @private
  18260. */
  18261. this._seriesIndices;
  18262. this._seriesIndicesMap;
  18263. mergeTheme(baseOption, this._theme.option);
  18264. // TODO Needs clone when merging to the unexisted property
  18265. merge(baseOption, globalDefault, false);
  18266. this.mergeOption(baseOption);
  18267. }
  18268. /**
  18269. * @inner
  18270. * @param {Array.<string>|string} types model types
  18271. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18272. */
  18273. function getComponentsByTypes(componentsMap, types) {
  18274. if (!isArray(types)) {
  18275. types = types ? [types] : [];
  18276. }
  18277. var ret = {};
  18278. each$1(types, function (type) {
  18279. ret[type] = (componentsMap.get(type) || []).slice();
  18280. });
  18281. return ret;
  18282. }
  18283. /**
  18284. * @inner
  18285. */
  18286. function determineSubType(mainType, newCptOption, existComponent) {
  18287. var subType = newCptOption.type
  18288. ? newCptOption.type
  18289. : existComponent
  18290. ? existComponent.subType
  18291. // Use determineSubType only when there is no existComponent.
  18292. : ComponentModel.determineSubType(mainType, newCptOption);
  18293. // tooltip, markline, markpoint may always has no subType
  18294. return subType;
  18295. }
  18296. /**
  18297. * @inner
  18298. */
  18299. function createSeriesIndices(ecModel, seriesModels) {
  18300. ecModel._seriesIndicesMap = createHashMap(
  18301. ecModel._seriesIndices = map(seriesModels, function (series) {
  18302. return series.componentIndex;
  18303. }) || []
  18304. );
  18305. }
  18306. /**
  18307. * @inner
  18308. */
  18309. function filterBySubType(components, condition) {
  18310. // Using hasOwnProperty for restrict. Consider
  18311. // subType is undefined in user payload.
  18312. return condition.hasOwnProperty('subType')
  18313. ? filter(components, function (cpt) {
  18314. return cpt.subType === condition.subType;
  18315. })
  18316. : components;
  18317. }
  18318. /**
  18319. * @inner
  18320. */
  18321. function assertSeriesInitialized(ecModel) {
  18322. // Components that use _seriesIndices should depends on series component,
  18323. // which make sure that their initialization is after series.
  18324. if (__DEV__) {
  18325. if (!ecModel._seriesIndices) {
  18326. throw new Error('Option should contains series.');
  18327. }
  18328. }
  18329. }
  18330. mixin(GlobalModel, colorPaletteMixin);
  18331. /*
  18332. * Licensed to the Apache Software Foundation (ASF) under one
  18333. * or more contributor license agreements. See the NOTICE file
  18334. * distributed with this work for additional information
  18335. * regarding copyright ownership. The ASF licenses this file
  18336. * to you under the Apache License, Version 2.0 (the
  18337. * "License"); you may not use this file except in compliance
  18338. * with the License. You may obtain a copy of the License at
  18339. *
  18340. * http://www.apache.org/licenses/LICENSE-2.0
  18341. *
  18342. * Unless required by applicable law or agreed to in writing,
  18343. * software distributed under the License is distributed on an
  18344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18345. * KIND, either express or implied. See the License for the
  18346. * specific language governing permissions and limitations
  18347. * under the License.
  18348. */
  18349. var echartsAPIList = [
  18350. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18351. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18352. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18353. ];
  18354. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18355. function ExtensionAPI(chartInstance) {
  18356. each$1(echartsAPIList, function (name) {
  18357. this[name] = bind(chartInstance[name], chartInstance);
  18358. }, this);
  18359. }
  18360. /*
  18361. * Licensed to the Apache Software Foundation (ASF) under one
  18362. * or more contributor license agreements. See the NOTICE file
  18363. * distributed with this work for additional information
  18364. * regarding copyright ownership. The ASF licenses this file
  18365. * to you under the Apache License, Version 2.0 (the
  18366. * "License"); you may not use this file except in compliance
  18367. * with the License. You may obtain a copy of the License at
  18368. *
  18369. * http://www.apache.org/licenses/LICENSE-2.0
  18370. *
  18371. * Unless required by applicable law or agreed to in writing,
  18372. * software distributed under the License is distributed on an
  18373. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18374. * KIND, either express or implied. See the License for the
  18375. * specific language governing permissions and limitations
  18376. * under the License.
  18377. */
  18378. var coordinateSystemCreators = {};
  18379. function CoordinateSystemManager() {
  18380. this._coordinateSystems = [];
  18381. }
  18382. CoordinateSystemManager.prototype = {
  18383. constructor: CoordinateSystemManager,
  18384. create: function (ecModel, api) {
  18385. var coordinateSystems = [];
  18386. each$1(coordinateSystemCreators, function (creater, type) {
  18387. var list = creater.create(ecModel, api);
  18388. coordinateSystems = coordinateSystems.concat(list || []);
  18389. });
  18390. this._coordinateSystems = coordinateSystems;
  18391. },
  18392. update: function (ecModel, api) {
  18393. each$1(this._coordinateSystems, function (coordSys) {
  18394. coordSys.update && coordSys.update(ecModel, api);
  18395. });
  18396. },
  18397. getCoordinateSystems: function () {
  18398. return this._coordinateSystems.slice();
  18399. }
  18400. };
  18401. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18402. coordinateSystemCreators[type] = coordinateSystemCreator;
  18403. };
  18404. CoordinateSystemManager.get = function (type) {
  18405. return coordinateSystemCreators[type];
  18406. };
  18407. /*
  18408. * Licensed to the Apache Software Foundation (ASF) under one
  18409. * or more contributor license agreements. See the NOTICE file
  18410. * distributed with this work for additional information
  18411. * regarding copyright ownership. The ASF licenses this file
  18412. * to you under the Apache License, Version 2.0 (the
  18413. * "License"); you may not use this file except in compliance
  18414. * with the License. You may obtain a copy of the License at
  18415. *
  18416. * http://www.apache.org/licenses/LICENSE-2.0
  18417. *
  18418. * Unless required by applicable law or agreed to in writing,
  18419. * software distributed under the License is distributed on an
  18420. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18421. * KIND, either express or implied. See the License for the
  18422. * specific language governing permissions and limitations
  18423. * under the License.
  18424. */
  18425. /**
  18426. * ECharts option manager
  18427. *
  18428. * @module {echarts/model/OptionManager}
  18429. */
  18430. var each$4 = each$1;
  18431. var clone$3 = clone;
  18432. var map$1 = map;
  18433. var merge$1 = merge;
  18434. var QUERY_REG = /^(min|max)?(.+)$/;
  18435. /**
  18436. * TERM EXPLANATIONS:
  18437. *
  18438. * [option]:
  18439. *
  18440. * An object that contains definitions of components. For example:
  18441. * var option = {
  18442. * title: {...},
  18443. * legend: {...},
  18444. * visualMap: {...},
  18445. * series: [
  18446. * {data: [...]},
  18447. * {data: [...]},
  18448. * ...
  18449. * ]
  18450. * };
  18451. *
  18452. * [rawOption]:
  18453. *
  18454. * An object input to echarts.setOption. 'rawOption' may be an
  18455. * 'option', or may be an object contains multi-options. For example:
  18456. * var option = {
  18457. * baseOption: {
  18458. * title: {...},
  18459. * legend: {...},
  18460. * series: [
  18461. * {data: [...]},
  18462. * {data: [...]},
  18463. * ...
  18464. * ]
  18465. * },
  18466. * timeline: {...},
  18467. * options: [
  18468. * {title: {...}, series: {data: [...]}},
  18469. * {title: {...}, series: {data: [...]}},
  18470. * ...
  18471. * ],
  18472. * media: [
  18473. * {
  18474. * query: {maxWidth: 320},
  18475. * option: {series: {x: 20}, visualMap: {show: false}}
  18476. * },
  18477. * {
  18478. * query: {minWidth: 320, maxWidth: 720},
  18479. * option: {series: {x: 500}, visualMap: {show: true}}
  18480. * },
  18481. * {
  18482. * option: {series: {x: 1200}, visualMap: {show: true}}
  18483. * }
  18484. * ]
  18485. * };
  18486. *
  18487. * @alias module:echarts/model/OptionManager
  18488. * @param {module:echarts/ExtensionAPI} api
  18489. */
  18490. function OptionManager(api) {
  18491. /**
  18492. * @private
  18493. * @type {module:echarts/ExtensionAPI}
  18494. */
  18495. this._api = api;
  18496. /**
  18497. * @private
  18498. * @type {Array.<number>}
  18499. */
  18500. this._timelineOptions = [];
  18501. /**
  18502. * @private
  18503. * @type {Array.<Object>}
  18504. */
  18505. this._mediaList = [];
  18506. /**
  18507. * @private
  18508. * @type {Object}
  18509. */
  18510. this._mediaDefault;
  18511. /**
  18512. * -1, means default.
  18513. * empty means no media.
  18514. * @private
  18515. * @type {Array.<number>}
  18516. */
  18517. this._currentMediaIndices = [];
  18518. /**
  18519. * @private
  18520. * @type {Object}
  18521. */
  18522. this._optionBackup;
  18523. /**
  18524. * @private
  18525. * @type {Object}
  18526. */
  18527. this._newBaseOption;
  18528. }
  18529. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18530. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18531. // rawOption cloned and backuped when timeline changed, which does no
  18532. // good to performance. What's more, that both timeline and setOption
  18533. // method supply 'notMerge' brings complex and some problems.
  18534. // Consider this case:
  18535. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18536. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18537. OptionManager.prototype = {
  18538. constructor: OptionManager,
  18539. /**
  18540. * @public
  18541. * @param {Object} rawOption Raw option.
  18542. * @param {module:echarts/model/Global} ecModel
  18543. * @param {Array.<Function>} optionPreprocessorFuncs
  18544. * @return {Object} Init option
  18545. */
  18546. setOption: function (rawOption, optionPreprocessorFuncs) {
  18547. if (rawOption) {
  18548. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18549. each$1(normalizeToArray(rawOption.series), function (series) {
  18550. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18551. });
  18552. }
  18553. // Caution: some series modify option data, if do not clone,
  18554. // it should ensure that the repeat modify correctly
  18555. // (create a new object when modify itself).
  18556. rawOption = clone$3(rawOption, true);
  18557. // FIXME
  18558. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18559. var oldOptionBackup = this._optionBackup;
  18560. var newParsedOption = parseRawOption.call(
  18561. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  18562. );
  18563. this._newBaseOption = newParsedOption.baseOption;
  18564. // For setOption at second time (using merge mode);
  18565. if (oldOptionBackup) {
  18566. // Only baseOption can be merged.
  18567. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  18568. // For simplicity, timeline options and media options do not support merge,
  18569. // that is, if you `setOption` twice and both has timeline options, the latter
  18570. // timeline opitons will not be merged to the formers, but just substitude them.
  18571. if (newParsedOption.timelineOptions.length) {
  18572. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18573. }
  18574. if (newParsedOption.mediaList.length) {
  18575. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18576. }
  18577. if (newParsedOption.mediaDefault) {
  18578. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18579. }
  18580. }
  18581. else {
  18582. this._optionBackup = newParsedOption;
  18583. }
  18584. },
  18585. /**
  18586. * @param {boolean} isRecreate
  18587. * @return {Object}
  18588. */
  18589. mountOption: function (isRecreate) {
  18590. var optionBackup = this._optionBackup;
  18591. // TODO
  18592. // 如果没有reset功能则不clone。
  18593. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18594. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18595. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18596. this._currentMediaIndices = [];
  18597. return clone$3(isRecreate
  18598. // this._optionBackup.baseOption, which is created at the first `setOption`
  18599. // called, and is merged into every new option by inner method `mergeOption`
  18600. // each time `setOption` called, can be only used in `isRecreate`, because
  18601. // its reliability is under suspicion. In other cases option merge is
  18602. // performed by `model.mergeOption`.
  18603. ? optionBackup.baseOption : this._newBaseOption
  18604. );
  18605. },
  18606. /**
  18607. * @param {module:echarts/model/Global} ecModel
  18608. * @return {Object}
  18609. */
  18610. getTimelineOption: function (ecModel) {
  18611. var option;
  18612. var timelineOptions = this._timelineOptions;
  18613. if (timelineOptions.length) {
  18614. // getTimelineOption can only be called after ecModel inited,
  18615. // so we can get currentIndex from timelineModel.
  18616. var timelineModel = ecModel.getComponent('timeline');
  18617. if (timelineModel) {
  18618. option = clone$3(
  18619. timelineOptions[timelineModel.getCurrentIndex()],
  18620. true
  18621. );
  18622. }
  18623. }
  18624. return option;
  18625. },
  18626. /**
  18627. * @param {module:echarts/model/Global} ecModel
  18628. * @return {Array.<Object>}
  18629. */
  18630. getMediaOption: function (ecModel) {
  18631. var ecWidth = this._api.getWidth();
  18632. var ecHeight = this._api.getHeight();
  18633. var mediaList = this._mediaList;
  18634. var mediaDefault = this._mediaDefault;
  18635. var indices = [];
  18636. var result = [];
  18637. // No media defined.
  18638. if (!mediaList.length && !mediaDefault) {
  18639. return result;
  18640. }
  18641. // Multi media may be applied, the latter defined media has higher priority.
  18642. for (var i = 0, len = mediaList.length; i < len; i++) {
  18643. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18644. indices.push(i);
  18645. }
  18646. }
  18647. // FIXME
  18648. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18649. if (!indices.length && mediaDefault) {
  18650. indices = [-1];
  18651. }
  18652. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18653. result = map$1(indices, function (index) {
  18654. return clone$3(
  18655. index === -1 ? mediaDefault.option : mediaList[index].option
  18656. );
  18657. });
  18658. }
  18659. // Otherwise return nothing.
  18660. this._currentMediaIndices = indices;
  18661. return result;
  18662. }
  18663. };
  18664. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18665. var timelineOptions = [];
  18666. var mediaList = [];
  18667. var mediaDefault;
  18668. var baseOption;
  18669. // Compatible with ec2.
  18670. var timelineOpt = rawOption.timeline;
  18671. if (rawOption.baseOption) {
  18672. baseOption = rawOption.baseOption;
  18673. }
  18674. // For timeline
  18675. if (timelineOpt || rawOption.options) {
  18676. baseOption = baseOption || {};
  18677. timelineOptions = (rawOption.options || []).slice();
  18678. }
  18679. // For media query
  18680. if (rawOption.media) {
  18681. baseOption = baseOption || {};
  18682. var media = rawOption.media;
  18683. each$4(media, function (singleMedia) {
  18684. if (singleMedia && singleMedia.option) {
  18685. if (singleMedia.query) {
  18686. mediaList.push(singleMedia);
  18687. }
  18688. else if (!mediaDefault) {
  18689. // Use the first media default.
  18690. mediaDefault = singleMedia;
  18691. }
  18692. }
  18693. });
  18694. }
  18695. // For normal option
  18696. if (!baseOption) {
  18697. baseOption = rawOption;
  18698. }
  18699. // Set timelineOpt to baseOption in ec3,
  18700. // which is convenient for merge option.
  18701. if (!baseOption.timeline) {
  18702. baseOption.timeline = timelineOpt;
  18703. }
  18704. // Preprocess.
  18705. each$4([baseOption].concat(timelineOptions)
  18706. .concat(map(mediaList, function (media) {
  18707. return media.option;
  18708. })),
  18709. function (option) {
  18710. each$4(optionPreprocessorFuncs, function (preProcess) {
  18711. preProcess(option, isNew);
  18712. });
  18713. }
  18714. );
  18715. return {
  18716. baseOption: baseOption,
  18717. timelineOptions: timelineOptions,
  18718. mediaDefault: mediaDefault,
  18719. mediaList: mediaList
  18720. };
  18721. }
  18722. /**
  18723. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18724. * Support: width, height, aspectRatio
  18725. * Can use max or min as prefix.
  18726. */
  18727. function applyMediaQuery(query, ecWidth, ecHeight) {
  18728. var realMap = {
  18729. width: ecWidth,
  18730. height: ecHeight,
  18731. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18732. };
  18733. var applicatable = true;
  18734. each$1(query, function (value, attr) {
  18735. var matched = attr.match(QUERY_REG);
  18736. if (!matched || !matched[1] || !matched[2]) {
  18737. return;
  18738. }
  18739. var operator = matched[1];
  18740. var realAttr = matched[2].toLowerCase();
  18741. if (!compare(realMap[realAttr], value, operator)) {
  18742. applicatable = false;
  18743. }
  18744. });
  18745. return applicatable;
  18746. }
  18747. function compare(real, expect, operator) {
  18748. if (operator === 'min') {
  18749. return real >= expect;
  18750. }
  18751. else if (operator === 'max') {
  18752. return real <= expect;
  18753. }
  18754. else { // Equals
  18755. return real === expect;
  18756. }
  18757. }
  18758. function indicesEquals(indices1, indices2) {
  18759. // indices is always order by asc and has only finite number.
  18760. return indices1.join(',') === indices2.join(',');
  18761. }
  18762. /**
  18763. * Consider case:
  18764. * `chart.setOption(opt1);`
  18765. * Then user do some interaction like dataZoom, dataView changing.
  18766. * `chart.setOption(opt2);`
  18767. * Then user press 'reset button' in toolbox.
  18768. *
  18769. * After doing that all of the interaction effects should be reset, the
  18770. * chart should be the same as the result of invoke
  18771. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18772. *
  18773. * Although it is not able ensure that
  18774. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18775. * `chart.setOption(merge(opt1, opt2));` exactly,
  18776. * this might be the only simple way to implement that feature.
  18777. *
  18778. * MEMO: We've considered some other approaches:
  18779. * 1. Each model handle its self restoration but not uniform treatment.
  18780. * (Too complex in logic and error-prone)
  18781. * 2. Use a shadow ecModel. (Performace expensive)
  18782. */
  18783. function mergeOption(oldOption, newOption) {
  18784. newOption = newOption || {};
  18785. each$4(newOption, function (newCptOpt, mainType) {
  18786. if (newCptOpt == null) {
  18787. return;
  18788. }
  18789. var oldCptOpt = oldOption[mainType];
  18790. if (!ComponentModel.hasClass(mainType)) {
  18791. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18792. }
  18793. else {
  18794. newCptOpt = normalizeToArray(newCptOpt);
  18795. oldCptOpt = normalizeToArray(oldCptOpt);
  18796. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18797. oldOption[mainType] = map$1(mapResult, function (item) {
  18798. return (item.option && item.exist)
  18799. ? merge$1(item.exist, item.option, true)
  18800. : (item.exist || item.option);
  18801. });
  18802. }
  18803. });
  18804. }
  18805. /*
  18806. * Licensed to the Apache Software Foundation (ASF) under one
  18807. * or more contributor license agreements. See the NOTICE file
  18808. * distributed with this work for additional information
  18809. * regarding copyright ownership. The ASF licenses this file
  18810. * to you under the Apache License, Version 2.0 (the
  18811. * "License"); you may not use this file except in compliance
  18812. * with the License. You may obtain a copy of the License at
  18813. *
  18814. * http://www.apache.org/licenses/LICENSE-2.0
  18815. *
  18816. * Unless required by applicable law or agreed to in writing,
  18817. * software distributed under the License is distributed on an
  18818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18819. * KIND, either express or implied. See the License for the
  18820. * specific language governing permissions and limitations
  18821. * under the License.
  18822. */
  18823. var each$5 = each$1;
  18824. var isObject$3 = isObject$1;
  18825. var POSSIBLE_STYLES = [
  18826. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18827. 'chordStyle', 'label', 'labelLine'
  18828. ];
  18829. function compatEC2ItemStyle(opt) {
  18830. var itemStyleOpt = opt && opt.itemStyle;
  18831. if (!itemStyleOpt) {
  18832. return;
  18833. }
  18834. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18835. var styleName = POSSIBLE_STYLES[i];
  18836. var normalItemStyleOpt = itemStyleOpt.normal;
  18837. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18838. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18839. opt[styleName] = opt[styleName] || {};
  18840. if (!opt[styleName].normal) {
  18841. opt[styleName].normal = normalItemStyleOpt[styleName];
  18842. }
  18843. else {
  18844. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18845. }
  18846. normalItemStyleOpt[styleName] = null;
  18847. }
  18848. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18849. opt[styleName] = opt[styleName] || {};
  18850. if (!opt[styleName].emphasis) {
  18851. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18852. }
  18853. else {
  18854. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18855. }
  18856. emphasisItemStyleOpt[styleName] = null;
  18857. }
  18858. }
  18859. }
  18860. function convertNormalEmphasis(opt, optType, useExtend) {
  18861. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18862. var normalOpt = opt[optType].normal;
  18863. var emphasisOpt = opt[optType].emphasis;
  18864. if (normalOpt) {
  18865. // Timeline controlStyle has other properties besides normal and emphasis
  18866. if (useExtend) {
  18867. opt[optType].normal = opt[optType].emphasis = null;
  18868. defaults(opt[optType], normalOpt);
  18869. }
  18870. else {
  18871. opt[optType] = normalOpt;
  18872. }
  18873. }
  18874. if (emphasisOpt) {
  18875. opt.emphasis = opt.emphasis || {};
  18876. opt.emphasis[optType] = emphasisOpt;
  18877. }
  18878. }
  18879. }
  18880. function removeEC3NormalStatus(opt) {
  18881. convertNormalEmphasis(opt, 'itemStyle');
  18882. convertNormalEmphasis(opt, 'lineStyle');
  18883. convertNormalEmphasis(opt, 'areaStyle');
  18884. convertNormalEmphasis(opt, 'label');
  18885. convertNormalEmphasis(opt, 'labelLine');
  18886. // treemap
  18887. convertNormalEmphasis(opt, 'upperLabel');
  18888. // graph
  18889. convertNormalEmphasis(opt, 'edgeLabel');
  18890. }
  18891. function compatTextStyle(opt, propName) {
  18892. // Check whether is not object (string\null\undefined ...)
  18893. var labelOptSingle = isObject$3(opt) && opt[propName];
  18894. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18895. if (textStyle) {
  18896. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18897. var propName = TEXT_STYLE_OPTIONS[i];
  18898. if (textStyle.hasOwnProperty(propName)) {
  18899. labelOptSingle[propName] = textStyle[propName];
  18900. }
  18901. }
  18902. }
  18903. }
  18904. function compatEC3CommonStyles(opt) {
  18905. if (opt) {
  18906. removeEC3NormalStatus(opt);
  18907. compatTextStyle(opt, 'label');
  18908. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18909. }
  18910. }
  18911. function processSeries(seriesOpt) {
  18912. if (!isObject$3(seriesOpt)) {
  18913. return;
  18914. }
  18915. compatEC2ItemStyle(seriesOpt);
  18916. removeEC3NormalStatus(seriesOpt);
  18917. compatTextStyle(seriesOpt, 'label');
  18918. // treemap
  18919. compatTextStyle(seriesOpt, 'upperLabel');
  18920. // graph
  18921. compatTextStyle(seriesOpt, 'edgeLabel');
  18922. if (seriesOpt.emphasis) {
  18923. compatTextStyle(seriesOpt.emphasis, 'label');
  18924. // treemap
  18925. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18926. // graph
  18927. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18928. }
  18929. var markPoint = seriesOpt.markPoint;
  18930. if (markPoint) {
  18931. compatEC2ItemStyle(markPoint);
  18932. compatEC3CommonStyles(markPoint);
  18933. }
  18934. var markLine = seriesOpt.markLine;
  18935. if (markLine) {
  18936. compatEC2ItemStyle(markLine);
  18937. compatEC3CommonStyles(markLine);
  18938. }
  18939. var markArea = seriesOpt.markArea;
  18940. if (markArea) {
  18941. compatEC3CommonStyles(markArea);
  18942. }
  18943. var data = seriesOpt.data;
  18944. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18945. // then the backward compat based on option type will not be performed.
  18946. if (seriesOpt.type === 'graph') {
  18947. data = data || seriesOpt.nodes;
  18948. var edgeData = seriesOpt.links || seriesOpt.edges;
  18949. if (edgeData && !isTypedArray(edgeData)) {
  18950. for (var i = 0; i < edgeData.length; i++) {
  18951. compatEC3CommonStyles(edgeData[i]);
  18952. }
  18953. }
  18954. each$1(seriesOpt.categories, function (opt) {
  18955. removeEC3NormalStatus(opt);
  18956. });
  18957. }
  18958. if (data && !isTypedArray(data)) {
  18959. for (var i = 0; i < data.length; i++) {
  18960. compatEC3CommonStyles(data[i]);
  18961. }
  18962. }
  18963. // mark point data
  18964. var markPoint = seriesOpt.markPoint;
  18965. if (markPoint && markPoint.data) {
  18966. var mpData = markPoint.data;
  18967. for (var i = 0; i < mpData.length; i++) {
  18968. compatEC3CommonStyles(mpData[i]);
  18969. }
  18970. }
  18971. // mark line data
  18972. var markLine = seriesOpt.markLine;
  18973. if (markLine && markLine.data) {
  18974. var mlData = markLine.data;
  18975. for (var i = 0; i < mlData.length; i++) {
  18976. if (isArray(mlData[i])) {
  18977. compatEC3CommonStyles(mlData[i][0]);
  18978. compatEC3CommonStyles(mlData[i][1]);
  18979. }
  18980. else {
  18981. compatEC3CommonStyles(mlData[i]);
  18982. }
  18983. }
  18984. }
  18985. // Series
  18986. if (seriesOpt.type === 'gauge') {
  18987. compatTextStyle(seriesOpt, 'axisLabel');
  18988. compatTextStyle(seriesOpt, 'title');
  18989. compatTextStyle(seriesOpt, 'detail');
  18990. }
  18991. else if (seriesOpt.type === 'treemap') {
  18992. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18993. each$1(seriesOpt.levels, function (opt) {
  18994. removeEC3NormalStatus(opt);
  18995. });
  18996. }
  18997. else if (seriesOpt.type === 'tree') {
  18998. removeEC3NormalStatus(seriesOpt.leaves);
  18999. }
  19000. // sunburst starts from ec4, so it does not need to compat levels.
  19001. }
  19002. function toArr(o) {
  19003. return isArray(o) ? o : o ? [o] : [];
  19004. }
  19005. function toObj(o) {
  19006. return (isArray(o) ? o[0] : o) || {};
  19007. }
  19008. var compatStyle = function (option, isTheme) {
  19009. each$5(toArr(option.series), function (seriesOpt) {
  19010. isObject$3(seriesOpt) && processSeries(seriesOpt);
  19011. });
  19012. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  19013. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  19014. each$5(
  19015. axes,
  19016. function (axisName) {
  19017. each$5(toArr(option[axisName]), function (axisOpt) {
  19018. if (axisOpt) {
  19019. compatTextStyle(axisOpt, 'axisLabel');
  19020. compatTextStyle(axisOpt.axisPointer, 'label');
  19021. }
  19022. });
  19023. }
  19024. );
  19025. each$5(toArr(option.parallel), function (parallelOpt) {
  19026. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  19027. compatTextStyle(parallelAxisDefault, 'axisLabel');
  19028. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  19029. });
  19030. each$5(toArr(option.calendar), function (calendarOpt) {
  19031. convertNormalEmphasis(calendarOpt, 'itemStyle');
  19032. compatTextStyle(calendarOpt, 'dayLabel');
  19033. compatTextStyle(calendarOpt, 'monthLabel');
  19034. compatTextStyle(calendarOpt, 'yearLabel');
  19035. });
  19036. // radar.name.textStyle
  19037. each$5(toArr(option.radar), function (radarOpt) {
  19038. compatTextStyle(radarOpt, 'name');
  19039. });
  19040. each$5(toArr(option.geo), function (geoOpt) {
  19041. if (isObject$3(geoOpt)) {
  19042. compatEC3CommonStyles(geoOpt);
  19043. each$5(toArr(geoOpt.regions), function (regionObj) {
  19044. compatEC3CommonStyles(regionObj);
  19045. });
  19046. }
  19047. });
  19048. each$5(toArr(option.timeline), function (timelineOpt) {
  19049. compatEC3CommonStyles(timelineOpt);
  19050. convertNormalEmphasis(timelineOpt, 'label');
  19051. convertNormalEmphasis(timelineOpt, 'itemStyle');
  19052. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  19053. var data = timelineOpt.data;
  19054. isArray(data) && each$1(data, function (item) {
  19055. if (isObject$1(item)) {
  19056. convertNormalEmphasis(item, 'label');
  19057. convertNormalEmphasis(item, 'itemStyle');
  19058. }
  19059. });
  19060. });
  19061. each$5(toArr(option.toolbox), function (toolboxOpt) {
  19062. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  19063. each$5(toolboxOpt.feature, function (featureOpt) {
  19064. convertNormalEmphasis(featureOpt, 'iconStyle');
  19065. });
  19066. });
  19067. compatTextStyle(toObj(option.axisPointer), 'label');
  19068. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  19069. };
  19070. /*
  19071. * Licensed to the Apache Software Foundation (ASF) under one
  19072. * or more contributor license agreements. See the NOTICE file
  19073. * distributed with this work for additional information
  19074. * regarding copyright ownership. The ASF licenses this file
  19075. * to you under the Apache License, Version 2.0 (the
  19076. * "License"); you may not use this file except in compliance
  19077. * with the License. You may obtain a copy of the License at
  19078. *
  19079. * http://www.apache.org/licenses/LICENSE-2.0
  19080. *
  19081. * Unless required by applicable law or agreed to in writing,
  19082. * software distributed under the License is distributed on an
  19083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19084. * KIND, either express or implied. See the License for the
  19085. * specific language governing permissions and limitations
  19086. * under the License.
  19087. */
  19088. // Compatitable with 2.0
  19089. function get(opt, path) {
  19090. path = path.split(',');
  19091. var obj = opt;
  19092. for (var i = 0; i < path.length; i++) {
  19093. obj = obj && obj[path[i]];
  19094. if (obj == null) {
  19095. break;
  19096. }
  19097. }
  19098. return obj;
  19099. }
  19100. function set$1(opt, path, val, overwrite) {
  19101. path = path.split(',');
  19102. var obj = opt;
  19103. var key;
  19104. for (var i = 0; i < path.length - 1; i++) {
  19105. key = path[i];
  19106. if (obj[key] == null) {
  19107. obj[key] = {};
  19108. }
  19109. obj = obj[key];
  19110. }
  19111. if (overwrite || obj[path[i]] == null) {
  19112. obj[path[i]] = val;
  19113. }
  19114. }
  19115. function compatLayoutProperties(option) {
  19116. each$1(LAYOUT_PROPERTIES, function (prop) {
  19117. if (prop[0] in option && !(prop[1] in option)) {
  19118. option[prop[1]] = option[prop[0]];
  19119. }
  19120. });
  19121. }
  19122. var LAYOUT_PROPERTIES = [
  19123. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19124. ];
  19125. var COMPATITABLE_COMPONENTS = [
  19126. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19127. ];
  19128. var backwardCompat = function (option, isTheme) {
  19129. compatStyle(option, isTheme);
  19130. // Make sure series array for model initialization.
  19131. option.series = normalizeToArray(option.series);
  19132. each$1(option.series, function (seriesOpt) {
  19133. if (!isObject$1(seriesOpt)) {
  19134. return;
  19135. }
  19136. var seriesType = seriesOpt.type;
  19137. if (seriesType === 'pie' || seriesType === 'gauge') {
  19138. if (seriesOpt.clockWise != null) {
  19139. seriesOpt.clockwise = seriesOpt.clockWise;
  19140. }
  19141. }
  19142. if (seriesType === 'gauge') {
  19143. var pointerColor = get(seriesOpt, 'pointer.color');
  19144. pointerColor != null
  19145. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19146. }
  19147. compatLayoutProperties(seriesOpt);
  19148. });
  19149. // dataRange has changed to visualMap
  19150. if (option.dataRange) {
  19151. option.visualMap = option.dataRange;
  19152. }
  19153. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19154. var options = option[componentName];
  19155. if (options) {
  19156. if (!isArray(options)) {
  19157. options = [options];
  19158. }
  19159. each$1(options, function (option) {
  19160. compatLayoutProperties(option);
  19161. });
  19162. }
  19163. });
  19164. };
  19165. /*
  19166. * Licensed to the Apache Software Foundation (ASF) under one
  19167. * or more contributor license agreements. See the NOTICE file
  19168. * distributed with this work for additional information
  19169. * regarding copyright ownership. The ASF licenses this file
  19170. * to you under the Apache License, Version 2.0 (the
  19171. * "License"); you may not use this file except in compliance
  19172. * with the License. You may obtain a copy of the License at
  19173. *
  19174. * http://www.apache.org/licenses/LICENSE-2.0
  19175. *
  19176. * Unless required by applicable law or agreed to in writing,
  19177. * software distributed under the License is distributed on an
  19178. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19179. * KIND, either express or implied. See the License for the
  19180. * specific language governing permissions and limitations
  19181. * under the License.
  19182. */
  19183. // (1) [Caution]: the logic is correct based on the premises:
  19184. // data processing stage is blocked in stream.
  19185. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19186. // (2) Only register once when import repeatly.
  19187. // Should be executed before after series filtered and before stack calculation.
  19188. var dataStack = function (ecModel) {
  19189. var stackInfoMap = createHashMap();
  19190. ecModel.eachSeries(function (seriesModel) {
  19191. var stack = seriesModel.get('stack');
  19192. // Compatibal: when `stack` is set as '', do not stack.
  19193. if (stack) {
  19194. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19195. var data = seriesModel.getData();
  19196. var stackInfo = {
  19197. // Used for calculate axis extent automatically.
  19198. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19199. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19200. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19201. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19202. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19203. data: data,
  19204. seriesModel: seriesModel
  19205. };
  19206. // If stacked on axis that do not support data stack.
  19207. if (!stackInfo.stackedDimension
  19208. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19209. ) {
  19210. return;
  19211. }
  19212. stackInfoList.length && data.setCalculationInfo(
  19213. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19214. );
  19215. stackInfoList.push(stackInfo);
  19216. }
  19217. });
  19218. stackInfoMap.each(calculateStack);
  19219. };
  19220. function calculateStack(stackInfoList) {
  19221. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19222. var resultVal = [];
  19223. var resultNaN = [NaN, NaN];
  19224. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19225. var targetData = targetStackInfo.data;
  19226. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19227. // Should not write on raw data, because stack series model list changes
  19228. // depending on legend selection.
  19229. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19230. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19231. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19232. // should also be NaN, to draw a appropriate belt area.
  19233. if (isNaN(sum)) {
  19234. return resultNaN;
  19235. }
  19236. var byValue;
  19237. var stackedDataRawIndex;
  19238. if (isStackedByIndex) {
  19239. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19240. }
  19241. else {
  19242. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19243. }
  19244. // If stackOver is NaN, chart view will render point on value start.
  19245. var stackedOver = NaN;
  19246. for (var j = idxInStack - 1; j >= 0; j--) {
  19247. var stackInfo = stackInfoList[j];
  19248. // Has been optimized by inverted indices on `stackedByDimension`.
  19249. if (!isStackedByIndex) {
  19250. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19251. }
  19252. if (stackedDataRawIndex >= 0) {
  19253. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19254. // Considering positive stack, negative stack and empty data
  19255. if ((sum >= 0 && val > 0) // Positive stack
  19256. || (sum <= 0 && val < 0) // Negative stack
  19257. ) {
  19258. sum += val;
  19259. stackedOver = val;
  19260. break;
  19261. }
  19262. }
  19263. }
  19264. resultVal[0] = sum;
  19265. resultVal[1] = stackedOver;
  19266. return resultVal;
  19267. });
  19268. targetData.hostModel.setData(newData);
  19269. // Update for consequent calculation
  19270. targetStackInfo.data = newData;
  19271. });
  19272. }
  19273. /*
  19274. * Licensed to the Apache Software Foundation (ASF) under one
  19275. * or more contributor license agreements. See the NOTICE file
  19276. * distributed with this work for additional information
  19277. * regarding copyright ownership. The ASF licenses this file
  19278. * to you under the Apache License, Version 2.0 (the
  19279. * "License"); you may not use this file except in compliance
  19280. * with the License. You may obtain a copy of the License at
  19281. *
  19282. * http://www.apache.org/licenses/LICENSE-2.0
  19283. *
  19284. * Unless required by applicable law or agreed to in writing,
  19285. * software distributed under the License is distributed on an
  19286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19287. * KIND, either express or implied. See the License for the
  19288. * specific language governing permissions and limitations
  19289. * under the License.
  19290. */
  19291. // TODO
  19292. // ??? refactor? check the outer usage of data provider.
  19293. // merge with defaultDimValueGetter?
  19294. /**
  19295. * If normal array used, mutable chunk size is supported.
  19296. * If typed array used, chunk size must be fixed.
  19297. */
  19298. function DefaultDataProvider(source, dimSize) {
  19299. if (!Source.isInstance(source)) {
  19300. source = Source.seriesDataToSource(source);
  19301. }
  19302. this._source = source;
  19303. var data = this._data = source.data;
  19304. var sourceFormat = source.sourceFormat;
  19305. // Typed array. TODO IE10+?
  19306. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19307. if (__DEV__) {
  19308. if (dimSize == null) {
  19309. throw new Error('Typed array data must specify dimension size');
  19310. }
  19311. }
  19312. this._offset = 0;
  19313. this._dimSize = dimSize;
  19314. this._data = data;
  19315. }
  19316. var methods = providerMethods[
  19317. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19318. ? sourceFormat + '_' + source.seriesLayoutBy
  19319. : sourceFormat
  19320. ];
  19321. if (__DEV__) {
  19322. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19323. }
  19324. extend(this, methods);
  19325. }
  19326. var providerProto = DefaultDataProvider.prototype;
  19327. // If data is pure without style configuration
  19328. providerProto.pure = false;
  19329. // If data is persistent and will not be released after use.
  19330. providerProto.persistent = true;
  19331. // ???! FIXME legacy data provider do not has method getSource
  19332. providerProto.getSource = function () {
  19333. return this._source;
  19334. };
  19335. var providerMethods = {
  19336. 'arrayRows_column': {
  19337. pure: true,
  19338. count: function () {
  19339. return Math.max(0, this._data.length - this._source.startIndex);
  19340. },
  19341. getItem: function (idx) {
  19342. return this._data[idx + this._source.startIndex];
  19343. },
  19344. appendData: appendDataSimply
  19345. },
  19346. 'arrayRows_row': {
  19347. pure: true,
  19348. count: function () {
  19349. var row = this._data[0];
  19350. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19351. },
  19352. getItem: function (idx) {
  19353. idx += this._source.startIndex;
  19354. var item = [];
  19355. var data = this._data;
  19356. for (var i = 0; i < data.length; i++) {
  19357. var row = data[i];
  19358. item.push(row ? row[idx] : null);
  19359. }
  19360. return item;
  19361. },
  19362. appendData: function () {
  19363. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19364. }
  19365. },
  19366. 'objectRows': {
  19367. pure: true,
  19368. count: countSimply,
  19369. getItem: getItemSimply,
  19370. appendData: appendDataSimply
  19371. },
  19372. 'keyedColumns': {
  19373. pure: true,
  19374. count: function () {
  19375. var dimName = this._source.dimensionsDefine[0].name;
  19376. var col = this._data[dimName];
  19377. return col ? col.length : 0;
  19378. },
  19379. getItem: function (idx) {
  19380. var item = [];
  19381. var dims = this._source.dimensionsDefine;
  19382. for (var i = 0; i < dims.length; i++) {
  19383. var col = this._data[dims[i].name];
  19384. item.push(col ? col[idx] : null);
  19385. }
  19386. return item;
  19387. },
  19388. appendData: function (newData) {
  19389. var data = this._data;
  19390. each$1(newData, function (newCol, key) {
  19391. var oldCol = data[key] || (data[key] = []);
  19392. for (var i = 0; i < (newCol || []).length; i++) {
  19393. oldCol.push(newCol[i]);
  19394. }
  19395. });
  19396. }
  19397. },
  19398. 'original': {
  19399. count: countSimply,
  19400. getItem: getItemSimply,
  19401. appendData: appendDataSimply
  19402. },
  19403. 'typedArray': {
  19404. persistent: false,
  19405. pure: true,
  19406. count: function () {
  19407. return this._data ? (this._data.length / this._dimSize) : 0;
  19408. },
  19409. getItem: function (idx, out) {
  19410. idx = idx - this._offset;
  19411. out = out || [];
  19412. var offset = this._dimSize * idx;
  19413. for (var i = 0; i < this._dimSize; i++) {
  19414. out[i] = this._data[offset + i];
  19415. }
  19416. return out;
  19417. },
  19418. appendData: function (newData) {
  19419. if (__DEV__) {
  19420. assert$1(
  19421. isTypedArray(newData),
  19422. 'Added data must be TypedArray if data in initialization is TypedArray'
  19423. );
  19424. }
  19425. this._data = newData;
  19426. },
  19427. // Clean self if data is already used.
  19428. clean: function () {
  19429. // PENDING
  19430. this._offset += this.count();
  19431. this._data = null;
  19432. }
  19433. }
  19434. };
  19435. function countSimply() {
  19436. return this._data.length;
  19437. }
  19438. function getItemSimply(idx) {
  19439. return this._data[idx];
  19440. }
  19441. function appendDataSimply(newData) {
  19442. for (var i = 0; i < newData.length; i++) {
  19443. this._data.push(newData[i]);
  19444. }
  19445. }
  19446. var rawValueGetters = {
  19447. arrayRows: getRawValueSimply,
  19448. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19449. return dimIndex != null ? dataItem[dimName] : dataItem;
  19450. },
  19451. keyedColumns: getRawValueSimply,
  19452. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19453. // FIXME
  19454. // In some case (markpoint in geo (geo-map.html)), dataItem
  19455. // is {coord: [...]}
  19456. var value = getDataItemValue(dataItem);
  19457. return (dimIndex == null || !(value instanceof Array))
  19458. ? value
  19459. : value[dimIndex];
  19460. },
  19461. typedArray: getRawValueSimply
  19462. };
  19463. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19464. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19465. }
  19466. var defaultDimValueGetters = {
  19467. arrayRows: getDimValueSimply,
  19468. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19469. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19470. },
  19471. keyedColumns: getDimValueSimply,
  19472. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19473. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19474. // If dataItem is an plain object with no value field, the var `value`
  19475. // will be assigned with the object, but it will be tread correctly
  19476. // in the `convertDataValue`.
  19477. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  19478. // If any dataItem is like { value: 10 }
  19479. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19480. this.hasItemOption = true;
  19481. }
  19482. return converDataValue(
  19483. (value instanceof Array)
  19484. ? value[dimIndex]
  19485. // If value is a single number or something else not array.
  19486. : value,
  19487. this._dimensionInfos[dimName]
  19488. );
  19489. },
  19490. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19491. return dataItem[dimIndex];
  19492. }
  19493. };
  19494. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19495. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19496. }
  19497. /**
  19498. * This helper method convert value in data.
  19499. * @param {string|number|Date} value
  19500. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19501. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19502. */
  19503. function converDataValue(value, dimInfo) {
  19504. // Performance sensitive.
  19505. var dimType = dimInfo && dimInfo.type;
  19506. if (dimType === 'ordinal') {
  19507. // If given value is a category string
  19508. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19509. return ordinalMeta
  19510. ? ordinalMeta.parseAndCollect(value)
  19511. : value;
  19512. }
  19513. if (dimType === 'time'
  19514. // spead up when using timestamp
  19515. && typeof value !== 'number'
  19516. && value != null
  19517. && value !== '-'
  19518. ) {
  19519. value = +parseDate(value);
  19520. }
  19521. // dimType defaults 'number'.
  19522. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19523. // parse to NaN.
  19524. return (value == null || value === '')
  19525. ? NaN
  19526. // If string (like '-'), using '+' parse to NaN
  19527. // If object, also parse to NaN
  19528. : +value;
  19529. }
  19530. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19531. // Consider persistent.
  19532. // Caution: why use raw value to display on label or tooltip?
  19533. // A reason is to avoid format. For example time value we do not know
  19534. // how to format is expected. More over, if stack is used, calculated
  19535. // value may be 0.91000000001, which have brings trouble to display.
  19536. // TODO: consider how to treat null/undefined/NaN when display?
  19537. /**
  19538. * @param {module:echarts/data/List} data
  19539. * @param {number} dataIndex
  19540. * @param {string|number} [dim] dimName or dimIndex
  19541. * @return {Array.<number>|string|number} can be null/undefined.
  19542. */
  19543. function retrieveRawValue(data, dataIndex, dim) {
  19544. if (!data) {
  19545. return;
  19546. }
  19547. // Consider data may be not persistent.
  19548. var dataItem = data.getRawDataItem(dataIndex);
  19549. if (dataItem == null) {
  19550. return;
  19551. }
  19552. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19553. var dimName;
  19554. var dimIndex;
  19555. var dimInfo = data.getDimensionInfo(dim);
  19556. if (dimInfo) {
  19557. dimName = dimInfo.name;
  19558. dimIndex = dimInfo.index;
  19559. }
  19560. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19561. }
  19562. /**
  19563. * Compatible with some cases (in pie, map) like:
  19564. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19565. * where only sourceFormat is 'original' and 'objectRows' supported.
  19566. *
  19567. * ??? TODO
  19568. * Supported detail options in data item when using 'arrayRows'.
  19569. *
  19570. * @param {module:echarts/data/List} data
  19571. * @param {number} dataIndex
  19572. * @param {string} attr like 'selected'
  19573. */
  19574. function retrieveRawAttr(data, dataIndex, attr) {
  19575. if (!data) {
  19576. return;
  19577. }
  19578. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19579. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  19580. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  19581. ) {
  19582. return;
  19583. }
  19584. var dataItem = data.getRawDataItem(dataIndex);
  19585. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19586. dataItem = null;
  19587. }
  19588. if (dataItem) {
  19589. return dataItem[attr];
  19590. }
  19591. }
  19592. /*
  19593. * Licensed to the Apache Software Foundation (ASF) under one
  19594. * or more contributor license agreements. See the NOTICE file
  19595. * distributed with this work for additional information
  19596. * regarding copyright ownership. The ASF licenses this file
  19597. * to you under the Apache License, Version 2.0 (the
  19598. * "License"); you may not use this file except in compliance
  19599. * with the License. You may obtain a copy of the License at
  19600. *
  19601. * http://www.apache.org/licenses/LICENSE-2.0
  19602. *
  19603. * Unless required by applicable law or agreed to in writing,
  19604. * software distributed under the License is distributed on an
  19605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19606. * KIND, either express or implied. See the License for the
  19607. * specific language governing permissions and limitations
  19608. * under the License.
  19609. */
  19610. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19611. // PENDING A little ugly
  19612. var dataFormatMixin = {
  19613. /**
  19614. * Get params for formatter
  19615. * @param {number} dataIndex
  19616. * @param {string} [dataType]
  19617. * @return {Object}
  19618. */
  19619. getDataParams: function (dataIndex, dataType) {
  19620. var data = this.getData(dataType);
  19621. var rawValue = this.getRawValue(dataIndex, dataType);
  19622. var rawDataIndex = data.getRawIndex(dataIndex);
  19623. var name = data.getName(dataIndex);
  19624. var itemOpt = data.getRawDataItem(dataIndex);
  19625. var color = data.getItemVisual(dataIndex, 'color');
  19626. var tooltipModel = this.ecModel.getComponent('tooltip');
  19627. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  19628. var renderMode = getTooltipRenderMode(renderModeOption);
  19629. var mainType = this.mainType;
  19630. var isSeries = mainType === 'series';
  19631. return {
  19632. componentType: mainType,
  19633. componentSubType: this.subType,
  19634. componentIndex: this.componentIndex,
  19635. seriesType: isSeries ? this.subType : null,
  19636. seriesIndex: this.seriesIndex,
  19637. seriesId: isSeries ? this.id : null,
  19638. seriesName: isSeries ? this.name : null,
  19639. name: name,
  19640. dataIndex: rawDataIndex,
  19641. data: itemOpt,
  19642. dataType: dataType,
  19643. value: rawValue,
  19644. color: color,
  19645. marker: getTooltipMarker({
  19646. color: color,
  19647. renderMode: renderMode
  19648. }),
  19649. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19650. $vars: ['seriesName', 'name', 'value']
  19651. };
  19652. },
  19653. /**
  19654. * Format label
  19655. * @param {number} dataIndex
  19656. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19657. * @param {string} [dataType]
  19658. * @param {number} [dimIndex]
  19659. * @param {string} [labelProp='label']
  19660. * @return {string} If not formatter, return null/undefined
  19661. */
  19662. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19663. status = status || 'normal';
  19664. var data = this.getData(dataType);
  19665. var itemModel = data.getItemModel(dataIndex);
  19666. var params = this.getDataParams(dataIndex, dataType);
  19667. if (dimIndex != null && (params.value instanceof Array)) {
  19668. params.value = params.value[dimIndex];
  19669. }
  19670. var formatter = itemModel.get(
  19671. status === 'normal'
  19672. ? [labelProp || 'label', 'formatter']
  19673. : [status, labelProp || 'label', 'formatter']
  19674. );
  19675. if (typeof formatter === 'function') {
  19676. params.status = status;
  19677. return formatter(params);
  19678. }
  19679. else if (typeof formatter === 'string') {
  19680. var str = formatTpl(formatter, params);
  19681. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19682. // Do not support '}' in dim name util have to.
  19683. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19684. var len = dim.length;
  19685. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19686. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19687. }
  19688. return retrieveRawValue(data, dataIndex, dim);
  19689. });
  19690. }
  19691. },
  19692. /**
  19693. * Get raw value in option
  19694. * @param {number} idx
  19695. * @param {string} [dataType]
  19696. * @return {Array|number|string}
  19697. */
  19698. getRawValue: function (idx, dataType) {
  19699. return retrieveRawValue(this.getData(dataType), idx);
  19700. },
  19701. /**
  19702. * Should be implemented.
  19703. * @param {number} dataIndex
  19704. * @param {boolean} [multipleSeries=false]
  19705. * @param {number} [dataType]
  19706. * @return {string} tooltip string
  19707. */
  19708. formatTooltip: function () {
  19709. // Empty function
  19710. }
  19711. };
  19712. /*
  19713. * Licensed to the Apache Software Foundation (ASF) under one
  19714. * or more contributor license agreements. See the NOTICE file
  19715. * distributed with this work for additional information
  19716. * regarding copyright ownership. The ASF licenses this file
  19717. * to you under the Apache License, Version 2.0 (the
  19718. * "License"); you may not use this file except in compliance
  19719. * with the License. You may obtain a copy of the License at
  19720. *
  19721. * http://www.apache.org/licenses/LICENSE-2.0
  19722. *
  19723. * Unless required by applicable law or agreed to in writing,
  19724. * software distributed under the License is distributed on an
  19725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19726. * KIND, either express or implied. See the License for the
  19727. * specific language governing permissions and limitations
  19728. * under the License.
  19729. */
  19730. /**
  19731. * @param {Object} define
  19732. * @return See the return of `createTask`.
  19733. */
  19734. function createTask(define) {
  19735. return new Task(define);
  19736. }
  19737. /**
  19738. * @constructor
  19739. * @param {Object} define
  19740. * @param {Function} define.reset Custom reset
  19741. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19742. * @param {Function} [define.count] count is used to determin data task.
  19743. * @param {Function} [define.onDirty] count is used to determin data task.
  19744. */
  19745. function Task(define) {
  19746. define = define || {};
  19747. this._reset = define.reset;
  19748. this._plan = define.plan;
  19749. this._count = define.count;
  19750. this._onDirty = define.onDirty;
  19751. this._dirty = true;
  19752. // Context must be specified implicitly, to
  19753. // avoid miss update context when model changed.
  19754. this.context;
  19755. }
  19756. var taskProto = Task.prototype;
  19757. /**
  19758. * @param {Object} performArgs
  19759. * @param {number} [performArgs.step] Specified step.
  19760. * @param {number} [performArgs.skip] Skip customer perform call.
  19761. * @param {number} [performArgs.modBy] Sampling window size.
  19762. * @param {number} [performArgs.modDataCount] Sampling count.
  19763. */
  19764. taskProto.perform = function (performArgs) {
  19765. var upTask = this._upstream;
  19766. var skip = performArgs && performArgs.skip;
  19767. // TODO some refactor.
  19768. // Pull data. Must pull data each time, because context.data
  19769. // may be updated by Series.setData.
  19770. if (this._dirty && upTask) {
  19771. var context = this.context;
  19772. context.data = context.outputData = upTask.context.outputData;
  19773. }
  19774. if (this.__pipeline) {
  19775. this.__pipeline.currentTask = this;
  19776. }
  19777. var planResult;
  19778. if (this._plan && !skip) {
  19779. planResult = this._plan(this.context);
  19780. }
  19781. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19782. // elements uniformed distributed when progress, especially when moving or zooming.
  19783. var lastModBy = normalizeModBy(this._modBy);
  19784. var lastModDataCount = this._modDataCount || 0;
  19785. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19786. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19787. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19788. planResult = 'reset';
  19789. }
  19790. function normalizeModBy(val) {
  19791. !(val >= 1) && (val = 1); // jshint ignore:line
  19792. return val;
  19793. }
  19794. var forceFirstProgress;
  19795. if (this._dirty || planResult === 'reset') {
  19796. this._dirty = false;
  19797. forceFirstProgress = reset(this, skip);
  19798. }
  19799. this._modBy = modBy;
  19800. this._modDataCount = modDataCount;
  19801. var step = performArgs && performArgs.step;
  19802. if (upTask) {
  19803. if (__DEV__) {
  19804. assert$1(upTask._outputDueEnd != null);
  19805. }
  19806. this._dueEnd = upTask._outputDueEnd;
  19807. }
  19808. // DataTask or overallTask
  19809. else {
  19810. if (__DEV__) {
  19811. assert$1(!this._progress || this._count);
  19812. }
  19813. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19814. }
  19815. // Note: Stubs, that its host overall task let it has progress, has progress.
  19816. // If no progress, pass index from upstream to downstream each time plan called.
  19817. if (this._progress) {
  19818. var start = this._dueIndex;
  19819. var end = Math.min(
  19820. step != null ? this._dueIndex + step : Infinity,
  19821. this._dueEnd
  19822. );
  19823. if (!skip && (forceFirstProgress || start < end)) {
  19824. var progress = this._progress;
  19825. if (isArray(progress)) {
  19826. for (var i = 0; i < progress.length; i++) {
  19827. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19828. }
  19829. }
  19830. else {
  19831. doProgress(this, progress, start, end, modBy, modDataCount);
  19832. }
  19833. }
  19834. this._dueIndex = end;
  19835. // If no `outputDueEnd`, assume that output data and
  19836. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19837. var outputDueEnd = this._settedOutputEnd != null
  19838. ? this._settedOutputEnd : end;
  19839. if (__DEV__) {
  19840. // ??? Can not rollback.
  19841. assert$1(outputDueEnd >= this._outputDueEnd);
  19842. }
  19843. this._outputDueEnd = outputDueEnd;
  19844. }
  19845. else {
  19846. // (1) Some overall task has no progress.
  19847. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19848. // This should always be performed so it can be passed to downstream.
  19849. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19850. ? this._settedOutputEnd : this._dueEnd;
  19851. }
  19852. return this.unfinished();
  19853. };
  19854. var iterator = (function () {
  19855. var end;
  19856. var current;
  19857. var modBy;
  19858. var modDataCount;
  19859. var winCount;
  19860. var it = {
  19861. reset: function (s, e, sStep, sCount) {
  19862. current = s;
  19863. end = e;
  19864. modBy = sStep;
  19865. modDataCount = sCount;
  19866. winCount = Math.ceil(modDataCount / modBy);
  19867. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  19868. }
  19869. };
  19870. return it;
  19871. function sequentialNext() {
  19872. return current < end ? current++ : null;
  19873. }
  19874. function modNext() {
  19875. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  19876. var result = current >= end
  19877. ? null
  19878. : dataIndex < modDataCount
  19879. ? dataIndex
  19880. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19881. // Use normal linear rendering mode.
  19882. : current;
  19883. current++;
  19884. return result;
  19885. }
  19886. })();
  19887. taskProto.dirty = function () {
  19888. this._dirty = true;
  19889. this._onDirty && this._onDirty(this.context);
  19890. };
  19891. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19892. iterator.reset(start, end, modBy, modDataCount);
  19893. taskIns._callingProgress = progress;
  19894. taskIns._callingProgress({
  19895. start: start, end: end, count: end - start, next: iterator.next
  19896. }, taskIns.context);
  19897. }
  19898. function reset(taskIns, skip) {
  19899. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19900. taskIns._settedOutputEnd = null;
  19901. var progress;
  19902. var forceFirstProgress;
  19903. if (!skip && taskIns._reset) {
  19904. progress = taskIns._reset(taskIns.context);
  19905. if (progress && progress.progress) {
  19906. forceFirstProgress = progress.forceFirstProgress;
  19907. progress = progress.progress;
  19908. }
  19909. // To simplify no progress checking, array must has item.
  19910. if (isArray(progress) && !progress.length) {
  19911. progress = null;
  19912. }
  19913. }
  19914. taskIns._progress = progress;
  19915. taskIns._modBy = taskIns._modDataCount = null;
  19916. var downstream = taskIns._downstream;
  19917. downstream && downstream.dirty();
  19918. return forceFirstProgress;
  19919. }
  19920. /**
  19921. * @return {boolean}
  19922. */
  19923. taskProto.unfinished = function () {
  19924. return this._progress && this._dueIndex < this._dueEnd;
  19925. };
  19926. /**
  19927. * @param {Object} downTask The downstream task.
  19928. * @return {Object} The downstream task.
  19929. */
  19930. taskProto.pipe = function (downTask) {
  19931. if (__DEV__) {
  19932. assert$1(downTask && !downTask._disposed && downTask !== this);
  19933. }
  19934. // If already downstream, do not dirty downTask.
  19935. if (this._downstream !== downTask || this._dirty) {
  19936. this._downstream = downTask;
  19937. downTask._upstream = this;
  19938. downTask.dirty();
  19939. }
  19940. };
  19941. taskProto.dispose = function () {
  19942. if (this._disposed) {
  19943. return;
  19944. }
  19945. this._upstream && (this._upstream._downstream = null);
  19946. this._downstream && (this._downstream._upstream = null);
  19947. this._dirty = false;
  19948. this._disposed = true;
  19949. };
  19950. taskProto.getUpstream = function () {
  19951. return this._upstream;
  19952. };
  19953. taskProto.getDownstream = function () {
  19954. return this._downstream;
  19955. };
  19956. taskProto.setOutputEnd = function (end) {
  19957. // This only happend in dataTask, dataZoom, map, currently.
  19958. // where dataZoom do not set end each time, but only set
  19959. // when reset. So we should record the setted end, in case
  19960. // that the stub of dataZoom perform again and earse the
  19961. // setted end by upstream.
  19962. this._outputDueEnd = this._settedOutputEnd = end;
  19963. };
  19964. ///////////////////////////////////////////////////////////
  19965. // For stream debug (Should be commented out after used!)
  19966. // Usage: printTask(this, 'begin');
  19967. // Usage: printTask(this, null, {someExtraProp});
  19968. // function printTask(task, prefix, extra) {
  19969. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19970. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19971. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19972. // var props = [];
  19973. // if (task.__pipeline) {
  19974. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19975. // props.push({text: 'idx', value: val});
  19976. // } else {
  19977. // var stubCount = 0;
  19978. // task.agentStubMap.each(() => stubCount++);
  19979. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19980. // }
  19981. // props.push({text: 'uid', value: task.uidDebug});
  19982. // if (task.__pipeline) {
  19983. // props.push({text: 'pid', value: task.__pipeline.id});
  19984. // task.agent && props.push(
  19985. // {text: 'stubFor', value: task.agent.uidDebug}
  19986. // );
  19987. // }
  19988. // props.push(
  19989. // {text: 'dirty', value: task._dirty},
  19990. // {text: 'dueIndex', value: task._dueIndex},
  19991. // {text: 'dueEnd', value: task._dueEnd},
  19992. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19993. // );
  19994. // if (extra) {
  19995. // Object.keys(extra).forEach(key => {
  19996. // props.push({text: key, value: extra[key]});
  19997. // });
  19998. // }
  19999. // var args = ['color: blue'];
  20000. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  20001. // args.push('color: black', 'color: red'),
  20002. // `${item.text}: %c${item.value}`
  20003. // )).join('%c, ');
  20004. // console.log.apply(console, [msg].concat(args));
  20005. // // console.log(this);
  20006. // }
  20007. /*
  20008. * Licensed to the Apache Software Foundation (ASF) under one
  20009. * or more contributor license agreements. See the NOTICE file
  20010. * distributed with this work for additional information
  20011. * regarding copyright ownership. The ASF licenses this file
  20012. * to you under the Apache License, Version 2.0 (the
  20013. * "License"); you may not use this file except in compliance
  20014. * with the License. You may obtain a copy of the License at
  20015. *
  20016. * http://www.apache.org/licenses/LICENSE-2.0
  20017. *
  20018. * Unless required by applicable law or agreed to in writing,
  20019. * software distributed under the License is distributed on an
  20020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20021. * KIND, either express or implied. See the License for the
  20022. * specific language governing permissions and limitations
  20023. * under the License.
  20024. */
  20025. var inner$4 = makeInner();
  20026. var SeriesModel = ComponentModel.extend({
  20027. type: 'series.__base__',
  20028. /**
  20029. * @readOnly
  20030. */
  20031. seriesIndex: 0,
  20032. // coodinateSystem will be injected in the echarts/CoordinateSystem
  20033. coordinateSystem: null,
  20034. /**
  20035. * @type {Object}
  20036. * @protected
  20037. */
  20038. defaultOption: null,
  20039. /**
  20040. * Data provided for legend
  20041. * @type {Function}
  20042. */
  20043. // PENDING
  20044. legendDataProvider: null,
  20045. /**
  20046. * Access path of color for visual
  20047. */
  20048. visualColorAccessPath: 'itemStyle.color',
  20049. /**
  20050. * Support merge layout params.
  20051. * Only support 'box' now (left/right/top/bottom/width/height).
  20052. * @type {string|Object} Object can be {ignoreSize: true}
  20053. * @readOnly
  20054. */
  20055. layoutMode: null,
  20056. init: function (option, parentModel, ecModel, extraOpt) {
  20057. /**
  20058. * @type {number}
  20059. * @readOnly
  20060. */
  20061. this.seriesIndex = this.componentIndex;
  20062. this.dataTask = createTask({
  20063. count: dataTaskCount,
  20064. reset: dataTaskReset
  20065. });
  20066. this.dataTask.context = {model: this};
  20067. this.mergeDefaultAndTheme(option, ecModel);
  20068. prepareSource(this);
  20069. var data = this.getInitialData(option, ecModel);
  20070. wrapData(data, this);
  20071. this.dataTask.context.data = data;
  20072. if (__DEV__) {
  20073. assert$1(data, 'getInitialData returned invalid data.');
  20074. }
  20075. /**
  20076. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  20077. * @private
  20078. */
  20079. inner$4(this).dataBeforeProcessed = data;
  20080. // If we reverse the order (make data firstly, and then make
  20081. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20082. // cause data.graph.data !== data when using
  20083. // module:echarts/data/Graph or module:echarts/data/Tree.
  20084. // See module:echarts/data/helper/linkList
  20085. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20086. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20087. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20088. // Call `seriesModel.getRawData()` instead.
  20089. // this.restoreData();
  20090. autoSeriesName(this);
  20091. },
  20092. /**
  20093. * Util for merge default and theme to option
  20094. * @param {Object} option
  20095. * @param {module:echarts/model/Global} ecModel
  20096. */
  20097. mergeDefaultAndTheme: function (option, ecModel) {
  20098. var layoutMode = this.layoutMode;
  20099. var inputPositionParams = layoutMode
  20100. ? getLayoutParams(option) : {};
  20101. // Backward compat: using subType on theme.
  20102. // But if name duplicate between series subType
  20103. // (for example: parallel) add component mainType,
  20104. // add suffix 'Series'.
  20105. var themeSubType = this.subType;
  20106. if (ComponentModel.hasClass(themeSubType)) {
  20107. themeSubType += 'Series';
  20108. }
  20109. merge(
  20110. option,
  20111. ecModel.getTheme().get(this.subType)
  20112. );
  20113. merge(option, this.getDefaultOption());
  20114. // Default label emphasis `show`
  20115. defaultEmphasis(option, 'label', ['show']);
  20116. this.fillDataTextStyle(option.data);
  20117. if (layoutMode) {
  20118. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20119. }
  20120. },
  20121. mergeOption: function (newSeriesOption, ecModel) {
  20122. // this.settingTask.dirty();
  20123. newSeriesOption = merge(this.option, newSeriesOption, true);
  20124. this.fillDataTextStyle(newSeriesOption.data);
  20125. var layoutMode = this.layoutMode;
  20126. if (layoutMode) {
  20127. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20128. }
  20129. prepareSource(this);
  20130. var data = this.getInitialData(newSeriesOption, ecModel);
  20131. wrapData(data, this);
  20132. this.dataTask.dirty();
  20133. this.dataTask.context.data = data;
  20134. inner$4(this).dataBeforeProcessed = data;
  20135. autoSeriesName(this);
  20136. },
  20137. fillDataTextStyle: function (data) {
  20138. // Default data label emphasis `show`
  20139. // FIXME Tree structure data ?
  20140. // FIXME Performance ?
  20141. if (data && !isTypedArray(data)) {
  20142. var props = ['show'];
  20143. for (var i = 0; i < data.length; i++) {
  20144. if (data[i] && data[i].label) {
  20145. defaultEmphasis(data[i], 'label', props);
  20146. }
  20147. }
  20148. }
  20149. },
  20150. /**
  20151. * Init a data structure from data related option in series
  20152. * Must be overwritten
  20153. */
  20154. getInitialData: function () {},
  20155. /**
  20156. * Append data to list
  20157. * @param {Object} params
  20158. * @param {Array|TypedArray} params.data
  20159. */
  20160. appendData: function (params) {
  20161. // FIXME ???
  20162. // (1) If data from dataset, forbidden append.
  20163. // (2) support append data of dataset.
  20164. var data = this.getRawData();
  20165. data.appendData(params.data);
  20166. },
  20167. /**
  20168. * Consider some method like `filter`, `map` need make new data,
  20169. * We should make sure that `seriesModel.getData()` get correct
  20170. * data in the stream procedure. So we fetch data from upstream
  20171. * each time `task.perform` called.
  20172. * @param {string} [dataType]
  20173. * @return {module:echarts/data/List}
  20174. */
  20175. getData: function (dataType) {
  20176. var task = getCurrentTask(this);
  20177. if (task) {
  20178. var data = task.context.data;
  20179. return dataType == null ? data : data.getLinkedData(dataType);
  20180. }
  20181. else {
  20182. // When series is not alive (that may happen when click toolbox
  20183. // restore or setOption with not merge mode), series data may
  20184. // be still need to judge animation or something when graphic
  20185. // elements want to know whether fade out.
  20186. return inner$4(this).data;
  20187. }
  20188. },
  20189. /**
  20190. * @param {module:echarts/data/List} data
  20191. */
  20192. setData: function (data) {
  20193. var task = getCurrentTask(this);
  20194. if (task) {
  20195. var context = task.context;
  20196. // Consider case: filter, data sample.
  20197. if (context.data !== data && task.modifyOutputEnd) {
  20198. task.setOutputEnd(data.count());
  20199. }
  20200. context.outputData = data;
  20201. // Caution: setData should update context.data,
  20202. // Because getData may be called multiply in a
  20203. // single stage and expect to get the data just
  20204. // set. (For example, AxisProxy, x y both call
  20205. // getData and setDate sequentially).
  20206. // So the context.data should be fetched from
  20207. // upstream each time when a stage starts to be
  20208. // performed.
  20209. if (task !== this.dataTask) {
  20210. context.data = data;
  20211. }
  20212. }
  20213. inner$4(this).data = data;
  20214. },
  20215. /**
  20216. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20217. * @return {module:echarts/data/Source} source
  20218. */
  20219. getSource: function () {
  20220. return getSource(this);
  20221. },
  20222. /**
  20223. * Get data before processed
  20224. * @return {module:echarts/data/List}
  20225. */
  20226. getRawData: function () {
  20227. return inner$4(this).dataBeforeProcessed;
  20228. },
  20229. /**
  20230. * Get base axis if has coordinate system and has axis.
  20231. * By default use coordSys.getBaseAxis();
  20232. * Can be overrided for some chart.
  20233. * @return {type} description
  20234. */
  20235. getBaseAxis: function () {
  20236. var coordSys = this.coordinateSystem;
  20237. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20238. },
  20239. // FIXME
  20240. /**
  20241. * Default tooltip formatter
  20242. *
  20243. * @param {number} dataIndex
  20244. * @param {boolean} [multipleSeries=false]
  20245. * @param {number} [dataType]
  20246. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  20247. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20248. * string is used as DOM HTML content.
  20249. * 'richText' is used for rendering tooltip in rich text form, for those where
  20250. * DOM operation is not supported.
  20251. * @return {Object} formatted tooltip with `html` and `markers`
  20252. */
  20253. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  20254. var series = this;
  20255. renderMode = renderMode || 'html';
  20256. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  20257. var isRichText = renderMode === 'richText';
  20258. var markers = {};
  20259. var markerId = 0;
  20260. function formatArrayValue(value) {
  20261. // ??? TODO refactor these logic.
  20262. // check: category-no-encode-has-axis-data in dataset.html
  20263. var vertially = reduce(value, function (vertially, val, idx) {
  20264. var dimItem = data.getDimensionInfo(idx);
  20265. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20266. }, 0);
  20267. var result = [];
  20268. tooltipDims.length
  20269. ? each$1(tooltipDims, function (dim) {
  20270. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20271. })
  20272. // By default, all dims is used on tooltip.
  20273. : each$1(value, setEachItem);
  20274. function setEachItem(val, dim) {
  20275. var dimInfo = data.getDimensionInfo(dim);
  20276. // If `dimInfo.tooltip` is not set, show tooltip.
  20277. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20278. return;
  20279. }
  20280. var dimType = dimInfo.type;
  20281. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  20282. var dimHead = getTooltipMarker({
  20283. color: color,
  20284. type: 'subItem',
  20285. renderMode: renderMode,
  20286. markerId: markName
  20287. });
  20288. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  20289. var valStr = (vertially
  20290. ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': '
  20291. : ''
  20292. )
  20293. // FIXME should not format time for raw data?
  20294. + encodeHTML(dimType === 'ordinal'
  20295. ? val + ''
  20296. : dimType === 'time'
  20297. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20298. : addCommas(val)
  20299. );
  20300. valStr && result.push(valStr);
  20301. if (isRichText) {
  20302. markers[markName] = color;
  20303. ++markerId;
  20304. }
  20305. }
  20306. var newLine = vertially ? (isRichText ? '\n' : '<br/>') : '';
  20307. var content = newLine + result.join(newLine || ', ');
  20308. return {
  20309. renderMode: renderMode,
  20310. content: content,
  20311. style: markers
  20312. };
  20313. }
  20314. function formatSingleValue(val) {
  20315. // return encodeHTML(addCommas(val));
  20316. return {
  20317. renderMode: renderMode,
  20318. content: encodeHTML(addCommas(val)),
  20319. style: markers
  20320. };
  20321. }
  20322. var data = this.getData();
  20323. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20324. var tooltipDimLen = tooltipDims.length;
  20325. var value = this.getRawValue(dataIndex);
  20326. var isValueArr = isArray(value);
  20327. var color = data.getItemVisual(dataIndex, 'color');
  20328. if (isObject$1(color) && color.colorStops) {
  20329. color = (color.colorStops[0] || {}).color;
  20330. }
  20331. color = color || 'transparent';
  20332. // Complicated rule for pretty tooltip.
  20333. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20334. ? formatArrayValue(value)
  20335. : tooltipDimLen
  20336. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20337. : formatSingleValue(isValueArr ? value[0] : value);
  20338. var content = formattedValue.content;
  20339. var markName = series.seriesIndex + 'at' + markerId;
  20340. var colorEl = getTooltipMarker({
  20341. color: color,
  20342. type: 'item',
  20343. renderMode: renderMode,
  20344. markerId: markName
  20345. });
  20346. markers[markName] = color;
  20347. ++markerId;
  20348. var name = data.getName(dataIndex);
  20349. var seriesName = this.name;
  20350. if (!isNameSpecified(this)) {
  20351. seriesName = '';
  20352. }
  20353. seriesName = seriesName
  20354. ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ')
  20355. : '';
  20356. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20357. var html = !multipleSeries
  20358. ? seriesName + colorStr
  20359. + (name
  20360. ? encodeHTML(name) + ': ' + content
  20361. : content
  20362. )
  20363. : colorStr + seriesName + content;
  20364. return {
  20365. html: html,
  20366. markers: markers
  20367. };
  20368. },
  20369. /**
  20370. * @return {boolean}
  20371. */
  20372. isAnimationEnabled: function () {
  20373. if (env$1.node) {
  20374. return false;
  20375. }
  20376. var animationEnabled = this.getShallow('animation');
  20377. if (animationEnabled) {
  20378. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20379. animationEnabled = false;
  20380. }
  20381. }
  20382. return animationEnabled;
  20383. },
  20384. restoreData: function () {
  20385. this.dataTask.dirty();
  20386. },
  20387. getColorFromPalette: function (name, scope, requestColorNum) {
  20388. var ecModel = this.ecModel;
  20389. // PENDING
  20390. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20391. if (!color) {
  20392. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20393. }
  20394. return color;
  20395. },
  20396. /**
  20397. * Use `data.mapDimension(coordDim, true)` instead.
  20398. * @deprecated
  20399. */
  20400. coordDimToDataDim: function (coordDim) {
  20401. return this.getRawData().mapDimension(coordDim, true);
  20402. },
  20403. /**
  20404. * Get progressive rendering count each step
  20405. * @return {number}
  20406. */
  20407. getProgressive: function () {
  20408. return this.get('progressive');
  20409. },
  20410. /**
  20411. * Get progressive rendering count each step
  20412. * @return {number}
  20413. */
  20414. getProgressiveThreshold: function () {
  20415. return this.get('progressiveThreshold');
  20416. },
  20417. /**
  20418. * Get data indices for show tooltip content. See tooltip.
  20419. * @abstract
  20420. * @param {Array.<string>|string} dim
  20421. * @param {Array.<number>} value
  20422. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20423. * @return {Object} {dataIndices, nestestValue}.
  20424. */
  20425. getAxisTooltipData: null,
  20426. /**
  20427. * See tooltip.
  20428. * @abstract
  20429. * @param {number} dataIndex
  20430. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20431. */
  20432. getTooltipPosition: null,
  20433. /**
  20434. * @see {module:echarts/stream/Scheduler}
  20435. */
  20436. pipeTask: null,
  20437. /**
  20438. * Convinient for override in extended class.
  20439. * @protected
  20440. * @type {Function}
  20441. */
  20442. preventIncremental: null,
  20443. /**
  20444. * @public
  20445. * @readOnly
  20446. * @type {Object}
  20447. */
  20448. pipelineContext: null
  20449. });
  20450. mixin(SeriesModel, dataFormatMixin);
  20451. mixin(SeriesModel, colorPaletteMixin);
  20452. /**
  20453. * MUST be called after `prepareSource` called
  20454. * Here we need to make auto series, especially for auto legend. But we
  20455. * do not modify series.name in option to avoid side effects.
  20456. */
  20457. function autoSeriesName(seriesModel) {
  20458. // User specified name has higher priority, otherwise it may cause
  20459. // series can not be queried unexpectedly.
  20460. var name = seriesModel.name;
  20461. if (!isNameSpecified(seriesModel)) {
  20462. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20463. }
  20464. }
  20465. function getSeriesAutoName(seriesModel) {
  20466. var data = seriesModel.getRawData();
  20467. var dataDims = data.mapDimension('seriesName', true);
  20468. var nameArr = [];
  20469. each$1(dataDims, function (dataDim) {
  20470. var dimInfo = data.getDimensionInfo(dataDim);
  20471. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20472. });
  20473. return nameArr.join(' ');
  20474. }
  20475. function dataTaskCount(context) {
  20476. return context.model.getRawData().count();
  20477. }
  20478. function dataTaskReset(context) {
  20479. var seriesModel = context.model;
  20480. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20481. return dataTaskProgress;
  20482. }
  20483. function dataTaskProgress(param, context) {
  20484. // Avoid repead cloneShallow when data just created in reset.
  20485. if (param.end > context.outputData.count()) {
  20486. context.model.getRawData().cloneShallow(context.outputData);
  20487. }
  20488. }
  20489. // TODO refactor
  20490. function wrapData(data, seriesModel) {
  20491. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20492. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20493. });
  20494. }
  20495. function onDataSelfChange(seriesModel) {
  20496. var task = getCurrentTask(seriesModel);
  20497. if (task) {
  20498. // Consider case: filter, selectRange
  20499. task.setOutputEnd(this.count());
  20500. }
  20501. }
  20502. function getCurrentTask(seriesModel) {
  20503. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20504. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20505. if (pipeline) {
  20506. // When pipline finished, the currrentTask keep the last
  20507. // task (renderTask).
  20508. var task = pipeline.currentTask;
  20509. if (task) {
  20510. var agentStubMap = task.agentStubMap;
  20511. if (agentStubMap) {
  20512. task = agentStubMap.get(seriesModel.uid);
  20513. }
  20514. }
  20515. return task;
  20516. }
  20517. }
  20518. /*
  20519. * Licensed to the Apache Software Foundation (ASF) under one
  20520. * or more contributor license agreements. See the NOTICE file
  20521. * distributed with this work for additional information
  20522. * regarding copyright ownership. The ASF licenses this file
  20523. * to you under the Apache License, Version 2.0 (the
  20524. * "License"); you may not use this file except in compliance
  20525. * with the License. You may obtain a copy of the License at
  20526. *
  20527. * http://www.apache.org/licenses/LICENSE-2.0
  20528. *
  20529. * Unless required by applicable law or agreed to in writing,
  20530. * software distributed under the License is distributed on an
  20531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20532. * KIND, either express or implied. See the License for the
  20533. * specific language governing permissions and limitations
  20534. * under the License.
  20535. */
  20536. var Component = function () {
  20537. /**
  20538. * @type {module:zrender/container/Group}
  20539. * @readOnly
  20540. */
  20541. this.group = new Group();
  20542. /**
  20543. * @type {string}
  20544. * @readOnly
  20545. */
  20546. this.uid = getUID('viewComponent');
  20547. };
  20548. Component.prototype = {
  20549. constructor: Component,
  20550. init: function (ecModel, api) {},
  20551. render: function (componentModel, ecModel, api, payload) {},
  20552. dispose: function () {},
  20553. /**
  20554. * @param {string} eventType
  20555. * @param {Object} query
  20556. * @param {module:zrender/Element} targetEl
  20557. * @param {Object} packedEvent
  20558. * @return {boolen} Pass only when return `true`.
  20559. */
  20560. filterForExposedEvent: null
  20561. };
  20562. var componentProto = Component.prototype;
  20563. componentProto.updateView
  20564. = componentProto.updateLayout
  20565. = componentProto.updateVisual
  20566. = function (seriesModel, ecModel, api, payload) {
  20567. // Do nothing;
  20568. };
  20569. // Enable Component.extend.
  20570. enableClassExtend(Component);
  20571. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20572. enableClassManagement(Component, {registerWhenExtend: true});
  20573. /*
  20574. * Licensed to the Apache Software Foundation (ASF) under one
  20575. * or more contributor license agreements. See the NOTICE file
  20576. * distributed with this work for additional information
  20577. * regarding copyright ownership. The ASF licenses this file
  20578. * to you under the Apache License, Version 2.0 (the
  20579. * "License"); you may not use this file except in compliance
  20580. * with the License. You may obtain a copy of the License at
  20581. *
  20582. * http://www.apache.org/licenses/LICENSE-2.0
  20583. *
  20584. * Unless required by applicable law or agreed to in writing,
  20585. * software distributed under the License is distributed on an
  20586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20587. * KIND, either express or implied. See the License for the
  20588. * specific language governing permissions and limitations
  20589. * under the License.
  20590. */
  20591. /**
  20592. * @return {string} If large mode changed, return string 'reset';
  20593. */
  20594. var createRenderPlanner = function () {
  20595. var inner = makeInner();
  20596. return function (seriesModel) {
  20597. var fields = inner(seriesModel);
  20598. var pipelineContext = seriesModel.pipelineContext;
  20599. var originalLarge = fields.large;
  20600. var originalProgressive = fields.progressiveRender;
  20601. var large = fields.large = pipelineContext.large;
  20602. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  20603. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  20604. };
  20605. };
  20606. /*
  20607. * Licensed to the Apache Software Foundation (ASF) under one
  20608. * or more contributor license agreements. See the NOTICE file
  20609. * distributed with this work for additional information
  20610. * regarding copyright ownership. The ASF licenses this file
  20611. * to you under the Apache License, Version 2.0 (the
  20612. * "License"); you may not use this file except in compliance
  20613. * with the License. You may obtain a copy of the License at
  20614. *
  20615. * http://www.apache.org/licenses/LICENSE-2.0
  20616. *
  20617. * Unless required by applicable law or agreed to in writing,
  20618. * software distributed under the License is distributed on an
  20619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20620. * KIND, either express or implied. See the License for the
  20621. * specific language governing permissions and limitations
  20622. * under the License.
  20623. */
  20624. var inner$5 = makeInner();
  20625. var renderPlanner = createRenderPlanner();
  20626. function Chart() {
  20627. /**
  20628. * @type {module:zrender/container/Group}
  20629. * @readOnly
  20630. */
  20631. this.group = new Group();
  20632. /**
  20633. * @type {string}
  20634. * @readOnly
  20635. */
  20636. this.uid = getUID('viewChart');
  20637. this.renderTask = createTask({
  20638. plan: renderTaskPlan,
  20639. reset: renderTaskReset
  20640. });
  20641. this.renderTask.context = {view: this};
  20642. }
  20643. Chart.prototype = {
  20644. type: 'chart',
  20645. /**
  20646. * Init the chart.
  20647. * @param {module:echarts/model/Global} ecModel
  20648. * @param {module:echarts/ExtensionAPI} api
  20649. */
  20650. init: function (ecModel, api) {},
  20651. /**
  20652. * Render the chart.
  20653. * @param {module:echarts/model/Series} seriesModel
  20654. * @param {module:echarts/model/Global} ecModel
  20655. * @param {module:echarts/ExtensionAPI} api
  20656. * @param {Object} payload
  20657. */
  20658. render: function (seriesModel, ecModel, api, payload) {},
  20659. /**
  20660. * Highlight series or specified data item.
  20661. * @param {module:echarts/model/Series} seriesModel
  20662. * @param {module:echarts/model/Global} ecModel
  20663. * @param {module:echarts/ExtensionAPI} api
  20664. * @param {Object} payload
  20665. */
  20666. highlight: function (seriesModel, ecModel, api, payload) {
  20667. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20668. },
  20669. /**
  20670. * Downplay series or specified data item.
  20671. * @param {module:echarts/model/Series} seriesModel
  20672. * @param {module:echarts/model/Global} ecModel
  20673. * @param {module:echarts/ExtensionAPI} api
  20674. * @param {Object} payload
  20675. */
  20676. downplay: function (seriesModel, ecModel, api, payload) {
  20677. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20678. },
  20679. /**
  20680. * Remove self.
  20681. * @param {module:echarts/model/Global} ecModel
  20682. * @param {module:echarts/ExtensionAPI} api
  20683. */
  20684. remove: function (ecModel, api) {
  20685. this.group.removeAll();
  20686. },
  20687. /**
  20688. * Dispose self.
  20689. * @param {module:echarts/model/Global} ecModel
  20690. * @param {module:echarts/ExtensionAPI} api
  20691. */
  20692. dispose: function () {},
  20693. /**
  20694. * Rendering preparation in progressive mode.
  20695. * @param {module:echarts/model/Series} seriesModel
  20696. * @param {module:echarts/model/Global} ecModel
  20697. * @param {module:echarts/ExtensionAPI} api
  20698. * @param {Object} payload
  20699. */
  20700. incrementalPrepareRender: null,
  20701. /**
  20702. * Render in progressive mode.
  20703. * @param {Object} params See taskParams in `stream/task.js`
  20704. * @param {module:echarts/model/Series} seriesModel
  20705. * @param {module:echarts/model/Global} ecModel
  20706. * @param {module:echarts/ExtensionAPI} api
  20707. * @param {Object} payload
  20708. */
  20709. incrementalRender: null,
  20710. /**
  20711. * Update transform directly.
  20712. * @param {module:echarts/model/Series} seriesModel
  20713. * @param {module:echarts/model/Global} ecModel
  20714. * @param {module:echarts/ExtensionAPI} api
  20715. * @param {Object} payload
  20716. * @return {Object} {update: true}
  20717. */
  20718. updateTransform: null,
  20719. /**
  20720. * The view contains the given point.
  20721. * @interface
  20722. * @param {Array.<number>} point
  20723. * @return {boolean}
  20724. */
  20725. // containPoint: function () {}
  20726. /**
  20727. * @param {string} eventType
  20728. * @param {Object} query
  20729. * @param {module:zrender/Element} targetEl
  20730. * @param {Object} packedEvent
  20731. * @return {boolen} Pass only when return `true`.
  20732. */
  20733. filterForExposedEvent: null
  20734. };
  20735. var chartProto = Chart.prototype;
  20736. chartProto.updateView
  20737. = chartProto.updateLayout
  20738. = chartProto.updateVisual
  20739. = function (seriesModel, ecModel, api, payload) {
  20740. this.render(seriesModel, ecModel, api, payload);
  20741. };
  20742. /**
  20743. * Set state of single element
  20744. * @param {module:zrender/Element} el
  20745. * @param {string} state
  20746. */
  20747. function elSetState(el, state) {
  20748. if (el) {
  20749. el.trigger(state);
  20750. if (el.type === 'group') {
  20751. for (var i = 0; i < el.childCount(); i++) {
  20752. elSetState(el.childAt(i), state);
  20753. }
  20754. }
  20755. }
  20756. }
  20757. /**
  20758. * @param {module:echarts/data/List} data
  20759. * @param {Object} payload
  20760. * @param {string} state 'normal'|'emphasis'
  20761. */
  20762. function toggleHighlight(data, payload, state) {
  20763. var dataIndex = queryDataIndex(data, payload);
  20764. if (dataIndex != null) {
  20765. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20766. elSetState(data.getItemGraphicEl(dataIdx), state);
  20767. });
  20768. }
  20769. else {
  20770. data.eachItemGraphicEl(function (el) {
  20771. elSetState(el, state);
  20772. });
  20773. }
  20774. }
  20775. // Enable Chart.extend.
  20776. enableClassExtend(Chart, ['dispose']);
  20777. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20778. enableClassManagement(Chart, {registerWhenExtend: true});
  20779. Chart.markUpdateMethod = function (payload, methodName) {
  20780. inner$5(payload).updateMethod = methodName;
  20781. };
  20782. function renderTaskPlan(context) {
  20783. return renderPlanner(context.model);
  20784. }
  20785. function renderTaskReset(context) {
  20786. var seriesModel = context.model;
  20787. var ecModel = context.ecModel;
  20788. var api = context.api;
  20789. var payload = context.payload;
  20790. // ???! remove updateView updateVisual
  20791. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20792. var view = context.view;
  20793. var updateMethod = payload && inner$5(payload).updateMethod;
  20794. var methodName = progressiveRender
  20795. ? 'incrementalPrepareRender'
  20796. : (updateMethod && view[updateMethod])
  20797. ? updateMethod
  20798. // `appendData` is also supported when data amount
  20799. // is less than progressive threshold.
  20800. : 'render';
  20801. if (methodName !== 'render') {
  20802. view[methodName](seriesModel, ecModel, api, payload);
  20803. }
  20804. return progressMethodMap[methodName];
  20805. }
  20806. var progressMethodMap = {
  20807. incrementalPrepareRender: {
  20808. progress: function (params, context) {
  20809. context.view.incrementalRender(
  20810. params, context.model, context.ecModel, context.api, context.payload
  20811. );
  20812. }
  20813. },
  20814. render: {
  20815. // Put view.render in `progress` to support appendData. But in this case
  20816. // view.render should not be called in reset, otherwise it will be called
  20817. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20818. // in any cases.
  20819. forceFirstProgress: true,
  20820. progress: function (params, context) {
  20821. context.view.render(
  20822. context.model, context.ecModel, context.api, context.payload
  20823. );
  20824. }
  20825. }
  20826. };
  20827. /*
  20828. * Licensed to the Apache Software Foundation (ASF) under one
  20829. * or more contributor license agreements. See the NOTICE file
  20830. * distributed with this work for additional information
  20831. * regarding copyright ownership. The ASF licenses this file
  20832. * to you under the Apache License, Version 2.0 (the
  20833. * "License"); you may not use this file except in compliance
  20834. * with the License. You may obtain a copy of the License at
  20835. *
  20836. * http://www.apache.org/licenses/LICENSE-2.0
  20837. *
  20838. * Unless required by applicable law or agreed to in writing,
  20839. * software distributed under the License is distributed on an
  20840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20841. * KIND, either express or implied. See the License for the
  20842. * specific language governing permissions and limitations
  20843. * under the License.
  20844. */
  20845. /**
  20846. * @public
  20847. * @param {(Function)} fn
  20848. * @param {number} [delay=0] Unit: ms.
  20849. * @param {boolean} [debounce=false]
  20850. * true: If call interval less than `delay`, only the last call works.
  20851. * false: If call interval less than `delay, call works on fixed rate.
  20852. * @return {(Function)} throttled fn.
  20853. */
  20854. function throttle(fn, delay, debounce) {
  20855. var currCall;
  20856. var lastCall = 0;
  20857. var lastExec = 0;
  20858. var timer = null;
  20859. var diff;
  20860. var scope;
  20861. var args;
  20862. var debounceNextCall;
  20863. delay = delay || 0;
  20864. function exec() {
  20865. lastExec = (new Date()).getTime();
  20866. timer = null;
  20867. fn.apply(scope, args || []);
  20868. }
  20869. var cb = function () {
  20870. currCall = (new Date()).getTime();
  20871. scope = this;
  20872. args = arguments;
  20873. var thisDelay = debounceNextCall || delay;
  20874. var thisDebounce = debounceNextCall || debounce;
  20875. debounceNextCall = null;
  20876. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20877. clearTimeout(timer);
  20878. // Here we should make sure that: the `exec` SHOULD NOT be called later
  20879. // than a new call of `cb`, that is, preserving the command order. Consider
  20880. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20881. // happens, either the `exec` is called dierectly, or the call is delayed.
  20882. // But the delayed call should never be later than next call of `cb`. Under
  20883. // this assurance, we can simply update view state each time `dispatchAction`
  20884. // triggered by user roaming, but not need to add extra code to avoid the
  20885. // state being "rolled-back".
  20886. if (thisDebounce) {
  20887. timer = setTimeout(exec, thisDelay);
  20888. }
  20889. else {
  20890. if (diff >= 0) {
  20891. exec();
  20892. }
  20893. else {
  20894. timer = setTimeout(exec, -diff);
  20895. }
  20896. }
  20897. lastCall = currCall;
  20898. };
  20899. /**
  20900. * Clear throttle.
  20901. * @public
  20902. */
  20903. cb.clear = function () {
  20904. if (timer) {
  20905. clearTimeout(timer);
  20906. timer = null;
  20907. }
  20908. };
  20909. /**
  20910. * Enable debounce once.
  20911. */
  20912. cb.debounceNextCall = function (debounceDelay) {
  20913. debounceNextCall = debounceDelay;
  20914. };
  20915. return cb;
  20916. }
  20917. /**
  20918. * Create throttle method or update throttle rate.
  20919. *
  20920. * @example
  20921. * ComponentView.prototype.render = function () {
  20922. * ...
  20923. * throttle.createOrUpdate(
  20924. * this,
  20925. * '_dispatchAction',
  20926. * this.model.get('throttle'),
  20927. * 'fixRate'
  20928. * );
  20929. * };
  20930. * ComponentView.prototype.remove = function () {
  20931. * throttle.clear(this, '_dispatchAction');
  20932. * };
  20933. * ComponentView.prototype.dispose = function () {
  20934. * throttle.clear(this, '_dispatchAction');
  20935. * };
  20936. *
  20937. * @public
  20938. * @param {Object} obj
  20939. * @param {string} fnAttr
  20940. * @param {number} [rate]
  20941. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20942. * @return {Function} throttled function.
  20943. */
  20944. /**
  20945. * Clear throttle. Example see throttle.createOrUpdate.
  20946. *
  20947. * @public
  20948. * @param {Object} obj
  20949. * @param {string} fnAttr
  20950. */
  20951. /*
  20952. * Licensed to the Apache Software Foundation (ASF) under one
  20953. * or more contributor license agreements. See the NOTICE file
  20954. * distributed with this work for additional information
  20955. * regarding copyright ownership. The ASF licenses this file
  20956. * to you under the Apache License, Version 2.0 (the
  20957. * "License"); you may not use this file except in compliance
  20958. * with the License. You may obtain a copy of the License at
  20959. *
  20960. * http://www.apache.org/licenses/LICENSE-2.0
  20961. *
  20962. * Unless required by applicable law or agreed to in writing,
  20963. * software distributed under the License is distributed on an
  20964. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20965. * KIND, either express or implied. See the License for the
  20966. * specific language governing permissions and limitations
  20967. * under the License.
  20968. */
  20969. var seriesColor = {
  20970. createOnAllSeries: true,
  20971. performRawSeries: true,
  20972. reset: function (seriesModel, ecModel) {
  20973. var data = seriesModel.getData();
  20974. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20975. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20976. || seriesModel.getColorFromPalette(
  20977. // TODO series count changed.
  20978. seriesModel.name, null, ecModel.getSeriesCount()
  20979. ); // Default color
  20980. // FIXME Set color function or use the platte color
  20981. data.setVisual('color', color);
  20982. // Only visible series has each data be visual encoded
  20983. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20984. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20985. data.each(function (idx) {
  20986. data.setItemVisual(
  20987. idx, 'color', color(seriesModel.getDataParams(idx))
  20988. );
  20989. });
  20990. }
  20991. // itemStyle in each data item
  20992. var dataEach = function (data, idx) {
  20993. var itemModel = data.getItemModel(idx);
  20994. var color = itemModel.get(colorAccessPath, true);
  20995. if (color != null) {
  20996. data.setItemVisual(idx, 'color', color);
  20997. }
  20998. };
  20999. return { dataEach: data.hasItemOption ? dataEach : null };
  21000. }
  21001. }
  21002. };
  21003. /*
  21004. * Licensed to the Apache Software Foundation (ASF) under one
  21005. * or more contributor license agreements. See the NOTICE file
  21006. * distributed with this work for additional information
  21007. * regarding copyright ownership. The ASF licenses this file
  21008. * to you under the Apache License, Version 2.0 (the
  21009. * "License"); you may not use this file except in compliance
  21010. * with the License. You may obtain a copy of the License at
  21011. *
  21012. * http://www.apache.org/licenses/LICENSE-2.0
  21013. *
  21014. * Unless required by applicable law or agreed to in writing,
  21015. * software distributed under the License is distributed on an
  21016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21017. * KIND, either express or implied. See the License for the
  21018. * specific language governing permissions and limitations
  21019. * under the License.
  21020. */
  21021. var lang = {
  21022. toolbox: {
  21023. brush: {
  21024. title: {
  21025. rect: '矩形选择',
  21026. polygon: '圈选',
  21027. lineX: '横向选择',
  21028. lineY: '纵向选择',
  21029. keep: '保持选择',
  21030. clear: '清除选择'
  21031. }
  21032. },
  21033. dataView: {
  21034. title: '数据视图',
  21035. lang: ['数据视图', '关闭', '刷新']
  21036. },
  21037. dataZoom: {
  21038. title: {
  21039. zoom: '区域缩放',
  21040. back: '区域缩放还原'
  21041. }
  21042. },
  21043. magicType: {
  21044. title: {
  21045. line: '切换为折线图',
  21046. bar: '切换为柱状图',
  21047. stack: '切换为堆叠',
  21048. tiled: '切换为平铺'
  21049. }
  21050. },
  21051. restore: {
  21052. title: '还原'
  21053. },
  21054. saveAsImage: {
  21055. title: '保存为图片',
  21056. lang: ['右键另存为图片']
  21057. }
  21058. },
  21059. series: {
  21060. typeNames: {
  21061. pie: '饼图',
  21062. bar: '柱状图',
  21063. line: '折线图',
  21064. scatter: '散点图',
  21065. effectScatter: '涟漪散点图',
  21066. radar: '雷达图',
  21067. tree: '树图',
  21068. treemap: '矩形树图',
  21069. boxplot: '箱型图',
  21070. candlestick: 'K线图',
  21071. k: 'K线图',
  21072. heatmap: '热力图',
  21073. map: '地图',
  21074. parallel: '平行坐标图',
  21075. lines: '线图',
  21076. graph: '关系图',
  21077. sankey: '桑基图',
  21078. funnel: '漏斗图',
  21079. gauge: '仪表盘图',
  21080. pictorialBar: '象形柱图',
  21081. themeRiver: '主题河流图',
  21082. sunburst: '旭日图'
  21083. }
  21084. },
  21085. aria: {
  21086. general: {
  21087. withTitle: '这是一个关于“{title}”的图表。',
  21088. withoutTitle: '这是一个图表,'
  21089. },
  21090. series: {
  21091. single: {
  21092. prefix: '',
  21093. withName: '图表类型是{seriesType},表示{seriesName}。',
  21094. withoutName: '图表类型是{seriesType}。'
  21095. },
  21096. multiple: {
  21097. prefix: '它由{seriesCount}个图表系列组成。',
  21098. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  21099. withoutName: '第{seriesId}个系列是一个{seriesType},',
  21100. separator: {
  21101. middle: ';',
  21102. end: '。'
  21103. }
  21104. }
  21105. },
  21106. data: {
  21107. allData: '其数据是——',
  21108. partialData: '其中,前{displayCnt}项是——',
  21109. withName: '{name}的数据是{value}',
  21110. withoutName: '{value}',
  21111. separator: {
  21112. middle: ',',
  21113. end: ''
  21114. }
  21115. }
  21116. }
  21117. };
  21118. /*
  21119. * Licensed to the Apache Software Foundation (ASF) under one
  21120. * or more contributor license agreements. See the NOTICE file
  21121. * distributed with this work for additional information
  21122. * regarding copyright ownership. The ASF licenses this file
  21123. * to you under the Apache License, Version 2.0 (the
  21124. * "License"); you may not use this file except in compliance
  21125. * with the License. You may obtain a copy of the License at
  21126. *
  21127. * http://www.apache.org/licenses/LICENSE-2.0
  21128. *
  21129. * Unless required by applicable law or agreed to in writing,
  21130. * software distributed under the License is distributed on an
  21131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21132. * KIND, either express or implied. See the License for the
  21133. * specific language governing permissions and limitations
  21134. * under the License.
  21135. */
  21136. var aria = function (dom, ecModel) {
  21137. var ariaModel = ecModel.getModel('aria');
  21138. if (!ariaModel.get('show')) {
  21139. return;
  21140. }
  21141. else if (ariaModel.get('description')) {
  21142. dom.setAttribute('aria-label', ariaModel.get('description'));
  21143. return;
  21144. }
  21145. var seriesCnt = 0;
  21146. ecModel.eachSeries(function (seriesModel, idx) {
  21147. ++seriesCnt;
  21148. }, this);
  21149. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  21150. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  21151. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  21152. var ariaLabel;
  21153. if (seriesCnt < 1) {
  21154. // No series, no aria label
  21155. return;
  21156. }
  21157. else {
  21158. var title = getTitle();
  21159. if (title) {
  21160. ariaLabel = replace(getConfig('general.withTitle'), {
  21161. title: title
  21162. });
  21163. }
  21164. else {
  21165. ariaLabel = getConfig('general.withoutTitle');
  21166. }
  21167. var seriesLabels = [];
  21168. var prefix = seriesCnt > 1
  21169. ? 'series.multiple.prefix'
  21170. : 'series.single.prefix';
  21171. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21172. ecModel.eachSeries(function (seriesModel, idx) {
  21173. if (idx < displaySeriesCnt) {
  21174. var seriesLabel;
  21175. var seriesName = seriesModel.get('name');
  21176. var seriesTpl = 'series.'
  21177. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21178. seriesLabel = getConfig(seriesName
  21179. ? seriesTpl + 'withName'
  21180. : seriesTpl + 'withoutName');
  21181. seriesLabel = replace(seriesLabel, {
  21182. seriesId: seriesModel.seriesIndex,
  21183. seriesName: seriesModel.get('name'),
  21184. seriesType: getSeriesTypeName(seriesModel.subType)
  21185. });
  21186. var data = seriesModel.getData();
  21187. window.data = data;
  21188. if (data.count() > maxDataCnt) {
  21189. // Show part of data
  21190. seriesLabel += replace(getConfig('data.partialData'), {
  21191. displayCnt: maxDataCnt
  21192. });
  21193. }
  21194. else {
  21195. seriesLabel += getConfig('data.allData');
  21196. }
  21197. var dataLabels = [];
  21198. for (var i = 0; i < data.count(); i++) {
  21199. if (i < maxDataCnt) {
  21200. var name = data.getName(i);
  21201. var value = retrieveRawValue(data, i);
  21202. dataLabels.push(
  21203. replace(
  21204. name
  21205. ? getConfig('data.withName')
  21206. : getConfig('data.withoutName'),
  21207. {
  21208. name: name,
  21209. value: value
  21210. }
  21211. )
  21212. );
  21213. }
  21214. }
  21215. seriesLabel += dataLabels
  21216. .join(getConfig('data.separator.middle'))
  21217. + getConfig('data.separator.end');
  21218. seriesLabels.push(seriesLabel);
  21219. }
  21220. });
  21221. ariaLabel += seriesLabels
  21222. .join(getConfig('series.multiple.separator.middle'))
  21223. + getConfig('series.multiple.separator.end');
  21224. dom.setAttribute('aria-label', ariaLabel);
  21225. }
  21226. function replace(str, keyValues) {
  21227. if (typeof str !== 'string') {
  21228. return str;
  21229. }
  21230. var result = str;
  21231. each$1(keyValues, function (value, key) {
  21232. result = result.replace(
  21233. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21234. value
  21235. );
  21236. });
  21237. return result;
  21238. }
  21239. function getConfig(path) {
  21240. var userConfig = ariaModel.get(path);
  21241. if (userConfig == null) {
  21242. var pathArr = path.split('.');
  21243. var result = lang.aria;
  21244. for (var i = 0; i < pathArr.length; ++i) {
  21245. result = result[pathArr[i]];
  21246. }
  21247. return result;
  21248. }
  21249. else {
  21250. return userConfig;
  21251. }
  21252. }
  21253. function getTitle() {
  21254. var title = ecModel.getModel('title').option;
  21255. if (title && title.length) {
  21256. title = title[0];
  21257. }
  21258. return title && title.text;
  21259. }
  21260. function getSeriesTypeName(type) {
  21261. return lang.series.typeNames[type] || '自定义图';
  21262. }
  21263. };
  21264. /*
  21265. * Licensed to the Apache Software Foundation (ASF) under one
  21266. * or more contributor license agreements. See the NOTICE file
  21267. * distributed with this work for additional information
  21268. * regarding copyright ownership. The ASF licenses this file
  21269. * to you under the Apache License, Version 2.0 (the
  21270. * "License"); you may not use this file except in compliance
  21271. * with the License. You may obtain a copy of the License at
  21272. *
  21273. * http://www.apache.org/licenses/LICENSE-2.0
  21274. *
  21275. * Unless required by applicable law or agreed to in writing,
  21276. * software distributed under the License is distributed on an
  21277. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21278. * KIND, either express or implied. See the License for the
  21279. * specific language governing permissions and limitations
  21280. * under the License.
  21281. */
  21282. var PI$1 = Math.PI;
  21283. /**
  21284. * @param {module:echarts/ExtensionAPI} api
  21285. * @param {Object} [opts]
  21286. * @param {string} [opts.text]
  21287. * @param {string} [opts.color]
  21288. * @param {string} [opts.textColor]
  21289. * @return {module:zrender/Element}
  21290. */
  21291. var loadingDefault = function (api, opts) {
  21292. opts = opts || {};
  21293. defaults(opts, {
  21294. text: 'loading',
  21295. color: '#c23531',
  21296. textColor: '#000',
  21297. maskColor: 'rgba(255, 255, 255, 0.8)',
  21298. zlevel: 0
  21299. });
  21300. var mask = new Rect({
  21301. style: {
  21302. fill: opts.maskColor
  21303. },
  21304. zlevel: opts.zlevel,
  21305. z: 10000
  21306. });
  21307. var arc = new Arc({
  21308. shape: {
  21309. startAngle: -PI$1 / 2,
  21310. endAngle: -PI$1 / 2 + 0.1,
  21311. r: 10
  21312. },
  21313. style: {
  21314. stroke: opts.color,
  21315. lineCap: 'round',
  21316. lineWidth: 5
  21317. },
  21318. zlevel: opts.zlevel,
  21319. z: 10001
  21320. });
  21321. var labelRect = new Rect({
  21322. style: {
  21323. fill: 'none',
  21324. text: opts.text,
  21325. textPosition: 'right',
  21326. textDistance: 10,
  21327. textFill: opts.textColor
  21328. },
  21329. zlevel: opts.zlevel,
  21330. z: 10001
  21331. });
  21332. arc.animateShape(true)
  21333. .when(1000, {
  21334. endAngle: PI$1 * 3 / 2
  21335. })
  21336. .start('circularInOut');
  21337. arc.animateShape(true)
  21338. .when(1000, {
  21339. startAngle: PI$1 * 3 / 2
  21340. })
  21341. .delay(300)
  21342. .start('circularInOut');
  21343. var group = new Group();
  21344. group.add(arc);
  21345. group.add(labelRect);
  21346. group.add(mask);
  21347. // Inject resize
  21348. group.resize = function () {
  21349. var cx = api.getWidth() / 2;
  21350. var cy = api.getHeight() / 2;
  21351. arc.setShape({
  21352. cx: cx,
  21353. cy: cy
  21354. });
  21355. var r = arc.shape.r;
  21356. labelRect.setShape({
  21357. x: cx - r,
  21358. y: cy - r,
  21359. width: r * 2,
  21360. height: r * 2
  21361. });
  21362. mask.setShape({
  21363. x: 0,
  21364. y: 0,
  21365. width: api.getWidth(),
  21366. height: api.getHeight()
  21367. });
  21368. };
  21369. group.resize();
  21370. return group;
  21371. };
  21372. /*
  21373. * Licensed to the Apache Software Foundation (ASF) under one
  21374. * or more contributor license agreements. See the NOTICE file
  21375. * distributed with this work for additional information
  21376. * regarding copyright ownership. The ASF licenses this file
  21377. * to you under the Apache License, Version 2.0 (the
  21378. * "License"); you may not use this file except in compliance
  21379. * with the License. You may obtain a copy of the License at
  21380. *
  21381. * http://www.apache.org/licenses/LICENSE-2.0
  21382. *
  21383. * Unless required by applicable law or agreed to in writing,
  21384. * software distributed under the License is distributed on an
  21385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21386. * KIND, either express or implied. See the License for the
  21387. * specific language governing permissions and limitations
  21388. * under the License.
  21389. */
  21390. /**
  21391. * @module echarts/stream/Scheduler
  21392. */
  21393. /**
  21394. * @constructor
  21395. */
  21396. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21397. this.ecInstance = ecInstance;
  21398. this.api = api;
  21399. this.unfinished;
  21400. // Fix current processors in case that in some rear cases that
  21401. // processors might be registered after echarts instance created.
  21402. // Register processors incrementally for a echarts instance is
  21403. // not supported by this stream architecture.
  21404. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21405. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21406. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21407. /**
  21408. * @private
  21409. * @type {
  21410. * [handlerUID: string]: {
  21411. * seriesTaskMap?: {
  21412. * [seriesUID: string]: Task
  21413. * },
  21414. * overallTask?: Task
  21415. * }
  21416. * }
  21417. */
  21418. this._stageTaskMap = createHashMap();
  21419. }
  21420. var proto = Scheduler.prototype;
  21421. /**
  21422. * @param {module:echarts/model/Global} ecModel
  21423. * @param {Object} payload
  21424. */
  21425. proto.restoreData = function (ecModel, payload) {
  21426. // TODO: Only restroe needed series and components, but not all components.
  21427. // Currently `restoreData` of all of the series and component will be called.
  21428. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21429. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21430. // and some components like coordinate system, axes, dataZoom, visualMap only
  21431. // need their target series refresh.
  21432. // (1) If we are implementing this feature some day, we should consider these cases:
  21433. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21434. // on the settings of `dataZoom`), it should be re-performed if the component
  21435. // is modified by `setOption`.
  21436. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21437. // it should be re-performed when the result array of `getTargetSeries` changed.
  21438. // We use `dependencies` to cover these issues.
  21439. // (3) How to update target series when coordinate system related components modified.
  21440. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21441. // and this case all of the tasks will be set as dirty.
  21442. ecModel.restoreData(payload);
  21443. // Theoretically an overall task not only depends on each of its target series, but also
  21444. // depends on all of the series.
  21445. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21446. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21447. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21448. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21449. // probably cause state chaos (consider `dataZoomProcessor`).
  21450. this._stageTaskMap.each(function (taskRecord) {
  21451. var overallTask = taskRecord.overallTask;
  21452. overallTask && overallTask.dirty();
  21453. });
  21454. };
  21455. // If seriesModel provided, incremental threshold is check by series data.
  21456. proto.getPerformArgs = function (task, isBlock) {
  21457. // For overall task
  21458. if (!task.__pipeline) {
  21459. return;
  21460. }
  21461. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21462. var pCtx = pipeline.context;
  21463. var incremental = !isBlock
  21464. && pipeline.progressiveEnabled
  21465. && (!pCtx || pCtx.progressiveRender)
  21466. && task.__idxInPipeline > pipeline.blockIndex;
  21467. var step = incremental ? pipeline.step : null;
  21468. var modDataCount = pCtx && pCtx.modDataCount;
  21469. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21470. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21471. };
  21472. proto.getPipeline = function (pipelineId) {
  21473. return this._pipelineMap.get(pipelineId);
  21474. };
  21475. /**
  21476. * Current, progressive rendering starts from visual and layout.
  21477. * Always detect render mode in the same stage, avoiding that incorrect
  21478. * detection caused by data filtering.
  21479. * Caution:
  21480. * `updateStreamModes` use `seriesModel.getData()`.
  21481. */
  21482. proto.updateStreamModes = function (seriesModel, view) {
  21483. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21484. var data = seriesModel.getData();
  21485. var dataLen = data.count();
  21486. // `progressiveRender` means that can render progressively in each
  21487. // animation frame. Note that some types of series do not provide
  21488. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21489. // use the term `incremental` but not `progressive` to describe the
  21490. // case that `chart.appendData`.
  21491. var progressiveRender = pipeline.progressiveEnabled
  21492. && view.incrementalPrepareRender
  21493. && dataLen >= pipeline.threshold;
  21494. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21495. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21496. // see `test/candlestick-large3.html`
  21497. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21498. seriesModel.pipelineContext = pipeline.context = {
  21499. progressiveRender: progressiveRender,
  21500. modDataCount: modDataCount,
  21501. large: large
  21502. };
  21503. };
  21504. proto.restorePipelines = function (ecModel) {
  21505. var scheduler = this;
  21506. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21507. ecModel.eachSeries(function (seriesModel) {
  21508. var progressive = seriesModel.getProgressive();
  21509. var pipelineId = seriesModel.uid;
  21510. pipelineMap.set(pipelineId, {
  21511. id: pipelineId,
  21512. head: null,
  21513. tail: null,
  21514. threshold: seriesModel.getProgressiveThreshold(),
  21515. progressiveEnabled: progressive
  21516. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21517. blockIndex: -1,
  21518. step: Math.round(progressive || 700),
  21519. count: 0
  21520. });
  21521. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21522. });
  21523. };
  21524. proto.prepareStageTasks = function () {
  21525. var stageTaskMap = this._stageTaskMap;
  21526. var ecModel = this.ecInstance.getModel();
  21527. var api = this.api;
  21528. each$1(this._allHandlers, function (handler) {
  21529. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21530. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21531. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21532. }, this);
  21533. };
  21534. proto.prepareView = function (view, model, ecModel, api) {
  21535. var renderTask = view.renderTask;
  21536. var context = renderTask.context;
  21537. context.model = model;
  21538. context.ecModel = ecModel;
  21539. context.api = api;
  21540. renderTask.__block = !view.incrementalPrepareRender;
  21541. pipe(this, model, renderTask);
  21542. };
  21543. proto.performDataProcessorTasks = function (ecModel, payload) {
  21544. // If we do not use `block` here, it should be considered when to update modes.
  21545. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21546. };
  21547. // opt
  21548. // opt.visualType: 'visual' or 'layout'
  21549. // opt.setDirty
  21550. proto.performVisualTasks = function (ecModel, payload, opt) {
  21551. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21552. };
  21553. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21554. opt = opt || {};
  21555. var unfinished;
  21556. each$1(stageHandlers, function (stageHandler, idx) {
  21557. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21558. return;
  21559. }
  21560. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21561. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21562. var overallTask = stageHandlerRecord.overallTask;
  21563. if (overallTask) {
  21564. var overallNeedDirty;
  21565. var agentStubMap = overallTask.agentStubMap;
  21566. agentStubMap.each(function (stub) {
  21567. if (needSetDirty(opt, stub)) {
  21568. stub.dirty();
  21569. overallNeedDirty = true;
  21570. }
  21571. });
  21572. overallNeedDirty && overallTask.dirty();
  21573. updatePayload(overallTask, payload);
  21574. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21575. // Execute stubs firstly, which may set the overall task dirty,
  21576. // then execute the overall task. And stub will call seriesModel.setData,
  21577. // which ensures that in the overallTask seriesModel.getData() will not
  21578. // return incorrect data.
  21579. agentStubMap.each(function (stub) {
  21580. stub.perform(performArgs);
  21581. });
  21582. unfinished |= overallTask.perform(performArgs);
  21583. }
  21584. else if (seriesTaskMap) {
  21585. seriesTaskMap.each(function (task, pipelineId) {
  21586. if (needSetDirty(opt, task)) {
  21587. task.dirty();
  21588. }
  21589. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21590. performArgs.skip = !stageHandler.performRawSeries
  21591. && ecModel.isSeriesFiltered(task.context.model);
  21592. updatePayload(task, payload);
  21593. unfinished |= task.perform(performArgs);
  21594. });
  21595. }
  21596. });
  21597. function needSetDirty(opt, task) {
  21598. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21599. }
  21600. scheduler.unfinished |= unfinished;
  21601. }
  21602. proto.performSeriesTasks = function (ecModel) {
  21603. var unfinished;
  21604. ecModel.eachSeries(function (seriesModel) {
  21605. // Progress to the end for dataInit and dataRestore.
  21606. unfinished |= seriesModel.dataTask.perform();
  21607. });
  21608. this.unfinished |= unfinished;
  21609. };
  21610. proto.plan = function () {
  21611. // Travel pipelines, check block.
  21612. this._pipelineMap.each(function (pipeline) {
  21613. var task = pipeline.tail;
  21614. do {
  21615. if (task.__block) {
  21616. pipeline.blockIndex = task.__idxInPipeline;
  21617. break;
  21618. }
  21619. task = task.getUpstream();
  21620. }
  21621. while (task);
  21622. });
  21623. };
  21624. var updatePayload = proto.updatePayload = function (task, payload) {
  21625. payload !== 'remain' && (task.context.payload = payload);
  21626. };
  21627. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21628. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21629. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21630. var seriesType = stageHandler.seriesType;
  21631. var getTargetSeries = stageHandler.getTargetSeries;
  21632. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21633. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21634. // it works but it may cause other irrelevant charts blocked.
  21635. if (stageHandler.createOnAllSeries) {
  21636. ecModel.eachRawSeries(create);
  21637. }
  21638. else if (seriesType) {
  21639. ecModel.eachRawSeriesByType(seriesType, create);
  21640. }
  21641. else if (getTargetSeries) {
  21642. getTargetSeries(ecModel, api).each(create);
  21643. }
  21644. function create(seriesModel) {
  21645. var pipelineId = seriesModel.uid;
  21646. // Init tasks for each seriesModel only once.
  21647. // Reuse original task instance.
  21648. var task = seriesTaskMap.get(pipelineId)
  21649. || seriesTaskMap.set(pipelineId, createTask({
  21650. plan: seriesTaskPlan,
  21651. reset: seriesTaskReset,
  21652. count: seriesTaskCount
  21653. }));
  21654. task.context = {
  21655. model: seriesModel,
  21656. ecModel: ecModel,
  21657. api: api,
  21658. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21659. plan: stageHandler.plan,
  21660. reset: stageHandler.reset,
  21661. scheduler: scheduler
  21662. };
  21663. pipe(scheduler, seriesModel, task);
  21664. }
  21665. // Clear unused series tasks.
  21666. var pipelineMap = scheduler._pipelineMap;
  21667. seriesTaskMap.each(function (task, pipelineId) {
  21668. if (!pipelineMap.get(pipelineId)) {
  21669. task.dispose();
  21670. seriesTaskMap.removeKey(pipelineId);
  21671. }
  21672. });
  21673. }
  21674. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21675. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21676. // For overall task, the function only be called on reset stage.
  21677. || createTask({reset: overallTaskReset});
  21678. overallTask.context = {
  21679. ecModel: ecModel,
  21680. api: api,
  21681. overallReset: stageHandler.overallReset,
  21682. scheduler: scheduler
  21683. };
  21684. // Reuse orignal stubs.
  21685. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21686. var seriesType = stageHandler.seriesType;
  21687. var getTargetSeries = stageHandler.getTargetSeries;
  21688. var overallProgress = true;
  21689. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21690. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21691. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21692. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21693. // we set the pipeline block.
  21694. if (seriesType) {
  21695. ecModel.eachRawSeriesByType(seriesType, createStub);
  21696. }
  21697. else if (getTargetSeries) {
  21698. getTargetSeries(ecModel, api).each(createStub);
  21699. }
  21700. // Otherwise, (usually it is legancy case), the overall task will only be
  21701. // executed when upstream dirty. Otherwise the progressive rendering of all
  21702. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21703. // dirty info from upsteam.
  21704. else {
  21705. overallProgress = false;
  21706. each$1(ecModel.getSeries(), createStub);
  21707. }
  21708. function createStub(seriesModel) {
  21709. var pipelineId = seriesModel.uid;
  21710. var stub = agentStubMap.get(pipelineId);
  21711. if (!stub) {
  21712. stub = agentStubMap.set(pipelineId, createTask(
  21713. {reset: stubReset, onDirty: stubOnDirty}
  21714. ));
  21715. // When the result of `getTargetSeries` changed, the overallTask
  21716. // should be set as dirty and re-performed.
  21717. overallTask.dirty();
  21718. }
  21719. stub.context = {
  21720. model: seriesModel,
  21721. overallProgress: overallProgress,
  21722. modifyOutputEnd: modifyOutputEnd
  21723. };
  21724. stub.agent = overallTask;
  21725. stub.__block = overallProgress;
  21726. pipe(scheduler, seriesModel, stub);
  21727. }
  21728. // Clear unused stubs.
  21729. var pipelineMap = scheduler._pipelineMap;
  21730. agentStubMap.each(function (stub, pipelineId) {
  21731. if (!pipelineMap.get(pipelineId)) {
  21732. stub.dispose();
  21733. // When the result of `getTargetSeries` changed, the overallTask
  21734. // should be set as dirty and re-performed.
  21735. overallTask.dirty();
  21736. agentStubMap.removeKey(pipelineId);
  21737. }
  21738. });
  21739. }
  21740. function overallTaskReset(context) {
  21741. context.overallReset(
  21742. context.ecModel, context.api, context.payload
  21743. );
  21744. }
  21745. function stubReset(context, upstreamContext) {
  21746. return context.overallProgress && stubProgress;
  21747. }
  21748. function stubProgress() {
  21749. this.agent.dirty();
  21750. this.getDownstream().dirty();
  21751. }
  21752. function stubOnDirty() {
  21753. this.agent && this.agent.dirty();
  21754. }
  21755. function seriesTaskPlan(context) {
  21756. return context.plan && context.plan(
  21757. context.model, context.ecModel, context.api, context.payload
  21758. );
  21759. }
  21760. function seriesTaskReset(context) {
  21761. if (context.useClearVisual) {
  21762. context.data.clearAllVisual();
  21763. }
  21764. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  21765. context.model, context.ecModel, context.api, context.payload
  21766. ));
  21767. return resetDefines.length > 1
  21768. ? map(resetDefines, function (v, idx) {
  21769. return makeSeriesTaskProgress(idx);
  21770. })
  21771. : singleSeriesTaskProgress;
  21772. }
  21773. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21774. function makeSeriesTaskProgress(resetDefineIdx) {
  21775. return function (params, context) {
  21776. var data = context.data;
  21777. var resetDefine = context.resetDefines[resetDefineIdx];
  21778. if (resetDefine && resetDefine.dataEach) {
  21779. for (var i = params.start; i < params.end; i++) {
  21780. resetDefine.dataEach(data, i);
  21781. }
  21782. }
  21783. else if (resetDefine && resetDefine.progress) {
  21784. resetDefine.progress(params, data);
  21785. }
  21786. };
  21787. }
  21788. function seriesTaskCount(context) {
  21789. return context.data.count();
  21790. }
  21791. function pipe(scheduler, seriesModel, task) {
  21792. var pipelineId = seriesModel.uid;
  21793. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21794. !pipeline.head && (pipeline.head = task);
  21795. pipeline.tail && pipeline.tail.pipe(task);
  21796. pipeline.tail = task;
  21797. task.__idxInPipeline = pipeline.count++;
  21798. task.__pipeline = pipeline;
  21799. }
  21800. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21801. if (isFunction$1(stageHandler)) {
  21802. stageHandler = {
  21803. overallReset: stageHandler,
  21804. seriesType: detectSeriseType(stageHandler)
  21805. };
  21806. }
  21807. stageHandler.uid = getUID('stageHandler');
  21808. visualType && (stageHandler.visualType = visualType);
  21809. return stageHandler;
  21810. };
  21811. /**
  21812. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21813. * To ensure that they can work normally, they should work in block mode, that is,
  21814. * they should not be started util the previous tasks finished. So they cause the
  21815. * progressive rendering disabled. We try to detect the series type, to narrow down
  21816. * the block range to only the series type they concern, but not all series.
  21817. */
  21818. function detectSeriseType(legacyFunc) {
  21819. seriesType = null;
  21820. try {
  21821. // Assume there is no async when calling `eachSeriesByType`.
  21822. legacyFunc(ecModelMock, apiMock);
  21823. }
  21824. catch (e) {
  21825. }
  21826. return seriesType;
  21827. }
  21828. var ecModelMock = {};
  21829. var apiMock = {};
  21830. var seriesType;
  21831. mockMethods(ecModelMock, GlobalModel);
  21832. mockMethods(apiMock, ExtensionAPI);
  21833. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21834. seriesType = type;
  21835. };
  21836. ecModelMock.eachComponent = function (cond) {
  21837. if (cond.mainType === 'series' && cond.subType) {
  21838. seriesType = cond.subType;
  21839. }
  21840. };
  21841. function mockMethods(target, Clz) {
  21842. /* eslint-disable */
  21843. for (var name in Clz.prototype) {
  21844. // Do not use hasOwnProperty
  21845. target[name] = noop;
  21846. }
  21847. /* eslint-enable */
  21848. }
  21849. /*
  21850. * Licensed to the Apache Software Foundation (ASF) under one
  21851. * or more contributor license agreements. See the NOTICE file
  21852. * distributed with this work for additional information
  21853. * regarding copyright ownership. The ASF licenses this file
  21854. * to you under the Apache License, Version 2.0 (the
  21855. * "License"); you may not use this file except in compliance
  21856. * with the License. You may obtain a copy of the License at
  21857. *
  21858. * http://www.apache.org/licenses/LICENSE-2.0
  21859. *
  21860. * Unless required by applicable law or agreed to in writing,
  21861. * software distributed under the License is distributed on an
  21862. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21863. * KIND, either express or implied. See the License for the
  21864. * specific language governing permissions and limitations
  21865. * under the License.
  21866. */
  21867. var colorAll = [
  21868. '#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f',
  21869. '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'
  21870. ];
  21871. var lightTheme = {
  21872. color: colorAll,
  21873. colorLayer: [
  21874. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  21875. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  21876. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  21877. colorAll
  21878. ]
  21879. };
  21880. /*
  21881. * Licensed to the Apache Software Foundation (ASF) under one
  21882. * or more contributor license agreements. See the NOTICE file
  21883. * distributed with this work for additional information
  21884. * regarding copyright ownership. The ASF licenses this file
  21885. * to you under the Apache License, Version 2.0 (the
  21886. * "License"); you may not use this file except in compliance
  21887. * with the License. You may obtain a copy of the License at
  21888. *
  21889. * http://www.apache.org/licenses/LICENSE-2.0
  21890. *
  21891. * Unless required by applicable law or agreed to in writing,
  21892. * software distributed under the License is distributed on an
  21893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21894. * KIND, either express or implied. See the License for the
  21895. * specific language governing permissions and limitations
  21896. * under the License.
  21897. */
  21898. var contrastColor = '#eee';
  21899. var axisCommon = function () {
  21900. return {
  21901. axisLine: {
  21902. lineStyle: {
  21903. color: contrastColor
  21904. }
  21905. },
  21906. axisTick: {
  21907. lineStyle: {
  21908. color: contrastColor
  21909. }
  21910. },
  21911. axisLabel: {
  21912. textStyle: {
  21913. color: contrastColor
  21914. }
  21915. },
  21916. splitLine: {
  21917. lineStyle: {
  21918. type: 'dashed',
  21919. color: '#aaa'
  21920. }
  21921. },
  21922. splitArea: {
  21923. areaStyle: {
  21924. color: contrastColor
  21925. }
  21926. }
  21927. };
  21928. };
  21929. var colorPalette = [
  21930. '#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53',
  21931. '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'
  21932. ];
  21933. var theme = {
  21934. color: colorPalette,
  21935. backgroundColor: '#333',
  21936. tooltip: {
  21937. axisPointer: {
  21938. lineStyle: {
  21939. color: contrastColor
  21940. },
  21941. crossStyle: {
  21942. color: contrastColor
  21943. }
  21944. }
  21945. },
  21946. legend: {
  21947. textStyle: {
  21948. color: contrastColor
  21949. }
  21950. },
  21951. textStyle: {
  21952. color: contrastColor
  21953. },
  21954. title: {
  21955. textStyle: {
  21956. color: contrastColor
  21957. }
  21958. },
  21959. toolbox: {
  21960. iconStyle: {
  21961. normal: {
  21962. borderColor: contrastColor
  21963. }
  21964. }
  21965. },
  21966. dataZoom: {
  21967. textStyle: {
  21968. color: contrastColor
  21969. }
  21970. },
  21971. visualMap: {
  21972. textStyle: {
  21973. color: contrastColor
  21974. }
  21975. },
  21976. timeline: {
  21977. lineStyle: {
  21978. color: contrastColor
  21979. },
  21980. itemStyle: {
  21981. normal: {
  21982. color: colorPalette[1]
  21983. }
  21984. },
  21985. label: {
  21986. normal: {
  21987. textStyle: {
  21988. color: contrastColor
  21989. }
  21990. }
  21991. },
  21992. controlStyle: {
  21993. normal: {
  21994. color: contrastColor,
  21995. borderColor: contrastColor
  21996. }
  21997. }
  21998. },
  21999. timeAxis: axisCommon(),
  22000. logAxis: axisCommon(),
  22001. valueAxis: axisCommon(),
  22002. categoryAxis: axisCommon(),
  22003. line: {
  22004. symbol: 'circle'
  22005. },
  22006. graph: {
  22007. color: colorPalette
  22008. },
  22009. gauge: {
  22010. title: {
  22011. textStyle: {
  22012. color: contrastColor
  22013. }
  22014. }
  22015. },
  22016. candlestick: {
  22017. itemStyle: {
  22018. normal: {
  22019. color: '#FD1050',
  22020. color0: '#0CF49B',
  22021. borderColor: '#FD1050',
  22022. borderColor0: '#0CF49B'
  22023. }
  22024. }
  22025. }
  22026. };
  22027. theme.categoryAxis.splitLine.show = false;
  22028. /*
  22029. * Licensed to the Apache Software Foundation (ASF) under one
  22030. * or more contributor license agreements. See the NOTICE file
  22031. * distributed with this work for additional information
  22032. * regarding copyright ownership. The ASF licenses this file
  22033. * to you under the Apache License, Version 2.0 (the
  22034. * "License"); you may not use this file except in compliance
  22035. * with the License. You may obtain a copy of the License at
  22036. *
  22037. * http://www.apache.org/licenses/LICENSE-2.0
  22038. *
  22039. * Unless required by applicable law or agreed to in writing,
  22040. * software distributed under the License is distributed on an
  22041. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22042. * KIND, either express or implied. See the License for the
  22043. * specific language governing permissions and limitations
  22044. * under the License.
  22045. */
  22046. /**
  22047. * This module is imported by echarts directly.
  22048. *
  22049. * Notice:
  22050. * Always keep this file exists for backward compatibility.
  22051. * Because before 4.1.0, dataset is an optional component,
  22052. * some users may import this module manually.
  22053. */
  22054. ComponentModel.extend({
  22055. type: 'dataset',
  22056. /**
  22057. * @protected
  22058. */
  22059. defaultOption: {
  22060. // 'row', 'column'
  22061. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  22062. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  22063. sourceHeader: null,
  22064. dimensions: null,
  22065. source: null
  22066. },
  22067. optionUpdated: function () {
  22068. detectSourceFormat(this);
  22069. }
  22070. });
  22071. Component.extend({
  22072. type: 'dataset'
  22073. });
  22074. /**
  22075. * 椭圆形状
  22076. * @module zrender/graphic/shape/Ellipse
  22077. */
  22078. var Ellipse = Path.extend({
  22079. type: 'ellipse',
  22080. shape: {
  22081. cx: 0, cy: 0,
  22082. rx: 0, ry: 0
  22083. },
  22084. buildPath: function (ctx, shape) {
  22085. var k = 0.5522848;
  22086. var x = shape.cx;
  22087. var y = shape.cy;
  22088. var a = shape.rx;
  22089. var b = shape.ry;
  22090. var ox = a * k; // 水平控制点偏移量
  22091. var oy = b * k; // 垂直控制点偏移量
  22092. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  22093. ctx.moveTo(x - a, y);
  22094. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  22095. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  22096. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  22097. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  22098. ctx.closePath();
  22099. }
  22100. });
  22101. // import RadialGradient from '../graphic/RadialGradient';
  22102. // import Pattern from '../graphic/Pattern';
  22103. // import * as vector from '../core/vector';
  22104. // Most of the values can be separated by comma and/or white space.
  22105. var DILIMITER_REG = /[\s,]+/;
  22106. /**
  22107. * For big svg string, this method might be time consuming.
  22108. *
  22109. * @param {string} svg xml string
  22110. * @return {Object} xml root.
  22111. */
  22112. function parseXML(svg) {
  22113. if (isString(svg)) {
  22114. var parser = new DOMParser();
  22115. svg = parser.parseFromString(svg, 'text/xml');
  22116. }
  22117. // Document node. If using $.get, doc node may be input.
  22118. if (svg.nodeType === 9) {
  22119. svg = svg.firstChild;
  22120. }
  22121. // nodeName of <!DOCTYPE svg> is also 'svg'.
  22122. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  22123. svg = svg.nextSibling;
  22124. }
  22125. return svg;
  22126. }
  22127. function SVGParser() {
  22128. this._defs = {};
  22129. this._root = null;
  22130. this._isDefine = false;
  22131. this._isText = false;
  22132. }
  22133. SVGParser.prototype.parse = function (xml, opt) {
  22134. opt = opt || {};
  22135. var svg = parseXML(xml);
  22136. if (!svg) {
  22137. throw new Error('Illegal svg');
  22138. }
  22139. var root = new Group();
  22140. this._root = root;
  22141. // parse view port
  22142. var viewBox = svg.getAttribute('viewBox') || '';
  22143. // If width/height not specified, means "100%" of `opt.width/height`.
  22144. // TODO: Other percent value not supported yet.
  22145. var width = parseFloat(svg.getAttribute('width') || opt.width);
  22146. var height = parseFloat(svg.getAttribute('height') || opt.height);
  22147. // If width/height not specified, set as null for output.
  22148. isNaN(width) && (width = null);
  22149. isNaN(height) && (height = null);
  22150. // Apply inline style on svg element.
  22151. parseAttributes(svg, root, null, true);
  22152. var child = svg.firstChild;
  22153. while (child) {
  22154. this._parseNode(child, root);
  22155. child = child.nextSibling;
  22156. }
  22157. var viewBoxRect;
  22158. var viewBoxTransform;
  22159. if (viewBox) {
  22160. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  22161. // Some invalid case like viewBox: 'none'.
  22162. if (viewBoxArr.length >= 4) {
  22163. viewBoxRect = {
  22164. x: parseFloat(viewBoxArr[0] || 0),
  22165. y: parseFloat(viewBoxArr[1] || 0),
  22166. width: parseFloat(viewBoxArr[2]),
  22167. height: parseFloat(viewBoxArr[3])
  22168. };
  22169. }
  22170. }
  22171. if (viewBoxRect && width != null && height != null) {
  22172. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  22173. if (!opt.ignoreViewBox) {
  22174. // If set transform on the output group, it probably bring trouble when
  22175. // some users only intend to show the clipped content inside the viewBox,
  22176. // but not intend to transform the output group. So we keep the output
  22177. // group no transform. If the user intend to use the viewBox as a
  22178. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  22179. // manually according to the viewBox info in the output of this method.
  22180. var elRoot = root;
  22181. root = new Group();
  22182. root.add(elRoot);
  22183. elRoot.scale = viewBoxTransform.scale.slice();
  22184. elRoot.position = viewBoxTransform.position.slice();
  22185. }
  22186. }
  22187. // Some shapes might be overflow the viewport, which should be
  22188. // clipped despite whether the viewBox is used, as the SVG does.
  22189. if (!opt.ignoreRootClip && width != null && height != null) {
  22190. root.setClipPath(new Rect({
  22191. shape: {x: 0, y: 0, width: width, height: height}
  22192. }));
  22193. }
  22194. // Set width/height on group just for output the viewport size.
  22195. return {
  22196. root: root,
  22197. width: width,
  22198. height: height,
  22199. viewBoxRect: viewBoxRect,
  22200. viewBoxTransform: viewBoxTransform
  22201. };
  22202. };
  22203. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  22204. var nodeName = xmlNode.nodeName.toLowerCase();
  22205. // TODO
  22206. // support <style>...</style> in svg, where nodeName is 'style',
  22207. // CSS classes is defined globally wherever the style tags are declared.
  22208. if (nodeName === 'defs') {
  22209. // define flag
  22210. this._isDefine = true;
  22211. }
  22212. else if (nodeName === 'text') {
  22213. this._isText = true;
  22214. }
  22215. var el;
  22216. if (this._isDefine) {
  22217. var parser = defineParsers[nodeName];
  22218. if (parser) {
  22219. var def = parser.call(this, xmlNode);
  22220. var id = xmlNode.getAttribute('id');
  22221. if (id) {
  22222. this._defs[id] = def;
  22223. }
  22224. }
  22225. }
  22226. else {
  22227. var parser = nodeParsers[nodeName];
  22228. if (parser) {
  22229. el = parser.call(this, xmlNode, parentGroup);
  22230. parentGroup.add(el);
  22231. }
  22232. }
  22233. var child = xmlNode.firstChild;
  22234. while (child) {
  22235. if (child.nodeType === 1) {
  22236. this._parseNode(child, el);
  22237. }
  22238. // Is text
  22239. if (child.nodeType === 3 && this._isText) {
  22240. this._parseText(child, el);
  22241. }
  22242. child = child.nextSibling;
  22243. }
  22244. // Quit define
  22245. if (nodeName === 'defs') {
  22246. this._isDefine = false;
  22247. }
  22248. else if (nodeName === 'text') {
  22249. this._isText = false;
  22250. }
  22251. };
  22252. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  22253. if (xmlNode.nodeType === 1) {
  22254. var dx = xmlNode.getAttribute('dx') || 0;
  22255. var dy = xmlNode.getAttribute('dy') || 0;
  22256. this._textX += parseFloat(dx);
  22257. this._textY += parseFloat(dy);
  22258. }
  22259. var text = new Text({
  22260. style: {
  22261. text: xmlNode.textContent,
  22262. transformText: true
  22263. },
  22264. position: [this._textX || 0, this._textY || 0]
  22265. });
  22266. inheritStyle(parentGroup, text);
  22267. parseAttributes(xmlNode, text, this._defs);
  22268. var fontSize = text.style.fontSize;
  22269. if (fontSize && fontSize < 9) {
  22270. // PENDING
  22271. text.style.fontSize = 9;
  22272. text.scale = text.scale || [1, 1];
  22273. text.scale[0] *= fontSize / 9;
  22274. text.scale[1] *= fontSize / 9;
  22275. }
  22276. var rect = text.getBoundingRect();
  22277. this._textX += rect.width;
  22278. parentGroup.add(text);
  22279. return text;
  22280. };
  22281. var nodeParsers = {
  22282. 'g': function (xmlNode, parentGroup) {
  22283. var g = new Group();
  22284. inheritStyle(parentGroup, g);
  22285. parseAttributes(xmlNode, g, this._defs);
  22286. return g;
  22287. },
  22288. 'rect': function (xmlNode, parentGroup) {
  22289. var rect = new Rect();
  22290. inheritStyle(parentGroup, rect);
  22291. parseAttributes(xmlNode, rect, this._defs);
  22292. rect.setShape({
  22293. x: parseFloat(xmlNode.getAttribute('x') || 0),
  22294. y: parseFloat(xmlNode.getAttribute('y') || 0),
  22295. width: parseFloat(xmlNode.getAttribute('width') || 0),
  22296. height: parseFloat(xmlNode.getAttribute('height') || 0)
  22297. });
  22298. // console.log(xmlNode.getAttribute('transform'));
  22299. // console.log(rect.transform);
  22300. return rect;
  22301. },
  22302. 'circle': function (xmlNode, parentGroup) {
  22303. var circle = new Circle();
  22304. inheritStyle(parentGroup, circle);
  22305. parseAttributes(xmlNode, circle, this._defs);
  22306. circle.setShape({
  22307. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22308. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22309. r: parseFloat(xmlNode.getAttribute('r') || 0)
  22310. });
  22311. return circle;
  22312. },
  22313. 'line': function (xmlNode, parentGroup) {
  22314. var line = new Line();
  22315. inheritStyle(parentGroup, line);
  22316. parseAttributes(xmlNode, line, this._defs);
  22317. line.setShape({
  22318. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  22319. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  22320. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  22321. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  22322. });
  22323. return line;
  22324. },
  22325. 'ellipse': function (xmlNode, parentGroup) {
  22326. var ellipse = new Ellipse();
  22327. inheritStyle(parentGroup, ellipse);
  22328. parseAttributes(xmlNode, ellipse, this._defs);
  22329. ellipse.setShape({
  22330. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  22331. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  22332. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  22333. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  22334. });
  22335. return ellipse;
  22336. },
  22337. 'polygon': function (xmlNode, parentGroup) {
  22338. var points = xmlNode.getAttribute('points');
  22339. if (points) {
  22340. points = parsePoints(points);
  22341. }
  22342. var polygon = new Polygon({
  22343. shape: {
  22344. points: points || []
  22345. }
  22346. });
  22347. inheritStyle(parentGroup, polygon);
  22348. parseAttributes(xmlNode, polygon, this._defs);
  22349. return polygon;
  22350. },
  22351. 'polyline': function (xmlNode, parentGroup) {
  22352. var path = new Path();
  22353. inheritStyle(parentGroup, path);
  22354. parseAttributes(xmlNode, path, this._defs);
  22355. var points = xmlNode.getAttribute('points');
  22356. if (points) {
  22357. points = parsePoints(points);
  22358. }
  22359. var polyline = new Polyline({
  22360. shape: {
  22361. points: points || []
  22362. }
  22363. });
  22364. return polyline;
  22365. },
  22366. 'image': function (xmlNode, parentGroup) {
  22367. var img = new ZImage();
  22368. inheritStyle(parentGroup, img);
  22369. parseAttributes(xmlNode, img, this._defs);
  22370. img.setStyle({
  22371. image: xmlNode.getAttribute('xlink:href'),
  22372. x: xmlNode.getAttribute('x'),
  22373. y: xmlNode.getAttribute('y'),
  22374. width: xmlNode.getAttribute('width'),
  22375. height: xmlNode.getAttribute('height')
  22376. });
  22377. return img;
  22378. },
  22379. 'text': function (xmlNode, parentGroup) {
  22380. var x = xmlNode.getAttribute('x') || 0;
  22381. var y = xmlNode.getAttribute('y') || 0;
  22382. var dx = xmlNode.getAttribute('dx') || 0;
  22383. var dy = xmlNode.getAttribute('dy') || 0;
  22384. this._textX = parseFloat(x) + parseFloat(dx);
  22385. this._textY = parseFloat(y) + parseFloat(dy);
  22386. var g = new Group();
  22387. inheritStyle(parentGroup, g);
  22388. parseAttributes(xmlNode, g, this._defs);
  22389. return g;
  22390. },
  22391. 'tspan': function (xmlNode, parentGroup) {
  22392. var x = xmlNode.getAttribute('x');
  22393. var y = xmlNode.getAttribute('y');
  22394. if (x != null) {
  22395. // new offset x
  22396. this._textX = parseFloat(x);
  22397. }
  22398. if (y != null) {
  22399. // new offset y
  22400. this._textY = parseFloat(y);
  22401. }
  22402. var dx = xmlNode.getAttribute('dx') || 0;
  22403. var dy = xmlNode.getAttribute('dy') || 0;
  22404. var g = new Group();
  22405. inheritStyle(parentGroup, g);
  22406. parseAttributes(xmlNode, g, this._defs);
  22407. this._textX += dx;
  22408. this._textY += dy;
  22409. return g;
  22410. },
  22411. 'path': function (xmlNode, parentGroup) {
  22412. // TODO svg fill rule
  22413. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22414. // path.style.globalCompositeOperation = 'xor';
  22415. var d = xmlNode.getAttribute('d') || '';
  22416. // Performance sensitive.
  22417. var path = createFromString(d);
  22418. inheritStyle(parentGroup, path);
  22419. parseAttributes(xmlNode, path, this._defs);
  22420. return path;
  22421. }
  22422. };
  22423. var defineParsers = {
  22424. 'lineargradient': function (xmlNode) {
  22425. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22426. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22427. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22428. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22429. var gradient = new LinearGradient(x1, y1, x2, y2);
  22430. _parseGradientColorStops(xmlNode, gradient);
  22431. return gradient;
  22432. },
  22433. 'radialgradient': function (xmlNode) {
  22434. }
  22435. };
  22436. function _parseGradientColorStops(xmlNode, gradient) {
  22437. var stop = xmlNode.firstChild;
  22438. while (stop) {
  22439. if (stop.nodeType === 1) {
  22440. var offset = stop.getAttribute('offset');
  22441. if (offset.indexOf('%') > 0) { // percentage
  22442. offset = parseInt(offset, 10) / 100;
  22443. }
  22444. else if (offset) { // number from 0 to 1
  22445. offset = parseFloat(offset);
  22446. }
  22447. else {
  22448. offset = 0;
  22449. }
  22450. var stopColor = stop.getAttribute('stop-color') || '#000000';
  22451. gradient.addColorStop(offset, stopColor);
  22452. }
  22453. stop = stop.nextSibling;
  22454. }
  22455. }
  22456. function inheritStyle(parent, child) {
  22457. if (parent && parent.__inheritedStyle) {
  22458. if (!child.__inheritedStyle) {
  22459. child.__inheritedStyle = {};
  22460. }
  22461. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  22462. }
  22463. }
  22464. function parsePoints(pointsString) {
  22465. var list = trim(pointsString).split(DILIMITER_REG);
  22466. var points = [];
  22467. for (var i = 0; i < list.length; i += 2) {
  22468. var x = parseFloat(list[i]);
  22469. var y = parseFloat(list[i + 1]);
  22470. points.push([x, y]);
  22471. }
  22472. return points;
  22473. }
  22474. var attributesMap = {
  22475. 'fill': 'fill',
  22476. 'stroke': 'stroke',
  22477. 'stroke-width': 'lineWidth',
  22478. 'opacity': 'opacity',
  22479. 'fill-opacity': 'fillOpacity',
  22480. 'stroke-opacity': 'strokeOpacity',
  22481. 'stroke-dasharray': 'lineDash',
  22482. 'stroke-dashoffset': 'lineDashOffset',
  22483. 'stroke-linecap': 'lineCap',
  22484. 'stroke-linejoin': 'lineJoin',
  22485. 'stroke-miterlimit': 'miterLimit',
  22486. 'font-family': 'fontFamily',
  22487. 'font-size': 'fontSize',
  22488. 'font-style': 'fontStyle',
  22489. 'font-weight': 'fontWeight',
  22490. 'text-align': 'textAlign',
  22491. 'alignment-baseline': 'textBaseline'
  22492. };
  22493. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  22494. var zrStyle = el.__inheritedStyle || {};
  22495. var isTextEl = el.type === 'text';
  22496. // TODO Shadow
  22497. if (xmlNode.nodeType === 1) {
  22498. parseTransformAttribute(xmlNode, el);
  22499. extend(zrStyle, parseStyleAttribute(xmlNode));
  22500. if (!onlyInlineStyle) {
  22501. for (var svgAttrName in attributesMap) {
  22502. if (attributesMap.hasOwnProperty(svgAttrName)) {
  22503. var attrValue = xmlNode.getAttribute(svgAttrName);
  22504. if (attrValue != null) {
  22505. zrStyle[attributesMap[svgAttrName]] = attrValue;
  22506. }
  22507. }
  22508. }
  22509. }
  22510. }
  22511. var elFillProp = isTextEl ? 'textFill' : 'fill';
  22512. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  22513. el.style = el.style || new Style();
  22514. var elStyle = el.style;
  22515. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  22516. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  22517. each$1([
  22518. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  22519. ], function (propName) {
  22520. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  22521. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  22522. });
  22523. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  22524. zrStyle.textBaseline = 'alphabetic';
  22525. }
  22526. if (zrStyle.textBaseline === 'alphabetic') {
  22527. zrStyle.textBaseline = 'bottom';
  22528. }
  22529. if (zrStyle.textAlign === 'start') {
  22530. zrStyle.textAlign = 'left';
  22531. }
  22532. if (zrStyle.textAlign === 'end') {
  22533. zrStyle.textAlign = 'right';
  22534. }
  22535. each$1(['lineDashOffset', 'lineCap', 'lineJoin',
  22536. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  22537. ], function (propName) {
  22538. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  22539. });
  22540. if (zrStyle.lineDash) {
  22541. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  22542. }
  22543. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  22544. // enable stroke
  22545. el[elStrokeProp] = true;
  22546. }
  22547. el.__inheritedStyle = zrStyle;
  22548. }
  22549. var urlRegex = /url\(\s*#(.*?)\)/;
  22550. function getPaint(str, defs) {
  22551. // if (str === 'none') {
  22552. // return;
  22553. // }
  22554. var urlMatch = defs && str && str.match(urlRegex);
  22555. if (urlMatch) {
  22556. var url = trim(urlMatch[1]);
  22557. var def = defs[url];
  22558. return def;
  22559. }
  22560. return str;
  22561. }
  22562. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  22563. function parseTransformAttribute(xmlNode, node) {
  22564. var transform = xmlNode.getAttribute('transform');
  22565. if (transform) {
  22566. transform = transform.replace(/,/g, ' ');
  22567. var m = null;
  22568. var transformOps = [];
  22569. transform.replace(transformRegex, function (str, type, value) {
  22570. transformOps.push(type, value);
  22571. });
  22572. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  22573. var value = transformOps[i];
  22574. var type = transformOps[i - 1];
  22575. m = m || create$1();
  22576. switch (type) {
  22577. case 'translate':
  22578. value = trim(value).split(DILIMITER_REG);
  22579. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  22580. break;
  22581. case 'scale':
  22582. value = trim(value).split(DILIMITER_REG);
  22583. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  22584. break;
  22585. case 'rotate':
  22586. value = trim(value).split(DILIMITER_REG);
  22587. rotate(m, m, parseFloat(value[0]));
  22588. break;
  22589. case 'skew':
  22590. value = trim(value).split(DILIMITER_REG);
  22591. console.warn('Skew transform is not supported yet');
  22592. break;
  22593. case 'matrix':
  22594. var value = trim(value).split(DILIMITER_REG);
  22595. m[0] = parseFloat(value[0]);
  22596. m[1] = parseFloat(value[1]);
  22597. m[2] = parseFloat(value[2]);
  22598. m[3] = parseFloat(value[3]);
  22599. m[4] = parseFloat(value[4]);
  22600. m[5] = parseFloat(value[5]);
  22601. break;
  22602. }
  22603. }
  22604. node.setLocalTransform(m);
  22605. }
  22606. }
  22607. // Value may contain space.
  22608. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  22609. function parseStyleAttribute(xmlNode) {
  22610. var style = xmlNode.getAttribute('style');
  22611. var result = {};
  22612. if (!style) {
  22613. return result;
  22614. }
  22615. var styleList = {};
  22616. styleRegex.lastIndex = 0;
  22617. var styleRegResult;
  22618. while ((styleRegResult = styleRegex.exec(style)) != null) {
  22619. styleList[styleRegResult[1]] = styleRegResult[2];
  22620. }
  22621. for (var svgAttrName in attributesMap) {
  22622. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  22623. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  22624. }
  22625. }
  22626. return result;
  22627. }
  22628. /**
  22629. * @param {Array.<number>} viewBoxRect
  22630. * @param {number} width
  22631. * @param {number} height
  22632. * @return {Object} {scale, position}
  22633. */
  22634. function makeViewBoxTransform(viewBoxRect, width, height) {
  22635. var scaleX = width / viewBoxRect.width;
  22636. var scaleY = height / viewBoxRect.height;
  22637. var scale = Math.min(scaleX, scaleY);
  22638. // preserveAspectRatio 'xMidYMid'
  22639. var viewBoxScale = [scale, scale];
  22640. var viewBoxPosition = [
  22641. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  22642. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  22643. ];
  22644. return {
  22645. scale: viewBoxScale,
  22646. position: viewBoxPosition
  22647. };
  22648. }
  22649. /**
  22650. * @param {string|XMLElement} xml
  22651. * @param {Object} [opt]
  22652. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  22653. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  22654. * @param {boolean} [opt.ignoreViewBox]
  22655. * @param {boolean} [opt.ignoreRootClip]
  22656. * @return {Object} result:
  22657. * {
  22658. * root: Group, The root of the the result tree of zrender shapes,
  22659. * width: number, the viewport width of the SVG,
  22660. * height: number, the viewport height of the SVG,
  22661. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  22662. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  22663. * }
  22664. */
  22665. /*
  22666. * Licensed to the Apache Software Foundation (ASF) under one
  22667. * or more contributor license agreements. See the NOTICE file
  22668. * distributed with this work for additional information
  22669. * regarding copyright ownership. The ASF licenses this file
  22670. * to you under the Apache License, Version 2.0 (the
  22671. * "License"); you may not use this file except in compliance
  22672. * with the License. You may obtain a copy of the License at
  22673. *
  22674. * http://www.apache.org/licenses/LICENSE-2.0
  22675. *
  22676. * Unless required by applicable law or agreed to in writing,
  22677. * software distributed under the License is distributed on an
  22678. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22679. * KIND, either express or implied. See the License for the
  22680. * specific language governing permissions and limitations
  22681. * under the License.
  22682. */
  22683. var storage = createHashMap();
  22684. // For minimize the code size of common echarts package,
  22685. // do not put too much logic in this module.
  22686. var mapDataStorage = {
  22687. // The format of record: see `echarts.registerMap`.
  22688. // Compatible with previous `echarts.registerMap`.
  22689. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  22690. var records;
  22691. if (isArray(rawGeoJson)) {
  22692. records = rawGeoJson;
  22693. }
  22694. else if (rawGeoJson.svg) {
  22695. records = [{
  22696. type: 'svg',
  22697. source: rawGeoJson.svg,
  22698. specialAreas: rawGeoJson.specialAreas
  22699. }];
  22700. }
  22701. else {
  22702. // Backward compatibility.
  22703. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  22704. rawSpecialAreas = rawGeoJson.specialAreas;
  22705. rawGeoJson = rawGeoJson.geoJson;
  22706. }
  22707. records = [{
  22708. type: 'geoJSON',
  22709. source: rawGeoJson,
  22710. specialAreas: rawSpecialAreas
  22711. }];
  22712. }
  22713. each$1(records, function (record) {
  22714. var type = record.type;
  22715. type === 'geoJson' && (type = record.type = 'geoJSON');
  22716. var parse = parsers[type];
  22717. if (__DEV__) {
  22718. assert$1(parse, 'Illegal map type: ' + type);
  22719. }
  22720. parse(record);
  22721. });
  22722. return storage.set(mapName, records);
  22723. },
  22724. retrieveMap: function (mapName) {
  22725. return storage.get(mapName);
  22726. }
  22727. };
  22728. var parsers = {
  22729. geoJSON: function (record) {
  22730. var source = record.source;
  22731. record.geoJSON = !isString(source)
  22732. ? source
  22733. : (typeof JSON !== 'undefined' && JSON.parse)
  22734. ? JSON.parse(source)
  22735. : (new Function('return (' + source + ');'))();
  22736. },
  22737. // Only perform parse to XML object here, which might be time
  22738. // consiming for large SVG.
  22739. // Although convert XML to zrender element is also time consiming,
  22740. // if we do it here, the clone of zrender elements has to be
  22741. // required. So we do it once for each geo instance, util real
  22742. // performance issues call for optimizing it.
  22743. svg: function (record) {
  22744. record.svgXML = parseXML(record.source);
  22745. }
  22746. };
  22747. /*
  22748. * Licensed to the Apache Software Foundation (ASF) under one
  22749. * or more contributor license agreements. See the NOTICE file
  22750. * distributed with this work for additional information
  22751. * regarding copyright ownership. The ASF licenses this file
  22752. * to you under the Apache License, Version 2.0 (the
  22753. * "License"); you may not use this file except in compliance
  22754. * with the License. You may obtain a copy of the License at
  22755. *
  22756. * http://www.apache.org/licenses/LICENSE-2.0
  22757. *
  22758. * Unless required by applicable law or agreed to in writing,
  22759. * software distributed under the License is distributed on an
  22760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22761. * KIND, either express or implied. See the License for the
  22762. * specific language governing permissions and limitations
  22763. * under the License.
  22764. */
  22765. var assert = assert$1;
  22766. var each = each$1;
  22767. var isFunction = isFunction$1;
  22768. var isObject = isObject$1;
  22769. var parseClassType = ComponentModel.parseClassType;
  22770. var version = '4.2.1';
  22771. var dependencies = {
  22772. zrender: '4.0.6'
  22773. };
  22774. var TEST_FRAME_REMAIN_TIME = 1;
  22775. var PRIORITY_PROCESSOR_FILTER = 1000;
  22776. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  22777. var PRIORITY_VISUAL_LAYOUT = 1000;
  22778. var PRIORITY_VISUAL_GLOBAL = 2000;
  22779. var PRIORITY_VISUAL_CHART = 3000;
  22780. var PRIORITY_VISUAL_COMPONENT = 4000;
  22781. // FIXME
  22782. // necessary?
  22783. var PRIORITY_VISUAL_BRUSH = 5000;
  22784. var PRIORITY = {
  22785. PROCESSOR: {
  22786. FILTER: PRIORITY_PROCESSOR_FILTER,
  22787. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  22788. },
  22789. VISUAL: {
  22790. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  22791. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  22792. CHART: PRIORITY_VISUAL_CHART,
  22793. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  22794. BRUSH: PRIORITY_VISUAL_BRUSH
  22795. }
  22796. };
  22797. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  22798. // where they must not be invoked nestedly, except the only case: invoke
  22799. // dispatchAction with updateMethod "none" in main process.
  22800. // This flag is used to carry out this rule.
  22801. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  22802. var IN_MAIN_PROCESS = '__flagInMainProcess';
  22803. var OPTION_UPDATED = '__optionUpdated';
  22804. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  22805. function createRegisterEventWithLowercaseName(method) {
  22806. return function (eventName, handler, context) {
  22807. // Event name is all lowercase
  22808. eventName = eventName && eventName.toLowerCase();
  22809. Eventful.prototype[method].call(this, eventName, handler, context);
  22810. };
  22811. }
  22812. /**
  22813. * @module echarts~MessageCenter
  22814. */
  22815. function MessageCenter() {
  22816. Eventful.call(this);
  22817. }
  22818. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  22819. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  22820. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  22821. mixin(MessageCenter, Eventful);
  22822. /**
  22823. * @module echarts~ECharts
  22824. */
  22825. function ECharts(dom, theme$$1, opts) {
  22826. opts = opts || {};
  22827. // Get theme by name
  22828. if (typeof theme$$1 === 'string') {
  22829. theme$$1 = themeStorage[theme$$1];
  22830. }
  22831. /**
  22832. * @type {string}
  22833. */
  22834. this.id;
  22835. /**
  22836. * Group id
  22837. * @type {string}
  22838. */
  22839. this.group;
  22840. /**
  22841. * @type {HTMLElement}
  22842. * @private
  22843. */
  22844. this._dom = dom;
  22845. var defaultRenderer = 'canvas';
  22846. if (__DEV__) {
  22847. defaultRenderer = (
  22848. typeof window === 'undefined' ? global : window
  22849. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  22850. }
  22851. /**
  22852. * @type {module:zrender/ZRender}
  22853. * @private
  22854. */
  22855. var zr = this._zr = init$1(dom, {
  22856. renderer: opts.renderer || defaultRenderer,
  22857. devicePixelRatio: opts.devicePixelRatio,
  22858. width: opts.width,
  22859. height: opts.height
  22860. });
  22861. /**
  22862. * Expect 60 pfs.
  22863. * @type {Function}
  22864. * @private
  22865. */
  22866. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  22867. var theme$$1 = clone(theme$$1);
  22868. theme$$1 && backwardCompat(theme$$1, true);
  22869. /**
  22870. * @type {Object}
  22871. * @private
  22872. */
  22873. this._theme = theme$$1;
  22874. /**
  22875. * @type {Array.<module:echarts/view/Chart>}
  22876. * @private
  22877. */
  22878. this._chartsViews = [];
  22879. /**
  22880. * @type {Object.<string, module:echarts/view/Chart>}
  22881. * @private
  22882. */
  22883. this._chartsMap = {};
  22884. /**
  22885. * @type {Array.<module:echarts/view/Component>}
  22886. * @private
  22887. */
  22888. this._componentsViews = [];
  22889. /**
  22890. * @type {Object.<string, module:echarts/view/Component>}
  22891. * @private
  22892. */
  22893. this._componentsMap = {};
  22894. /**
  22895. * @type {module:echarts/CoordinateSystem}
  22896. * @private
  22897. */
  22898. this._coordSysMgr = new CoordinateSystemManager();
  22899. /**
  22900. * @type {module:echarts/ExtensionAPI}
  22901. * @private
  22902. */
  22903. var api = this._api = createExtensionAPI(this);
  22904. // Sort on demand
  22905. function prioritySortFunc(a, b) {
  22906. return a.__prio - b.__prio;
  22907. }
  22908. sort(visualFuncs, prioritySortFunc);
  22909. sort(dataProcessorFuncs, prioritySortFunc);
  22910. /**
  22911. * @type {module:echarts/stream/Scheduler}
  22912. */
  22913. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22914. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  22915. /**
  22916. * @type {module:echarts~MessageCenter}
  22917. * @private
  22918. */
  22919. this._messageCenter = new MessageCenter();
  22920. // Init mouse events
  22921. this._initEvents();
  22922. // In case some people write `window.onresize = chart.resize`
  22923. this.resize = bind(this.resize, this);
  22924. // Can't dispatch action during rendering procedure
  22925. this._pendingActions = [];
  22926. zr.animation.on('frame', this._onframe, this);
  22927. bindRenderedEvent(zr, this);
  22928. // ECharts instance can be used as value.
  22929. setAsPrimitive(this);
  22930. }
  22931. var echartsProto = ECharts.prototype;
  22932. echartsProto._onframe = function () {
  22933. if (this._disposed) {
  22934. return;
  22935. }
  22936. var scheduler = this._scheduler;
  22937. // Lazy update
  22938. if (this[OPTION_UPDATED]) {
  22939. var silent = this[OPTION_UPDATED].silent;
  22940. this[IN_MAIN_PROCESS] = true;
  22941. prepare(this);
  22942. updateMethods.update.call(this);
  22943. this[IN_MAIN_PROCESS] = false;
  22944. this[OPTION_UPDATED] = false;
  22945. flushPendingActions.call(this, silent);
  22946. triggerUpdatedEvent.call(this, silent);
  22947. }
  22948. // Avoid do both lazy update and progress in one frame.
  22949. else if (scheduler.unfinished) {
  22950. // Stream progress.
  22951. var remainTime = TEST_FRAME_REMAIN_TIME;
  22952. var ecModel = this._model;
  22953. var api = this._api;
  22954. scheduler.unfinished = false;
  22955. do {
  22956. var startTime = +new Date();
  22957. scheduler.performSeriesTasks(ecModel);
  22958. // Currently dataProcessorFuncs do not check threshold.
  22959. scheduler.performDataProcessorTasks(ecModel);
  22960. updateStreamModes(this, ecModel);
  22961. // Do not update coordinate system here. Because that coord system update in
  22962. // each frame is not a good user experience. So we follow the rule that
  22963. // the extent of the coordinate system is determin in the first frame (the
  22964. // frame is executed immedietely after task reset.
  22965. // this._coordSysMgr.update(ecModel, api);
  22966. // console.log('--- ec frame visual ---', remainTime);
  22967. scheduler.performVisualTasks(ecModel);
  22968. renderSeries(this, this._model, api, 'remain');
  22969. remainTime -= (+new Date() - startTime);
  22970. }
  22971. while (remainTime > 0 && scheduler.unfinished);
  22972. // Call flush explicitly for trigger finished event.
  22973. if (!scheduler.unfinished) {
  22974. this._zr.flush();
  22975. }
  22976. // Else, zr flushing be ensue within the same frame,
  22977. // because zr flushing is after onframe event.
  22978. }
  22979. };
  22980. /**
  22981. * @return {HTMLElement}
  22982. */
  22983. echartsProto.getDom = function () {
  22984. return this._dom;
  22985. };
  22986. /**
  22987. * @return {module:zrender~ZRender}
  22988. */
  22989. echartsProto.getZr = function () {
  22990. return this._zr;
  22991. };
  22992. /**
  22993. * Usage:
  22994. * chart.setOption(option, notMerge, lazyUpdate);
  22995. * chart.setOption(option, {
  22996. * notMerge: ...,
  22997. * lazyUpdate: ...,
  22998. * silent: ...
  22999. * });
  23000. *
  23001. * @param {Object} option
  23002. * @param {Object|boolean} [opts] opts or notMerge.
  23003. * @param {boolean} [opts.notMerge=false]
  23004. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  23005. */
  23006. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  23007. if (__DEV__) {
  23008. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  23009. }
  23010. var silent;
  23011. if (isObject(notMerge)) {
  23012. lazyUpdate = notMerge.lazyUpdate;
  23013. silent = notMerge.silent;
  23014. notMerge = notMerge.notMerge;
  23015. }
  23016. this[IN_MAIN_PROCESS] = true;
  23017. if (!this._model || notMerge) {
  23018. var optionManager = new OptionManager(this._api);
  23019. var theme$$1 = this._theme;
  23020. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  23021. ecModel.scheduler = this._scheduler;
  23022. ecModel.init(null, null, theme$$1, optionManager);
  23023. }
  23024. this._model.setOption(option, optionPreprocessorFuncs);
  23025. if (lazyUpdate) {
  23026. this[OPTION_UPDATED] = {silent: silent};
  23027. this[IN_MAIN_PROCESS] = false;
  23028. }
  23029. else {
  23030. prepare(this);
  23031. updateMethods.update.call(this);
  23032. // Ensure zr refresh sychronously, and then pixel in canvas can be
  23033. // fetched after `setOption`.
  23034. this._zr.flush();
  23035. this[OPTION_UPDATED] = false;
  23036. this[IN_MAIN_PROCESS] = false;
  23037. flushPendingActions.call(this, silent);
  23038. triggerUpdatedEvent.call(this, silent);
  23039. }
  23040. };
  23041. /**
  23042. * @DEPRECATED
  23043. */
  23044. echartsProto.setTheme = function () {
  23045. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  23046. };
  23047. /**
  23048. * @return {module:echarts/model/Global}
  23049. */
  23050. echartsProto.getModel = function () {
  23051. return this._model;
  23052. };
  23053. /**
  23054. * @return {Object}
  23055. */
  23056. echartsProto.getOption = function () {
  23057. return this._model && this._model.getOption();
  23058. };
  23059. /**
  23060. * @return {number}
  23061. */
  23062. echartsProto.getWidth = function () {
  23063. return this._zr.getWidth();
  23064. };
  23065. /**
  23066. * @return {number}
  23067. */
  23068. echartsProto.getHeight = function () {
  23069. return this._zr.getHeight();
  23070. };
  23071. /**
  23072. * @return {number}
  23073. */
  23074. echartsProto.getDevicePixelRatio = function () {
  23075. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  23076. };
  23077. /**
  23078. * Get canvas which has all thing rendered
  23079. * @param {Object} opts
  23080. * @param {string} [opts.backgroundColor]
  23081. * @return {string}
  23082. */
  23083. echartsProto.getRenderedCanvas = function (opts) {
  23084. if (!env$1.canvasSupported) {
  23085. return;
  23086. }
  23087. opts = opts || {};
  23088. opts.pixelRatio = opts.pixelRatio || 1;
  23089. opts.backgroundColor = opts.backgroundColor
  23090. || this._model.get('backgroundColor');
  23091. var zr = this._zr;
  23092. // var list = zr.storage.getDisplayList();
  23093. // Stop animations
  23094. // Never works before in init animation, so remove it.
  23095. // zrUtil.each(list, function (el) {
  23096. // el.stopAnimation(true);
  23097. // });
  23098. return zr.painter.getRenderedCanvas(opts);
  23099. };
  23100. /**
  23101. * Get svg data url
  23102. * @return {string}
  23103. */
  23104. echartsProto.getSvgDataUrl = function () {
  23105. if (!env$1.svgSupported) {
  23106. return;
  23107. }
  23108. var zr = this._zr;
  23109. var list = zr.storage.getDisplayList();
  23110. // Stop animations
  23111. each$1(list, function (el) {
  23112. el.stopAnimation(true);
  23113. });
  23114. return zr.painter.pathToDataUrl();
  23115. };
  23116. /**
  23117. * @return {string}
  23118. * @param {Object} opts
  23119. * @param {string} [opts.type='png']
  23120. * @param {string} [opts.pixelRatio=1]
  23121. * @param {string} [opts.backgroundColor]
  23122. * @param {string} [opts.excludeComponents]
  23123. */
  23124. echartsProto.getDataURL = function (opts) {
  23125. opts = opts || {};
  23126. var excludeComponents = opts.excludeComponents;
  23127. var ecModel = this._model;
  23128. var excludesComponentViews = [];
  23129. var self = this;
  23130. each(excludeComponents, function (componentType) {
  23131. ecModel.eachComponent({
  23132. mainType: componentType
  23133. }, function (component) {
  23134. var view = self._componentsMap[component.__viewId];
  23135. if (!view.group.ignore) {
  23136. excludesComponentViews.push(view);
  23137. view.group.ignore = true;
  23138. }
  23139. });
  23140. });
  23141. var url = this._zr.painter.getType() === 'svg'
  23142. ? this.getSvgDataUrl()
  23143. : this.getRenderedCanvas(opts).toDataURL(
  23144. 'image/' + (opts && opts.type || 'png')
  23145. );
  23146. each(excludesComponentViews, function (view) {
  23147. view.group.ignore = false;
  23148. });
  23149. return url;
  23150. };
  23151. /**
  23152. * @return {string}
  23153. * @param {Object} opts
  23154. * @param {string} [opts.type='png']
  23155. * @param {string} [opts.pixelRatio=1]
  23156. * @param {string} [opts.backgroundColor]
  23157. */
  23158. echartsProto.getConnectedDataURL = function (opts) {
  23159. if (!env$1.canvasSupported) {
  23160. return;
  23161. }
  23162. var groupId = this.group;
  23163. var mathMin = Math.min;
  23164. var mathMax = Math.max;
  23165. var MAX_NUMBER = Infinity;
  23166. if (connectedGroups[groupId]) {
  23167. var left = MAX_NUMBER;
  23168. var top = MAX_NUMBER;
  23169. var right = -MAX_NUMBER;
  23170. var bottom = -MAX_NUMBER;
  23171. var canvasList = [];
  23172. var dpr = (opts && opts.pixelRatio) || 1;
  23173. each$1(instances, function (chart, id) {
  23174. if (chart.group === groupId) {
  23175. var canvas = chart.getRenderedCanvas(
  23176. clone(opts)
  23177. );
  23178. var boundingRect = chart.getDom().getBoundingClientRect();
  23179. left = mathMin(boundingRect.left, left);
  23180. top = mathMin(boundingRect.top, top);
  23181. right = mathMax(boundingRect.right, right);
  23182. bottom = mathMax(boundingRect.bottom, bottom);
  23183. canvasList.push({
  23184. dom: canvas,
  23185. left: boundingRect.left,
  23186. top: boundingRect.top
  23187. });
  23188. }
  23189. });
  23190. left *= dpr;
  23191. top *= dpr;
  23192. right *= dpr;
  23193. bottom *= dpr;
  23194. var width = right - left;
  23195. var height = bottom - top;
  23196. var targetCanvas = createCanvas();
  23197. targetCanvas.width = width;
  23198. targetCanvas.height = height;
  23199. var zr = init$1(targetCanvas);
  23200. each(canvasList, function (item) {
  23201. var img = new ZImage({
  23202. style: {
  23203. x: item.left * dpr - left,
  23204. y: item.top * dpr - top,
  23205. image: item.dom
  23206. }
  23207. });
  23208. zr.add(img);
  23209. });
  23210. zr.refreshImmediately();
  23211. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  23212. }
  23213. else {
  23214. return this.getDataURL(opts);
  23215. }
  23216. };
  23217. /**
  23218. * Convert from logical coordinate system to pixel coordinate system.
  23219. * See CoordinateSystem#convertToPixel.
  23220. * @param {string|Object} finder
  23221. * If string, e.g., 'geo', means {geoIndex: 0}.
  23222. * If Object, could contain some of these properties below:
  23223. * {
  23224. * seriesIndex / seriesId / seriesName,
  23225. * geoIndex / geoId, geoName,
  23226. * bmapIndex / bmapId / bmapName,
  23227. * xAxisIndex / xAxisId / xAxisName,
  23228. * yAxisIndex / yAxisId / yAxisName,
  23229. * gridIndex / gridId / gridName,
  23230. * ... (can be extended)
  23231. * }
  23232. * @param {Array|number} value
  23233. * @return {Array|number} result
  23234. */
  23235. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  23236. /**
  23237. * Convert from pixel coordinate system to logical coordinate system.
  23238. * See CoordinateSystem#convertFromPixel.
  23239. * @param {string|Object} finder
  23240. * If string, e.g., 'geo', means {geoIndex: 0}.
  23241. * If Object, could contain some of these properties below:
  23242. * {
  23243. * seriesIndex / seriesId / seriesName,
  23244. * geoIndex / geoId / geoName,
  23245. * bmapIndex / bmapId / bmapName,
  23246. * xAxisIndex / xAxisId / xAxisName,
  23247. * yAxisIndex / yAxisId / yAxisName
  23248. * gridIndex / gridId / gridName,
  23249. * ... (can be extended)
  23250. * }
  23251. * @param {Array|number} value
  23252. * @return {Array|number} result
  23253. */
  23254. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  23255. function doConvertPixel(methodName, finder, value) {
  23256. var ecModel = this._model;
  23257. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  23258. var result;
  23259. finder = parseFinder(ecModel, finder);
  23260. for (var i = 0; i < coordSysList.length; i++) {
  23261. var coordSys = coordSysList[i];
  23262. if (coordSys[methodName]
  23263. && (result = coordSys[methodName](ecModel, finder, value)) != null
  23264. ) {
  23265. return result;
  23266. }
  23267. }
  23268. if (__DEV__) {
  23269. console.warn(
  23270. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  23271. );
  23272. }
  23273. }
  23274. /**
  23275. * Is the specified coordinate systems or components contain the given pixel point.
  23276. * @param {string|Object} finder
  23277. * If string, e.g., 'geo', means {geoIndex: 0}.
  23278. * If Object, could contain some of these properties below:
  23279. * {
  23280. * seriesIndex / seriesId / seriesName,
  23281. * geoIndex / geoId / geoName,
  23282. * bmapIndex / bmapId / bmapName,
  23283. * xAxisIndex / xAxisId / xAxisName,
  23284. * yAxisIndex / yAxisId / yAxisName,
  23285. * gridIndex / gridId / gridName,
  23286. * ... (can be extended)
  23287. * }
  23288. * @param {Array|number} value
  23289. * @return {boolean} result
  23290. */
  23291. echartsProto.containPixel = function (finder, value) {
  23292. var ecModel = this._model;
  23293. var result;
  23294. finder = parseFinder(ecModel, finder);
  23295. each$1(finder, function (models, key) {
  23296. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  23297. var coordSys = model.coordinateSystem;
  23298. if (coordSys && coordSys.containPoint) {
  23299. result |= !!coordSys.containPoint(value);
  23300. }
  23301. else if (key === 'seriesModels') {
  23302. var view = this._chartsMap[model.__viewId];
  23303. if (view && view.containPoint) {
  23304. result |= view.containPoint(value, model);
  23305. }
  23306. else {
  23307. if (__DEV__) {
  23308. console.warn(key + ': ' + (view
  23309. ? 'The found component do not support containPoint.'
  23310. : 'No view mapping to the found component.'
  23311. ));
  23312. }
  23313. }
  23314. }
  23315. else {
  23316. if (__DEV__) {
  23317. console.warn(key + ': containPoint is not supported');
  23318. }
  23319. }
  23320. }, this);
  23321. }, this);
  23322. return !!result;
  23323. };
  23324. /**
  23325. * Get visual from series or data.
  23326. * @param {string|Object} finder
  23327. * If string, e.g., 'series', means {seriesIndex: 0}.
  23328. * If Object, could contain some of these properties below:
  23329. * {
  23330. * seriesIndex / seriesId / seriesName,
  23331. * dataIndex / dataIndexInside
  23332. * }
  23333. * If dataIndex is not specified, series visual will be fetched,
  23334. * but not data item visual.
  23335. * If all of seriesIndex, seriesId, seriesName are not specified,
  23336. * visual will be fetched from first series.
  23337. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  23338. */
  23339. echartsProto.getVisual = function (finder, visualType) {
  23340. var ecModel = this._model;
  23341. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  23342. var seriesModel = finder.seriesModel;
  23343. if (__DEV__) {
  23344. if (!seriesModel) {
  23345. console.warn('There is no specified seires model');
  23346. }
  23347. }
  23348. var data = seriesModel.getData();
  23349. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  23350. ? finder.dataIndexInside
  23351. : finder.hasOwnProperty('dataIndex')
  23352. ? data.indexOfRawIndex(finder.dataIndex)
  23353. : null;
  23354. return dataIndexInside != null
  23355. ? data.getItemVisual(dataIndexInside, visualType)
  23356. : data.getVisual(visualType);
  23357. };
  23358. /**
  23359. * Get view of corresponding component model
  23360. * @param {module:echarts/model/Component} componentModel
  23361. * @return {module:echarts/view/Component}
  23362. */
  23363. echartsProto.getViewOfComponentModel = function (componentModel) {
  23364. return this._componentsMap[componentModel.__viewId];
  23365. };
  23366. /**
  23367. * Get view of corresponding series model
  23368. * @param {module:echarts/model/Series} seriesModel
  23369. * @return {module:echarts/view/Chart}
  23370. */
  23371. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23372. return this._chartsMap[seriesModel.__viewId];
  23373. };
  23374. var updateMethods = {
  23375. prepareAndUpdate: function (payload) {
  23376. prepare(this);
  23377. updateMethods.update.call(this, payload);
  23378. },
  23379. /**
  23380. * @param {Object} payload
  23381. * @private
  23382. */
  23383. update: function (payload) {
  23384. // console.profile && console.profile('update');
  23385. var ecModel = this._model;
  23386. var api = this._api;
  23387. var zr = this._zr;
  23388. var coordSysMgr = this._coordSysMgr;
  23389. var scheduler = this._scheduler;
  23390. // update before setOption
  23391. if (!ecModel) {
  23392. return;
  23393. }
  23394. scheduler.restoreData(ecModel, payload);
  23395. scheduler.performSeriesTasks(ecModel);
  23396. // TODO
  23397. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23398. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23399. // Create new coordinate system each update
  23400. // In LineView may save the old coordinate system and use it to get the orignal point
  23401. coordSysMgr.create(ecModel, api);
  23402. scheduler.performDataProcessorTasks(ecModel, payload);
  23403. // Current stream render is not supported in data process. So we can update
  23404. // stream modes after data processing, where the filtered data is used to
  23405. // deteming whether use progressive rendering.
  23406. updateStreamModes(this, ecModel);
  23407. // We update stream modes before coordinate system updated, then the modes info
  23408. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23409. // the drawback is the full coord info can not be fetched. Fortunately this full
  23410. // coord is not requied in stream mode updater currently.
  23411. coordSysMgr.update(ecModel, api);
  23412. clearColorPalette(ecModel);
  23413. scheduler.performVisualTasks(ecModel, payload);
  23414. render(this, ecModel, api, payload);
  23415. // Set background
  23416. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  23417. // In IE8
  23418. if (!env$1.canvasSupported) {
  23419. var colorArr = parse(backgroundColor);
  23420. backgroundColor = stringify(colorArr, 'rgb');
  23421. if (colorArr[3] === 0) {
  23422. backgroundColor = 'transparent';
  23423. }
  23424. }
  23425. else {
  23426. zr.setBackgroundColor(backgroundColor);
  23427. }
  23428. performPostUpdateFuncs(ecModel, api);
  23429. // console.profile && console.profileEnd('update');
  23430. },
  23431. /**
  23432. * @param {Object} payload
  23433. * @private
  23434. */
  23435. updateTransform: function (payload) {
  23436. var ecModel = this._model;
  23437. var ecIns = this;
  23438. var api = this._api;
  23439. // update before setOption
  23440. if (!ecModel) {
  23441. return;
  23442. }
  23443. // ChartView.markUpdateMethod(payload, 'updateTransform');
  23444. var componentDirtyList = [];
  23445. ecModel.eachComponent(function (componentType, componentModel) {
  23446. var componentView = ecIns.getViewOfComponentModel(componentModel);
  23447. if (componentView && componentView.__alive) {
  23448. if (componentView.updateTransform) {
  23449. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  23450. result && result.update && componentDirtyList.push(componentView);
  23451. }
  23452. else {
  23453. componentDirtyList.push(componentView);
  23454. }
  23455. }
  23456. });
  23457. var seriesDirtyMap = createHashMap();
  23458. ecModel.eachSeries(function (seriesModel) {
  23459. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23460. if (chartView.updateTransform) {
  23461. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  23462. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  23463. }
  23464. else {
  23465. seriesDirtyMap.set(seriesModel.uid, 1);
  23466. }
  23467. });
  23468. clearColorPalette(ecModel);
  23469. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23470. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23471. this._scheduler.performVisualTasks(
  23472. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  23473. );
  23474. // Currently, not call render of components. Geo render cost a lot.
  23475. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  23476. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  23477. performPostUpdateFuncs(ecModel, this._api);
  23478. },
  23479. /**
  23480. * @param {Object} payload
  23481. * @private
  23482. */
  23483. updateView: function (payload) {
  23484. var ecModel = this._model;
  23485. // update before setOption
  23486. if (!ecModel) {
  23487. return;
  23488. }
  23489. Chart.markUpdateMethod(payload, 'updateView');
  23490. clearColorPalette(ecModel);
  23491. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23492. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23493. render(this, this._model, this._api, payload);
  23494. performPostUpdateFuncs(ecModel, this._api);
  23495. },
  23496. /**
  23497. * @param {Object} payload
  23498. * @private
  23499. */
  23500. updateVisual: function (payload) {
  23501. updateMethods.update.call(this, payload);
  23502. // var ecModel = this._model;
  23503. // // update before setOption
  23504. // if (!ecModel) {
  23505. // return;
  23506. // }
  23507. // ChartView.markUpdateMethod(payload, 'updateVisual');
  23508. // clearColorPalette(ecModel);
  23509. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23510. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  23511. // render(this, this._model, this._api, payload);
  23512. // performPostUpdateFuncs(ecModel, this._api);
  23513. },
  23514. /**
  23515. * @param {Object} payload
  23516. * @private
  23517. */
  23518. updateLayout: function (payload) {
  23519. updateMethods.update.call(this, payload);
  23520. // var ecModel = this._model;
  23521. // // update before setOption
  23522. // if (!ecModel) {
  23523. // return;
  23524. // }
  23525. // ChartView.markUpdateMethod(payload, 'updateLayout');
  23526. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23527. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23528. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23529. // render(this, this._model, this._api, payload);
  23530. // performPostUpdateFuncs(ecModel, this._api);
  23531. }
  23532. };
  23533. function prepare(ecIns) {
  23534. var ecModel = ecIns._model;
  23535. var scheduler = ecIns._scheduler;
  23536. scheduler.restorePipelines(ecModel);
  23537. scheduler.prepareStageTasks();
  23538. prepareView(ecIns, 'component', ecModel, scheduler);
  23539. prepareView(ecIns, 'chart', ecModel, scheduler);
  23540. scheduler.plan();
  23541. }
  23542. /**
  23543. * @private
  23544. */
  23545. function updateDirectly(ecIns, method, payload, mainType, subType) {
  23546. var ecModel = ecIns._model;
  23547. // broadcast
  23548. if (!mainType) {
  23549. // FIXME
  23550. // Chart will not be update directly here, except set dirty.
  23551. // But there is no such scenario now.
  23552. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  23553. return;
  23554. }
  23555. var query = {};
  23556. query[mainType + 'Id'] = payload[mainType + 'Id'];
  23557. query[mainType + 'Index'] = payload[mainType + 'Index'];
  23558. query[mainType + 'Name'] = payload[mainType + 'Name'];
  23559. var condition = {mainType: mainType, query: query};
  23560. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  23561. var excludeSeriesId = payload.excludeSeriesId;
  23562. if (excludeSeriesId != null) {
  23563. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  23564. }
  23565. // If dispatchAction before setOption, do nothing.
  23566. ecModel && ecModel.eachComponent(condition, function (model) {
  23567. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  23568. callView(ecIns[
  23569. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  23570. ][model.__viewId]);
  23571. }
  23572. }, ecIns);
  23573. function callView(view) {
  23574. view && view.__alive && view[method] && view[method](
  23575. view.__model, ecModel, ecIns._api, payload
  23576. );
  23577. }
  23578. }
  23579. /**
  23580. * Resize the chart
  23581. * @param {Object} opts
  23582. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  23583. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  23584. * @param {boolean} [opts.silent=false]
  23585. */
  23586. echartsProto.resize = function (opts) {
  23587. if (__DEV__) {
  23588. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  23589. }
  23590. this._zr.resize(opts);
  23591. var ecModel = this._model;
  23592. // Resize loading effect
  23593. this._loadingFX && this._loadingFX.resize();
  23594. if (!ecModel) {
  23595. return;
  23596. }
  23597. var optionChanged = ecModel.resetOption('media');
  23598. var silent = opts && opts.silent;
  23599. this[IN_MAIN_PROCESS] = true;
  23600. optionChanged && prepare(this);
  23601. updateMethods.update.call(this);
  23602. this[IN_MAIN_PROCESS] = false;
  23603. flushPendingActions.call(this, silent);
  23604. triggerUpdatedEvent.call(this, silent);
  23605. };
  23606. function updateStreamModes(ecIns, ecModel) {
  23607. var chartsMap = ecIns._chartsMap;
  23608. var scheduler = ecIns._scheduler;
  23609. ecModel.eachSeries(function (seriesModel) {
  23610. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  23611. });
  23612. }
  23613. /**
  23614. * Show loading effect
  23615. * @param {string} [name='default']
  23616. * @param {Object} [cfg]
  23617. */
  23618. echartsProto.showLoading = function (name, cfg) {
  23619. if (isObject(name)) {
  23620. cfg = name;
  23621. name = '';
  23622. }
  23623. name = name || 'default';
  23624. this.hideLoading();
  23625. if (!loadingEffects[name]) {
  23626. if (__DEV__) {
  23627. console.warn('Loading effects ' + name + ' not exists.');
  23628. }
  23629. return;
  23630. }
  23631. var el = loadingEffects[name](this._api, cfg);
  23632. var zr = this._zr;
  23633. this._loadingFX = el;
  23634. zr.add(el);
  23635. };
  23636. /**
  23637. * Hide loading effect
  23638. */
  23639. echartsProto.hideLoading = function () {
  23640. this._loadingFX && this._zr.remove(this._loadingFX);
  23641. this._loadingFX = null;
  23642. };
  23643. /**
  23644. * @param {Object} eventObj
  23645. * @return {Object}
  23646. */
  23647. echartsProto.makeActionFromEvent = function (eventObj) {
  23648. var payload = extend({}, eventObj);
  23649. payload.type = eventActionMap[eventObj.type];
  23650. return payload;
  23651. };
  23652. /**
  23653. * @pubilc
  23654. * @param {Object} payload
  23655. * @param {string} [payload.type] Action type
  23656. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  23657. * @param {boolean} [opt.silent=false] Whether trigger events.
  23658. * @param {boolean} [opt.flush=undefined]
  23659. * true: Flush immediately, and then pixel in canvas can be fetched
  23660. * immediately. Caution: it might affect performance.
  23661. * false: Not not flush.
  23662. * undefined: Auto decide whether perform flush.
  23663. */
  23664. echartsProto.dispatchAction = function (payload, opt) {
  23665. if (!isObject(opt)) {
  23666. opt = {silent: !!opt};
  23667. }
  23668. if (!actions[payload.type]) {
  23669. return;
  23670. }
  23671. // Avoid dispatch action before setOption. Especially in `connect`.
  23672. if (!this._model) {
  23673. return;
  23674. }
  23675. // May dispatchAction in rendering procedure
  23676. if (this[IN_MAIN_PROCESS]) {
  23677. this._pendingActions.push(payload);
  23678. return;
  23679. }
  23680. doDispatchAction.call(this, payload, opt.silent);
  23681. if (opt.flush) {
  23682. this._zr.flush(true);
  23683. }
  23684. else if (opt.flush !== false && env$1.browser.weChat) {
  23685. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  23686. // hang when sliding page (on touch event), which cause that zr does not
  23687. // refresh util user interaction finished, which is not expected.
  23688. // But `dispatchAction` may be called too frequently when pan on touch
  23689. // screen, which impacts performance if do not throttle them.
  23690. this._throttledZrFlush();
  23691. }
  23692. flushPendingActions.call(this, opt.silent);
  23693. triggerUpdatedEvent.call(this, opt.silent);
  23694. };
  23695. function doDispatchAction(payload, silent) {
  23696. var payloadType = payload.type;
  23697. var escapeConnect = payload.escapeConnect;
  23698. var actionWrap = actions[payloadType];
  23699. var actionInfo = actionWrap.actionInfo;
  23700. var cptType = (actionInfo.update || 'update').split(':');
  23701. var updateMethod = cptType.pop();
  23702. cptType = cptType[0] != null && parseClassType(cptType[0]);
  23703. this[IN_MAIN_PROCESS] = true;
  23704. var payloads = [payload];
  23705. var batched = false;
  23706. // Batch action
  23707. if (payload.batch) {
  23708. batched = true;
  23709. payloads = map(payload.batch, function (item) {
  23710. item = defaults(extend({}, item), payload);
  23711. item.batch = null;
  23712. return item;
  23713. });
  23714. }
  23715. var eventObjBatch = [];
  23716. var eventObj;
  23717. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  23718. each(payloads, function (batchItem) {
  23719. // Action can specify the event by return it.
  23720. eventObj = actionWrap.action(batchItem, this._model, this._api);
  23721. // Emit event outside
  23722. eventObj = eventObj || extend({}, batchItem);
  23723. // Convert type to eventType
  23724. eventObj.type = actionInfo.event || eventObj.type;
  23725. eventObjBatch.push(eventObj);
  23726. // light update does not perform data process, layout and visual.
  23727. if (isHighDown) {
  23728. // method, payload, mainType, subType
  23729. updateDirectly(this, updateMethod, batchItem, 'series');
  23730. }
  23731. else if (cptType) {
  23732. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  23733. }
  23734. }, this);
  23735. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  23736. // Still dirty
  23737. if (this[OPTION_UPDATED]) {
  23738. // FIXME Pass payload ?
  23739. prepare(this);
  23740. updateMethods.update.call(this, payload);
  23741. this[OPTION_UPDATED] = false;
  23742. }
  23743. else {
  23744. updateMethods[updateMethod].call(this, payload);
  23745. }
  23746. }
  23747. // Follow the rule of action batch
  23748. if (batched) {
  23749. eventObj = {
  23750. type: actionInfo.event || payloadType,
  23751. escapeConnect: escapeConnect,
  23752. batch: eventObjBatch
  23753. };
  23754. }
  23755. else {
  23756. eventObj = eventObjBatch[0];
  23757. }
  23758. this[IN_MAIN_PROCESS] = false;
  23759. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  23760. }
  23761. function flushPendingActions(silent) {
  23762. var pendingActions = this._pendingActions;
  23763. while (pendingActions.length) {
  23764. var payload = pendingActions.shift();
  23765. doDispatchAction.call(this, payload, silent);
  23766. }
  23767. }
  23768. function triggerUpdatedEvent(silent) {
  23769. !silent && this.trigger('updated');
  23770. }
  23771. /**
  23772. * Event `rendered` is triggered when zr
  23773. * rendered. It is useful for realtime
  23774. * snapshot (reflect animation).
  23775. *
  23776. * Event `finished` is triggered when:
  23777. * (1) zrender rendering finished.
  23778. * (2) initial animation finished.
  23779. * (3) progressive rendering finished.
  23780. * (4) no pending action.
  23781. * (5) no delayed setOption needs to be processed.
  23782. */
  23783. function bindRenderedEvent(zr, ecIns) {
  23784. zr.on('rendered', function () {
  23785. ecIns.trigger('rendered');
  23786. // The `finished` event should not be triggered repeatly,
  23787. // so it should only be triggered when rendering indeed happend
  23788. // in zrender. (Consider the case that dipatchAction is keep
  23789. // triggering when mouse move).
  23790. if (
  23791. // Although zr is dirty if initial animation is not finished
  23792. // and this checking is called on frame, we also check
  23793. // animation finished for robustness.
  23794. zr.animation.isFinished()
  23795. && !ecIns[OPTION_UPDATED]
  23796. && !ecIns._scheduler.unfinished
  23797. && !ecIns._pendingActions.length
  23798. ) {
  23799. ecIns.trigger('finished');
  23800. }
  23801. });
  23802. }
  23803. /**
  23804. * @param {Object} params
  23805. * @param {number} params.seriesIndex
  23806. * @param {Array|TypedArray} params.data
  23807. */
  23808. echartsProto.appendData = function (params) {
  23809. var seriesIndex = params.seriesIndex;
  23810. var ecModel = this.getModel();
  23811. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  23812. if (__DEV__) {
  23813. assert(params.data && seriesModel);
  23814. }
  23815. seriesModel.appendData(params);
  23816. // Note: `appendData` does not support that update extent of coordinate
  23817. // system, util some scenario require that. In the expected usage of
  23818. // `appendData`, the initial extent of coordinate system should better
  23819. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  23820. // the extent changed while `appendData`, the location of the painted
  23821. // graphic elements have to be changed, which make the usage of
  23822. // `appendData` meaningless.
  23823. this._scheduler.unfinished = true;
  23824. };
  23825. /**
  23826. * Register event
  23827. * @method
  23828. */
  23829. echartsProto.on = createRegisterEventWithLowercaseName('on');
  23830. echartsProto.off = createRegisterEventWithLowercaseName('off');
  23831. echartsProto.one = createRegisterEventWithLowercaseName('one');
  23832. /**
  23833. * Prepare view instances of charts and components
  23834. * @param {module:echarts/model/Global} ecModel
  23835. * @private
  23836. */
  23837. function prepareView(ecIns, type, ecModel, scheduler) {
  23838. var isComponent = type === 'component';
  23839. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  23840. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  23841. var zr = ecIns._zr;
  23842. var api = ecIns._api;
  23843. for (var i = 0; i < viewList.length; i++) {
  23844. viewList[i].__alive = false;
  23845. }
  23846. isComponent
  23847. ? ecModel.eachComponent(function (componentType, model) {
  23848. componentType !== 'series' && doPrepare(model);
  23849. })
  23850. : ecModel.eachSeries(doPrepare);
  23851. function doPrepare(model) {
  23852. // Consider: id same and type changed.
  23853. var viewId = '_ec_' + model.id + '_' + model.type;
  23854. var view = viewMap[viewId];
  23855. if (!view) {
  23856. var classType = parseClassType(model.type);
  23857. var Clazz = isComponent
  23858. ? Component.getClass(classType.main, classType.sub)
  23859. : Chart.getClass(classType.sub);
  23860. if (__DEV__) {
  23861. assert(Clazz, classType.sub + ' does not exist.');
  23862. }
  23863. view = new Clazz();
  23864. view.init(ecModel, api);
  23865. viewMap[viewId] = view;
  23866. viewList.push(view);
  23867. zr.add(view.group);
  23868. }
  23869. model.__viewId = view.__id = viewId;
  23870. view.__alive = true;
  23871. view.__model = model;
  23872. view.group.__ecComponentInfo = {
  23873. mainType: model.mainType,
  23874. index: model.componentIndex
  23875. };
  23876. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23877. }
  23878. for (var i = 0; i < viewList.length;) {
  23879. var view = viewList[i];
  23880. if (!view.__alive) {
  23881. !isComponent && view.renderTask.dispose();
  23882. zr.remove(view.group);
  23883. view.dispose(ecModel, api);
  23884. viewList.splice(i, 1);
  23885. delete viewMap[view.__id];
  23886. view.__id = view.group.__ecComponentInfo = null;
  23887. }
  23888. else {
  23889. i++;
  23890. }
  23891. }
  23892. }
  23893. // /**
  23894. // * Encode visual infomation from data after data processing
  23895. // *
  23896. // * @param {module:echarts/model/Global} ecModel
  23897. // * @param {object} layout
  23898. // * @param {boolean} [layoutFilter] `true`: only layout,
  23899. // * `false`: only not layout,
  23900. // * `null`/`undefined`: all.
  23901. // * @param {string} taskBaseTag
  23902. // * @private
  23903. // */
  23904. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23905. // each(visualFuncs, function (visual, index) {
  23906. // var isLayout = visual.isLayout;
  23907. // if (layoutFilter == null
  23908. // || (layoutFilter === false && !isLayout)
  23909. // || (layoutFilter === true && isLayout)
  23910. // ) {
  23911. // visual.func(ecModel, api, payload);
  23912. // }
  23913. // });
  23914. // }
  23915. function clearColorPalette(ecModel) {
  23916. ecModel.clearColorPalette();
  23917. ecModel.eachSeries(function (seriesModel) {
  23918. seriesModel.clearColorPalette();
  23919. });
  23920. }
  23921. function render(ecIns, ecModel, api, payload) {
  23922. renderComponents(ecIns, ecModel, api, payload);
  23923. each(ecIns._chartsViews, function (chart) {
  23924. chart.__alive = false;
  23925. });
  23926. renderSeries(ecIns, ecModel, api, payload);
  23927. // Remove groups of unrendered charts
  23928. each(ecIns._chartsViews, function (chart) {
  23929. if (!chart.__alive) {
  23930. chart.remove(ecModel, api);
  23931. }
  23932. });
  23933. }
  23934. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23935. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23936. var componentModel = componentView.__model;
  23937. componentView.render(componentModel, ecModel, api, payload);
  23938. updateZ(componentModel, componentView);
  23939. });
  23940. }
  23941. /**
  23942. * Render each chart and component
  23943. * @private
  23944. */
  23945. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23946. // Render all charts
  23947. var scheduler = ecIns._scheduler;
  23948. var unfinished;
  23949. ecModel.eachSeries(function (seriesModel) {
  23950. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23951. chartView.__alive = true;
  23952. var renderTask = chartView.renderTask;
  23953. scheduler.updatePayload(renderTask, payload);
  23954. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23955. renderTask.dirty();
  23956. }
  23957. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23958. chartView.group.silent = !!seriesModel.get('silent');
  23959. updateZ(seriesModel, chartView);
  23960. updateBlend(seriesModel, chartView);
  23961. });
  23962. scheduler.unfinished |= unfinished;
  23963. // If use hover layer
  23964. updateHoverLayerStatus(ecIns._zr, ecModel);
  23965. // Add aria
  23966. aria(ecIns._zr.dom, ecModel);
  23967. }
  23968. function performPostUpdateFuncs(ecModel, api) {
  23969. each(postUpdateFuncs, function (func) {
  23970. func(ecModel, api);
  23971. });
  23972. }
  23973. var MOUSE_EVENT_NAMES = [
  23974. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  23975. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  23976. ];
  23977. /**
  23978. * @private
  23979. */
  23980. echartsProto._initEvents = function () {
  23981. each(MOUSE_EVENT_NAMES, function (eveName) {
  23982. var handler = function (e) {
  23983. var ecModel = this.getModel();
  23984. var el = e.target;
  23985. var params;
  23986. var isGlobalOut = eveName === 'globalout';
  23987. // no e.target when 'globalout'.
  23988. if (isGlobalOut) {
  23989. params = {};
  23990. }
  23991. else if (el && el.dataIndex != null) {
  23992. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23993. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  23994. }
  23995. // If element has custom eventData of components
  23996. else if (el && el.eventData) {
  23997. params = extend({}, el.eventData);
  23998. }
  23999. // Contract: if params prepared in mouse event,
  24000. // these properties must be specified:
  24001. // {
  24002. // componentType: string (component main type)
  24003. // componentIndex: number
  24004. // }
  24005. // Otherwise event query can not work.
  24006. if (params) {
  24007. var componentType = params.componentType;
  24008. var componentIndex = params.componentIndex;
  24009. // Special handling for historic reason: when trigger by
  24010. // markLine/markPoint/markArea, the componentType is
  24011. // 'markLine'/'markPoint'/'markArea', but we should better
  24012. // enable them to be queried by seriesIndex, since their
  24013. // option is set in each series.
  24014. if (componentType === 'markLine'
  24015. || componentType === 'markPoint'
  24016. || componentType === 'markArea'
  24017. ) {
  24018. componentType = 'series';
  24019. componentIndex = params.seriesIndex;
  24020. }
  24021. var model = componentType && componentIndex != null
  24022. && ecModel.getComponent(componentType, componentIndex);
  24023. var view = model && this[
  24024. model.mainType === 'series' ? '_chartsMap' : '_componentsMap'
  24025. ][model.__viewId];
  24026. if (__DEV__) {
  24027. // `event.componentType` and `event[componentTpype + 'Index']` must not
  24028. // be missed, otherwise there is no way to distinguish source component.
  24029. // See `dataFormat.getDataParams`.
  24030. if (!isGlobalOut && !(model && view)) {
  24031. console.warn('model or view can not be found by params');
  24032. }
  24033. }
  24034. params.event = e;
  24035. params.type = eveName;
  24036. this._ecEventProcessor.eventInfo = {
  24037. targetEl: el,
  24038. packedEvent: params,
  24039. model: model,
  24040. view: view
  24041. };
  24042. this.trigger(eveName, params);
  24043. }
  24044. };
  24045. // Consider that some component (like tooltip, brush, ...)
  24046. // register zr event handler, but user event handler might
  24047. // do anything, such as call `setOption` or `dispatchAction`,
  24048. // which probably update any of the content and probably
  24049. // cause problem if it is called previous other inner handlers.
  24050. handler.zrEventfulCallAtLast = true;
  24051. this._zr.on(eveName, handler, this);
  24052. }, this);
  24053. each(eventActionMap, function (actionType, eventType) {
  24054. this._messageCenter.on(eventType, function (event) {
  24055. this.trigger(eventType, event);
  24056. }, this);
  24057. }, this);
  24058. };
  24059. /**
  24060. * @return {boolean}
  24061. */
  24062. echartsProto.isDisposed = function () {
  24063. return this._disposed;
  24064. };
  24065. /**
  24066. * Clear
  24067. */
  24068. echartsProto.clear = function () {
  24069. this.setOption({ series: [] }, true);
  24070. };
  24071. /**
  24072. * Dispose instance
  24073. */
  24074. echartsProto.dispose = function () {
  24075. if (this._disposed) {
  24076. if (__DEV__) {
  24077. console.warn('Instance ' + this.id + ' has been disposed');
  24078. }
  24079. return;
  24080. }
  24081. this._disposed = true;
  24082. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  24083. var api = this._api;
  24084. var ecModel = this._model;
  24085. each(this._componentsViews, function (component) {
  24086. component.dispose(ecModel, api);
  24087. });
  24088. each(this._chartsViews, function (chart) {
  24089. chart.dispose(ecModel, api);
  24090. });
  24091. // Dispose after all views disposed
  24092. this._zr.dispose();
  24093. delete instances[this.id];
  24094. };
  24095. mixin(ECharts, Eventful);
  24096. function updateHoverLayerStatus(zr, ecModel) {
  24097. var storage = zr.storage;
  24098. var elCount = 0;
  24099. storage.traverse(function (el) {
  24100. if (!el.isGroup) {
  24101. elCount++;
  24102. }
  24103. });
  24104. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  24105. storage.traverse(function (el) {
  24106. if (!el.isGroup) {
  24107. // Don't switch back.
  24108. el.useHoverLayer = true;
  24109. }
  24110. });
  24111. }
  24112. }
  24113. /**
  24114. * Update chart progressive and blend.
  24115. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24116. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24117. */
  24118. function updateBlend(seriesModel, chartView) {
  24119. var blendMode = seriesModel.get('blendMode') || null;
  24120. if (__DEV__) {
  24121. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  24122. console.warn('Only canvas support blendMode');
  24123. }
  24124. }
  24125. chartView.group.traverse(function (el) {
  24126. // FIXME marker and other components
  24127. if (!el.isGroup) {
  24128. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  24129. if (el.style.blend !== blendMode) {
  24130. el.setStyle('blend', blendMode);
  24131. }
  24132. }
  24133. if (el.eachPendingDisplayable) {
  24134. el.eachPendingDisplayable(function (displayable) {
  24135. displayable.setStyle('blend', blendMode);
  24136. });
  24137. }
  24138. });
  24139. }
  24140. /**
  24141. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  24142. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  24143. */
  24144. function updateZ(model, view) {
  24145. var z = model.get('z');
  24146. var zlevel = model.get('zlevel');
  24147. // Set z and zlevel
  24148. view.group.traverse(function (el) {
  24149. if (el.type !== 'group') {
  24150. z != null && (el.z = z);
  24151. zlevel != null && (el.zlevel = zlevel);
  24152. }
  24153. });
  24154. }
  24155. function createExtensionAPI(ecInstance) {
  24156. var coordSysMgr = ecInstance._coordSysMgr;
  24157. return extend(new ExtensionAPI(ecInstance), {
  24158. // Inject methods
  24159. getCoordinateSystems: bind(
  24160. coordSysMgr.getCoordinateSystems, coordSysMgr
  24161. ),
  24162. getComponentByElement: function (el) {
  24163. while (el) {
  24164. var modelInfo = el.__ecComponentInfo;
  24165. if (modelInfo != null) {
  24166. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  24167. }
  24168. el = el.parent;
  24169. }
  24170. }
  24171. });
  24172. }
  24173. /**
  24174. * @class
  24175. * Usage of query:
  24176. * `chart.on('click', query, handler);`
  24177. * The `query` can be:
  24178. * + The component type query string, only `mainType` or `mainType.subType`,
  24179. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  24180. * + The component query object, like:
  24181. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  24182. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  24183. * + The data query object, like:
  24184. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  24185. * + The other query object (cmponent customized query), like:
  24186. * `{element: 'some'}` (only available in custom series).
  24187. *
  24188. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  24189. * same as there is no such prop in the `query` object.
  24190. */
  24191. function EventProcessor() {
  24192. // These info required: targetEl, packedEvent, model, view
  24193. this.eventInfo;
  24194. }
  24195. EventProcessor.prototype = {
  24196. constructor: EventProcessor,
  24197. normalizeQuery: function (query) {
  24198. var cptQuery = {};
  24199. var dataQuery = {};
  24200. var otherQuery = {};
  24201. // `query` is `mainType` or `mainType.subType` of component.
  24202. if (isString(query)) {
  24203. var condCptType = parseClassType(query);
  24204. // `.main` and `.sub` may be ''.
  24205. cptQuery.mainType = condCptType.main || null;
  24206. cptQuery.subType = condCptType.sub || null;
  24207. }
  24208. // `query` is an object, convert to {mainType, index, name, id}.
  24209. else {
  24210. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  24211. // can not be used in `compomentModel.filterForExposedEvent`.
  24212. var suffixes = ['Index', 'Name', 'Id'];
  24213. var dataKeys = {name: 1, dataIndex: 1, dataType: 1};
  24214. each$1(query, function (val, key) {
  24215. var reserved = false;
  24216. for (var i = 0; i < suffixes.length; i++) {
  24217. var propSuffix = suffixes[i];
  24218. var suffixPos = key.lastIndexOf(propSuffix);
  24219. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  24220. var mainType = key.slice(0, suffixPos);
  24221. // Consider `dataIndex`.
  24222. if (mainType !== 'data') {
  24223. cptQuery.mainType = mainType;
  24224. cptQuery[propSuffix.toLowerCase()] = val;
  24225. reserved = true;
  24226. }
  24227. }
  24228. }
  24229. if (dataKeys.hasOwnProperty(key)) {
  24230. dataQuery[key] = val;
  24231. reserved = true;
  24232. }
  24233. if (!reserved) {
  24234. otherQuery[key] = val;
  24235. }
  24236. });
  24237. }
  24238. return {
  24239. cptQuery: cptQuery,
  24240. dataQuery: dataQuery,
  24241. otherQuery: otherQuery
  24242. };
  24243. },
  24244. filter: function (eventType, query, args) {
  24245. // They should be assigned before each trigger call.
  24246. var eventInfo = this.eventInfo;
  24247. if (!eventInfo) {
  24248. return true;
  24249. }
  24250. var targetEl = eventInfo.targetEl;
  24251. var packedEvent = eventInfo.packedEvent;
  24252. var model = eventInfo.model;
  24253. var view = eventInfo.view;
  24254. // For event like 'globalout'.
  24255. if (!model || !view) {
  24256. return true;
  24257. }
  24258. var cptQuery = query.cptQuery;
  24259. var dataQuery = query.dataQuery;
  24260. return check(cptQuery, model, 'mainType')
  24261. && check(cptQuery, model, 'subType')
  24262. && check(cptQuery, model, 'index', 'componentIndex')
  24263. && check(cptQuery, model, 'name')
  24264. && check(cptQuery, model, 'id')
  24265. && check(dataQuery, packedEvent, 'name')
  24266. && check(dataQuery, packedEvent, 'dataIndex')
  24267. && check(dataQuery, packedEvent, 'dataType')
  24268. && (!view.filterForExposedEvent || view.filterForExposedEvent(
  24269. eventType, query.otherQuery, targetEl, packedEvent
  24270. ));
  24271. function check(query, host, prop, propOnHost) {
  24272. return query[prop] == null || host[propOnHost || prop] === query[prop];
  24273. }
  24274. },
  24275. afterTrigger: function () {
  24276. // Make sure the eventInfo wont be used in next trigger.
  24277. this.eventInfo = null;
  24278. }
  24279. };
  24280. /**
  24281. * @type {Object} key: actionType.
  24282. * @inner
  24283. */
  24284. var actions = {};
  24285. /**
  24286. * Map eventType to actionType
  24287. * @type {Object}
  24288. */
  24289. var eventActionMap = {};
  24290. /**
  24291. * Data processor functions of each stage
  24292. * @type {Array.<Object.<string, Function>>}
  24293. * @inner
  24294. */
  24295. var dataProcessorFuncs = [];
  24296. /**
  24297. * @type {Array.<Function>}
  24298. * @inner
  24299. */
  24300. var optionPreprocessorFuncs = [];
  24301. /**
  24302. * @type {Array.<Function>}
  24303. * @inner
  24304. */
  24305. var postUpdateFuncs = [];
  24306. /**
  24307. * Visual encoding functions of each stage
  24308. * @type {Array.<Object.<string, Function>>}
  24309. */
  24310. var visualFuncs = [];
  24311. /**
  24312. * Theme storage
  24313. * @type {Object.<key, Object>}
  24314. */
  24315. var themeStorage = {};
  24316. /**
  24317. * Loading effects
  24318. */
  24319. var loadingEffects = {};
  24320. var instances = {};
  24321. var connectedGroups = {};
  24322. var idBase = new Date() - 0;
  24323. var groupIdBase = new Date() - 0;
  24324. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  24325. function enableConnect(chart) {
  24326. var STATUS_PENDING = 0;
  24327. var STATUS_UPDATING = 1;
  24328. var STATUS_UPDATED = 2;
  24329. var STATUS_KEY = '__connectUpdateStatus';
  24330. function updateConnectedChartsStatus(charts, status) {
  24331. for (var i = 0; i < charts.length; i++) {
  24332. var otherChart = charts[i];
  24333. otherChart[STATUS_KEY] = status;
  24334. }
  24335. }
  24336. each(eventActionMap, function (actionType, eventType) {
  24337. chart._messageCenter.on(eventType, function (event) {
  24338. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  24339. if (event && event.escapeConnect) {
  24340. return;
  24341. }
  24342. var action = chart.makeActionFromEvent(event);
  24343. var otherCharts = [];
  24344. each(instances, function (otherChart) {
  24345. if (otherChart !== chart && otherChart.group === chart.group) {
  24346. otherCharts.push(otherChart);
  24347. }
  24348. });
  24349. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  24350. each(otherCharts, function (otherChart) {
  24351. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  24352. otherChart.dispatchAction(action);
  24353. }
  24354. });
  24355. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  24356. }
  24357. });
  24358. });
  24359. }
  24360. /**
  24361. * @param {HTMLElement} dom
  24362. * @param {Object} [theme]
  24363. * @param {Object} opts
  24364. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  24365. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  24366. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  24367. * Can be 'auto' (the same as null/undefined)
  24368. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  24369. * Can be 'auto' (the same as null/undefined)
  24370. */
  24371. function init(dom, theme$$1, opts) {
  24372. if (__DEV__) {
  24373. // Check version
  24374. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  24375. throw new Error(
  24376. 'zrender/src ' + version$1
  24377. + ' is too old for ECharts ' + version
  24378. + '. Current version need ZRender '
  24379. + dependencies.zrender + '+'
  24380. );
  24381. }
  24382. if (!dom) {
  24383. throw new Error('Initialize failed: invalid dom.');
  24384. }
  24385. }
  24386. var existInstance = getInstanceByDom(dom);
  24387. if (existInstance) {
  24388. if (__DEV__) {
  24389. console.warn('There is a chart instance already initialized on the dom.');
  24390. }
  24391. return existInstance;
  24392. }
  24393. if (__DEV__) {
  24394. if (isDom(dom)
  24395. && dom.nodeName.toUpperCase() !== 'CANVAS'
  24396. && (
  24397. (!dom.clientWidth && (!opts || opts.width == null))
  24398. || (!dom.clientHeight && (!opts || opts.height == null))
  24399. )
  24400. ) {
  24401. console.warn('Can\'t get dom width or height');
  24402. }
  24403. }
  24404. var chart = new ECharts(dom, theme$$1, opts);
  24405. chart.id = 'ec_' + idBase++;
  24406. instances[chart.id] = chart;
  24407. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  24408. enableConnect(chart);
  24409. return chart;
  24410. }
  24411. /**
  24412. * @return {string|Array.<module:echarts~ECharts>} groupId
  24413. */
  24414. function connect(groupId) {
  24415. // Is array of charts
  24416. if (isArray(groupId)) {
  24417. var charts = groupId;
  24418. groupId = null;
  24419. // If any chart has group
  24420. each(charts, function (chart) {
  24421. if (chart.group != null) {
  24422. groupId = chart.group;
  24423. }
  24424. });
  24425. groupId = groupId || ('g_' + groupIdBase++);
  24426. each(charts, function (chart) {
  24427. chart.group = groupId;
  24428. });
  24429. }
  24430. connectedGroups[groupId] = true;
  24431. return groupId;
  24432. }
  24433. /**
  24434. * @DEPRECATED
  24435. * @return {string} groupId
  24436. */
  24437. function disConnect(groupId) {
  24438. connectedGroups[groupId] = false;
  24439. }
  24440. /**
  24441. * @return {string} groupId
  24442. */
  24443. var disconnect = disConnect;
  24444. /**
  24445. * Dispose a chart instance
  24446. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  24447. */
  24448. function dispose(chart) {
  24449. if (typeof chart === 'string') {
  24450. chart = instances[chart];
  24451. }
  24452. else if (!(chart instanceof ECharts)) {
  24453. // Try to treat as dom
  24454. chart = getInstanceByDom(chart);
  24455. }
  24456. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  24457. chart.dispose();
  24458. }
  24459. }
  24460. /**
  24461. * @param {HTMLElement} dom
  24462. * @return {echarts~ECharts}
  24463. */
  24464. function getInstanceByDom(dom) {
  24465. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  24466. }
  24467. /**
  24468. * @param {string} key
  24469. * @return {echarts~ECharts}
  24470. */
  24471. function getInstanceById(key) {
  24472. return instances[key];
  24473. }
  24474. /**
  24475. * Register theme
  24476. */
  24477. function registerTheme(name, theme$$1) {
  24478. themeStorage[name] = theme$$1;
  24479. }
  24480. /**
  24481. * Register option preprocessor
  24482. * @param {Function} preprocessorFunc
  24483. */
  24484. function registerPreprocessor(preprocessorFunc) {
  24485. optionPreprocessorFuncs.push(preprocessorFunc);
  24486. }
  24487. /**
  24488. * @param {number} [priority=1000]
  24489. * @param {Object|Function} processor
  24490. */
  24491. function registerProcessor(priority, processor) {
  24492. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  24493. }
  24494. /**
  24495. * Register postUpdater
  24496. * @param {Function} postUpdateFunc
  24497. */
  24498. function registerPostUpdate(postUpdateFunc) {
  24499. postUpdateFuncs.push(postUpdateFunc);
  24500. }
  24501. /**
  24502. * Usage:
  24503. * registerAction('someAction', 'someEvent', function () { ... });
  24504. * registerAction('someAction', function () { ... });
  24505. * registerAction(
  24506. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  24507. * function () { ... }
  24508. * );
  24509. *
  24510. * @param {(string|Object)} actionInfo
  24511. * @param {string} actionInfo.type
  24512. * @param {string} [actionInfo.event]
  24513. * @param {string} [actionInfo.update]
  24514. * @param {string} [eventName]
  24515. * @param {Function} action
  24516. */
  24517. function registerAction(actionInfo, eventName, action) {
  24518. if (typeof eventName === 'function') {
  24519. action = eventName;
  24520. eventName = '';
  24521. }
  24522. var actionType = isObject(actionInfo)
  24523. ? actionInfo.type
  24524. : ([actionInfo, actionInfo = {
  24525. event: eventName
  24526. }][0]);
  24527. // Event name is all lowercase
  24528. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  24529. eventName = actionInfo.event;
  24530. // Validate action type and event name.
  24531. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  24532. if (!actions[actionType]) {
  24533. actions[actionType] = {action: action, actionInfo: actionInfo};
  24534. }
  24535. eventActionMap[eventName] = actionType;
  24536. }
  24537. /**
  24538. * @param {string} type
  24539. * @param {*} CoordinateSystem
  24540. */
  24541. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  24542. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  24543. }
  24544. /**
  24545. * Get dimensions of specified coordinate system.
  24546. * @param {string} type
  24547. * @return {Array.<string|Object>}
  24548. */
  24549. function getCoordinateSystemDimensions(type) {
  24550. var coordSysCreator = CoordinateSystemManager.get(type);
  24551. if (coordSysCreator) {
  24552. return coordSysCreator.getDimensionsInfo
  24553. ? coordSysCreator.getDimensionsInfo()
  24554. : coordSysCreator.dimensions.slice();
  24555. }
  24556. }
  24557. /**
  24558. * Layout is a special stage of visual encoding
  24559. * Most visual encoding like color are common for different chart
  24560. * But each chart has it's own layout algorithm
  24561. *
  24562. * @param {number} [priority=1000]
  24563. * @param {Function} layoutTask
  24564. */
  24565. function registerLayout(priority, layoutTask) {
  24566. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  24567. }
  24568. /**
  24569. * @param {number} [priority=3000]
  24570. * @param {module:echarts/stream/Task} visualTask
  24571. */
  24572. function registerVisual(priority, visualTask) {
  24573. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  24574. }
  24575. /**
  24576. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  24577. */
  24578. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  24579. if (isFunction(priority) || isObject(priority)) {
  24580. fn = priority;
  24581. priority = defaultPriority;
  24582. }
  24583. if (__DEV__) {
  24584. if (isNaN(priority) || priority == null) {
  24585. throw new Error('Illegal priority');
  24586. }
  24587. // Check duplicate
  24588. each(targetList, function (wrap) {
  24589. assert(wrap.__raw !== fn);
  24590. });
  24591. }
  24592. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  24593. stageHandler.__prio = priority;
  24594. stageHandler.__raw = fn;
  24595. targetList.push(stageHandler);
  24596. return stageHandler;
  24597. }
  24598. /**
  24599. * @param {string} name
  24600. */
  24601. function registerLoading(name, loadingFx) {
  24602. loadingEffects[name] = loadingFx;
  24603. }
  24604. /**
  24605. * @param {Object} opts
  24606. * @param {string} [superClass]
  24607. */
  24608. function extendComponentModel(opts/*, superClass*/) {
  24609. // var Clazz = ComponentModel;
  24610. // if (superClass) {
  24611. // var classType = parseClassType(superClass);
  24612. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24613. // }
  24614. return ComponentModel.extend(opts);
  24615. }
  24616. /**
  24617. * @param {Object} opts
  24618. * @param {string} [superClass]
  24619. */
  24620. function extendComponentView(opts/*, superClass*/) {
  24621. // var Clazz = ComponentView;
  24622. // if (superClass) {
  24623. // var classType = parseClassType(superClass);
  24624. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  24625. // }
  24626. return Component.extend(opts);
  24627. }
  24628. /**
  24629. * @param {Object} opts
  24630. * @param {string} [superClass]
  24631. */
  24632. function extendSeriesModel(opts/*, superClass*/) {
  24633. // var Clazz = SeriesModel;
  24634. // if (superClass) {
  24635. // superClass = 'series.' + superClass.replace('series.', '');
  24636. // var classType = parseClassType(superClass);
  24637. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24638. // }
  24639. return SeriesModel.extend(opts);
  24640. }
  24641. /**
  24642. * @param {Object} opts
  24643. * @param {string} [superClass]
  24644. */
  24645. function extendChartView(opts/*, superClass*/) {
  24646. // var Clazz = ChartView;
  24647. // if (superClass) {
  24648. // superClass = superClass.replace('series.', '');
  24649. // var classType = parseClassType(superClass);
  24650. // Clazz = ChartView.getClass(classType.main, true);
  24651. // }
  24652. return Chart.extend(opts);
  24653. }
  24654. /**
  24655. * ZRender need a canvas context to do measureText.
  24656. * But in node environment canvas may be created by node-canvas.
  24657. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  24658. *
  24659. * Be careful of using it in the browser.
  24660. *
  24661. * @param {Function} creator
  24662. * @example
  24663. * var Canvas = require('canvas');
  24664. * var echarts = require('echarts');
  24665. * echarts.setCanvasCreator(function () {
  24666. * // Small size is enough.
  24667. * return new Canvas(32, 32);
  24668. * });
  24669. */
  24670. function setCanvasCreator(creator) {
  24671. $override('createCanvas', creator);
  24672. }
  24673. /**
  24674. * @param {string} mapName
  24675. * @param {Array.<Object>|Object|string} geoJson
  24676. * @param {Object} [specialAreas]
  24677. *
  24678. * @example GeoJSON
  24679. * $.get('USA.json', function (geoJson) {
  24680. * echarts.registerMap('USA', geoJson);
  24681. * // Or
  24682. * echarts.registerMap('USA', {
  24683. * geoJson: geoJson,
  24684. * specialAreas: {}
  24685. * })
  24686. * });
  24687. *
  24688. * $.get('airport.svg', function (svg) {
  24689. * echarts.registerMap('airport', {
  24690. * svg: svg
  24691. * }
  24692. * });
  24693. *
  24694. * echarts.registerMap('eu', [
  24695. * {svg: eu-topographic.svg},
  24696. * {geoJSON: eu.json}
  24697. * ])
  24698. */
  24699. function registerMap(mapName, geoJson, specialAreas) {
  24700. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  24701. }
  24702. /**
  24703. * @param {string} mapName
  24704. * @return {Object}
  24705. */
  24706. function getMap(mapName) {
  24707. // For backward compatibility, only return the first one.
  24708. var records = mapDataStorage.retrieveMap(mapName);
  24709. return records && records[0] && {
  24710. geoJson: records[0].geoJSON,
  24711. specialAreas: records[0].specialAreas
  24712. };
  24713. }
  24714. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  24715. registerPreprocessor(backwardCompat);
  24716. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  24717. registerLoading('default', loadingDefault);
  24718. // Default actions
  24719. registerAction({
  24720. type: 'highlight',
  24721. event: 'highlight',
  24722. update: 'highlight'
  24723. }, noop);
  24724. registerAction({
  24725. type: 'downplay',
  24726. event: 'downplay',
  24727. update: 'downplay'
  24728. }, noop);
  24729. // Default theme
  24730. registerTheme('light', lightTheme);
  24731. registerTheme('dark', theme);
  24732. // For backward compatibility, where the namespace `dataTool` will
  24733. // be mounted on `echarts` is the extension `dataTool` is imported.
  24734. var dataTool = {};
  24735. /*
  24736. * Licensed to the Apache Software Foundation (ASF) under one
  24737. * or more contributor license agreements. See the NOTICE file
  24738. * distributed with this work for additional information
  24739. * regarding copyright ownership. The ASF licenses this file
  24740. * to you under the Apache License, Version 2.0 (the
  24741. * "License"); you may not use this file except in compliance
  24742. * with the License. You may obtain a copy of the License at
  24743. *
  24744. * http://www.apache.org/licenses/LICENSE-2.0
  24745. *
  24746. * Unless required by applicable law or agreed to in writing,
  24747. * software distributed under the License is distributed on an
  24748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24749. * KIND, either express or implied. See the License for the
  24750. * specific language governing permissions and limitations
  24751. * under the License.
  24752. */
  24753. function defaultKeyGetter(item) {
  24754. return item;
  24755. }
  24756. /**
  24757. * @param {Array} oldArr
  24758. * @param {Array} newArr
  24759. * @param {Function} oldKeyGetter
  24760. * @param {Function} newKeyGetter
  24761. * @param {Object} [context] Can be visited by this.context in callback.
  24762. */
  24763. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  24764. this._old = oldArr;
  24765. this._new = newArr;
  24766. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  24767. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  24768. this.context = context;
  24769. }
  24770. DataDiffer.prototype = {
  24771. constructor: DataDiffer,
  24772. /**
  24773. * Callback function when add a data
  24774. */
  24775. add: function (func) {
  24776. this._add = func;
  24777. return this;
  24778. },
  24779. /**
  24780. * Callback function when update a data
  24781. */
  24782. update: function (func) {
  24783. this._update = func;
  24784. return this;
  24785. },
  24786. /**
  24787. * Callback function when remove a data
  24788. */
  24789. remove: function (func) {
  24790. this._remove = func;
  24791. return this;
  24792. },
  24793. execute: function () {
  24794. var oldArr = this._old;
  24795. var newArr = this._new;
  24796. var oldDataIndexMap = {};
  24797. var newDataIndexMap = {};
  24798. var oldDataKeyArr = [];
  24799. var newDataKeyArr = [];
  24800. var i;
  24801. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  24802. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  24803. // Travel by inverted order to make sure order consistency
  24804. // when duplicate keys exists (consider newDataIndex.pop() below).
  24805. // For performance consideration, these code below do not look neat.
  24806. for (i = 0; i < oldArr.length; i++) {
  24807. var key = oldDataKeyArr[i];
  24808. var idx = newDataIndexMap[key];
  24809. // idx can never be empty array here. see 'set null' logic below.
  24810. if (idx != null) {
  24811. // Consider there is duplicate key (for example, use dataItem.name as key).
  24812. // We should make sure every item in newArr and oldArr can be visited.
  24813. var len = idx.length;
  24814. if (len) {
  24815. len === 1 && (newDataIndexMap[key] = null);
  24816. idx = idx.unshift();
  24817. }
  24818. else {
  24819. newDataIndexMap[key] = null;
  24820. }
  24821. this._update && this._update(idx, i);
  24822. }
  24823. else {
  24824. this._remove && this._remove(i);
  24825. }
  24826. }
  24827. for (var i = 0; i < newDataKeyArr.length; i++) {
  24828. var key = newDataKeyArr[i];
  24829. if (newDataIndexMap.hasOwnProperty(key)) {
  24830. var idx = newDataIndexMap[key];
  24831. if (idx == null) {
  24832. continue;
  24833. }
  24834. // idx can never be empty array here. see 'set null' logic above.
  24835. if (!idx.length) {
  24836. this._add && this._add(idx);
  24837. }
  24838. else {
  24839. for (var j = 0, len = idx.length; j < len; j++) {
  24840. this._add && this._add(idx[j]);
  24841. }
  24842. }
  24843. }
  24844. }
  24845. }
  24846. };
  24847. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  24848. for (var i = 0; i < arr.length; i++) {
  24849. // Add prefix to avoid conflict with Object.prototype.
  24850. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  24851. var existence = map[key];
  24852. if (existence == null) {
  24853. keyArr.push(key);
  24854. map[key] = i;
  24855. }
  24856. else {
  24857. if (!existence.length) {
  24858. map[key] = existence = [existence];
  24859. }
  24860. existence.push(i);
  24861. }
  24862. }
  24863. }
  24864. /*
  24865. * Licensed to the Apache Software Foundation (ASF) under one
  24866. * or more contributor license agreements. See the NOTICE file
  24867. * distributed with this work for additional information
  24868. * regarding copyright ownership. The ASF licenses this file
  24869. * to you under the Apache License, Version 2.0 (the
  24870. * "License"); you may not use this file except in compliance
  24871. * with the License. You may obtain a copy of the License at
  24872. *
  24873. * http://www.apache.org/licenses/LICENSE-2.0
  24874. *
  24875. * Unless required by applicable law or agreed to in writing,
  24876. * software distributed under the License is distributed on an
  24877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24878. * KIND, either express or implied. See the License for the
  24879. * specific language governing permissions and limitations
  24880. * under the License.
  24881. */
  24882. var OTHER_DIMENSIONS = createHashMap([
  24883. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  24884. ]);
  24885. function summarizeDimensions(data) {
  24886. var summary = {};
  24887. var encode = summary.encode = {};
  24888. var notExtraCoordDimMap = createHashMap();
  24889. var defaultedLabel = [];
  24890. var defaultedTooltip = [];
  24891. each$1(data.dimensions, function (dimName) {
  24892. var dimItem = data.getDimensionInfo(dimName);
  24893. var coordDim = dimItem.coordDim;
  24894. if (coordDim) {
  24895. if (__DEV__) {
  24896. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  24897. }
  24898. var coordDimArr = encode[coordDim];
  24899. if (!encode.hasOwnProperty(coordDim)) {
  24900. coordDimArr = encode[coordDim] = [];
  24901. }
  24902. coordDimArr[dimItem.coordDimIndex] = dimName;
  24903. if (!dimItem.isExtraCoord) {
  24904. notExtraCoordDimMap.set(coordDim, 1);
  24905. // Use the last coord dim (and label friendly) as default label,
  24906. // because when dataset is used, it is hard to guess which dimension
  24907. // can be value dimension. If both show x, y on label is not look good,
  24908. // and conventionally y axis is focused more.
  24909. if (mayLabelDimType(dimItem.type)) {
  24910. defaultedLabel[0] = dimName;
  24911. }
  24912. }
  24913. if (dimItem.defaultTooltip) {
  24914. defaultedTooltip.push(dimName);
  24915. }
  24916. }
  24917. OTHER_DIMENSIONS.each(function (v, otherDim) {
  24918. var otherDimArr = encode[otherDim];
  24919. if (!encode.hasOwnProperty(otherDim)) {
  24920. otherDimArr = encode[otherDim] = [];
  24921. }
  24922. var dimIndex = dimItem.otherDims[otherDim];
  24923. if (dimIndex != null && dimIndex !== false) {
  24924. otherDimArr[dimIndex] = dimItem.name;
  24925. }
  24926. });
  24927. });
  24928. var dataDimsOnCoord = [];
  24929. var encodeFirstDimNotExtra = {};
  24930. notExtraCoordDimMap.each(function (v, coordDim) {
  24931. var dimArr = encode[coordDim];
  24932. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  24933. // But should fix the case that radar axes: simplify the logic
  24934. // of `completeDimension`, remove `extraPrefix`.
  24935. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  24936. // Not necessary to remove duplicate, because a data
  24937. // dim canot on more than one coordDim.
  24938. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  24939. });
  24940. summary.dataDimsOnCoord = dataDimsOnCoord;
  24941. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  24942. var encodeLabel = encode.label;
  24943. // FIXME `encode.label` is not recommanded, because formatter can not be set
  24944. // in this way. Use label.formatter instead. May be remove this approach someday.
  24945. if (encodeLabel && encodeLabel.length) {
  24946. defaultedLabel = encodeLabel.slice();
  24947. }
  24948. var encodeTooltip = encode.tooltip;
  24949. if (encodeTooltip && encodeTooltip.length) {
  24950. defaultedTooltip = encodeTooltip.slice();
  24951. }
  24952. else if (!defaultedTooltip.length) {
  24953. defaultedTooltip = defaultedLabel.slice();
  24954. }
  24955. encode.defaultedLabel = defaultedLabel;
  24956. encode.defaultedTooltip = defaultedTooltip;
  24957. return summary;
  24958. }
  24959. function getDimensionTypeByAxis(axisType) {
  24960. return axisType === 'category'
  24961. ? 'ordinal'
  24962. : axisType === 'time'
  24963. ? 'time'
  24964. : 'float';
  24965. }
  24966. function mayLabelDimType(dimType) {
  24967. // In most cases, ordinal and time do not suitable for label.
  24968. // Ordinal info can be displayed on axis. Time is too long.
  24969. return !(dimType === 'ordinal' || dimType === 'time');
  24970. }
  24971. // function findTheLastDimMayLabel(data) {
  24972. // // Get last value dim
  24973. // var dimensions = data.dimensions.slice();
  24974. // var valueType;
  24975. // var valueDim;
  24976. // while (dimensions.length && (
  24977. // valueDim = dimensions.pop(),
  24978. // valueType = data.getDimensionInfo(valueDim).type,
  24979. // valueType === 'ordinal' || valueType === 'time'
  24980. // )) {} // jshint ignore:line
  24981. // return valueDim;
  24982. // }
  24983. /*
  24984. * Licensed to the Apache Software Foundation (ASF) under one
  24985. * or more contributor license agreements. See the NOTICE file
  24986. * distributed with this work for additional information
  24987. * regarding copyright ownership. The ASF licenses this file
  24988. * to you under the Apache License, Version 2.0 (the
  24989. * "License"); you may not use this file except in compliance
  24990. * with the License. You may obtain a copy of the License at
  24991. *
  24992. * http://www.apache.org/licenses/LICENSE-2.0
  24993. *
  24994. * Unless required by applicable law or agreed to in writing,
  24995. * software distributed under the License is distributed on an
  24996. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24997. * KIND, either express or implied. See the License for the
  24998. * specific language governing permissions and limitations
  24999. * under the License.
  25000. */
  25001. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  25002. /**
  25003. * List for data storage
  25004. * @module echarts/data/List
  25005. */
  25006. var isObject$4 = isObject$1;
  25007. var UNDEFINED = 'undefined';
  25008. var INDEX_NOT_FOUND = -1;
  25009. // Use prefix to avoid index to be the same as otherIdList[idx],
  25010. // which will cause weird udpate animation.
  25011. var ID_PREFIX = 'e\0\0';
  25012. var dataCtors = {
  25013. 'float': typeof Float64Array === UNDEFINED
  25014. ? Array : Float64Array,
  25015. 'int': typeof Int32Array === UNDEFINED
  25016. ? Array : Int32Array,
  25017. // Ordinal data type can be string or int
  25018. 'ordinal': Array,
  25019. 'number': Array,
  25020. 'time': Array
  25021. };
  25022. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  25023. // different from the Ctor of typed array.
  25024. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  25025. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  25026. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  25027. function getIndicesCtor(list) {
  25028. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  25029. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  25030. }
  25031. function cloneChunk(originalChunk) {
  25032. var Ctor = originalChunk.constructor;
  25033. // Only shallow clone is enough when Array.
  25034. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  25035. }
  25036. var TRANSFERABLE_PROPERTIES = [
  25037. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  25038. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  25039. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  25040. ];
  25041. var CLONE_PROPERTIES = [
  25042. '_extent', '_approximateExtent', '_rawExtent'
  25043. ];
  25044. function transferProperties(target, source) {
  25045. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  25046. if (source.hasOwnProperty(propName)) {
  25047. target[propName] = source[propName];
  25048. }
  25049. });
  25050. target.__wrappedMethods = source.__wrappedMethods;
  25051. each$1(CLONE_PROPERTIES, function (propName) {
  25052. target[propName] = clone(source[propName]);
  25053. });
  25054. target._calculationInfo = extend(source._calculationInfo);
  25055. }
  25056. /**
  25057. * @constructor
  25058. * @alias module:echarts/data/List
  25059. *
  25060. * @param {Array.<string|Object>} dimensions
  25061. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  25062. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  25063. * Spetial fields: {
  25064. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  25065. * createInvertedIndices: <boolean>
  25066. * }
  25067. * @param {module:echarts/model/Model} hostModel
  25068. */
  25069. var List = function (dimensions, hostModel) {
  25070. dimensions = dimensions || ['x', 'y'];
  25071. var dimensionInfos = {};
  25072. var dimensionNames = [];
  25073. var invertedIndicesMap = {};
  25074. for (var i = 0; i < dimensions.length; i++) {
  25075. // Use the original dimensions[i], where other flag props may exists.
  25076. var dimensionInfo = dimensions[i];
  25077. if (isString(dimensionInfo)) {
  25078. dimensionInfo = {name: dimensionInfo};
  25079. }
  25080. var dimensionName = dimensionInfo.name;
  25081. dimensionInfo.type = dimensionInfo.type || 'float';
  25082. if (!dimensionInfo.coordDim) {
  25083. dimensionInfo.coordDim = dimensionName;
  25084. dimensionInfo.coordDimIndex = 0;
  25085. }
  25086. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  25087. dimensionNames.push(dimensionName);
  25088. dimensionInfos[dimensionName] = dimensionInfo;
  25089. dimensionInfo.index = i;
  25090. if (dimensionInfo.createInvertedIndices) {
  25091. invertedIndicesMap[dimensionName] = [];
  25092. }
  25093. }
  25094. /**
  25095. * @readOnly
  25096. * @type {Array.<string>}
  25097. */
  25098. this.dimensions = dimensionNames;
  25099. /**
  25100. * Infomation of each data dimension, like data type.
  25101. * @type {Object}
  25102. */
  25103. this._dimensionInfos = dimensionInfos;
  25104. /**
  25105. * @type {module:echarts/model/Model}
  25106. */
  25107. this.hostModel = hostModel;
  25108. /**
  25109. * @type {module:echarts/model/Model}
  25110. */
  25111. this.dataType;
  25112. /**
  25113. * Indices stores the indices of data subset after filtered.
  25114. * This data subset will be used in chart.
  25115. * @type {Array.<number>}
  25116. * @readOnly
  25117. */
  25118. this._indices = null;
  25119. this._count = 0;
  25120. this._rawCount = 0;
  25121. /**
  25122. * Data storage
  25123. * @type {Object.<key, Array.<TypedArray|Array>>}
  25124. * @private
  25125. */
  25126. this._storage = {};
  25127. /**
  25128. * @type {Array.<string>}
  25129. */
  25130. this._nameList = [];
  25131. /**
  25132. * @type {Array.<string>}
  25133. */
  25134. this._idList = [];
  25135. /**
  25136. * Models of data option is stored sparse for optimizing memory cost
  25137. * @type {Array.<module:echarts/model/Model>}
  25138. * @private
  25139. */
  25140. this._optionModels = [];
  25141. /**
  25142. * Global visual properties after visual coding
  25143. * @type {Object}
  25144. * @private
  25145. */
  25146. this._visual = {};
  25147. /**
  25148. * Globel layout properties.
  25149. * @type {Object}
  25150. * @private
  25151. */
  25152. this._layout = {};
  25153. /**
  25154. * Item visual properties after visual coding
  25155. * @type {Array.<Object>}
  25156. * @private
  25157. */
  25158. this._itemVisuals = [];
  25159. /**
  25160. * Key: visual type, Value: boolean
  25161. * @type {Object}
  25162. * @readOnly
  25163. */
  25164. this.hasItemVisual = {};
  25165. /**
  25166. * Item layout properties after layout
  25167. * @type {Array.<Object>}
  25168. * @private
  25169. */
  25170. this._itemLayouts = [];
  25171. /**
  25172. * Graphic elemnents
  25173. * @type {Array.<module:zrender/Element>}
  25174. * @private
  25175. */
  25176. this._graphicEls = [];
  25177. /**
  25178. * Max size of each chunk.
  25179. * @type {number}
  25180. * @private
  25181. */
  25182. this._chunkSize = 1e5;
  25183. /**
  25184. * @type {number}
  25185. * @private
  25186. */
  25187. this._chunkCount = 0;
  25188. /**
  25189. * @type {Array.<Array|Object>}
  25190. * @private
  25191. */
  25192. this._rawData;
  25193. /**
  25194. * Raw extent will not be cloned, but only transfered.
  25195. * It will not be calculated util needed.
  25196. * key: dim,
  25197. * value: {end: number, extent: Array.<number>}
  25198. * @type {Object}
  25199. * @private
  25200. */
  25201. this._rawExtent = {};
  25202. /**
  25203. * @type {Object}
  25204. * @private
  25205. */
  25206. this._extent = {};
  25207. /**
  25208. * key: dim
  25209. * value: extent
  25210. * @type {Object}
  25211. * @private
  25212. */
  25213. this._approximateExtent = {};
  25214. /**
  25215. * Cache summary info for fast visit. See "dimensionHelper".
  25216. * @type {Object}
  25217. * @private
  25218. */
  25219. this._dimensionsSummary = summarizeDimensions(this);
  25220. /**
  25221. * @type {Object.<Array|TypedArray>}
  25222. * @private
  25223. */
  25224. this._invertedIndicesMap = invertedIndicesMap;
  25225. /**
  25226. * @type {Object}
  25227. * @private
  25228. */
  25229. this._calculationInfo = {};
  25230. };
  25231. var listProto = List.prototype;
  25232. listProto.type = 'list';
  25233. /**
  25234. * If each data item has it's own option
  25235. * @type {boolean}
  25236. */
  25237. listProto.hasItemOption = true;
  25238. /**
  25239. * Get dimension name
  25240. * @param {string|number} dim
  25241. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25242. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25243. * @return {string} Concrete dim name.
  25244. */
  25245. listProto.getDimension = function (dim) {
  25246. if (!isNaN(dim)) {
  25247. dim = this.dimensions[dim] || dim;
  25248. }
  25249. return dim;
  25250. };
  25251. /**
  25252. * Get type and calculation info of particular dimension
  25253. * @param {string|number} dim
  25254. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  25255. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  25256. */
  25257. listProto.getDimensionInfo = function (dim) {
  25258. // Do not clone, because there may be categories in dimInfo.
  25259. return this._dimensionInfos[this.getDimension(dim)];
  25260. };
  25261. /**
  25262. * @return {Array.<string>} concrete dimension name list on coord.
  25263. */
  25264. listProto.getDimensionsOnCoord = function () {
  25265. return this._dimensionsSummary.dataDimsOnCoord.slice();
  25266. };
  25267. /**
  25268. * @param {string} coordDim
  25269. * @param {number} [idx] A coordDim may map to more than one data dim.
  25270. * If idx is `true`, return a array of all mapped dims.
  25271. * If idx is not specified, return the first dim not extra.
  25272. * @return {string|Array.<string>} concrete data dim.
  25273. * If idx is number, and not found, return null/undefined.
  25274. * If idx is `true`, and not found, return empty array (always return array).
  25275. */
  25276. listProto.mapDimension = function (coordDim, idx) {
  25277. var dimensionsSummary = this._dimensionsSummary;
  25278. if (idx == null) {
  25279. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  25280. }
  25281. var dims = dimensionsSummary.encode[coordDim];
  25282. return idx === true
  25283. // always return array if idx is `true`
  25284. ? (dims || []).slice()
  25285. : (dims && dims[idx]);
  25286. };
  25287. /**
  25288. * Initialize from data
  25289. * @param {Array.<Object|number|Array>} data source or data or data provider.
  25290. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  25291. * defualt label/tooltip.
  25292. * A name can be specified in encode.itemName,
  25293. * or dataItem.name (only for series option data),
  25294. * or provided in nameList from outside.
  25295. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  25296. */
  25297. listProto.initData = function (data, nameList, dimValueGetter) {
  25298. var notProvider = Source.isInstance(data) || isArrayLike(data);
  25299. if (notProvider) {
  25300. data = new DefaultDataProvider(data, this.dimensions.length);
  25301. }
  25302. if (__DEV__) {
  25303. if (!notProvider && (typeof data.getItem !== 'function' || typeof data.count !== 'function')) {
  25304. throw new Error('Inavlid data provider.');
  25305. }
  25306. }
  25307. this._rawData = data;
  25308. // Clear
  25309. this._storage = {};
  25310. this._indices = null;
  25311. this._nameList = nameList || [];
  25312. this._idList = [];
  25313. this._nameRepeatCount = {};
  25314. if (!dimValueGetter) {
  25315. this.hasItemOption = false;
  25316. }
  25317. /**
  25318. * @readOnly
  25319. */
  25320. this.defaultDimValueGetter = defaultDimValueGetters[
  25321. this._rawData.getSource().sourceFormat
  25322. ];
  25323. // Default dim value getter
  25324. this._dimValueGetter = dimValueGetter = dimValueGetter
  25325. || this.defaultDimValueGetter;
  25326. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows;
  25327. // Reset raw extent.
  25328. this._rawExtent = {};
  25329. this._initDataFromProvider(0, data.count());
  25330. // If data has no item option.
  25331. if (data.pure) {
  25332. this.hasItemOption = false;
  25333. }
  25334. };
  25335. listProto.getProvider = function () {
  25336. return this._rawData;
  25337. };
  25338. /**
  25339. * Caution: Can be only called on raw data (before `this._indices` created).
  25340. */
  25341. listProto.appendData = function (data) {
  25342. if (__DEV__) {
  25343. assert$1(!this._indices, 'appendData can only be called on raw data.');
  25344. }
  25345. var rawData = this._rawData;
  25346. var start = this.count();
  25347. rawData.appendData(data);
  25348. var end = rawData.count();
  25349. if (!rawData.persistent) {
  25350. end += start;
  25351. }
  25352. this._initDataFromProvider(start, end);
  25353. };
  25354. /**
  25355. * Caution: Can be only called on raw data (before `this._indices` created).
  25356. * This method does not modify `rawData` (`dataProvider`), but only
  25357. * add values to storage.
  25358. *
  25359. * The final count will be increased by `Math.max(values.length, names.length)`.
  25360. *
  25361. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  25362. * [
  25363. * [12, 33, 44],
  25364. * [NaN, 43, 1],
  25365. * ['-', 'asdf', 0]
  25366. * ]
  25367. * Each item is exaclty cooresponding to a dimension.
  25368. * @param {Array.<string>} [names]
  25369. */
  25370. listProto.appendValues = function (values, names) {
  25371. var chunkSize = this._chunkSize;
  25372. var storage = this._storage;
  25373. var dimensions = this.dimensions;
  25374. var dimLen = dimensions.length;
  25375. var rawExtent = this._rawExtent;
  25376. var start = this.count();
  25377. var end = start + Math.max(values.length, names ? names.length : 0);
  25378. var originalChunkCount = this._chunkCount;
  25379. for (var i = 0; i < dimLen; i++) {
  25380. var dim = dimensions[i];
  25381. if (!rawExtent[dim]) {
  25382. rawExtent[dim] = getInitialExtent();
  25383. }
  25384. if (!storage[dim]) {
  25385. storage[dim] = [];
  25386. }
  25387. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25388. this._chunkCount = storage[dim].length;
  25389. }
  25390. var emptyDataItem = new Array(dimLen);
  25391. for (var idx = start; idx < end; idx++) {
  25392. var sourceIdx = idx - start;
  25393. var chunkIndex = Math.floor(idx / chunkSize);
  25394. var chunkOffset = idx % chunkSize;
  25395. // Store the data by dimensions
  25396. for (var k = 0; k < dimLen; k++) {
  25397. var dim = dimensions[k];
  25398. var val = this._dimValueGetterArrayRows(
  25399. values[sourceIdx] || emptyDataItem, dim, sourceIdx, k
  25400. );
  25401. storage[dim][chunkIndex][chunkOffset] = val;
  25402. var dimRawExtent = rawExtent[dim];
  25403. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25404. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25405. }
  25406. if (names) {
  25407. this._nameList[idx] = names[sourceIdx];
  25408. }
  25409. }
  25410. this._rawCount = this._count = end;
  25411. // Reset data extent
  25412. this._extent = {};
  25413. prepareInvertedIndex(this);
  25414. };
  25415. listProto._initDataFromProvider = function (start, end) {
  25416. // Optimize.
  25417. if (start >= end) {
  25418. return;
  25419. }
  25420. var chunkSize = this._chunkSize;
  25421. var rawData = this._rawData;
  25422. var storage = this._storage;
  25423. var dimensions = this.dimensions;
  25424. var dimLen = dimensions.length;
  25425. var dimensionInfoMap = this._dimensionInfos;
  25426. var nameList = this._nameList;
  25427. var idList = this._idList;
  25428. var rawExtent = this._rawExtent;
  25429. var nameRepeatCount = this._nameRepeatCount = {};
  25430. var nameDimIdx;
  25431. var originalChunkCount = this._chunkCount;
  25432. for (var i = 0; i < dimLen; i++) {
  25433. var dim = dimensions[i];
  25434. if (!rawExtent[dim]) {
  25435. rawExtent[dim] = getInitialExtent();
  25436. }
  25437. var dimInfo = dimensionInfoMap[dim];
  25438. if (dimInfo.otherDims.itemName === 0) {
  25439. nameDimIdx = this._nameDimIdx = i;
  25440. }
  25441. if (dimInfo.otherDims.itemId === 0) {
  25442. this._idDimIdx = i;
  25443. }
  25444. if (!storage[dim]) {
  25445. storage[dim] = [];
  25446. }
  25447. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  25448. this._chunkCount = storage[dim].length;
  25449. }
  25450. var dataItem = new Array(dimLen);
  25451. for (var idx = start; idx < end; idx++) {
  25452. // NOTICE: Try not to write things into dataItem
  25453. dataItem = rawData.getItem(idx, dataItem);
  25454. // Each data item is value
  25455. // [1, 2]
  25456. // 2
  25457. // Bar chart, line chart which uses category axis
  25458. // only gives the 'y' value. 'x' value is the indices of category
  25459. // Use a tempValue to normalize the value to be a (x, y) value
  25460. var chunkIndex = Math.floor(idx / chunkSize);
  25461. var chunkOffset = idx % chunkSize;
  25462. // Store the data by dimensions
  25463. for (var k = 0; k < dimLen; k++) {
  25464. var dim = dimensions[k];
  25465. var dimStorage = storage[dim][chunkIndex];
  25466. // PENDING NULL is empty or zero
  25467. var val = this._dimValueGetter(dataItem, dim, idx, k);
  25468. dimStorage[chunkOffset] = val;
  25469. var dimRawExtent = rawExtent[dim];
  25470. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25471. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25472. }
  25473. // ??? FIXME not check by pure but sourceFormat?
  25474. // TODO refactor these logic.
  25475. if (!rawData.pure) {
  25476. var name = nameList[idx];
  25477. if (dataItem && name == null) {
  25478. // If dataItem is {name: ...}, it has highest priority.
  25479. // That is appropriate for many common cases.
  25480. if (dataItem.name != null) {
  25481. // There is no other place to persistent dataItem.name,
  25482. // so save it to nameList.
  25483. nameList[idx] = name = dataItem.name;
  25484. }
  25485. else if (nameDimIdx != null) {
  25486. var nameDim = dimensions[nameDimIdx];
  25487. var nameDimChunk = storage[nameDim][chunkIndex];
  25488. if (nameDimChunk) {
  25489. name = nameDimChunk[chunkOffset];
  25490. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  25491. if (ordinalMeta && ordinalMeta.categories.length) {
  25492. name = ordinalMeta.categories[name];
  25493. }
  25494. }
  25495. }
  25496. }
  25497. // Try using the id in option
  25498. // id or name is used on dynamical data, mapping old and new items.
  25499. var id = dataItem == null ? null : dataItem.id;
  25500. if (id == null && name != null) {
  25501. // Use name as id and add counter to avoid same name
  25502. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  25503. id = name;
  25504. if (nameRepeatCount[name] > 0) {
  25505. id += '__ec__' + nameRepeatCount[name];
  25506. }
  25507. nameRepeatCount[name]++;
  25508. }
  25509. id != null && (idList[idx] = id);
  25510. }
  25511. }
  25512. if (!rawData.persistent && rawData.clean) {
  25513. // Clean unused data if data source is typed array.
  25514. rawData.clean();
  25515. }
  25516. this._rawCount = this._count = end;
  25517. // Reset data extent
  25518. this._extent = {};
  25519. prepareInvertedIndex(this);
  25520. };
  25521. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  25522. var DataCtor = dataCtors[dimInfo.type];
  25523. var lastChunkIndex = chunkCount - 1;
  25524. var dim = dimInfo.name;
  25525. var resizeChunkArray = storage[dim][lastChunkIndex];
  25526. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  25527. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  25528. // The cost of the copy is probably inconsiderable
  25529. // within the initial chunkSize.
  25530. for (var j = 0; j < resizeChunkArray.length; j++) {
  25531. newStore[j] = resizeChunkArray[j];
  25532. }
  25533. storage[dim][lastChunkIndex] = newStore;
  25534. }
  25535. // Create new chunks.
  25536. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  25537. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  25538. }
  25539. }
  25540. function prepareInvertedIndex(list) {
  25541. var invertedIndicesMap = list._invertedIndicesMap;
  25542. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  25543. var dimInfo = list._dimensionInfos[dim];
  25544. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  25545. var ordinalMeta = dimInfo.ordinalMeta;
  25546. if (ordinalMeta) {
  25547. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(
  25548. ordinalMeta.categories.length
  25549. );
  25550. // The default value of TypedArray is 0. To avoid miss
  25551. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  25552. for (var i = 0; i < invertedIndices.length; i++) {
  25553. invertedIndices[i] = INDEX_NOT_FOUND;
  25554. }
  25555. for (var i = 0; i < list._count; i++) {
  25556. // Only support the case that all values are distinct.
  25557. invertedIndices[list.get(dim, i)] = i;
  25558. }
  25559. }
  25560. });
  25561. }
  25562. function getRawValueFromStore(list, dimIndex, rawIndex) {
  25563. var val;
  25564. if (dimIndex != null) {
  25565. var chunkSize = list._chunkSize;
  25566. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25567. var chunkOffset = rawIndex % chunkSize;
  25568. var dim = list.dimensions[dimIndex];
  25569. var chunk = list._storage[dim][chunkIndex];
  25570. if (chunk) {
  25571. val = chunk[chunkOffset];
  25572. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  25573. if (ordinalMeta && ordinalMeta.categories.length) {
  25574. val = ordinalMeta.categories[val];
  25575. }
  25576. }
  25577. }
  25578. return val;
  25579. }
  25580. /**
  25581. * @return {number}
  25582. */
  25583. listProto.count = function () {
  25584. return this._count;
  25585. };
  25586. listProto.getIndices = function () {
  25587. var newIndices;
  25588. var indices = this._indices;
  25589. if (indices) {
  25590. var Ctor = indices.constructor;
  25591. var thisCount = this._count;
  25592. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  25593. if (Ctor === Array) {
  25594. newIndices = new Ctor(thisCount);
  25595. for (var i = 0; i < thisCount; i++) {
  25596. newIndices[i] = indices[i];
  25597. }
  25598. }
  25599. else {
  25600. newIndices = new Ctor(indices.buffer, 0, thisCount);
  25601. }
  25602. }
  25603. else {
  25604. var Ctor = getIndicesCtor(this);
  25605. var newIndices = new Ctor(this.count());
  25606. for (var i = 0; i < newIndices.length; i++) {
  25607. newIndices[i] = i;
  25608. }
  25609. }
  25610. return newIndices;
  25611. };
  25612. /**
  25613. * Get value. Return NaN if idx is out of range.
  25614. * @param {string} dim Dim must be concrete name.
  25615. * @param {number} idx
  25616. * @param {boolean} stack
  25617. * @return {number}
  25618. */
  25619. listProto.get = function (dim, idx /*, stack */) {
  25620. if (!(idx >= 0 && idx < this._count)) {
  25621. return NaN;
  25622. }
  25623. var storage = this._storage;
  25624. if (!storage[dim]) {
  25625. // TODO Warn ?
  25626. return NaN;
  25627. }
  25628. idx = this.getRawIndex(idx);
  25629. var chunkIndex = Math.floor(idx / this._chunkSize);
  25630. var chunkOffset = idx % this._chunkSize;
  25631. var chunkStore = storage[dim][chunkIndex];
  25632. var value = chunkStore[chunkOffset];
  25633. // FIXME ordinal data type is not stackable
  25634. // if (stack) {
  25635. // var dimensionInfo = this._dimensionInfos[dim];
  25636. // if (dimensionInfo && dimensionInfo.stackable) {
  25637. // var stackedOn = this.stackedOn;
  25638. // while (stackedOn) {
  25639. // // Get no stacked data of stacked on
  25640. // var stackedValue = stackedOn.get(dim, idx);
  25641. // // Considering positive stack, negative stack and empty data
  25642. // if ((value >= 0 && stackedValue > 0) // Positive stack
  25643. // || (value <= 0 && stackedValue < 0) // Negative stack
  25644. // ) {
  25645. // value += stackedValue;
  25646. // }
  25647. // stackedOn = stackedOn.stackedOn;
  25648. // }
  25649. // }
  25650. // }
  25651. return value;
  25652. };
  25653. /**
  25654. * @param {string} dim concrete dim
  25655. * @param {number} rawIndex
  25656. * @return {number|string}
  25657. */
  25658. listProto.getByRawIndex = function (dim, rawIdx) {
  25659. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  25660. return NaN;
  25661. }
  25662. var dimStore = this._storage[dim];
  25663. if (!dimStore) {
  25664. // TODO Warn ?
  25665. return NaN;
  25666. }
  25667. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25668. var chunkOffset = rawIdx % this._chunkSize;
  25669. var chunkStore = dimStore[chunkIndex];
  25670. return chunkStore[chunkOffset];
  25671. };
  25672. /**
  25673. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  25674. * Hack a much simpler _getFast
  25675. * @private
  25676. */
  25677. listProto._getFast = function (dim, rawIdx) {
  25678. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25679. var chunkOffset = rawIdx % this._chunkSize;
  25680. var chunkStore = this._storage[dim][chunkIndex];
  25681. return chunkStore[chunkOffset];
  25682. };
  25683. /**
  25684. * Get value for multi dimensions.
  25685. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  25686. * @param {number} idx
  25687. * @return {number}
  25688. */
  25689. listProto.getValues = function (dimensions, idx /*, stack */) {
  25690. var values = [];
  25691. if (!isArray(dimensions)) {
  25692. // stack = idx;
  25693. idx = dimensions;
  25694. dimensions = this.dimensions;
  25695. }
  25696. for (var i = 0, len = dimensions.length; i < len; i++) {
  25697. values.push(this.get(dimensions[i], idx /*, stack */));
  25698. }
  25699. return values;
  25700. };
  25701. /**
  25702. * If value is NaN. Inlcuding '-'
  25703. * Only check the coord dimensions.
  25704. * @param {string} dim
  25705. * @param {number} idx
  25706. * @return {number}
  25707. */
  25708. listProto.hasValue = function (idx) {
  25709. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  25710. var dimensionInfos = this._dimensionInfos;
  25711. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  25712. if (
  25713. // Ordinal type can be string or number
  25714. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  25715. // FIXME check ordinal when using index?
  25716. && isNaN(this.get(dataDimsOnCoord[i], idx))
  25717. ) {
  25718. return false;
  25719. }
  25720. }
  25721. return true;
  25722. };
  25723. /**
  25724. * Get extent of data in one dimension
  25725. * @param {string} dim
  25726. * @param {boolean} stack
  25727. */
  25728. listProto.getDataExtent = function (dim /*, stack */) {
  25729. // Make sure use concrete dim as cache name.
  25730. dim = this.getDimension(dim);
  25731. var dimData = this._storage[dim];
  25732. var initialExtent = getInitialExtent();
  25733. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  25734. if (!dimData) {
  25735. return initialExtent;
  25736. }
  25737. // Make more strict checkings to ensure hitting cache.
  25738. var currEnd = this.count();
  25739. // var cacheName = [dim, !!stack].join('_');
  25740. // var cacheName = dim;
  25741. // Consider the most cases when using data zoom, `getDataExtent`
  25742. // happened before filtering. We cache raw extent, which is not
  25743. // necessary to be cleared and recalculated when restore data.
  25744. var useRaw = !this._indices; // && !stack;
  25745. var dimExtent;
  25746. if (useRaw) {
  25747. return this._rawExtent[dim].slice();
  25748. }
  25749. dimExtent = this._extent[dim];
  25750. if (dimExtent) {
  25751. return dimExtent.slice();
  25752. }
  25753. dimExtent = initialExtent;
  25754. var min = dimExtent[0];
  25755. var max = dimExtent[1];
  25756. for (var i = 0; i < currEnd; i++) {
  25757. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  25758. var value = this._getFast(dim, this.getRawIndex(i));
  25759. value < min && (min = value);
  25760. value > max && (max = value);
  25761. }
  25762. dimExtent = [min, max];
  25763. this._extent[dim] = dimExtent;
  25764. return dimExtent;
  25765. };
  25766. /**
  25767. * Optimize for the scenario that data is filtered by a given extent.
  25768. * Consider that if data amount is more than hundreds of thousand,
  25769. * extent calculation will cost more than 10ms and the cache will
  25770. * be erased because of the filtering.
  25771. */
  25772. listProto.getApproximateExtent = function (dim /*, stack */) {
  25773. dim = this.getDimension(dim);
  25774. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  25775. };
  25776. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  25777. dim = this.getDimension(dim);
  25778. this._approximateExtent[dim] = extent.slice();
  25779. };
  25780. /**
  25781. * @param {string} key
  25782. * @return {*}
  25783. */
  25784. listProto.getCalculationInfo = function (key) {
  25785. return this._calculationInfo[key];
  25786. };
  25787. /**
  25788. * @param {string|Object} key or k-v object
  25789. * @param {*} [value]
  25790. */
  25791. listProto.setCalculationInfo = function (key, value) {
  25792. isObject$4(key)
  25793. ? extend(this._calculationInfo, key)
  25794. : (this._calculationInfo[key] = value);
  25795. };
  25796. /**
  25797. * Get sum of data in one dimension
  25798. * @param {string} dim
  25799. */
  25800. listProto.getSum = function (dim /*, stack */) {
  25801. var dimData = this._storage[dim];
  25802. var sum = 0;
  25803. if (dimData) {
  25804. for (var i = 0, len = this.count(); i < len; i++) {
  25805. var value = this.get(dim, i /*, stack */);
  25806. if (!isNaN(value)) {
  25807. sum += value;
  25808. }
  25809. }
  25810. }
  25811. return sum;
  25812. };
  25813. /**
  25814. * Get median of data in one dimension
  25815. * @param {string} dim
  25816. */
  25817. listProto.getMedian = function (dim /*, stack */) {
  25818. var dimDataArray = [];
  25819. // map all data of one dimension
  25820. this.each(dim, function (val, idx) {
  25821. if (!isNaN(val)) {
  25822. dimDataArray.push(val);
  25823. }
  25824. });
  25825. // TODO
  25826. // Use quick select?
  25827. // immutability & sort
  25828. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  25829. return a - b;
  25830. });
  25831. var len = this.count();
  25832. // calculate median
  25833. return len === 0
  25834. ? 0
  25835. : len % 2 === 1
  25836. ? sortedDimDataArray[(len - 1) / 2]
  25837. : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  25838. };
  25839. // /**
  25840. // * Retreive the index with given value
  25841. // * @param {string} dim Concrete dimension.
  25842. // * @param {number} value
  25843. // * @return {number}
  25844. // */
  25845. // Currently incorrect: should return dataIndex but not rawIndex.
  25846. // Do not fix it until this method is to be used somewhere.
  25847. // FIXME Precision of float value
  25848. // listProto.indexOf = function (dim, value) {
  25849. // var storage = this._storage;
  25850. // var dimData = storage[dim];
  25851. // var chunkSize = this._chunkSize;
  25852. // if (dimData) {
  25853. // for (var i = 0, len = this.count(); i < len; i++) {
  25854. // var chunkIndex = Math.floor(i / chunkSize);
  25855. // var chunkOffset = i % chunkSize;
  25856. // if (dimData[chunkIndex][chunkOffset] === value) {
  25857. // return i;
  25858. // }
  25859. // }
  25860. // }
  25861. // return -1;
  25862. // };
  25863. /**
  25864. * Only support the dimension which inverted index created.
  25865. * Do not support other cases until required.
  25866. * @param {string} concrete dim
  25867. * @param {number|string} value
  25868. * @return {number} rawIndex
  25869. */
  25870. listProto.rawIndexOf = function (dim, value) {
  25871. var invertedIndices = dim && this._invertedIndicesMap[dim];
  25872. if (__DEV__) {
  25873. if (!invertedIndices) {
  25874. throw new Error('Do not supported yet');
  25875. }
  25876. }
  25877. var rawIndex = invertedIndices[value];
  25878. if (rawIndex == null || isNaN(rawIndex)) {
  25879. return INDEX_NOT_FOUND;
  25880. }
  25881. return rawIndex;
  25882. };
  25883. /**
  25884. * Retreive the index with given name
  25885. * @param {number} idx
  25886. * @param {number} name
  25887. * @return {number}
  25888. */
  25889. listProto.indexOfName = function (name) {
  25890. for (var i = 0, len = this.count(); i < len; i++) {
  25891. if (this.getName(i) === name) {
  25892. return i;
  25893. }
  25894. }
  25895. return -1;
  25896. };
  25897. /**
  25898. * Retreive the index with given raw data index
  25899. * @param {number} idx
  25900. * @param {number} name
  25901. * @return {number}
  25902. */
  25903. listProto.indexOfRawIndex = function (rawIndex) {
  25904. if (!this._indices) {
  25905. return rawIndex;
  25906. }
  25907. if (rawIndex >= this._rawCount || rawIndex < 0) {
  25908. return -1;
  25909. }
  25910. // Indices are ascending
  25911. var indices = this._indices;
  25912. // If rawIndex === dataIndex
  25913. var rawDataIndex = indices[rawIndex];
  25914. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  25915. return rawIndex;
  25916. }
  25917. var left = 0;
  25918. var right = this._count - 1;
  25919. while (left <= right) {
  25920. var mid = (left + right) / 2 | 0;
  25921. if (indices[mid] < rawIndex) {
  25922. left = mid + 1;
  25923. }
  25924. else if (indices[mid] > rawIndex) {
  25925. right = mid - 1;
  25926. }
  25927. else {
  25928. return mid;
  25929. }
  25930. }
  25931. return -1;
  25932. };
  25933. /**
  25934. * Retreive the index of nearest value
  25935. * @param {string} dim
  25936. * @param {number} value
  25937. * @param {number} [maxDistance=Infinity]
  25938. * @return {Array.<number>} Considere multiple points has the same value.
  25939. */
  25940. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  25941. var storage = this._storage;
  25942. var dimData = storage[dim];
  25943. var nearestIndices = [];
  25944. if (!dimData) {
  25945. return nearestIndices;
  25946. }
  25947. if (maxDistance == null) {
  25948. maxDistance = Infinity;
  25949. }
  25950. var minDist = Number.MAX_VALUE;
  25951. var minDiff = -1;
  25952. for (var i = 0, len = this.count(); i < len; i++) {
  25953. var diff = value - this.get(dim, i /*, stack */);
  25954. var dist = Math.abs(diff);
  25955. if (diff <= maxDistance && dist <= minDist) {
  25956. // For the case of two data are same on xAxis, which has sequence data.
  25957. // Show the nearest index
  25958. // https://github.com/ecomfe/echarts/issues/2869
  25959. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  25960. minDist = dist;
  25961. minDiff = diff;
  25962. nearestIndices.length = 0;
  25963. }
  25964. nearestIndices.push(i);
  25965. }
  25966. }
  25967. return nearestIndices;
  25968. };
  25969. /**
  25970. * Get raw data index
  25971. * @param {number} idx
  25972. * @return {number}
  25973. */
  25974. listProto.getRawIndex = getRawIndexWithoutIndices;
  25975. function getRawIndexWithoutIndices(idx) {
  25976. return idx;
  25977. }
  25978. function getRawIndexWithIndices(idx) {
  25979. if (idx < this._count && idx >= 0) {
  25980. return this._indices[idx];
  25981. }
  25982. return -1;
  25983. }
  25984. /**
  25985. * Get raw data item
  25986. * @param {number} idx
  25987. * @return {number}
  25988. */
  25989. listProto.getRawDataItem = function (idx) {
  25990. if (!this._rawData.persistent) {
  25991. var val = [];
  25992. for (var i = 0; i < this.dimensions.length; i++) {
  25993. var dim = this.dimensions[i];
  25994. val.push(this.get(dim, idx));
  25995. }
  25996. return val;
  25997. }
  25998. else {
  25999. return this._rawData.getItem(this.getRawIndex(idx));
  26000. }
  26001. };
  26002. /**
  26003. * @param {number} idx
  26004. * @param {boolean} [notDefaultIdx=false]
  26005. * @return {string}
  26006. */
  26007. listProto.getName = function (idx) {
  26008. var rawIndex = this.getRawIndex(idx);
  26009. return this._nameList[rawIndex]
  26010. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  26011. || '';
  26012. };
  26013. /**
  26014. * @param {number} idx
  26015. * @param {boolean} [notDefaultIdx=false]
  26016. * @return {string}
  26017. */
  26018. listProto.getId = function (idx) {
  26019. return getId(this, this.getRawIndex(idx));
  26020. };
  26021. function getId(list, rawIndex) {
  26022. var id = list._idList[rawIndex];
  26023. if (id == null) {
  26024. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  26025. }
  26026. if (id == null) {
  26027. // FIXME Check the usage in graph, should not use prefix.
  26028. id = ID_PREFIX + rawIndex;
  26029. }
  26030. return id;
  26031. }
  26032. function normalizeDimensions(dimensions) {
  26033. if (!isArray(dimensions)) {
  26034. dimensions = [dimensions];
  26035. }
  26036. return dimensions;
  26037. }
  26038. function validateDimensions(list, dims) {
  26039. for (var i = 0; i < dims.length; i++) {
  26040. // stroage may be empty when no data, so use
  26041. // dimensionInfos to check.
  26042. if (!list._dimensionInfos[dims[i]]) {
  26043. console.error('Unkown dimension ' + dims[i]);
  26044. }
  26045. }
  26046. }
  26047. /**
  26048. * Data iteration
  26049. * @param {string|Array.<string>}
  26050. * @param {Function} cb
  26051. * @param {*} [context=this]
  26052. *
  26053. * @example
  26054. * list.each('x', function (x, idx) {});
  26055. * list.each(['x', 'y'], function (x, y, idx) {});
  26056. * list.each(function (idx) {})
  26057. */
  26058. listProto.each = function (dims, cb, context, contextCompat) {
  26059. 'use strict';
  26060. if (!this._count) {
  26061. return;
  26062. }
  26063. if (typeof dims === 'function') {
  26064. contextCompat = context;
  26065. context = cb;
  26066. cb = dims;
  26067. dims = [];
  26068. }
  26069. // contextCompat just for compat echarts3
  26070. context = context || contextCompat || this;
  26071. dims = map(normalizeDimensions(dims), this.getDimension, this);
  26072. if (__DEV__) {
  26073. validateDimensions(this, dims);
  26074. }
  26075. var dimSize = dims.length;
  26076. for (var i = 0; i < this.count(); i++) {
  26077. // Simple optimization
  26078. switch (dimSize) {
  26079. case 0:
  26080. cb.call(context, i);
  26081. break;
  26082. case 1:
  26083. cb.call(context, this.get(dims[0], i), i);
  26084. break;
  26085. case 2:
  26086. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  26087. break;
  26088. default:
  26089. var k = 0;
  26090. var value = [];
  26091. for (; k < dimSize; k++) {
  26092. value[k] = this.get(dims[k], i);
  26093. }
  26094. // Index
  26095. value[k] = i;
  26096. cb.apply(context, value);
  26097. }
  26098. }
  26099. };
  26100. /**
  26101. * Data filter
  26102. * @param {string|Array.<string>}
  26103. * @param {Function} cb
  26104. * @param {*} [context=this]
  26105. */
  26106. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  26107. 'use strict';
  26108. if (!this._count) {
  26109. return;
  26110. }
  26111. if (typeof dimensions === 'function') {
  26112. contextCompat = context;
  26113. context = cb;
  26114. cb = dimensions;
  26115. dimensions = [];
  26116. }
  26117. // contextCompat just for compat echarts3
  26118. context = context || contextCompat || this;
  26119. dimensions = map(
  26120. normalizeDimensions(dimensions), this.getDimension, this
  26121. );
  26122. if (__DEV__) {
  26123. validateDimensions(this, dimensions);
  26124. }
  26125. var count = this.count();
  26126. var Ctor = getIndicesCtor(this);
  26127. var newIndices = new Ctor(count);
  26128. var value = [];
  26129. var dimSize = dimensions.length;
  26130. var offset = 0;
  26131. var dim0 = dimensions[0];
  26132. for (var i = 0; i < count; i++) {
  26133. var keep;
  26134. var rawIdx = this.getRawIndex(i);
  26135. // Simple optimization
  26136. if (dimSize === 0) {
  26137. keep = cb.call(context, i);
  26138. }
  26139. else if (dimSize === 1) {
  26140. var val = this._getFast(dim0, rawIdx);
  26141. keep = cb.call(context, val, i);
  26142. }
  26143. else {
  26144. for (var k = 0; k < dimSize; k++) {
  26145. value[k] = this._getFast(dim0, rawIdx);
  26146. }
  26147. value[k] = i;
  26148. keep = cb.apply(context, value);
  26149. }
  26150. if (keep) {
  26151. newIndices[offset++] = rawIdx;
  26152. }
  26153. }
  26154. // Set indices after filtered.
  26155. if (offset < count) {
  26156. this._indices = newIndices;
  26157. }
  26158. this._count = offset;
  26159. // Reset data extent
  26160. this._extent = {};
  26161. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26162. return this;
  26163. };
  26164. /**
  26165. * Select data in range. (For optimization of filter)
  26166. * (Manually inline code, support 5 million data filtering in data zoom.)
  26167. */
  26168. listProto.selectRange = function (range) {
  26169. 'use strict';
  26170. if (!this._count) {
  26171. return;
  26172. }
  26173. var dimensions = [];
  26174. for (var dim in range) {
  26175. if (range.hasOwnProperty(dim)) {
  26176. dimensions.push(dim);
  26177. }
  26178. }
  26179. if (__DEV__) {
  26180. validateDimensions(this, dimensions);
  26181. }
  26182. var dimSize = dimensions.length;
  26183. if (!dimSize) {
  26184. return;
  26185. }
  26186. var originalCount = this.count();
  26187. var Ctor = getIndicesCtor(this);
  26188. var newIndices = new Ctor(originalCount);
  26189. var offset = 0;
  26190. var dim0 = dimensions[0];
  26191. var min = range[dim0][0];
  26192. var max = range[dim0][1];
  26193. var quickFinished = false;
  26194. if (!this._indices) {
  26195. // Extreme optimization for common case. About 2x faster in chrome.
  26196. var idx = 0;
  26197. if (dimSize === 1) {
  26198. var dimStorage = this._storage[dimensions[0]];
  26199. for (var k = 0; k < this._chunkCount; k++) {
  26200. var chunkStorage = dimStorage[k];
  26201. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26202. for (var i = 0; i < len; i++) {
  26203. var val = chunkStorage[i];
  26204. // NaN will not be filtered. Consider the case, in line chart, empty
  26205. // value indicates the line should be broken. But for the case like
  26206. // scatter plot, a data item with empty value will not be rendered,
  26207. // but the axis extent may be effected if some other dim of the data
  26208. // item has value. Fortunately it is not a significant negative effect.
  26209. if (
  26210. (val >= min && val <= max) || isNaN(val)
  26211. ) {
  26212. newIndices[offset++] = idx;
  26213. }
  26214. idx++;
  26215. }
  26216. }
  26217. quickFinished = true;
  26218. }
  26219. else if (dimSize === 2) {
  26220. var dimStorage = this._storage[dim0];
  26221. var dimStorage2 = this._storage[dimensions[1]];
  26222. var min2 = range[dimensions[1]][0];
  26223. var max2 = range[dimensions[1]][1];
  26224. for (var k = 0; k < this._chunkCount; k++) {
  26225. var chunkStorage = dimStorage[k];
  26226. var chunkStorage2 = dimStorage2[k];
  26227. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  26228. for (var i = 0; i < len; i++) {
  26229. var val = chunkStorage[i];
  26230. var val2 = chunkStorage2[i];
  26231. // Do not filter NaN, see comment above.
  26232. if ((
  26233. (val >= min && val <= max) || isNaN(val)
  26234. )
  26235. && (
  26236. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  26237. )
  26238. ) {
  26239. newIndices[offset++] = idx;
  26240. }
  26241. idx++;
  26242. }
  26243. }
  26244. quickFinished = true;
  26245. }
  26246. }
  26247. if (!quickFinished) {
  26248. if (dimSize === 1) {
  26249. for (var i = 0; i < originalCount; i++) {
  26250. var rawIndex = this.getRawIndex(i);
  26251. var val = this._getFast(dim0, rawIndex);
  26252. // Do not filter NaN, see comment above.
  26253. if (
  26254. (val >= min && val <= max) || isNaN(val)
  26255. ) {
  26256. newIndices[offset++] = rawIndex;
  26257. }
  26258. }
  26259. }
  26260. else {
  26261. for (var i = 0; i < originalCount; i++) {
  26262. var keep = true;
  26263. var rawIndex = this.getRawIndex(i);
  26264. for (var k = 0; k < dimSize; k++) {
  26265. var dimk = dimensions[k];
  26266. var val = this._getFast(dim, rawIndex);
  26267. // Do not filter NaN, see comment above.
  26268. if (val < range[dimk][0] || val > range[dimk][1]) {
  26269. keep = false;
  26270. }
  26271. }
  26272. if (keep) {
  26273. newIndices[offset++] = this.getRawIndex(i);
  26274. }
  26275. }
  26276. }
  26277. }
  26278. // Set indices after filtered.
  26279. if (offset < originalCount) {
  26280. this._indices = newIndices;
  26281. }
  26282. this._count = offset;
  26283. // Reset data extent
  26284. this._extent = {};
  26285. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26286. return this;
  26287. };
  26288. /**
  26289. * Data mapping to a plain array
  26290. * @param {string|Array.<string>} [dimensions]
  26291. * @param {Function} cb
  26292. * @param {*} [context=this]
  26293. * @return {Array}
  26294. */
  26295. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  26296. 'use strict';
  26297. if (typeof dimensions === 'function') {
  26298. contextCompat = context;
  26299. context = cb;
  26300. cb = dimensions;
  26301. dimensions = [];
  26302. }
  26303. // contextCompat just for compat echarts3
  26304. context = context || contextCompat || this;
  26305. var result = [];
  26306. this.each(dimensions, function () {
  26307. result.push(cb && cb.apply(this, arguments));
  26308. }, context);
  26309. return result;
  26310. };
  26311. // Data in excludeDimensions is copied, otherwise transfered.
  26312. function cloneListForMapAndSample(original, excludeDimensions) {
  26313. var allDimensions = original.dimensions;
  26314. var list = new List(
  26315. map(allDimensions, original.getDimensionInfo, original),
  26316. original.hostModel
  26317. );
  26318. // FIXME If needs stackedOn, value may already been stacked
  26319. transferProperties(list, original);
  26320. var storage = list._storage = {};
  26321. var originalStorage = original._storage;
  26322. // Init storage
  26323. for (var i = 0; i < allDimensions.length; i++) {
  26324. var dim = allDimensions[i];
  26325. if (originalStorage[dim]) {
  26326. // Notice that we do not reset invertedIndicesMap here, becuase
  26327. // there is no scenario of mapping or sampling ordinal dimension.
  26328. if (indexOf(excludeDimensions, dim) >= 0) {
  26329. storage[dim] = cloneDimStore(originalStorage[dim]);
  26330. list._rawExtent[dim] = getInitialExtent();
  26331. list._extent[dim] = null;
  26332. }
  26333. else {
  26334. // Direct reference for other dimensions
  26335. storage[dim] = originalStorage[dim];
  26336. }
  26337. }
  26338. }
  26339. return list;
  26340. }
  26341. function cloneDimStore(originalDimStore) {
  26342. var newDimStore = new Array(originalDimStore.length);
  26343. for (var j = 0; j < originalDimStore.length; j++) {
  26344. newDimStore[j] = cloneChunk(originalDimStore[j]);
  26345. }
  26346. return newDimStore;
  26347. }
  26348. function getInitialExtent() {
  26349. return [Infinity, -Infinity];
  26350. }
  26351. /**
  26352. * Data mapping to a new List with given dimensions
  26353. * @param {string|Array.<string>} dimensions
  26354. * @param {Function} cb
  26355. * @param {*} [context=this]
  26356. * @return {Array}
  26357. */
  26358. listProto.map = function (dimensions, cb, context, contextCompat) {
  26359. 'use strict';
  26360. // contextCompat just for compat echarts3
  26361. context = context || contextCompat || this;
  26362. dimensions = map(
  26363. normalizeDimensions(dimensions), this.getDimension, this
  26364. );
  26365. if (__DEV__) {
  26366. validateDimensions(this, dimensions);
  26367. }
  26368. var list = cloneListForMapAndSample(this, dimensions);
  26369. // Following properties are all immutable.
  26370. // So we can reference to the same value
  26371. list._indices = this._indices;
  26372. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26373. var storage = list._storage;
  26374. var tmpRetValue = [];
  26375. var chunkSize = this._chunkSize;
  26376. var dimSize = dimensions.length;
  26377. var dataCount = this.count();
  26378. var values = [];
  26379. var rawExtent = list._rawExtent;
  26380. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  26381. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  26382. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  26383. }
  26384. values[dimSize] = dataIndex;
  26385. var retValue = cb && cb.apply(context, values);
  26386. if (retValue != null) {
  26387. // a number or string (in oridinal dimension)?
  26388. if (typeof retValue !== 'object') {
  26389. tmpRetValue[0] = retValue;
  26390. retValue = tmpRetValue;
  26391. }
  26392. var rawIndex = this.getRawIndex(dataIndex);
  26393. var chunkIndex = Math.floor(rawIndex / chunkSize);
  26394. var chunkOffset = rawIndex % chunkSize;
  26395. for (var i = 0; i < retValue.length; i++) {
  26396. var dim = dimensions[i];
  26397. var val = retValue[i];
  26398. var rawExtentOnDim = rawExtent[dim];
  26399. var dimStore = storage[dim];
  26400. if (dimStore) {
  26401. dimStore[chunkIndex][chunkOffset] = val;
  26402. }
  26403. if (val < rawExtentOnDim[0]) {
  26404. rawExtentOnDim[0] = val;
  26405. }
  26406. if (val > rawExtentOnDim[1]) {
  26407. rawExtentOnDim[1] = val;
  26408. }
  26409. }
  26410. }
  26411. }
  26412. return list;
  26413. };
  26414. /**
  26415. * Large data down sampling on given dimension
  26416. * @param {string} dimension
  26417. * @param {number} rate
  26418. * @param {Function} sampleValue
  26419. * @param {Function} sampleIndex Sample index for name and id
  26420. */
  26421. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  26422. var list = cloneListForMapAndSample(this, [dimension]);
  26423. var targetStorage = list._storage;
  26424. var frameValues = [];
  26425. var frameSize = Math.floor(1 / rate);
  26426. var dimStore = targetStorage[dimension];
  26427. var len = this.count();
  26428. var chunkSize = this._chunkSize;
  26429. var rawExtentOnDim = list._rawExtent[dimension];
  26430. var newIndices = new (getIndicesCtor(this))(len);
  26431. var offset = 0;
  26432. for (var i = 0; i < len; i += frameSize) {
  26433. // Last frame
  26434. if (frameSize > len - i) {
  26435. frameSize = len - i;
  26436. frameValues.length = frameSize;
  26437. }
  26438. for (var k = 0; k < frameSize; k++) {
  26439. var dataIdx = this.getRawIndex(i + k);
  26440. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  26441. var originalChunkOffset = dataIdx % chunkSize;
  26442. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  26443. }
  26444. var value = sampleValue(frameValues);
  26445. var sampleFrameIdx = this.getRawIndex(
  26446. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  26447. );
  26448. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  26449. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  26450. // Only write value on the filtered data
  26451. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  26452. if (value < rawExtentOnDim[0]) {
  26453. rawExtentOnDim[0] = value;
  26454. }
  26455. if (value > rawExtentOnDim[1]) {
  26456. rawExtentOnDim[1] = value;
  26457. }
  26458. newIndices[offset++] = sampleFrameIdx;
  26459. }
  26460. list._count = offset;
  26461. list._indices = newIndices;
  26462. list.getRawIndex = getRawIndexWithIndices;
  26463. return list;
  26464. };
  26465. /**
  26466. * Get model of one data item.
  26467. *
  26468. * @param {number} idx
  26469. */
  26470. // FIXME Model proxy ?
  26471. listProto.getItemModel = function (idx) {
  26472. var hostModel = this.hostModel;
  26473. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  26474. };
  26475. /**
  26476. * Create a data differ
  26477. * @param {module:echarts/data/List} otherList
  26478. * @return {module:echarts/data/DataDiffer}
  26479. */
  26480. listProto.diff = function (otherList) {
  26481. var thisList = this;
  26482. return new DataDiffer(
  26483. otherList ? otherList.getIndices() : [],
  26484. this.getIndices(),
  26485. function (idx) {
  26486. return getId(otherList, idx);
  26487. },
  26488. function (idx) {
  26489. return getId(thisList, idx);
  26490. }
  26491. );
  26492. };
  26493. /**
  26494. * Get visual property.
  26495. * @param {string} key
  26496. */
  26497. listProto.getVisual = function (key) {
  26498. var visual = this._visual;
  26499. return visual && visual[key];
  26500. };
  26501. /**
  26502. * Set visual property
  26503. * @param {string|Object} key
  26504. * @param {*} [value]
  26505. *
  26506. * @example
  26507. * setVisual('color', color);
  26508. * setVisual({
  26509. * 'color': color
  26510. * });
  26511. */
  26512. listProto.setVisual = function (key, val) {
  26513. if (isObject$4(key)) {
  26514. for (var name in key) {
  26515. if (key.hasOwnProperty(name)) {
  26516. this.setVisual(name, key[name]);
  26517. }
  26518. }
  26519. return;
  26520. }
  26521. this._visual = this._visual || {};
  26522. this._visual[key] = val;
  26523. };
  26524. /**
  26525. * Set layout property.
  26526. * @param {string|Object} key
  26527. * @param {*} [val]
  26528. */
  26529. listProto.setLayout = function (key, val) {
  26530. if (isObject$4(key)) {
  26531. for (var name in key) {
  26532. if (key.hasOwnProperty(name)) {
  26533. this.setLayout(name, key[name]);
  26534. }
  26535. }
  26536. return;
  26537. }
  26538. this._layout[key] = val;
  26539. };
  26540. /**
  26541. * Get layout property.
  26542. * @param {string} key.
  26543. * @return {*}
  26544. */
  26545. listProto.getLayout = function (key) {
  26546. return this._layout[key];
  26547. };
  26548. /**
  26549. * Get layout of single data item
  26550. * @param {number} idx
  26551. */
  26552. listProto.getItemLayout = function (idx) {
  26553. return this._itemLayouts[idx];
  26554. };
  26555. /**
  26556. * Set layout of single data item
  26557. * @param {number} idx
  26558. * @param {Object} layout
  26559. * @param {boolean=} [merge=false]
  26560. */
  26561. listProto.setItemLayout = function (idx, layout, merge$$1) {
  26562. this._itemLayouts[idx] = merge$$1
  26563. ? extend(this._itemLayouts[idx] || {}, layout)
  26564. : layout;
  26565. };
  26566. /**
  26567. * Clear all layout of single data item
  26568. */
  26569. listProto.clearItemLayouts = function () {
  26570. this._itemLayouts.length = 0;
  26571. };
  26572. /**
  26573. * Get visual property of single data item
  26574. * @param {number} idx
  26575. * @param {string} key
  26576. * @param {boolean} [ignoreParent=false]
  26577. */
  26578. listProto.getItemVisual = function (idx, key, ignoreParent) {
  26579. var itemVisual = this._itemVisuals[idx];
  26580. var val = itemVisual && itemVisual[key];
  26581. if (val == null && !ignoreParent) {
  26582. // Use global visual property
  26583. return this.getVisual(key);
  26584. }
  26585. return val;
  26586. };
  26587. /**
  26588. * Set visual property of single data item
  26589. *
  26590. * @param {number} idx
  26591. * @param {string|Object} key
  26592. * @param {*} [value]
  26593. *
  26594. * @example
  26595. * setItemVisual(0, 'color', color);
  26596. * setItemVisual(0, {
  26597. * 'color': color
  26598. * });
  26599. */
  26600. listProto.setItemVisual = function (idx, key, value) {
  26601. var itemVisual = this._itemVisuals[idx] || {};
  26602. var hasItemVisual = this.hasItemVisual;
  26603. this._itemVisuals[idx] = itemVisual;
  26604. if (isObject$4(key)) {
  26605. for (var name in key) {
  26606. if (key.hasOwnProperty(name)) {
  26607. itemVisual[name] = key[name];
  26608. hasItemVisual[name] = true;
  26609. }
  26610. }
  26611. return;
  26612. }
  26613. itemVisual[key] = value;
  26614. hasItemVisual[key] = true;
  26615. };
  26616. /**
  26617. * Clear itemVisuals and list visual.
  26618. */
  26619. listProto.clearAllVisual = function () {
  26620. this._visual = {};
  26621. this._itemVisuals = [];
  26622. this.hasItemVisual = {};
  26623. };
  26624. var setItemDataAndSeriesIndex = function (child) {
  26625. child.seriesIndex = this.seriesIndex;
  26626. child.dataIndex = this.dataIndex;
  26627. child.dataType = this.dataType;
  26628. };
  26629. /**
  26630. * Set graphic element relative to data. It can be set as null
  26631. * @param {number} idx
  26632. * @param {module:zrender/Element} [el]
  26633. */
  26634. listProto.setItemGraphicEl = function (idx, el) {
  26635. var hostModel = this.hostModel;
  26636. if (el) {
  26637. // Add data index and series index for indexing the data by element
  26638. // Useful in tooltip
  26639. el.dataIndex = idx;
  26640. el.dataType = this.dataType;
  26641. el.seriesIndex = hostModel && hostModel.seriesIndex;
  26642. if (el.type === 'group') {
  26643. el.traverse(setItemDataAndSeriesIndex, el);
  26644. }
  26645. }
  26646. this._graphicEls[idx] = el;
  26647. };
  26648. /**
  26649. * @param {number} idx
  26650. * @return {module:zrender/Element}
  26651. */
  26652. listProto.getItemGraphicEl = function (idx) {
  26653. return this._graphicEls[idx];
  26654. };
  26655. /**
  26656. * @param {Function} cb
  26657. * @param {*} context
  26658. */
  26659. listProto.eachItemGraphicEl = function (cb, context) {
  26660. each$1(this._graphicEls, function (el, idx) {
  26661. if (el) {
  26662. cb && cb.call(context, el, idx);
  26663. }
  26664. });
  26665. };
  26666. /**
  26667. * Shallow clone a new list except visual and layout properties, and graph elements.
  26668. * New list only change the indices.
  26669. */
  26670. listProto.cloneShallow = function (list) {
  26671. if (!list) {
  26672. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  26673. list = new List(dimensionInfoList, this.hostModel);
  26674. }
  26675. // FIXME
  26676. list._storage = this._storage;
  26677. transferProperties(list, this);
  26678. // Clone will not change the data extent and indices
  26679. if (this._indices) {
  26680. var Ctor = this._indices.constructor;
  26681. list._indices = new Ctor(this._indices);
  26682. }
  26683. else {
  26684. list._indices = null;
  26685. }
  26686. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26687. return list;
  26688. };
  26689. /**
  26690. * Wrap some method to add more feature
  26691. * @param {string} methodName
  26692. * @param {Function} injectFunction
  26693. */
  26694. listProto.wrapMethod = function (methodName, injectFunction) {
  26695. var originalMethod = this[methodName];
  26696. if (typeof originalMethod !== 'function') {
  26697. return;
  26698. }
  26699. this.__wrappedMethods = this.__wrappedMethods || [];
  26700. this.__wrappedMethods.push(methodName);
  26701. this[methodName] = function () {
  26702. var res = originalMethod.apply(this, arguments);
  26703. return injectFunction.apply(this, [res].concat(slice(arguments)));
  26704. };
  26705. };
  26706. // Methods that create a new list based on this list should be listed here.
  26707. // Notice that those method should `RETURN` the new list.
  26708. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  26709. // Methods that change indices of this list should be listed here.
  26710. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26711. /*
  26712. * Licensed to the Apache Software Foundation (ASF) under one
  26713. * or more contributor license agreements. See the NOTICE file
  26714. * distributed with this work for additional information
  26715. * regarding copyright ownership. The ASF licenses this file
  26716. * to you under the Apache License, Version 2.0 (the
  26717. * "License"); you may not use this file except in compliance
  26718. * with the License. You may obtain a copy of the License at
  26719. *
  26720. * http://www.apache.org/licenses/LICENSE-2.0
  26721. *
  26722. * Unless required by applicable law or agreed to in writing,
  26723. * software distributed under the License is distributed on an
  26724. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26725. * KIND, either express or implied. See the License for the
  26726. * specific language governing permissions and limitations
  26727. * under the License.
  26728. */
  26729. /**
  26730. * @deprecated
  26731. * Use `echarts/data/helper/createDimensions` instead.
  26732. */
  26733. /**
  26734. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  26735. *
  26736. * Complete the dimensions array, by user defined `dimension` and `encode`,
  26737. * and guessing from the data structure.
  26738. * If no 'value' dimension specified, the first no-named dimension will be
  26739. * named as 'value'.
  26740. *
  26741. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  26742. * provides not only dim template, but also default order.
  26743. * properties: 'name', 'type', 'displayName'.
  26744. * `name` of each item provides default coord name.
  26745. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  26746. * provide dims count that the sysDim required.
  26747. * [{ordinalMeta}] can be specified.
  26748. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  26749. * @param {Object} [opt]
  26750. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  26751. * For example: ['asdf', {name, type}, ...].
  26752. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  26753. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  26754. * If not specified, extra dim names will be:
  26755. * 'value', 'value0', 'value1', ...
  26756. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  26757. * If `generateCoordCount` specified, the generated dim names will be:
  26758. * `generateCoord` + 0, `generateCoord` + 1, ...
  26759. * can be Infinity, indicate that use all of the remain columns.
  26760. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  26761. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  26762. * @return {Array.<Object>} [{
  26763. * name: string mandatory,
  26764. * displayName: string, the origin name in dimsDef, see source helper.
  26765. * If displayName given, the tooltip will displayed vertically.
  26766. * coordDim: string mandatory,
  26767. * coordDimIndex: number mandatory,
  26768. * type: string optional,
  26769. * otherDims: { never null/undefined
  26770. * tooltip: number optional,
  26771. * label: number optional,
  26772. * itemName: number optional,
  26773. * seriesName: number optional,
  26774. * },
  26775. * isExtraCoord: boolean true if coord is generated
  26776. * (not specified in encode and not series specified)
  26777. * other props ...
  26778. * }]
  26779. */
  26780. function completeDimensions(sysDims, source, opt) {
  26781. if (!Source.isInstance(source)) {
  26782. source = Source.seriesDataToSource(source);
  26783. }
  26784. opt = opt || {};
  26785. sysDims = (sysDims || []).slice();
  26786. var dimsDef = (opt.dimsDef || []).slice();
  26787. var encodeDef = createHashMap(opt.encodeDef);
  26788. var dataDimNameMap = createHashMap();
  26789. var coordDimNameMap = createHashMap();
  26790. // var valueCandidate;
  26791. var result = [];
  26792. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  26793. // Apply user defined dims (`name` and `type`) and init result.
  26794. for (var i = 0; i < dimCount; i++) {
  26795. var dimDefItem = dimsDef[i] = extend(
  26796. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  26797. );
  26798. var userDimName = dimDefItem.name;
  26799. var resultItem = result[i] = {otherDims: {}};
  26800. // Name will be applied later for avoiding duplication.
  26801. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  26802. // Only if `series.dimensions` is defined in option
  26803. // displayName, will be set, and dimension will be diplayed vertically in
  26804. // tooltip by default.
  26805. resultItem.name = resultItem.displayName = userDimName;
  26806. dataDimNameMap.set(userDimName, i);
  26807. }
  26808. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  26809. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  26810. }
  26811. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  26812. encodeDef.each(function (dataDims, coordDim) {
  26813. dataDims = normalizeToArray(dataDims).slice();
  26814. // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  26815. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  26816. // this case.
  26817. if (dataDims.length === 1 && dataDims[0] < 0) {
  26818. encodeDef.set(coordDim, false);
  26819. return;
  26820. }
  26821. var validDataDims = encodeDef.set(coordDim, []);
  26822. each$1(dataDims, function (resultDimIdx, idx) {
  26823. // The input resultDimIdx can be dim name or index.
  26824. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  26825. if (resultDimIdx != null && resultDimIdx < dimCount) {
  26826. validDataDims[idx] = resultDimIdx;
  26827. applyDim(result[resultDimIdx], coordDim, idx);
  26828. }
  26829. });
  26830. });
  26831. // Apply templetes and default order from `sysDims`.
  26832. var availDimIdx = 0;
  26833. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  26834. var coordDim;
  26835. var sysDimItem;
  26836. var sysDimItemDimsDef;
  26837. var sysDimItemOtherDims;
  26838. if (isString(sysDimItem)) {
  26839. coordDim = sysDimItem;
  26840. sysDimItem = {};
  26841. }
  26842. else {
  26843. coordDim = sysDimItem.name;
  26844. var ordinalMeta = sysDimItem.ordinalMeta;
  26845. sysDimItem.ordinalMeta = null;
  26846. sysDimItem = clone(sysDimItem);
  26847. sysDimItem.ordinalMeta = ordinalMeta;
  26848. // `coordDimIndex` should not be set directly.
  26849. sysDimItemDimsDef = sysDimItem.dimsDef;
  26850. sysDimItemOtherDims = sysDimItem.otherDims;
  26851. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  26852. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  26853. }
  26854. var dataDims = encodeDef.get(coordDim);
  26855. // negative resultDimIdx means no need to mapping.
  26856. if (dataDims === false) {
  26857. return;
  26858. }
  26859. var dataDims = normalizeToArray(dataDims);
  26860. // dimensions provides default dim sequences.
  26861. if (!dataDims.length) {
  26862. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  26863. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  26864. availDimIdx++;
  26865. }
  26866. availDimIdx < result.length && dataDims.push(availDimIdx++);
  26867. }
  26868. }
  26869. // Apply templates.
  26870. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  26871. var resultItem = result[resultDimIdx];
  26872. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  26873. if (resultItem.name == null && sysDimItemDimsDef) {
  26874. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  26875. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  26876. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  26877. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  26878. }
  26879. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  26880. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  26881. });
  26882. });
  26883. function applyDim(resultItem, coordDim, coordDimIndex) {
  26884. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  26885. resultItem.otherDims[coordDim] = coordDimIndex;
  26886. }
  26887. else {
  26888. resultItem.coordDim = coordDim;
  26889. resultItem.coordDimIndex = coordDimIndex;
  26890. coordDimNameMap.set(coordDim, true);
  26891. }
  26892. }
  26893. // Make sure the first extra dim is 'value'.
  26894. var generateCoord = opt.generateCoord;
  26895. var generateCoordCount = opt.generateCoordCount;
  26896. var fromZero = generateCoordCount != null;
  26897. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  26898. var extra = generateCoord || 'value';
  26899. // Set dim `name` and other `coordDim` and other props.
  26900. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  26901. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  26902. var coordDim = resultItem.coordDim;
  26903. if (coordDim == null) {
  26904. resultItem.coordDim = genName(
  26905. extra, coordDimNameMap, fromZero
  26906. );
  26907. resultItem.coordDimIndex = 0;
  26908. if (!generateCoord || generateCoordCount <= 0) {
  26909. resultItem.isExtraCoord = true;
  26910. }
  26911. generateCoordCount--;
  26912. }
  26913. resultItem.name == null && (resultItem.name = genName(
  26914. resultItem.coordDim,
  26915. dataDimNameMap
  26916. ));
  26917. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  26918. resultItem.type = 'ordinal';
  26919. }
  26920. }
  26921. return result;
  26922. }
  26923. // ??? TODO
  26924. // Originally detect dimCount by data[0]. Should we
  26925. // optimize it to only by sysDims and dimensions and encode.
  26926. // So only necessary dims will be initialized.
  26927. // But
  26928. // (1) custom series should be considered. where other dims
  26929. // may be visited.
  26930. // (2) sometimes user need to calcualte bubble size or use visualMap
  26931. // on other dimensions besides coordSys needed.
  26932. // So, dims that is not used by system, should be shared in storage?
  26933. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  26934. // Note that the result dimCount should not small than columns count
  26935. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  26936. var dimCount = Math.max(
  26937. source.dimensionsDetectCount || 1,
  26938. sysDims.length,
  26939. dimsDef.length,
  26940. optDimCount || 0
  26941. );
  26942. each$1(sysDims, function (sysDimItem) {
  26943. var sysDimItemDimsDef = sysDimItem.dimsDef;
  26944. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  26945. });
  26946. return dimCount;
  26947. }
  26948. function genName(name, map$$1, fromZero) {
  26949. if (fromZero || map$$1.get(name) != null) {
  26950. var i = 0;
  26951. while (map$$1.get(name + i) != null) {
  26952. i++;
  26953. }
  26954. name += i;
  26955. }
  26956. map$$1.set(name, true);
  26957. return name;
  26958. }
  26959. /*
  26960. * Licensed to the Apache Software Foundation (ASF) under one
  26961. * or more contributor license agreements. See the NOTICE file
  26962. * distributed with this work for additional information
  26963. * regarding copyright ownership. The ASF licenses this file
  26964. * to you under the Apache License, Version 2.0 (the
  26965. * "License"); you may not use this file except in compliance
  26966. * with the License. You may obtain a copy of the License at
  26967. *
  26968. * http://www.apache.org/licenses/LICENSE-2.0
  26969. *
  26970. * Unless required by applicable law or agreed to in writing,
  26971. * software distributed under the License is distributed on an
  26972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26973. * KIND, either express or implied. See the License for the
  26974. * specific language governing permissions and limitations
  26975. * under the License.
  26976. */
  26977. /**
  26978. * Substitute `completeDimensions`.
  26979. * `completeDimensions` is to be deprecated.
  26980. */
  26981. /**
  26982. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  26983. * @param {Object|Array} [opt]
  26984. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  26985. * @param {number} [opt.dimensionsCount]
  26986. * @param {string} [opt.generateCoord]
  26987. * @param {string} [opt.generateCoordCount]
  26988. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  26989. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  26990. * @return {Array.<Object>} dimensionsInfo
  26991. */
  26992. var createDimensions = function (source, opt) {
  26993. opt = opt || {};
  26994. return completeDimensions(opt.coordDimensions || [], source, {
  26995. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  26996. encodeDef: opt.encodeDefine || source.encodeDefine,
  26997. dimCount: opt.dimensionsCount,
  26998. generateCoord: opt.generateCoord,
  26999. generateCoordCount: opt.generateCoordCount
  27000. });
  27001. };
  27002. /*
  27003. * Licensed to the Apache Software Foundation (ASF) under one
  27004. * or more contributor license agreements. See the NOTICE file
  27005. * distributed with this work for additional information
  27006. * regarding copyright ownership. The ASF licenses this file
  27007. * to you under the Apache License, Version 2.0 (the
  27008. * "License"); you may not use this file except in compliance
  27009. * with the License. You may obtain a copy of the License at
  27010. *
  27011. * http://www.apache.org/licenses/LICENSE-2.0
  27012. *
  27013. * Unless required by applicable law or agreed to in writing,
  27014. * software distributed under the License is distributed on an
  27015. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27016. * KIND, either express or implied. See the License for the
  27017. * specific language governing permissions and limitations
  27018. * under the License.
  27019. */
  27020. /**
  27021. * Note that it is too complicated to support 3d stack by value
  27022. * (have to create two-dimension inverted index), so in 3d case
  27023. * we just support that stacked by index.
  27024. *
  27025. * @param {module:echarts/model/Series} seriesModel
  27026. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  27027. * The input dimensionInfoList will be modified.
  27028. * @param {Object} [opt]
  27029. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  27030. * @param {boolean} [opt.byIndex=false]
  27031. * @return {Object} calculationInfo
  27032. * {
  27033. * stackedDimension: string
  27034. * stackedByDimension: string
  27035. * isStackedByIndex: boolean
  27036. * stackedOverDimension: string
  27037. * stackResultDimension: string
  27038. * }
  27039. */
  27040. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  27041. opt = opt || {};
  27042. var byIndex = opt.byIndex;
  27043. var stackedCoordDimension = opt.stackedCoordDimension;
  27044. // Compatibal: when `stack` is set as '', do not stack.
  27045. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  27046. var stackedByDimInfo;
  27047. var stackedDimInfo;
  27048. var stackResultDimension;
  27049. var stackedOverDimension;
  27050. each$1(dimensionInfoList, function (dimensionInfo, index) {
  27051. if (isString(dimensionInfo)) {
  27052. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  27053. }
  27054. if (mayStack && !dimensionInfo.isExtraCoord) {
  27055. // Find the first ordinal dimension as the stackedByDimInfo.
  27056. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  27057. stackedByDimInfo = dimensionInfo;
  27058. }
  27059. // Find the first stackable dimension as the stackedDimInfo.
  27060. if (!stackedDimInfo
  27061. && dimensionInfo.type !== 'ordinal'
  27062. && dimensionInfo.type !== 'time'
  27063. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  27064. ) {
  27065. stackedDimInfo = dimensionInfo;
  27066. }
  27067. }
  27068. });
  27069. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  27070. // Compatible with previous design, value axis (time axis) only stack by index.
  27071. // It may make sense if the user provides elaborately constructed data.
  27072. byIndex = true;
  27073. }
  27074. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  27075. // That put stack logic in List is for using conveniently in echarts extensions, but it
  27076. // might not be a good way.
  27077. if (stackedDimInfo) {
  27078. // Use a weird name that not duplicated with other names.
  27079. stackResultDimension = '__\0ecstackresult';
  27080. stackedOverDimension = '__\0ecstackedover';
  27081. // Create inverted index to fast query index by value.
  27082. if (stackedByDimInfo) {
  27083. stackedByDimInfo.createInvertedIndices = true;
  27084. }
  27085. var stackedDimCoordDim = stackedDimInfo.coordDim;
  27086. var stackedDimType = stackedDimInfo.type;
  27087. var stackedDimCoordIndex = 0;
  27088. each$1(dimensionInfoList, function (dimensionInfo) {
  27089. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  27090. stackedDimCoordIndex++;
  27091. }
  27092. });
  27093. dimensionInfoList.push({
  27094. name: stackResultDimension,
  27095. coordDim: stackedDimCoordDim,
  27096. coordDimIndex: stackedDimCoordIndex,
  27097. type: stackedDimType,
  27098. isExtraCoord: true,
  27099. isCalculationCoord: true
  27100. });
  27101. stackedDimCoordIndex++;
  27102. dimensionInfoList.push({
  27103. name: stackedOverDimension,
  27104. // This dimension contains stack base (generally, 0), so do not set it as
  27105. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  27106. coordDim: stackedOverDimension,
  27107. coordDimIndex: stackedDimCoordIndex,
  27108. type: stackedDimType,
  27109. isExtraCoord: true,
  27110. isCalculationCoord: true
  27111. });
  27112. }
  27113. return {
  27114. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  27115. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  27116. isStackedByIndex: byIndex,
  27117. stackedOverDimension: stackedOverDimension,
  27118. stackResultDimension: stackResultDimension
  27119. };
  27120. }
  27121. /**
  27122. * @param {module:echarts/data/List} data
  27123. * @param {string} stackedDim
  27124. */
  27125. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  27126. // Each single series only maps to one pair of axis. So we do not need to
  27127. // check stackByDim, whatever stacked by a dimension or stacked by index.
  27128. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  27129. // && (
  27130. // stackedByDim != null
  27131. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  27132. // : data.getCalculationInfo('isStackedByIndex')
  27133. // );
  27134. }
  27135. /**
  27136. * @param {module:echarts/data/List} data
  27137. * @param {string} targetDim
  27138. * @param {string} [stackedByDim] If not input this parameter, check whether
  27139. * stacked by index.
  27140. * @return {string} dimension
  27141. */
  27142. function getStackedDimension(data, targetDim) {
  27143. return isDimensionStacked(data, targetDim)
  27144. ? data.getCalculationInfo('stackResultDimension')
  27145. : targetDim;
  27146. }
  27147. /*
  27148. * Licensed to the Apache Software Foundation (ASF) under one
  27149. * or more contributor license agreements. See the NOTICE file
  27150. * distributed with this work for additional information
  27151. * regarding copyright ownership. The ASF licenses this file
  27152. * to you under the Apache License, Version 2.0 (the
  27153. * "License"); you may not use this file except in compliance
  27154. * with the License. You may obtain a copy of the License at
  27155. *
  27156. * http://www.apache.org/licenses/LICENSE-2.0
  27157. *
  27158. * Unless required by applicable law or agreed to in writing,
  27159. * software distributed under the License is distributed on an
  27160. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27161. * KIND, either express or implied. See the License for the
  27162. * specific language governing permissions and limitations
  27163. * under the License.
  27164. */
  27165. /**
  27166. * @param {module:echarts/data/Source|Array} source Or raw data.
  27167. * @param {module:echarts/model/Series} seriesModel
  27168. * @param {Object} [opt]
  27169. * @param {string} [opt.generateCoord]
  27170. */
  27171. function createListFromArray(source, seriesModel, opt) {
  27172. opt = opt || {};
  27173. if (!Source.isInstance(source)) {
  27174. source = Source.seriesDataToSource(source);
  27175. }
  27176. var coordSysName = seriesModel.get('coordinateSystem');
  27177. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  27178. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  27179. var coordSysDimDefs;
  27180. if (coordSysDefine) {
  27181. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  27182. var dimInfo = {name: dim};
  27183. var axisModel = coordSysDefine.axisMap.get(dim);
  27184. if (axisModel) {
  27185. var axisType = axisModel.get('type');
  27186. dimInfo.type = getDimensionTypeByAxis(axisType);
  27187. // dimInfo.stackable = isStackable(axisType);
  27188. }
  27189. return dimInfo;
  27190. });
  27191. }
  27192. if (!coordSysDimDefs) {
  27193. // Get dimensions from registered coordinate system
  27194. coordSysDimDefs = (registeredCoordSys && (
  27195. registeredCoordSys.getDimensionsInfo
  27196. ? registeredCoordSys.getDimensionsInfo()
  27197. : registeredCoordSys.dimensions.slice()
  27198. )) || ['x', 'y'];
  27199. }
  27200. var dimInfoList = createDimensions(source, {
  27201. coordDimensions: coordSysDimDefs,
  27202. generateCoord: opt.generateCoord
  27203. });
  27204. var firstCategoryDimIndex;
  27205. var hasNameEncode;
  27206. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  27207. var coordDim = dimInfo.coordDim;
  27208. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  27209. if (categoryAxisModel) {
  27210. if (firstCategoryDimIndex == null) {
  27211. firstCategoryDimIndex = dimIndex;
  27212. }
  27213. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  27214. }
  27215. if (dimInfo.otherDims.itemName != null) {
  27216. hasNameEncode = true;
  27217. }
  27218. });
  27219. if (!hasNameEncode && firstCategoryDimIndex != null) {
  27220. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  27221. }
  27222. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  27223. var list = new List(dimInfoList, seriesModel);
  27224. list.setCalculationInfo(stackCalculationInfo);
  27225. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  27226. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  27227. // Use dataIndex as ordinal value in categoryAxis
  27228. return dimIndex === firstCategoryDimIndex
  27229. ? dataIndex
  27230. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  27231. }
  27232. : null;
  27233. list.hasItemOption = false;
  27234. list.initData(source, null, dimValueGetter);
  27235. return list;
  27236. }
  27237. function isNeedCompleteOrdinalData(source) {
  27238. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  27239. var sampleItem = firstDataNotNull(source.data || []);
  27240. return sampleItem != null
  27241. && !isArray(getDataItemValue(sampleItem));
  27242. }
  27243. }
  27244. function firstDataNotNull(data) {
  27245. var i = 0;
  27246. while (i < data.length && data[i] == null) {
  27247. i++;
  27248. }
  27249. return data[i];
  27250. }
  27251. /*
  27252. * Licensed to the Apache Software Foundation (ASF) under one
  27253. * or more contributor license agreements. See the NOTICE file
  27254. * distributed with this work for additional information
  27255. * regarding copyright ownership. The ASF licenses this file
  27256. * to you under the Apache License, Version 2.0 (the
  27257. * "License"); you may not use this file except in compliance
  27258. * with the License. You may obtain a copy of the License at
  27259. *
  27260. * http://www.apache.org/licenses/LICENSE-2.0
  27261. *
  27262. * Unless required by applicable law or agreed to in writing,
  27263. * software distributed under the License is distributed on an
  27264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27265. * KIND, either express or implied. See the License for the
  27266. * specific language governing permissions and limitations
  27267. * under the License.
  27268. */
  27269. SeriesModel.extend({
  27270. type: 'series.line',
  27271. dependencies: ['grid', 'polar'],
  27272. getInitialData: function (option, ecModel) {
  27273. if (__DEV__) {
  27274. var coordSys = option.coordinateSystem;
  27275. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  27276. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  27277. }
  27278. }
  27279. return createListFromArray(this.getSource(), this);
  27280. },
  27281. defaultOption: {
  27282. zlevel: 0,
  27283. z: 2,
  27284. coordinateSystem: 'cartesian2d',
  27285. legendHoverLink: true,
  27286. hoverAnimation: true,
  27287. // stack: null
  27288. // xAxisIndex: 0,
  27289. // yAxisIndex: 0,
  27290. // polarIndex: 0,
  27291. // If clip the overflow value
  27292. clipOverflow: true,
  27293. // cursor: null,
  27294. label: {
  27295. position: 'top'
  27296. },
  27297. // itemStyle: {
  27298. // },
  27299. lineStyle: {
  27300. width: 2,
  27301. type: 'solid'
  27302. },
  27303. // areaStyle: {
  27304. // origin of areaStyle. Valid values:
  27305. // `'auto'/null/undefined`: from axisLine to data
  27306. // `'start'`: from min to data
  27307. // `'end'`: from data to max
  27308. // origin: 'auto'
  27309. // },
  27310. // false, 'start', 'end', 'middle'
  27311. step: false,
  27312. // Disabled if step is true
  27313. smooth: false,
  27314. smoothMonotone: null,
  27315. symbol: 'emptyCircle',
  27316. symbolSize: 4,
  27317. symbolRotate: null,
  27318. showSymbol: true,
  27319. // `false`: follow the label interval strategy.
  27320. // `true`: show all symbols.
  27321. // `'auto'`: If possible, show all symbols, otherwise
  27322. // follow the label interval strategy.
  27323. showAllSymbol: 'auto',
  27324. // Whether to connect break point.
  27325. connectNulls: false,
  27326. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  27327. sampling: 'none',
  27328. animationEasing: 'linear',
  27329. // Disable progressive
  27330. progressive: 0,
  27331. hoverLayerThreshold: Infinity
  27332. }
  27333. });
  27334. /*
  27335. * Licensed to the Apache Software Foundation (ASF) under one
  27336. * or more contributor license agreements. See the NOTICE file
  27337. * distributed with this work for additional information
  27338. * regarding copyright ownership. The ASF licenses this file
  27339. * to you under the Apache License, Version 2.0 (the
  27340. * "License"); you may not use this file except in compliance
  27341. * with the License. You may obtain a copy of the License at
  27342. *
  27343. * http://www.apache.org/licenses/LICENSE-2.0
  27344. *
  27345. * Unless required by applicable law or agreed to in writing,
  27346. * software distributed under the License is distributed on an
  27347. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27348. * KIND, either express or implied. See the License for the
  27349. * specific language governing permissions and limitations
  27350. * under the License.
  27351. */
  27352. // Symbol factory
  27353. /**
  27354. * Triangle shape
  27355. * @inner
  27356. */
  27357. var Triangle = extendShape({
  27358. type: 'triangle',
  27359. shape: {
  27360. cx: 0,
  27361. cy: 0,
  27362. width: 0,
  27363. height: 0
  27364. },
  27365. buildPath: function (path, shape) {
  27366. var cx = shape.cx;
  27367. var cy = shape.cy;
  27368. var width = shape.width / 2;
  27369. var height = shape.height / 2;
  27370. path.moveTo(cx, cy - height);
  27371. path.lineTo(cx + width, cy + height);
  27372. path.lineTo(cx - width, cy + height);
  27373. path.closePath();
  27374. }
  27375. });
  27376. /**
  27377. * Diamond shape
  27378. * @inner
  27379. */
  27380. var Diamond = extendShape({
  27381. type: 'diamond',
  27382. shape: {
  27383. cx: 0,
  27384. cy: 0,
  27385. width: 0,
  27386. height: 0
  27387. },
  27388. buildPath: function (path, shape) {
  27389. var cx = shape.cx;
  27390. var cy = shape.cy;
  27391. var width = shape.width / 2;
  27392. var height = shape.height / 2;
  27393. path.moveTo(cx, cy - height);
  27394. path.lineTo(cx + width, cy);
  27395. path.lineTo(cx, cy + height);
  27396. path.lineTo(cx - width, cy);
  27397. path.closePath();
  27398. }
  27399. });
  27400. /**
  27401. * Pin shape
  27402. * @inner
  27403. */
  27404. var Pin = extendShape({
  27405. type: 'pin',
  27406. shape: {
  27407. // x, y on the cusp
  27408. x: 0,
  27409. y: 0,
  27410. width: 0,
  27411. height: 0
  27412. },
  27413. buildPath: function (path, shape) {
  27414. var x = shape.x;
  27415. var y = shape.y;
  27416. var w = shape.width / 5 * 3;
  27417. // Height must be larger than width
  27418. var h = Math.max(w, shape.height);
  27419. var r = w / 2;
  27420. // Dist on y with tangent point and circle center
  27421. var dy = r * r / (h - r);
  27422. var cy = y - h + r + dy;
  27423. var angle = Math.asin(dy / r);
  27424. // Dist on x with tangent point and circle center
  27425. var dx = Math.cos(angle) * r;
  27426. var tanX = Math.sin(angle);
  27427. var tanY = Math.cos(angle);
  27428. var cpLen = r * 0.6;
  27429. var cpLen2 = r * 0.7;
  27430. path.moveTo(x - dx, cy + dy);
  27431. path.arc(
  27432. x, cy, r,
  27433. Math.PI - angle,
  27434. Math.PI * 2 + angle
  27435. );
  27436. path.bezierCurveTo(
  27437. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  27438. x, y - cpLen2,
  27439. x, y
  27440. );
  27441. path.bezierCurveTo(
  27442. x, y - cpLen2,
  27443. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  27444. x - dx, cy + dy
  27445. );
  27446. path.closePath();
  27447. }
  27448. });
  27449. /**
  27450. * Arrow shape
  27451. * @inner
  27452. */
  27453. var Arrow = extendShape({
  27454. type: 'arrow',
  27455. shape: {
  27456. x: 0,
  27457. y: 0,
  27458. width: 0,
  27459. height: 0
  27460. },
  27461. buildPath: function (ctx, shape) {
  27462. var height = shape.height;
  27463. var width = shape.width;
  27464. var x = shape.x;
  27465. var y = shape.y;
  27466. var dx = width / 3 * 2;
  27467. ctx.moveTo(x, y);
  27468. ctx.lineTo(x + dx, y + height);
  27469. ctx.lineTo(x, y + height / 4 * 3);
  27470. ctx.lineTo(x - dx, y + height);
  27471. ctx.lineTo(x, y);
  27472. ctx.closePath();
  27473. }
  27474. });
  27475. /**
  27476. * Map of path contructors
  27477. * @type {Object.<string, module:zrender/graphic/Path>}
  27478. */
  27479. var symbolCtors = {
  27480. line: Line,
  27481. rect: Rect,
  27482. roundRect: Rect,
  27483. square: Rect,
  27484. circle: Circle,
  27485. diamond: Diamond,
  27486. pin: Pin,
  27487. arrow: Arrow,
  27488. triangle: Triangle
  27489. };
  27490. var symbolShapeMakers = {
  27491. line: function (x, y, w, h, shape) {
  27492. // FIXME
  27493. shape.x1 = x;
  27494. shape.y1 = y + h / 2;
  27495. shape.x2 = x + w;
  27496. shape.y2 = y + h / 2;
  27497. },
  27498. rect: function (x, y, w, h, shape) {
  27499. shape.x = x;
  27500. shape.y = y;
  27501. shape.width = w;
  27502. shape.height = h;
  27503. },
  27504. roundRect: function (x, y, w, h, shape) {
  27505. shape.x = x;
  27506. shape.y = y;
  27507. shape.width = w;
  27508. shape.height = h;
  27509. shape.r = Math.min(w, h) / 4;
  27510. },
  27511. square: function (x, y, w, h, shape) {
  27512. var size = Math.min(w, h);
  27513. shape.x = x;
  27514. shape.y = y;
  27515. shape.width = size;
  27516. shape.height = size;
  27517. },
  27518. circle: function (x, y, w, h, shape) {
  27519. // Put circle in the center of square
  27520. shape.cx = x + w / 2;
  27521. shape.cy = y + h / 2;
  27522. shape.r = Math.min(w, h) / 2;
  27523. },
  27524. diamond: function (x, y, w, h, shape) {
  27525. shape.cx = x + w / 2;
  27526. shape.cy = y + h / 2;
  27527. shape.width = w;
  27528. shape.height = h;
  27529. },
  27530. pin: function (x, y, w, h, shape) {
  27531. shape.x = x + w / 2;
  27532. shape.y = y + h / 2;
  27533. shape.width = w;
  27534. shape.height = h;
  27535. },
  27536. arrow: function (x, y, w, h, shape) {
  27537. shape.x = x + w / 2;
  27538. shape.y = y + h / 2;
  27539. shape.width = w;
  27540. shape.height = h;
  27541. },
  27542. triangle: function (x, y, w, h, shape) {
  27543. shape.cx = x + w / 2;
  27544. shape.cy = y + h / 2;
  27545. shape.width = w;
  27546. shape.height = h;
  27547. }
  27548. };
  27549. var symbolBuildProxies = {};
  27550. each$1(symbolCtors, function (Ctor, name) {
  27551. symbolBuildProxies[name] = new Ctor();
  27552. });
  27553. var SymbolClz$2 = extendShape({
  27554. type: 'symbol',
  27555. shape: {
  27556. symbolType: '',
  27557. x: 0,
  27558. y: 0,
  27559. width: 0,
  27560. height: 0
  27561. },
  27562. beforeBrush: function () {
  27563. var style = this.style;
  27564. var shape = this.shape;
  27565. // FIXME
  27566. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  27567. style.textPosition = ['50%', '40%'];
  27568. style.textAlign = 'center';
  27569. style.textVerticalAlign = 'middle';
  27570. }
  27571. },
  27572. buildPath: function (ctx, shape, inBundle) {
  27573. var symbolType = shape.symbolType;
  27574. var proxySymbol = symbolBuildProxies[symbolType];
  27575. if (shape.symbolType !== 'none') {
  27576. if (!proxySymbol) {
  27577. // Default rect
  27578. symbolType = 'rect';
  27579. proxySymbol = symbolBuildProxies[symbolType];
  27580. }
  27581. symbolShapeMakers[symbolType](
  27582. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  27583. );
  27584. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  27585. }
  27586. }
  27587. });
  27588. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  27589. function symbolPathSetColor(color, innerColor) {
  27590. if (this.type !== 'image') {
  27591. var symbolStyle = this.style;
  27592. var symbolShape = this.shape;
  27593. if (symbolShape && symbolShape.symbolType === 'line') {
  27594. symbolStyle.stroke = color;
  27595. }
  27596. else if (this.__isEmptyBrush) {
  27597. symbolStyle.stroke = color;
  27598. symbolStyle.fill = innerColor || '#fff';
  27599. }
  27600. else {
  27601. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  27602. symbolStyle.fill && (symbolStyle.fill = color);
  27603. symbolStyle.stroke && (symbolStyle.stroke = color);
  27604. }
  27605. this.dirty(false);
  27606. }
  27607. }
  27608. /**
  27609. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  27610. * @param {string} symbolType
  27611. * @param {number} x
  27612. * @param {number} y
  27613. * @param {number} w
  27614. * @param {number} h
  27615. * @param {string} color
  27616. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  27617. * for path and image only.
  27618. */
  27619. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  27620. // TODO Support image object, DynamicImage.
  27621. var isEmpty = symbolType.indexOf('empty') === 0;
  27622. if (isEmpty) {
  27623. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  27624. }
  27625. var symbolPath;
  27626. if (symbolType.indexOf('image://') === 0) {
  27627. symbolPath = makeImage(
  27628. symbolType.slice(8),
  27629. new BoundingRect(x, y, w, h),
  27630. keepAspect ? 'center' : 'cover'
  27631. );
  27632. }
  27633. else if (symbolType.indexOf('path://') === 0) {
  27634. symbolPath = makePath(
  27635. symbolType.slice(7),
  27636. {},
  27637. new BoundingRect(x, y, w, h),
  27638. keepAspect ? 'center' : 'cover'
  27639. );
  27640. }
  27641. else {
  27642. symbolPath = new SymbolClz$2({
  27643. shape: {
  27644. symbolType: symbolType,
  27645. x: x,
  27646. y: y,
  27647. width: w,
  27648. height: h
  27649. }
  27650. });
  27651. }
  27652. symbolPath.__isEmptyBrush = isEmpty;
  27653. symbolPath.setColor = symbolPathSetColor;
  27654. symbolPath.setColor(color);
  27655. return symbolPath;
  27656. }
  27657. /*
  27658. * Licensed to the Apache Software Foundation (ASF) under one
  27659. * or more contributor license agreements. See the NOTICE file
  27660. * distributed with this work for additional information
  27661. * regarding copyright ownership. The ASF licenses this file
  27662. * to you under the Apache License, Version 2.0 (the
  27663. * "License"); you may not use this file except in compliance
  27664. * with the License. You may obtain a copy of the License at
  27665. *
  27666. * http://www.apache.org/licenses/LICENSE-2.0
  27667. *
  27668. * Unless required by applicable law or agreed to in writing,
  27669. * software distributed under the License is distributed on an
  27670. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27671. * KIND, either express or implied. See the License for the
  27672. * specific language governing permissions and limitations
  27673. * under the License.
  27674. */
  27675. /**
  27676. * @param {module:echarts/data/List} data
  27677. * @param {number} dataIndex
  27678. * @return {string} label string. Not null/undefined
  27679. */
  27680. function getDefaultLabel(data, dataIndex) {
  27681. var labelDims = data.mapDimension('defaultedLabel', true);
  27682. var len = labelDims.length;
  27683. // Simple optimization (in lots of cases, label dims length is 1)
  27684. if (len === 1) {
  27685. return retrieveRawValue(data, dataIndex, labelDims[0]);
  27686. }
  27687. else if (len) {
  27688. var vals = [];
  27689. for (var i = 0; i < labelDims.length; i++) {
  27690. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  27691. vals.push(val);
  27692. }
  27693. return vals.join(' ');
  27694. }
  27695. }
  27696. /*
  27697. * Licensed to the Apache Software Foundation (ASF) under one
  27698. * or more contributor license agreements. See the NOTICE file
  27699. * distributed with this work for additional information
  27700. * regarding copyright ownership. The ASF licenses this file
  27701. * to you under the Apache License, Version 2.0 (the
  27702. * "License"); you may not use this file except in compliance
  27703. * with the License. You may obtain a copy of the License at
  27704. *
  27705. * http://www.apache.org/licenses/LICENSE-2.0
  27706. *
  27707. * Unless required by applicable law or agreed to in writing,
  27708. * software distributed under the License is distributed on an
  27709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27710. * KIND, either express or implied. See the License for the
  27711. * specific language governing permissions and limitations
  27712. * under the License.
  27713. */
  27714. /**
  27715. * @module echarts/chart/helper/Symbol
  27716. */
  27717. /**
  27718. * @constructor
  27719. * @alias {module:echarts/chart/helper/Symbol}
  27720. * @param {module:echarts/data/List} data
  27721. * @param {number} idx
  27722. * @extends {module:zrender/graphic/Group}
  27723. */
  27724. function SymbolClz(data, idx, seriesScope) {
  27725. Group.call(this);
  27726. this.updateData(data, idx, seriesScope);
  27727. }
  27728. var symbolProto = SymbolClz.prototype;
  27729. /**
  27730. * @public
  27731. * @static
  27732. * @param {module:echarts/data/List} data
  27733. * @param {number} dataIndex
  27734. * @return {Array.<number>} [width, height]
  27735. */
  27736. var getSymbolSize = SymbolClz.getSymbolSize = function (data, idx) {
  27737. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  27738. return symbolSize instanceof Array
  27739. ? symbolSize.slice()
  27740. : [+symbolSize, +symbolSize];
  27741. };
  27742. function getScale(symbolSize) {
  27743. return [symbolSize[0] / 2, symbolSize[1] / 2];
  27744. }
  27745. function driftSymbol(dx, dy) {
  27746. this.parent.drift(dx, dy);
  27747. }
  27748. symbolProto._createSymbol = function (
  27749. symbolType,
  27750. data,
  27751. idx,
  27752. symbolSize,
  27753. keepAspect
  27754. ) {
  27755. // Remove paths created before
  27756. this.removeAll();
  27757. var color = data.getItemVisual(idx, 'color');
  27758. // var symbolPath = createSymbol(
  27759. // symbolType, -0.5, -0.5, 1, 1, color
  27760. // );
  27761. // If width/height are set too small (e.g., set to 1) on ios10
  27762. // and macOS Sierra, a circle stroke become a rect, no matter what
  27763. // the scale is set. So we set width/height as 2. See #4150.
  27764. var symbolPath = createSymbol(
  27765. symbolType, -1, -1, 2, 2, color, keepAspect
  27766. );
  27767. symbolPath.attr({
  27768. z2: 100,
  27769. culling: true,
  27770. scale: getScale(symbolSize)
  27771. });
  27772. // Rewrite drift method
  27773. symbolPath.drift = driftSymbol;
  27774. this._symbolType = symbolType;
  27775. this.add(symbolPath);
  27776. };
  27777. /**
  27778. * Stop animation
  27779. * @param {boolean} toLastFrame
  27780. */
  27781. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  27782. this.childAt(0).stopAnimation(toLastFrame);
  27783. };
  27784. /**
  27785. * FIXME:
  27786. * Caution: This method breaks the encapsulation of this module,
  27787. * but it indeed brings convenience. So do not use the method
  27788. * unless you detailedly know all the implements of `Symbol`,
  27789. * especially animation.
  27790. *
  27791. * Get symbol path element.
  27792. */
  27793. symbolProto.getSymbolPath = function () {
  27794. return this.childAt(0);
  27795. };
  27796. /**
  27797. * Get scale(aka, current symbol size).
  27798. * Including the change caused by animation
  27799. */
  27800. symbolProto.getScale = function () {
  27801. return this.childAt(0).scale;
  27802. };
  27803. /**
  27804. * Highlight symbol
  27805. */
  27806. symbolProto.highlight = function () {
  27807. this.childAt(0).trigger('emphasis');
  27808. };
  27809. /**
  27810. * Downplay symbol
  27811. */
  27812. symbolProto.downplay = function () {
  27813. this.childAt(0).trigger('normal');
  27814. };
  27815. /**
  27816. * @param {number} zlevel
  27817. * @param {number} z
  27818. */
  27819. symbolProto.setZ = function (zlevel, z) {
  27820. var symbolPath = this.childAt(0);
  27821. symbolPath.zlevel = zlevel;
  27822. symbolPath.z = z;
  27823. };
  27824. symbolProto.setDraggable = function (draggable) {
  27825. var symbolPath = this.childAt(0);
  27826. symbolPath.draggable = draggable;
  27827. symbolPath.cursor = draggable ? 'move' : 'pointer';
  27828. };
  27829. /**
  27830. * Update symbol properties
  27831. * @param {module:echarts/data/List} data
  27832. * @param {number} idx
  27833. * @param {Object} [seriesScope]
  27834. * @param {Object} [seriesScope.itemStyle]
  27835. * @param {Object} [seriesScope.hoverItemStyle]
  27836. * @param {Object} [seriesScope.symbolRotate]
  27837. * @param {Object} [seriesScope.symbolOffset]
  27838. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  27839. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  27840. * @param {boolean} [seriesScope.hoverAnimation]
  27841. * @param {Object} [seriesScope.cursorStyle]
  27842. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  27843. * @param {string} [seriesScope.symbolInnerColor]
  27844. * @param {Object} [seriesScope.fadeIn=false]
  27845. */
  27846. symbolProto.updateData = function (data, idx, seriesScope) {
  27847. this.silent = false;
  27848. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  27849. var seriesModel = data.hostModel;
  27850. var symbolSize = getSymbolSize(data, idx);
  27851. var isInit = symbolType !== this._symbolType;
  27852. if (isInit) {
  27853. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  27854. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  27855. }
  27856. else {
  27857. var symbolPath = this.childAt(0);
  27858. symbolPath.silent = false;
  27859. updateProps(symbolPath, {
  27860. scale: getScale(symbolSize)
  27861. }, seriesModel, idx);
  27862. }
  27863. this._updateCommon(data, idx, symbolSize, seriesScope);
  27864. if (isInit) {
  27865. var symbolPath = this.childAt(0);
  27866. var fadeIn = seriesScope && seriesScope.fadeIn;
  27867. var target = {scale: symbolPath.scale.slice()};
  27868. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  27869. symbolPath.scale = [0, 0];
  27870. fadeIn && (symbolPath.style.opacity = 0);
  27871. initProps(symbolPath, target, seriesModel, idx);
  27872. }
  27873. this._seriesModel = seriesModel;
  27874. };
  27875. // Update common properties
  27876. var normalStyleAccessPath = ['itemStyle'];
  27877. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  27878. var normalLabelAccessPath = ['label'];
  27879. var emphasisLabelAccessPath = ['emphasis', 'label'];
  27880. /**
  27881. * @param {module:echarts/data/List} data
  27882. * @param {number} idx
  27883. * @param {Array.<number>} symbolSize
  27884. * @param {Object} [seriesScope]
  27885. */
  27886. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  27887. var symbolPath = this.childAt(0);
  27888. var seriesModel = data.hostModel;
  27889. var color = data.getItemVisual(idx, 'color');
  27890. // Reset style
  27891. if (symbolPath.type !== 'image') {
  27892. symbolPath.useStyle({
  27893. strokeNoScale: true
  27894. });
  27895. }
  27896. var itemStyle = seriesScope && seriesScope.itemStyle;
  27897. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  27898. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  27899. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  27900. var labelModel = seriesScope && seriesScope.labelModel;
  27901. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  27902. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  27903. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  27904. if (!seriesScope || data.hasItemOption) {
  27905. var itemModel = (seriesScope && seriesScope.itemModel)
  27906. ? seriesScope.itemModel : data.getItemModel(idx);
  27907. // Color must be excluded.
  27908. // Because symbol provide setColor individually to set fill and stroke
  27909. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  27910. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  27911. symbolRotate = itemModel.getShallow('symbolRotate');
  27912. symbolOffset = itemModel.getShallow('symbolOffset');
  27913. labelModel = itemModel.getModel(normalLabelAccessPath);
  27914. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  27915. hoverAnimation = itemModel.getShallow('hoverAnimation');
  27916. cursorStyle = itemModel.getShallow('cursor');
  27917. }
  27918. else {
  27919. hoverItemStyle = extend({}, hoverItemStyle);
  27920. }
  27921. var elStyle = symbolPath.style;
  27922. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  27923. if (symbolOffset) {
  27924. symbolPath.attr('position', [
  27925. parsePercent$1(symbolOffset[0], symbolSize[0]),
  27926. parsePercent$1(symbolOffset[1], symbolSize[1])
  27927. ]);
  27928. }
  27929. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  27930. // PENDING setColor before setStyle!!!
  27931. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  27932. symbolPath.setStyle(itemStyle);
  27933. var opacity = data.getItemVisual(idx, 'opacity');
  27934. if (opacity != null) {
  27935. elStyle.opacity = opacity;
  27936. }
  27937. var liftZ = data.getItemVisual(idx, 'liftZ');
  27938. var z2Origin = symbolPath.__z2Origin;
  27939. if (liftZ != null) {
  27940. if (z2Origin == null) {
  27941. symbolPath.__z2Origin = symbolPath.z2;
  27942. symbolPath.z2 += liftZ;
  27943. }
  27944. }
  27945. else if (z2Origin != null) {
  27946. symbolPath.z2 = z2Origin;
  27947. symbolPath.__z2Origin = null;
  27948. }
  27949. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  27950. setLabelStyle(
  27951. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  27952. {
  27953. labelFetcher: seriesModel,
  27954. labelDataIndex: idx,
  27955. defaultText: getLabelDefaultText,
  27956. isRectText: true,
  27957. autoColor: color
  27958. }
  27959. );
  27960. // Do not execute util needed.
  27961. function getLabelDefaultText(idx, opt) {
  27962. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  27963. }
  27964. symbolPath.off('mouseover')
  27965. .off('mouseout')
  27966. .off('emphasis')
  27967. .off('normal');
  27968. symbolPath.hoverStyle = hoverItemStyle;
  27969. // FIXME
  27970. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  27971. setHoverStyle(symbolPath);
  27972. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  27973. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  27974. // Note: consider `off`, should use static function here.
  27975. symbolPath.on('mouseover', onMouseOver)
  27976. .on('mouseout', onMouseOut)
  27977. .on('emphasis', onEmphasis)
  27978. .on('normal', onNormal);
  27979. }
  27980. };
  27981. function onMouseOver() {
  27982. // see comment in `graphic.isInEmphasis`
  27983. !isInEmphasis(this) && onEmphasis.call(this);
  27984. }
  27985. function onMouseOut() {
  27986. // see comment in `graphic.isInEmphasis`
  27987. !isInEmphasis(this) && onNormal.call(this);
  27988. }
  27989. function onEmphasis() {
  27990. // Do not support this hover animation util some scenario required.
  27991. // Animation can only be supported in hover layer when using `el.incremetal`.
  27992. if (this.incremental || this.useHoverLayer) {
  27993. return;
  27994. }
  27995. var scale = this.__symbolOriginalScale;
  27996. var ratio = scale[1] / scale[0];
  27997. this.animateTo({
  27998. scale: [
  27999. Math.max(scale[0] * 1.1, scale[0] + 3),
  28000. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  28001. ]
  28002. }, 400, 'elasticOut');
  28003. }
  28004. function onNormal() {
  28005. if (this.incremental || this.useHoverLayer) {
  28006. return;
  28007. }
  28008. this.animateTo({
  28009. scale: this.__symbolOriginalScale
  28010. }, 400, 'elasticOut');
  28011. }
  28012. /**
  28013. * @param {Function} cb
  28014. * @param {Object} [opt]
  28015. * @param {Object} [opt.keepLabel=true]
  28016. */
  28017. symbolProto.fadeOut = function (cb, opt) {
  28018. var symbolPath = this.childAt(0);
  28019. // Avoid mistaken hover when fading out
  28020. this.silent = symbolPath.silent = true;
  28021. // Not show text when animating
  28022. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  28023. updateProps(
  28024. symbolPath,
  28025. {
  28026. style: {opacity: 0},
  28027. scale: [0, 0]
  28028. },
  28029. this._seriesModel,
  28030. this.dataIndex,
  28031. cb
  28032. );
  28033. };
  28034. inherits(SymbolClz, Group);
  28035. /*
  28036. * Licensed to the Apache Software Foundation (ASF) under one
  28037. * or more contributor license agreements. See the NOTICE file
  28038. * distributed with this work for additional information
  28039. * regarding copyright ownership. The ASF licenses this file
  28040. * to you under the Apache License, Version 2.0 (the
  28041. * "License"); you may not use this file except in compliance
  28042. * with the License. You may obtain a copy of the License at
  28043. *
  28044. * http://www.apache.org/licenses/LICENSE-2.0
  28045. *
  28046. * Unless required by applicable law or agreed to in writing,
  28047. * software distributed under the License is distributed on an
  28048. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28049. * KIND, either express or implied. See the License for the
  28050. * specific language governing permissions and limitations
  28051. * under the License.
  28052. */
  28053. /**
  28054. * @module echarts/chart/helper/SymbolDraw
  28055. */
  28056. /**
  28057. * @constructor
  28058. * @alias module:echarts/chart/helper/SymbolDraw
  28059. * @param {module:zrender/graphic/Group} [symbolCtor]
  28060. */
  28061. function SymbolDraw(symbolCtor) {
  28062. this.group = new Group();
  28063. this._symbolCtor = symbolCtor || SymbolClz;
  28064. }
  28065. var symbolDrawProto = SymbolDraw.prototype;
  28066. function symbolNeedsDraw(data, point, idx, opt) {
  28067. return point && !isNaN(point[0]) && !isNaN(point[1])
  28068. && !(opt.isIgnore && opt.isIgnore(idx))
  28069. // We do not set clipShape on group, because it will cut part of
  28070. // the symbol element shape. We use the same clip shape here as
  28071. // the line clip.
  28072. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  28073. && data.getItemVisual(idx, 'symbol') !== 'none';
  28074. }
  28075. /**
  28076. * Update symbols draw by new data
  28077. * @param {module:echarts/data/List} data
  28078. * @param {Object} [opt] Or isIgnore
  28079. * @param {Function} [opt.isIgnore]
  28080. * @param {Object} [opt.clipShape]
  28081. */
  28082. symbolDrawProto.updateData = function (data, opt) {
  28083. opt = normalizeUpdateOpt(opt);
  28084. var group = this.group;
  28085. var seriesModel = data.hostModel;
  28086. var oldData = this._data;
  28087. var SymbolCtor = this._symbolCtor;
  28088. var seriesScope = makeSeriesScope(data);
  28089. // There is no oldLineData only when first rendering or switching from
  28090. // stream mode to normal mode, where previous elements should be removed.
  28091. if (!oldData) {
  28092. group.removeAll();
  28093. }
  28094. data.diff(oldData)
  28095. .add(function (newIdx) {
  28096. var point = data.getItemLayout(newIdx);
  28097. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  28098. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  28099. symbolEl.attr('position', point);
  28100. data.setItemGraphicEl(newIdx, symbolEl);
  28101. group.add(symbolEl);
  28102. }
  28103. })
  28104. .update(function (newIdx, oldIdx) {
  28105. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  28106. var point = data.getItemLayout(newIdx);
  28107. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  28108. group.remove(symbolEl);
  28109. return;
  28110. }
  28111. if (!symbolEl) {
  28112. symbolEl = new SymbolCtor(data, newIdx);
  28113. symbolEl.attr('position', point);
  28114. }
  28115. else {
  28116. symbolEl.updateData(data, newIdx, seriesScope);
  28117. updateProps(symbolEl, {
  28118. position: point
  28119. }, seriesModel);
  28120. }
  28121. // Add back
  28122. group.add(symbolEl);
  28123. data.setItemGraphicEl(newIdx, symbolEl);
  28124. })
  28125. .remove(function (oldIdx) {
  28126. var el = oldData.getItemGraphicEl(oldIdx);
  28127. el && el.fadeOut(function () {
  28128. group.remove(el);
  28129. });
  28130. })
  28131. .execute();
  28132. this._data = data;
  28133. };
  28134. symbolDrawProto.isPersistent = function () {
  28135. return true;
  28136. };
  28137. symbolDrawProto.updateLayout = function () {
  28138. var data = this._data;
  28139. if (data) {
  28140. // Not use animation
  28141. data.eachItemGraphicEl(function (el, idx) {
  28142. var point = data.getItemLayout(idx);
  28143. el.attr('position', point);
  28144. });
  28145. }
  28146. };
  28147. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  28148. this._seriesScope = makeSeriesScope(data);
  28149. this._data = null;
  28150. this.group.removeAll();
  28151. };
  28152. /**
  28153. * Update symbols draw by new data
  28154. * @param {module:echarts/data/List} data
  28155. * @param {Object} [opt] Or isIgnore
  28156. * @param {Function} [opt.isIgnore]
  28157. * @param {Object} [opt.clipShape]
  28158. */
  28159. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  28160. opt = normalizeUpdateOpt(opt);
  28161. function updateIncrementalAndHover(el) {
  28162. if (!el.isGroup) {
  28163. el.incremental = el.useHoverLayer = true;
  28164. }
  28165. }
  28166. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  28167. var point = data.getItemLayout(idx);
  28168. if (symbolNeedsDraw(data, point, idx, opt)) {
  28169. var el = new this._symbolCtor(data, idx, this._seriesScope);
  28170. el.traverse(updateIncrementalAndHover);
  28171. el.attr('position', point);
  28172. this.group.add(el);
  28173. data.setItemGraphicEl(idx, el);
  28174. }
  28175. }
  28176. };
  28177. function normalizeUpdateOpt(opt) {
  28178. if (opt != null && !isObject$1(opt)) {
  28179. opt = {isIgnore: opt};
  28180. }
  28181. return opt || {};
  28182. }
  28183. symbolDrawProto.remove = function (enableAnimation) {
  28184. var group = this.group;
  28185. var data = this._data;
  28186. // Incremental model do not have this._data.
  28187. if (data && enableAnimation) {
  28188. data.eachItemGraphicEl(function (el) {
  28189. el.fadeOut(function () {
  28190. group.remove(el);
  28191. });
  28192. });
  28193. }
  28194. else {
  28195. group.removeAll();
  28196. }
  28197. };
  28198. function makeSeriesScope(data) {
  28199. var seriesModel = data.hostModel;
  28200. return {
  28201. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  28202. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  28203. symbolRotate: seriesModel.get('symbolRotate'),
  28204. symbolOffset: seriesModel.get('symbolOffset'),
  28205. hoverAnimation: seriesModel.get('hoverAnimation'),
  28206. labelModel: seriesModel.getModel('label'),
  28207. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  28208. cursorStyle: seriesModel.get('cursor')
  28209. };
  28210. }
  28211. /*
  28212. * Licensed to the Apache Software Foundation (ASF) under one
  28213. * or more contributor license agreements. See the NOTICE file
  28214. * distributed with this work for additional information
  28215. * regarding copyright ownership. The ASF licenses this file
  28216. * to you under the Apache License, Version 2.0 (the
  28217. * "License"); you may not use this file except in compliance
  28218. * with the License. You may obtain a copy of the License at
  28219. *
  28220. * http://www.apache.org/licenses/LICENSE-2.0
  28221. *
  28222. * Unless required by applicable law or agreed to in writing,
  28223. * software distributed under the License is distributed on an
  28224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28225. * KIND, either express or implied. See the License for the
  28226. * specific language governing permissions and limitations
  28227. * under the License.
  28228. */
  28229. /**
  28230. * @param {Object} coordSys
  28231. * @param {module:echarts/data/List} data
  28232. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  28233. */
  28234. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  28235. var baseAxis = coordSys.getBaseAxis();
  28236. var valueAxis = coordSys.getOtherAxis(baseAxis);
  28237. var valueStart = getValueStart(valueAxis, valueOrigin);
  28238. var baseAxisDim = baseAxis.dim;
  28239. var valueAxisDim = valueAxis.dim;
  28240. var valueDim = data.mapDimension(valueAxisDim);
  28241. var baseDim = data.mapDimension(baseAxisDim);
  28242. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  28243. var dims = map(coordSys.dimensions, function (coordDim) {
  28244. return data.mapDimension(coordDim);
  28245. });
  28246. var stacked;
  28247. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  28248. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  28249. dims[0] = stackResultDim;
  28250. }
  28251. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  28252. dims[1] = stackResultDim;
  28253. }
  28254. return {
  28255. dataDimsForPoint: dims,
  28256. valueStart: valueStart,
  28257. valueAxisDim: valueAxisDim,
  28258. baseAxisDim: baseAxisDim,
  28259. stacked: !!stacked,
  28260. valueDim: valueDim,
  28261. baseDim: baseDim,
  28262. baseDataOffset: baseDataOffset,
  28263. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  28264. };
  28265. }
  28266. function getValueStart(valueAxis, valueOrigin) {
  28267. var valueStart = 0;
  28268. var extent = valueAxis.scale.getExtent();
  28269. if (valueOrigin === 'start') {
  28270. valueStart = extent[0];
  28271. }
  28272. else if (valueOrigin === 'end') {
  28273. valueStart = extent[1];
  28274. }
  28275. // auto
  28276. else {
  28277. // Both positive
  28278. if (extent[0] > 0) {
  28279. valueStart = extent[0];
  28280. }
  28281. // Both negative
  28282. else if (extent[1] < 0) {
  28283. valueStart = extent[1];
  28284. }
  28285. // If is one positive, and one negative, onZero shall be true
  28286. }
  28287. return valueStart;
  28288. }
  28289. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  28290. var value = NaN;
  28291. if (dataCoordInfo.stacked) {
  28292. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  28293. }
  28294. if (isNaN(value)) {
  28295. value = dataCoordInfo.valueStart;
  28296. }
  28297. var baseDataOffset = dataCoordInfo.baseDataOffset;
  28298. var stackedData = [];
  28299. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  28300. stackedData[1 - baseDataOffset] = value;
  28301. return coordSys.dataToPoint(stackedData);
  28302. }
  28303. /*
  28304. * Licensed to the Apache Software Foundation (ASF) under one
  28305. * or more contributor license agreements. See the NOTICE file
  28306. * distributed with this work for additional information
  28307. * regarding copyright ownership. The ASF licenses this file
  28308. * to you under the Apache License, Version 2.0 (the
  28309. * "License"); you may not use this file except in compliance
  28310. * with the License. You may obtain a copy of the License at
  28311. *
  28312. * http://www.apache.org/licenses/LICENSE-2.0
  28313. *
  28314. * Unless required by applicable law or agreed to in writing,
  28315. * software distributed under the License is distributed on an
  28316. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28317. * KIND, either express or implied. See the License for the
  28318. * specific language governing permissions and limitations
  28319. * under the License.
  28320. */
  28321. // var arrayDiff = require('zrender/src/core/arrayDiff');
  28322. // 'zrender/src/core/arrayDiff' has been used before, but it did
  28323. // not do well in performance when roam with fixed dataZoom window.
  28324. // function convertToIntId(newIdList, oldIdList) {
  28325. // // Generate int id instead of string id.
  28326. // // Compare string maybe slow in score function of arrDiff
  28327. // // Assume id in idList are all unique
  28328. // var idIndicesMap = {};
  28329. // var idx = 0;
  28330. // for (var i = 0; i < newIdList.length; i++) {
  28331. // idIndicesMap[newIdList[i]] = idx;
  28332. // newIdList[i] = idx++;
  28333. // }
  28334. // for (var i = 0; i < oldIdList.length; i++) {
  28335. // var oldId = oldIdList[i];
  28336. // // Same with newIdList
  28337. // if (idIndicesMap[oldId]) {
  28338. // oldIdList[i] = idIndicesMap[oldId];
  28339. // }
  28340. // else {
  28341. // oldIdList[i] = idx++;
  28342. // }
  28343. // }
  28344. // }
  28345. function diffData(oldData, newData) {
  28346. var diffResult = [];
  28347. newData.diff(oldData)
  28348. .add(function (idx) {
  28349. diffResult.push({cmd: '+', idx: idx});
  28350. })
  28351. .update(function (newIdx, oldIdx) {
  28352. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  28353. })
  28354. .remove(function (idx) {
  28355. diffResult.push({cmd: '-', idx: idx});
  28356. })
  28357. .execute();
  28358. return diffResult;
  28359. }
  28360. var lineAnimationDiff = function (
  28361. oldData, newData,
  28362. oldStackedOnPoints, newStackedOnPoints,
  28363. oldCoordSys, newCoordSys,
  28364. oldValueOrigin, newValueOrigin
  28365. ) {
  28366. var diff = diffData(oldData, newData);
  28367. // var newIdList = newData.mapArray(newData.getId);
  28368. // var oldIdList = oldData.mapArray(oldData.getId);
  28369. // convertToIntId(newIdList, oldIdList);
  28370. // // FIXME One data ?
  28371. // diff = arrayDiff(oldIdList, newIdList);
  28372. var currPoints = [];
  28373. var nextPoints = [];
  28374. // Points for stacking base line
  28375. var currStackedPoints = [];
  28376. var nextStackedPoints = [];
  28377. var status = [];
  28378. var sortedIndices = [];
  28379. var rawIndices = [];
  28380. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  28381. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  28382. for (var i = 0; i < diff.length; i++) {
  28383. var diffItem = diff[i];
  28384. var pointAdded = true;
  28385. // FIXME, animation is not so perfect when dataZoom window moves fast
  28386. // Which is in case remvoing or add more than one data in the tail or head
  28387. switch (diffItem.cmd) {
  28388. case '=':
  28389. var currentPt = oldData.getItemLayout(diffItem.idx);
  28390. var nextPt = newData.getItemLayout(diffItem.idx1);
  28391. // If previous data is NaN, use next point directly
  28392. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  28393. currentPt = nextPt.slice();
  28394. }
  28395. currPoints.push(currentPt);
  28396. nextPoints.push(nextPt);
  28397. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  28398. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  28399. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  28400. break;
  28401. case '+':
  28402. var idx = diffItem.idx;
  28403. currPoints.push(
  28404. oldCoordSys.dataToPoint([
  28405. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  28406. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  28407. ])
  28408. );
  28409. nextPoints.push(newData.getItemLayout(idx).slice());
  28410. currStackedPoints.push(
  28411. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  28412. );
  28413. nextStackedPoints.push(newStackedOnPoints[idx]);
  28414. rawIndices.push(newData.getRawIndex(idx));
  28415. break;
  28416. case '-':
  28417. var idx = diffItem.idx;
  28418. var rawIndex = oldData.getRawIndex(idx);
  28419. // Data is replaced. In the case of dynamic data queue
  28420. // FIXME FIXME FIXME
  28421. if (rawIndex !== idx) {
  28422. currPoints.push(oldData.getItemLayout(idx));
  28423. nextPoints.push(newCoordSys.dataToPoint([
  28424. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  28425. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  28426. ]));
  28427. currStackedPoints.push(oldStackedOnPoints[idx]);
  28428. nextStackedPoints.push(
  28429. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  28430. );
  28431. rawIndices.push(rawIndex);
  28432. }
  28433. else {
  28434. pointAdded = false;
  28435. }
  28436. }
  28437. // Original indices
  28438. if (pointAdded) {
  28439. status.push(diffItem);
  28440. sortedIndices.push(sortedIndices.length);
  28441. }
  28442. }
  28443. // Diff result may be crossed if all items are changed
  28444. // Sort by data index
  28445. sortedIndices.sort(function (a, b) {
  28446. return rawIndices[a] - rawIndices[b];
  28447. });
  28448. var sortedCurrPoints = [];
  28449. var sortedNextPoints = [];
  28450. var sortedCurrStackedPoints = [];
  28451. var sortedNextStackedPoints = [];
  28452. var sortedStatus = [];
  28453. for (var i = 0; i < sortedIndices.length; i++) {
  28454. var idx = sortedIndices[i];
  28455. sortedCurrPoints[i] = currPoints[idx];
  28456. sortedNextPoints[i] = nextPoints[idx];
  28457. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  28458. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  28459. sortedStatus[i] = status[idx];
  28460. }
  28461. return {
  28462. current: sortedCurrPoints,
  28463. next: sortedNextPoints,
  28464. stackedOnCurrent: sortedCurrStackedPoints,
  28465. stackedOnNext: sortedNextStackedPoints,
  28466. status: sortedStatus
  28467. };
  28468. };
  28469. /*
  28470. * Licensed to the Apache Software Foundation (ASF) under one
  28471. * or more contributor license agreements. See the NOTICE file
  28472. * distributed with this work for additional information
  28473. * regarding copyright ownership. The ASF licenses this file
  28474. * to you under the Apache License, Version 2.0 (the
  28475. * "License"); you may not use this file except in compliance
  28476. * with the License. You may obtain a copy of the License at
  28477. *
  28478. * http://www.apache.org/licenses/LICENSE-2.0
  28479. *
  28480. * Unless required by applicable law or agreed to in writing,
  28481. * software distributed under the License is distributed on an
  28482. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28483. * KIND, either express or implied. See the License for the
  28484. * specific language governing permissions and limitations
  28485. * under the License.
  28486. */
  28487. // Poly path support NaN point
  28488. var vec2Min = min;
  28489. var vec2Max = max;
  28490. var scaleAndAdd$1 = scaleAndAdd;
  28491. var v2Copy = copy;
  28492. // Temporary variable
  28493. var v = [];
  28494. var cp0 = [];
  28495. var cp1 = [];
  28496. function isPointNull(p) {
  28497. return isNaN(p[0]) || isNaN(p[1]);
  28498. }
  28499. function drawSegment(
  28500. ctx, points, start, segLen, allLen,
  28501. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28502. ) {
  28503. // if (smoothMonotone == null) {
  28504. // if (isMono(points, 'x')) {
  28505. // return drawMono(ctx, points, start, segLen, allLen,
  28506. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  28507. // }
  28508. // else if (isMono(points, 'y')) {
  28509. // return drawMono(ctx, points, start, segLen, allLen,
  28510. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  28511. // }
  28512. // else {
  28513. // return drawNonMono.apply(this, arguments);
  28514. // }
  28515. // }
  28516. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  28517. // return drawMono.apply(this, arguments);
  28518. // }
  28519. // else {
  28520. // return drawNonMono.apply(this, arguments);
  28521. // }
  28522. if (smoothMonotone === 'none' || !smoothMonotone) {
  28523. return drawNonMono.apply(this, arguments);
  28524. }
  28525. else {
  28526. return drawMono.apply(this, arguments);
  28527. }
  28528. }
  28529. /**
  28530. * Check if points is in monotone.
  28531. *
  28532. * @param {number[][]} points Array of points which is in [x, y] form
  28533. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  28534. * dimension that is checking.
  28535. * If is 'none', `drawNonMono` should be
  28536. * called.
  28537. * If is undefined, either being monotone
  28538. * in 'x' or 'y' will call `drawMono`.
  28539. */
  28540. // function isMono(points, smoothMonotone) {
  28541. // if (points.length <= 1) {
  28542. // return true;
  28543. // }
  28544. // var dim = smoothMonotone === 'x' ? 0 : 1;
  28545. // var last = points[0][dim];
  28546. // var lastDiff = 0;
  28547. // for (var i = 1; i < points.length; ++i) {
  28548. // var diff = points[i][dim] - last;
  28549. // if (!isNaN(diff) && !isNaN(lastDiff)
  28550. // && diff !== 0 && lastDiff !== 0
  28551. // && ((diff >= 0) !== (lastDiff >= 0))
  28552. // ) {
  28553. // return false;
  28554. // }
  28555. // if (!isNaN(diff) && diff !== 0) {
  28556. // lastDiff = diff;
  28557. // last = points[i][dim];
  28558. // }
  28559. // }
  28560. // return true;
  28561. // }
  28562. /**
  28563. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  28564. * control points will be used. This should be used when points are monotone
  28565. * either in x or y dimension.
  28566. */
  28567. function drawMono(
  28568. ctx, points, start, segLen, allLen,
  28569. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28570. ) {
  28571. var prevIdx = 0;
  28572. var idx = start;
  28573. for (var k = 0; k < segLen; k++) {
  28574. var p = points[idx];
  28575. if (idx >= allLen || idx < 0) {
  28576. break;
  28577. }
  28578. if (isPointNull(p)) {
  28579. if (connectNulls) {
  28580. idx += dir;
  28581. continue;
  28582. }
  28583. break;
  28584. }
  28585. if (idx === start) {
  28586. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28587. }
  28588. else {
  28589. if (smooth > 0) {
  28590. var prevP = points[prevIdx];
  28591. var dim = smoothMonotone === 'y' ? 1 : 0;
  28592. // Length of control point to p, either in x or y, but not both
  28593. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  28594. v2Copy(cp0, prevP);
  28595. cp0[dim] = prevP[dim] + ctrlLen;
  28596. v2Copy(cp1, p);
  28597. cp1[dim] = p[dim] - ctrlLen;
  28598. ctx.bezierCurveTo(
  28599. cp0[0], cp0[1],
  28600. cp1[0], cp1[1],
  28601. p[0], p[1]
  28602. );
  28603. }
  28604. else {
  28605. ctx.lineTo(p[0], p[1]);
  28606. }
  28607. }
  28608. prevIdx = idx;
  28609. idx += dir;
  28610. }
  28611. return k;
  28612. }
  28613. /**
  28614. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  28615. * situations. This should be used when points are non-monotone neither in x or
  28616. * y dimension.
  28617. */
  28618. function drawNonMono(
  28619. ctx, points, start, segLen, allLen,
  28620. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  28621. ) {
  28622. var prevIdx = 0;
  28623. var idx = start;
  28624. for (var k = 0; k < segLen; k++) {
  28625. var p = points[idx];
  28626. if (idx >= allLen || idx < 0) {
  28627. break;
  28628. }
  28629. if (isPointNull(p)) {
  28630. if (connectNulls) {
  28631. idx += dir;
  28632. continue;
  28633. }
  28634. break;
  28635. }
  28636. if (idx === start) {
  28637. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  28638. v2Copy(cp0, p);
  28639. }
  28640. else {
  28641. if (smooth > 0) {
  28642. var nextIdx = idx + dir;
  28643. var nextP = points[nextIdx];
  28644. if (connectNulls) {
  28645. // Find next point not null
  28646. while (nextP && isPointNull(points[nextIdx])) {
  28647. nextIdx += dir;
  28648. nextP = points[nextIdx];
  28649. }
  28650. }
  28651. var ratioNextSeg = 0.5;
  28652. var prevP = points[prevIdx];
  28653. var nextP = points[nextIdx];
  28654. // Last point
  28655. if (!nextP || isPointNull(nextP)) {
  28656. v2Copy(cp1, p);
  28657. }
  28658. else {
  28659. // If next data is null in not connect case
  28660. if (isPointNull(nextP) && !connectNulls) {
  28661. nextP = p;
  28662. }
  28663. sub(v, nextP, prevP);
  28664. var lenPrevSeg;
  28665. var lenNextSeg;
  28666. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  28667. var dim = smoothMonotone === 'x' ? 0 : 1;
  28668. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  28669. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  28670. }
  28671. else {
  28672. lenPrevSeg = dist(p, prevP);
  28673. lenNextSeg = dist(p, nextP);
  28674. }
  28675. // Use ratio of seg length
  28676. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  28677. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  28678. }
  28679. // Smooth constraint
  28680. vec2Min(cp0, cp0, smoothMax);
  28681. vec2Max(cp0, cp0, smoothMin);
  28682. vec2Min(cp1, cp1, smoothMax);
  28683. vec2Max(cp1, cp1, smoothMin);
  28684. ctx.bezierCurveTo(
  28685. cp0[0], cp0[1],
  28686. cp1[0], cp1[1],
  28687. p[0], p[1]
  28688. );
  28689. // cp0 of next segment
  28690. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  28691. }
  28692. else {
  28693. ctx.lineTo(p[0], p[1]);
  28694. }
  28695. }
  28696. prevIdx = idx;
  28697. idx += dir;
  28698. }
  28699. return k;
  28700. }
  28701. function getBoundingBox(points, smoothConstraint) {
  28702. var ptMin = [Infinity, Infinity];
  28703. var ptMax = [-Infinity, -Infinity];
  28704. if (smoothConstraint) {
  28705. for (var i = 0; i < points.length; i++) {
  28706. var pt = points[i];
  28707. if (pt[0] < ptMin[0]) {
  28708. ptMin[0] = pt[0];
  28709. }
  28710. if (pt[1] < ptMin[1]) {
  28711. ptMin[1] = pt[1];
  28712. }
  28713. if (pt[0] > ptMax[0]) {
  28714. ptMax[0] = pt[0];
  28715. }
  28716. if (pt[1] > ptMax[1]) {
  28717. ptMax[1] = pt[1];
  28718. }
  28719. }
  28720. }
  28721. return {
  28722. min: smoothConstraint ? ptMin : ptMax,
  28723. max: smoothConstraint ? ptMax : ptMin
  28724. };
  28725. }
  28726. var Polyline$1 = Path.extend({
  28727. type: 'ec-polyline',
  28728. shape: {
  28729. points: [],
  28730. smooth: 0,
  28731. smoothConstraint: true,
  28732. smoothMonotone: null,
  28733. connectNulls: false
  28734. },
  28735. style: {
  28736. fill: null,
  28737. stroke: '#000'
  28738. },
  28739. brush: fixClipWithShadow(Path.prototype.brush),
  28740. buildPath: function (ctx, shape) {
  28741. var points = shape.points;
  28742. var i = 0;
  28743. var len$$1 = points.length;
  28744. var result = getBoundingBox(points, shape.smoothConstraint);
  28745. if (shape.connectNulls) {
  28746. // Must remove first and last null values avoid draw error in polygon
  28747. for (; len$$1 > 0; len$$1--) {
  28748. if (!isPointNull(points[len$$1 - 1])) {
  28749. break;
  28750. }
  28751. }
  28752. for (; i < len$$1; i++) {
  28753. if (!isPointNull(points[i])) {
  28754. break;
  28755. }
  28756. }
  28757. }
  28758. while (i < len$$1) {
  28759. i += drawSegment(
  28760. ctx, points, i, len$$1, len$$1,
  28761. 1, result.min, result.max, shape.smooth,
  28762. shape.smoothMonotone, shape.connectNulls
  28763. ) + 1;
  28764. }
  28765. }
  28766. });
  28767. var Polygon$1 = Path.extend({
  28768. type: 'ec-polygon',
  28769. shape: {
  28770. points: [],
  28771. // Offset between stacked base points and points
  28772. stackedOnPoints: [],
  28773. smooth: 0,
  28774. stackedOnSmooth: 0,
  28775. smoothConstraint: true,
  28776. smoothMonotone: null,
  28777. connectNulls: false
  28778. },
  28779. brush: fixClipWithShadow(Path.prototype.brush),
  28780. buildPath: function (ctx, shape) {
  28781. var points = shape.points;
  28782. var stackedOnPoints = shape.stackedOnPoints;
  28783. var i = 0;
  28784. var len$$1 = points.length;
  28785. var smoothMonotone = shape.smoothMonotone;
  28786. var bbox = getBoundingBox(points, shape.smoothConstraint);
  28787. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  28788. if (shape.connectNulls) {
  28789. // Must remove first and last null values avoid draw error in polygon
  28790. for (; len$$1 > 0; len$$1--) {
  28791. if (!isPointNull(points[len$$1 - 1])) {
  28792. break;
  28793. }
  28794. }
  28795. for (; i < len$$1; i++) {
  28796. if (!isPointNull(points[i])) {
  28797. break;
  28798. }
  28799. }
  28800. }
  28801. while (i < len$$1) {
  28802. var k = drawSegment(
  28803. ctx, points, i, len$$1, len$$1,
  28804. 1, bbox.min, bbox.max, shape.smooth,
  28805. smoothMonotone, shape.connectNulls
  28806. );
  28807. drawSegment(
  28808. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  28809. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  28810. smoothMonotone, shape.connectNulls
  28811. );
  28812. i += k + 1;
  28813. ctx.closePath();
  28814. }
  28815. }
  28816. });
  28817. /*
  28818. * Licensed to the Apache Software Foundation (ASF) under one
  28819. * or more contributor license agreements. See the NOTICE file
  28820. * distributed with this work for additional information
  28821. * regarding copyright ownership. The ASF licenses this file
  28822. * to you under the Apache License, Version 2.0 (the
  28823. * "License"); you may not use this file except in compliance
  28824. * with the License. You may obtain a copy of the License at
  28825. *
  28826. * http://www.apache.org/licenses/LICENSE-2.0
  28827. *
  28828. * Unless required by applicable law or agreed to in writing,
  28829. * software distributed under the License is distributed on an
  28830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28831. * KIND, either express or implied. See the License for the
  28832. * specific language governing permissions and limitations
  28833. * under the License.
  28834. */
  28835. // FIXME step not support polar
  28836. function isPointsSame(points1, points2) {
  28837. if (points1.length !== points2.length) {
  28838. return;
  28839. }
  28840. for (var i = 0; i < points1.length; i++) {
  28841. var p1 = points1[i];
  28842. var p2 = points2[i];
  28843. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  28844. return;
  28845. }
  28846. }
  28847. return true;
  28848. }
  28849. function getSmooth(smooth) {
  28850. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  28851. }
  28852. function getAxisExtentWithGap(axis) {
  28853. var extent = axis.getGlobalExtent();
  28854. if (axis.onBand) {
  28855. // Remove extra 1px to avoid line miter in clipped edge
  28856. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  28857. var dir = extent[1] > extent[0] ? 1 : -1;
  28858. extent[0] += dir * halfBandWidth;
  28859. extent[1] -= dir * halfBandWidth;
  28860. }
  28861. return extent;
  28862. }
  28863. /**
  28864. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  28865. * @param {module:echarts/data/List} data
  28866. * @param {Object} dataCoordInfo
  28867. * @param {Array.<Array.<number>>} points
  28868. */
  28869. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  28870. if (!dataCoordInfo.valueDim) {
  28871. return [];
  28872. }
  28873. var points = [];
  28874. for (var idx = 0, len = data.count(); idx < len; idx++) {
  28875. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  28876. }
  28877. return points;
  28878. }
  28879. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  28880. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  28881. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  28882. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  28883. var x = Math.min(xExtent[0], xExtent[1]);
  28884. var y = Math.min(yExtent[0], yExtent[1]);
  28885. var width = Math.max(xExtent[0], xExtent[1]) - x;
  28886. var height = Math.max(yExtent[0], yExtent[1]) - y;
  28887. // Avoid float number rounding error for symbol on the edge of axis extent.
  28888. // See #7913 and `test/dataZoom-clip.html`.
  28889. if (forSymbol) {
  28890. x -= 0.5;
  28891. width += 0.5;
  28892. y -= 0.5;
  28893. height += 0.5;
  28894. }
  28895. else {
  28896. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  28897. // Expand clip shape to avoid clipping when line value exceeds axis
  28898. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  28899. if (isHorizontal) {
  28900. y -= expandSize;
  28901. height += expandSize * 2;
  28902. }
  28903. else {
  28904. x -= expandSize;
  28905. width += expandSize * 2;
  28906. }
  28907. }
  28908. var clipPath = new Rect({
  28909. shape: {
  28910. x: x,
  28911. y: y,
  28912. width: width,
  28913. height: height
  28914. }
  28915. });
  28916. if (hasAnimation) {
  28917. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  28918. initProps(clipPath, {
  28919. shape: {
  28920. width: width,
  28921. height: height
  28922. }
  28923. }, seriesModel);
  28924. }
  28925. return clipPath;
  28926. }
  28927. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  28928. var angleAxis = polar.getAngleAxis();
  28929. var radiusAxis = polar.getRadiusAxis();
  28930. var radiusExtent = radiusAxis.getExtent().slice();
  28931. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  28932. var angleExtent = angleAxis.getExtent();
  28933. var RADIAN = Math.PI / 180;
  28934. // Avoid float number rounding error for symbol on the edge of axis extent.
  28935. if (forSymbol) {
  28936. radiusExtent[0] -= 0.5;
  28937. radiusExtent[1] += 0.5;
  28938. }
  28939. var clipPath = new Sector({
  28940. shape: {
  28941. cx: round$2(polar.cx, 1),
  28942. cy: round$2(polar.cy, 1),
  28943. r0: round$2(radiusExtent[0], 1),
  28944. r: round$2(radiusExtent[1], 1),
  28945. startAngle: -angleExtent[0] * RADIAN,
  28946. endAngle: -angleExtent[1] * RADIAN,
  28947. clockwise: angleAxis.inverse
  28948. }
  28949. });
  28950. if (hasAnimation) {
  28951. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  28952. initProps(clipPath, {
  28953. shape: {
  28954. endAngle: -angleExtent[1] * RADIAN
  28955. }
  28956. }, seriesModel);
  28957. }
  28958. return clipPath;
  28959. }
  28960. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  28961. return coordSys.type === 'polar'
  28962. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  28963. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  28964. }
  28965. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  28966. var baseAxis = coordSys.getBaseAxis();
  28967. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  28968. var stepPoints = [];
  28969. for (var i = 0; i < points.length - 1; i++) {
  28970. var nextPt = points[i + 1];
  28971. var pt = points[i];
  28972. stepPoints.push(pt);
  28973. var stepPt = [];
  28974. switch (stepTurnAt) {
  28975. case 'end':
  28976. stepPt[baseIndex] = nextPt[baseIndex];
  28977. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28978. // default is start
  28979. stepPoints.push(stepPt);
  28980. break;
  28981. case 'middle':
  28982. // default is start
  28983. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  28984. var stepPt2 = [];
  28985. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  28986. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  28987. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  28988. stepPoints.push(stepPt);
  28989. stepPoints.push(stepPt2);
  28990. break;
  28991. default:
  28992. stepPt[baseIndex] = pt[baseIndex];
  28993. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  28994. // default is start
  28995. stepPoints.push(stepPt);
  28996. }
  28997. }
  28998. // Last points
  28999. points[i] && stepPoints.push(points[i]);
  29000. return stepPoints;
  29001. }
  29002. function getVisualGradient(data, coordSys) {
  29003. var visualMetaList = data.getVisual('visualMeta');
  29004. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  29005. // When data.count() is 0, gradient range can not be calculated.
  29006. return;
  29007. }
  29008. if (coordSys.type !== 'cartesian2d') {
  29009. if (__DEV__) {
  29010. console.warn('Visual map on line style is only supported on cartesian2d.');
  29011. }
  29012. return;
  29013. }
  29014. var coordDim;
  29015. var visualMeta;
  29016. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  29017. var dimIndex = visualMetaList[i].dimension;
  29018. var dimName = data.dimensions[dimIndex];
  29019. var dimInfo = data.getDimensionInfo(dimName);
  29020. coordDim = dimInfo && dimInfo.coordDim;
  29021. // Can only be x or y
  29022. if (coordDim === 'x' || coordDim === 'y') {
  29023. visualMeta = visualMetaList[i];
  29024. break;
  29025. }
  29026. }
  29027. if (!visualMeta) {
  29028. if (__DEV__) {
  29029. console.warn('Visual map on line style only support x or y dimension.');
  29030. }
  29031. return;
  29032. }
  29033. // If the area to be rendered is bigger than area defined by LinearGradient,
  29034. // the canvas spec prescribes that the color of the first stop and the last
  29035. // stop should be used. But if two stops are added at offset 0, in effect
  29036. // browsers use the color of the second stop to render area outside
  29037. // LinearGradient. So we can only infinitesimally extend area defined in
  29038. // LinearGradient to render `outerColors`.
  29039. var axis = coordSys.getAxis(coordDim);
  29040. // dataToCoor mapping may not be linear, but must be monotonic.
  29041. var colorStops = map(visualMeta.stops, function (stop) {
  29042. return {
  29043. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  29044. color: stop.color
  29045. };
  29046. });
  29047. var stopLen = colorStops.length;
  29048. var outerColors = visualMeta.outerColors.slice();
  29049. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  29050. colorStops.reverse();
  29051. outerColors.reverse();
  29052. }
  29053. var tinyExtent = 10; // Arbitrary value: 10px
  29054. var minCoord = colorStops[0].coord - tinyExtent;
  29055. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  29056. var coordSpan = maxCoord - minCoord;
  29057. if (coordSpan < 1e-3) {
  29058. return 'transparent';
  29059. }
  29060. each$1(colorStops, function (stop) {
  29061. stop.offset = (stop.coord - minCoord) / coordSpan;
  29062. });
  29063. colorStops.push({
  29064. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  29065. color: outerColors[1] || 'transparent'
  29066. });
  29067. colorStops.unshift({ // notice colorStops.length have been changed.
  29068. offset: stopLen ? colorStops[0].offset : 0.5,
  29069. color: outerColors[0] || 'transparent'
  29070. });
  29071. // zrUtil.each(colorStops, function (colorStop) {
  29072. // // Make sure each offset has rounded px to avoid not sharp edge
  29073. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  29074. // });
  29075. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  29076. gradient[coordDim] = minCoord;
  29077. gradient[coordDim + '2'] = maxCoord;
  29078. return gradient;
  29079. }
  29080. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  29081. var showAllSymbol = seriesModel.get('showAllSymbol');
  29082. var isAuto = showAllSymbol === 'auto';
  29083. if (showAllSymbol && !isAuto) {
  29084. return;
  29085. }
  29086. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  29087. if (!categoryAxis) {
  29088. return;
  29089. }
  29090. // Note that category label interval strategy might bring some weird effect
  29091. // in some scenario: users may wonder why some of the symbols are not
  29092. // displayed. So we show all symbols as possible as we can.
  29093. if (isAuto
  29094. // Simplify the logic, do not determine label overlap here.
  29095. && canShowAllSymbolForCategory(categoryAxis, data)
  29096. ) {
  29097. return;
  29098. }
  29099. // Otherwise follow the label interval strategy on category axis.
  29100. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  29101. var labelMap = {};
  29102. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  29103. labelMap[labelItem.tickValue] = 1;
  29104. });
  29105. return function (dataIndex) {
  29106. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  29107. };
  29108. }
  29109. function canShowAllSymbolForCategory(categoryAxis, data) {
  29110. // In mose cases, line is monotonous on category axis, and the label size
  29111. // is close with each other. So we check the symbol size and some of the
  29112. // label size alone with the category axis to estimate whether all symbol
  29113. // can be shown without overlap.
  29114. var axisExtent = categoryAxis.getExtent();
  29115. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  29116. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  29117. // Sampling some points, max 5.
  29118. var dataLen = data.count();
  29119. var step = Math.max(1, Math.round(dataLen / 5));
  29120. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  29121. if (SymbolClz.getSymbolSize(
  29122. data, dataIndex
  29123. // Only for cartesian, where `isHorizontal` exists.
  29124. )[categoryAxis.isHorizontal() ? 1 : 0]
  29125. // Empirical number
  29126. * 1.5 > availSize
  29127. ) {
  29128. return false;
  29129. }
  29130. }
  29131. return true;
  29132. }
  29133. Chart.extend({
  29134. type: 'line',
  29135. init: function () {
  29136. var lineGroup = new Group();
  29137. var symbolDraw = new SymbolDraw();
  29138. this.group.add(symbolDraw.group);
  29139. this._symbolDraw = symbolDraw;
  29140. this._lineGroup = lineGroup;
  29141. },
  29142. render: function (seriesModel, ecModel, api) {
  29143. var coordSys = seriesModel.coordinateSystem;
  29144. var group = this.group;
  29145. var data = seriesModel.getData();
  29146. var lineStyleModel = seriesModel.getModel('lineStyle');
  29147. var areaStyleModel = seriesModel.getModel('areaStyle');
  29148. var points = data.mapArray(data.getItemLayout);
  29149. var isCoordSysPolar = coordSys.type === 'polar';
  29150. var prevCoordSys = this._coordSys;
  29151. var symbolDraw = this._symbolDraw;
  29152. var polyline = this._polyline;
  29153. var polygon = this._polygon;
  29154. var lineGroup = this._lineGroup;
  29155. var hasAnimation = seriesModel.get('animation');
  29156. var isAreaChart = !areaStyleModel.isEmpty();
  29157. var valueOrigin = areaStyleModel.get('origin');
  29158. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  29159. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  29160. var showSymbol = seriesModel.get('showSymbol');
  29161. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  29162. && getIsIgnoreFunc(seriesModel, data, coordSys);
  29163. // Remove temporary symbols
  29164. var oldData = this._data;
  29165. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  29166. if (el.__temp) {
  29167. group.remove(el);
  29168. oldData.setItemGraphicEl(idx, null);
  29169. }
  29170. });
  29171. // Remove previous created symbols if showSymbol changed to false
  29172. if (!showSymbol) {
  29173. symbolDraw.remove();
  29174. }
  29175. group.add(lineGroup);
  29176. // FIXME step not support polar
  29177. var step = !isCoordSysPolar && seriesModel.get('step');
  29178. // Initialization animation or coordinate system changed
  29179. if (
  29180. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  29181. ) {
  29182. showSymbol && symbolDraw.updateData(data, {
  29183. isIgnore: isIgnoreFunc,
  29184. clipShape: createClipShape(coordSys, false, true, seriesModel)
  29185. });
  29186. if (step) {
  29187. // TODO If stacked series is not step
  29188. points = turnPointsIntoStep(points, coordSys, step);
  29189. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  29190. }
  29191. polyline = this._newPolyline(points, coordSys, hasAnimation);
  29192. if (isAreaChart) {
  29193. polygon = this._newPolygon(
  29194. points, stackedOnPoints,
  29195. coordSys, hasAnimation
  29196. );
  29197. }
  29198. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  29199. }
  29200. else {
  29201. if (isAreaChart && !polygon) {
  29202. // If areaStyle is added
  29203. polygon = this._newPolygon(
  29204. points, stackedOnPoints,
  29205. coordSys, hasAnimation
  29206. );
  29207. }
  29208. else if (polygon && !isAreaChart) {
  29209. // If areaStyle is removed
  29210. lineGroup.remove(polygon);
  29211. polygon = this._polygon = null;
  29212. }
  29213. // Update clipPath
  29214. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  29215. // Always update, or it is wrong in the case turning on legend
  29216. // because points are not changed
  29217. showSymbol && symbolDraw.updateData(data, {
  29218. isIgnore: isIgnoreFunc,
  29219. clipShape: createClipShape(coordSys, false, true, seriesModel)
  29220. });
  29221. // Stop symbol animation and sync with line points
  29222. // FIXME performance?
  29223. data.eachItemGraphicEl(function (el) {
  29224. el.stopAnimation(true);
  29225. });
  29226. // In the case data zoom triggerred refreshing frequently
  29227. // Data may not change if line has a category axis. So it should animate nothing
  29228. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  29229. || !isPointsSame(this._points, points)
  29230. ) {
  29231. if (hasAnimation) {
  29232. this._updateAnimation(
  29233. data, stackedOnPoints, coordSys, api, step, valueOrigin
  29234. );
  29235. }
  29236. else {
  29237. // Not do it in update with animation
  29238. if (step) {
  29239. // TODO If stacked series is not step
  29240. points = turnPointsIntoStep(points, coordSys, step);
  29241. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  29242. }
  29243. polyline.setShape({
  29244. points: points
  29245. });
  29246. polygon && polygon.setShape({
  29247. points: points,
  29248. stackedOnPoints: stackedOnPoints
  29249. });
  29250. }
  29251. }
  29252. }
  29253. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  29254. polyline.useStyle(defaults(
  29255. // Use color in lineStyle first
  29256. lineStyleModel.getLineStyle(),
  29257. {
  29258. fill: 'none',
  29259. stroke: visualColor,
  29260. lineJoin: 'bevel'
  29261. }
  29262. ));
  29263. var smooth = seriesModel.get('smooth');
  29264. smooth = getSmooth(seriesModel.get('smooth'));
  29265. polyline.setShape({
  29266. smooth: smooth,
  29267. smoothMonotone: seriesModel.get('smoothMonotone'),
  29268. connectNulls: seriesModel.get('connectNulls')
  29269. });
  29270. if (polygon) {
  29271. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  29272. var stackedOnSmooth = 0;
  29273. polygon.useStyle(defaults(
  29274. areaStyleModel.getAreaStyle(),
  29275. {
  29276. fill: visualColor,
  29277. opacity: 0.7,
  29278. lineJoin: 'bevel'
  29279. }
  29280. ));
  29281. if (stackedOnSeries) {
  29282. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  29283. }
  29284. polygon.setShape({
  29285. smooth: smooth,
  29286. stackedOnSmooth: stackedOnSmooth,
  29287. smoothMonotone: seriesModel.get('smoothMonotone'),
  29288. connectNulls: seriesModel.get('connectNulls')
  29289. });
  29290. }
  29291. this._data = data;
  29292. // Save the coordinate system for transition animation when data changed
  29293. this._coordSys = coordSys;
  29294. this._stackedOnPoints = stackedOnPoints;
  29295. this._points = points;
  29296. this._step = step;
  29297. this._valueOrigin = valueOrigin;
  29298. },
  29299. dispose: function () {},
  29300. highlight: function (seriesModel, ecModel, api, payload) {
  29301. var data = seriesModel.getData();
  29302. var dataIndex = queryDataIndex(data, payload);
  29303. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  29304. var symbol = data.getItemGraphicEl(dataIndex);
  29305. if (!symbol) {
  29306. // Create a temporary symbol if it is not exists
  29307. var pt = data.getItemLayout(dataIndex);
  29308. if (!pt) {
  29309. // Null data
  29310. return;
  29311. }
  29312. symbol = new SymbolClz(data, dataIndex);
  29313. symbol.position = pt;
  29314. symbol.setZ(
  29315. seriesModel.get('zlevel'),
  29316. seriesModel.get('z')
  29317. );
  29318. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  29319. symbol.__temp = true;
  29320. data.setItemGraphicEl(dataIndex, symbol);
  29321. // Stop scale animation
  29322. symbol.stopSymbolAnimation(true);
  29323. this.group.add(symbol);
  29324. }
  29325. symbol.highlight();
  29326. }
  29327. else {
  29328. // Highlight whole series
  29329. Chart.prototype.highlight.call(
  29330. this, seriesModel, ecModel, api, payload
  29331. );
  29332. }
  29333. },
  29334. downplay: function (seriesModel, ecModel, api, payload) {
  29335. var data = seriesModel.getData();
  29336. var dataIndex = queryDataIndex(data, payload);
  29337. if (dataIndex != null && dataIndex >= 0) {
  29338. var symbol = data.getItemGraphicEl(dataIndex);
  29339. if (symbol) {
  29340. if (symbol.__temp) {
  29341. data.setItemGraphicEl(dataIndex, null);
  29342. this.group.remove(symbol);
  29343. }
  29344. else {
  29345. symbol.downplay();
  29346. }
  29347. }
  29348. }
  29349. else {
  29350. // FIXME
  29351. // can not downplay completely.
  29352. // Downplay whole series
  29353. Chart.prototype.downplay.call(
  29354. this, seriesModel, ecModel, api, payload
  29355. );
  29356. }
  29357. },
  29358. /**
  29359. * @param {module:zrender/container/Group} group
  29360. * @param {Array.<Array.<number>>} points
  29361. * @private
  29362. */
  29363. _newPolyline: function (points) {
  29364. var polyline = this._polyline;
  29365. // Remove previous created polyline
  29366. if (polyline) {
  29367. this._lineGroup.remove(polyline);
  29368. }
  29369. polyline = new Polyline$1({
  29370. shape: {
  29371. points: points
  29372. },
  29373. silent: true,
  29374. z2: 10
  29375. });
  29376. this._lineGroup.add(polyline);
  29377. this._polyline = polyline;
  29378. return polyline;
  29379. },
  29380. /**
  29381. * @param {module:zrender/container/Group} group
  29382. * @param {Array.<Array.<number>>} stackedOnPoints
  29383. * @param {Array.<Array.<number>>} points
  29384. * @private
  29385. */
  29386. _newPolygon: function (points, stackedOnPoints) {
  29387. var polygon = this._polygon;
  29388. // Remove previous created polygon
  29389. if (polygon) {
  29390. this._lineGroup.remove(polygon);
  29391. }
  29392. polygon = new Polygon$1({
  29393. shape: {
  29394. points: points,
  29395. stackedOnPoints: stackedOnPoints
  29396. },
  29397. silent: true
  29398. });
  29399. this._lineGroup.add(polygon);
  29400. this._polygon = polygon;
  29401. return polygon;
  29402. },
  29403. /**
  29404. * @private
  29405. */
  29406. // FIXME Two value axis
  29407. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  29408. var polyline = this._polyline;
  29409. var polygon = this._polygon;
  29410. var seriesModel = data.hostModel;
  29411. var diff = lineAnimationDiff(
  29412. this._data, data,
  29413. this._stackedOnPoints, stackedOnPoints,
  29414. this._coordSys, coordSys,
  29415. this._valueOrigin, valueOrigin
  29416. );
  29417. var current = diff.current;
  29418. var stackedOnCurrent = diff.stackedOnCurrent;
  29419. var next = diff.next;
  29420. var stackedOnNext = diff.stackedOnNext;
  29421. if (step) {
  29422. // TODO If stacked series is not step
  29423. current = turnPointsIntoStep(diff.current, coordSys, step);
  29424. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  29425. next = turnPointsIntoStep(diff.next, coordSys, step);
  29426. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  29427. }
  29428. // `diff.current` is subset of `current` (which should be ensured by
  29429. // turnPointsIntoStep), so points in `__points` can be updated when
  29430. // points in `current` are update during animation.
  29431. polyline.shape.__points = diff.current;
  29432. polyline.shape.points = current;
  29433. updateProps(polyline, {
  29434. shape: {
  29435. points: next
  29436. }
  29437. }, seriesModel);
  29438. if (polygon) {
  29439. polygon.setShape({
  29440. points: current,
  29441. stackedOnPoints: stackedOnCurrent
  29442. });
  29443. updateProps(polygon, {
  29444. shape: {
  29445. points: next,
  29446. stackedOnPoints: stackedOnNext
  29447. }
  29448. }, seriesModel);
  29449. }
  29450. var updatedDataInfo = [];
  29451. var diffStatus = diff.status;
  29452. for (var i = 0; i < diffStatus.length; i++) {
  29453. var cmd = diffStatus[i].cmd;
  29454. if (cmd === '=') {
  29455. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  29456. if (el) {
  29457. updatedDataInfo.push({
  29458. el: el,
  29459. ptIdx: i // Index of points
  29460. });
  29461. }
  29462. }
  29463. }
  29464. if (polyline.animators && polyline.animators.length) {
  29465. polyline.animators[0].during(function () {
  29466. for (var i = 0; i < updatedDataInfo.length; i++) {
  29467. var el = updatedDataInfo[i].el;
  29468. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  29469. }
  29470. });
  29471. }
  29472. },
  29473. remove: function (ecModel) {
  29474. var group = this.group;
  29475. var oldData = this._data;
  29476. this._lineGroup.removeAll();
  29477. this._symbolDraw.remove(true);
  29478. // Remove temporary created elements when highlighting
  29479. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  29480. if (el.__temp) {
  29481. group.remove(el);
  29482. oldData.setItemGraphicEl(idx, null);
  29483. }
  29484. });
  29485. this._polyline
  29486. = this._polygon
  29487. = this._coordSys
  29488. = this._points
  29489. = this._stackedOnPoints
  29490. = this._data = null;
  29491. }
  29492. });
  29493. /*
  29494. * Licensed to the Apache Software Foundation (ASF) under one
  29495. * or more contributor license agreements. See the NOTICE file
  29496. * distributed with this work for additional information
  29497. * regarding copyright ownership. The ASF licenses this file
  29498. * to you under the Apache License, Version 2.0 (the
  29499. * "License"); you may not use this file except in compliance
  29500. * with the License. You may obtain a copy of the License at
  29501. *
  29502. * http://www.apache.org/licenses/LICENSE-2.0
  29503. *
  29504. * Unless required by applicable law or agreed to in writing,
  29505. * software distributed under the License is distributed on an
  29506. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29507. * KIND, either express or implied. See the License for the
  29508. * specific language governing permissions and limitations
  29509. * under the License.
  29510. */
  29511. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  29512. // Encoding visual for all series include which is filtered for legend drawing
  29513. return {
  29514. seriesType: seriesType,
  29515. // For legend.
  29516. performRawSeries: true,
  29517. reset: function (seriesModel, ecModel, api) {
  29518. var data = seriesModel.getData();
  29519. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  29520. var symbolSize = seriesModel.get('symbolSize');
  29521. var keepAspect = seriesModel.get('symbolKeepAspect');
  29522. data.setVisual({
  29523. legendSymbol: legendSymbol || symbolType,
  29524. symbol: symbolType,
  29525. symbolSize: symbolSize,
  29526. symbolKeepAspect: keepAspect
  29527. });
  29528. // Only visible series has each data be visual encoded
  29529. if (ecModel.isSeriesFiltered(seriesModel)) {
  29530. return;
  29531. }
  29532. var hasCallback = typeof symbolSize === 'function';
  29533. function dataEach(data, idx) {
  29534. if (typeof symbolSize === 'function') {
  29535. var rawValue = seriesModel.getRawValue(idx);
  29536. // FIXME
  29537. var params = seriesModel.getDataParams(idx);
  29538. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  29539. }
  29540. if (data.hasItemOption) {
  29541. var itemModel = data.getItemModel(idx);
  29542. var itemSymbolType = itemModel.getShallow('symbol', true);
  29543. var itemSymbolSize = itemModel.getShallow('symbolSize',
  29544. true);
  29545. var itemSymbolKeepAspect
  29546. = itemModel.getShallow('symbolKeepAspect', true);
  29547. // If has item symbol
  29548. if (itemSymbolType != null) {
  29549. data.setItemVisual(idx, 'symbol', itemSymbolType);
  29550. }
  29551. if (itemSymbolSize != null) {
  29552. // PENDING Transform symbolSize ?
  29553. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  29554. }
  29555. if (itemSymbolKeepAspect != null) {
  29556. data.setItemVisual(idx, 'symbolKeepAspect',
  29557. itemSymbolKeepAspect);
  29558. }
  29559. }
  29560. }
  29561. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  29562. }
  29563. };
  29564. };
  29565. /*
  29566. * Licensed to the Apache Software Foundation (ASF) under one
  29567. * or more contributor license agreements. See the NOTICE file
  29568. * distributed with this work for additional information
  29569. * regarding copyright ownership. The ASF licenses this file
  29570. * to you under the Apache License, Version 2.0 (the
  29571. * "License"); you may not use this file except in compliance
  29572. * with the License. You may obtain a copy of the License at
  29573. *
  29574. * http://www.apache.org/licenses/LICENSE-2.0
  29575. *
  29576. * Unless required by applicable law or agreed to in writing,
  29577. * software distributed under the License is distributed on an
  29578. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29579. * KIND, either express or implied. See the License for the
  29580. * specific language governing permissions and limitations
  29581. * under the License.
  29582. */
  29583. /* global Float32Array */
  29584. var layoutPoints = function (seriesType) {
  29585. return {
  29586. seriesType: seriesType,
  29587. plan: createRenderPlanner(),
  29588. reset: function (seriesModel) {
  29589. var data = seriesModel.getData();
  29590. var coordSys = seriesModel.coordinateSystem;
  29591. var pipelineContext = seriesModel.pipelineContext;
  29592. var isLargeRender = pipelineContext.large;
  29593. if (!coordSys) {
  29594. return;
  29595. }
  29596. var dims = map(coordSys.dimensions, function (dim) {
  29597. return data.mapDimension(dim);
  29598. }).slice(0, 2);
  29599. var dimLen = dims.length;
  29600. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29601. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  29602. dims[0] = stackResultDim;
  29603. }
  29604. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  29605. dims[1] = stackResultDim;
  29606. }
  29607. function progress(params, data) {
  29608. var segCount = params.end - params.start;
  29609. var points = isLargeRender && new Float32Array(segCount * dimLen);
  29610. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  29611. var point;
  29612. if (dimLen === 1) {
  29613. var x = data.get(dims[0], i);
  29614. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  29615. }
  29616. else {
  29617. var x = tmpIn[0] = data.get(dims[0], i);
  29618. var y = tmpIn[1] = data.get(dims[1], i);
  29619. // Also {Array.<number>}, not undefined to avoid if...else... statement
  29620. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  29621. }
  29622. if (isLargeRender) {
  29623. points[offset++] = point ? point[0] : NaN;
  29624. points[offset++] = point ? point[1] : NaN;
  29625. }
  29626. else {
  29627. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  29628. }
  29629. }
  29630. isLargeRender && data.setLayout('symbolPoints', points);
  29631. }
  29632. return dimLen && {progress: progress};
  29633. }
  29634. };
  29635. };
  29636. /*
  29637. * Licensed to the Apache Software Foundation (ASF) under one
  29638. * or more contributor license agreements. See the NOTICE file
  29639. * distributed with this work for additional information
  29640. * regarding copyright ownership. The ASF licenses this file
  29641. * to you under the Apache License, Version 2.0 (the
  29642. * "License"); you may not use this file except in compliance
  29643. * with the License. You may obtain a copy of the License at
  29644. *
  29645. * http://www.apache.org/licenses/LICENSE-2.0
  29646. *
  29647. * Unless required by applicable law or agreed to in writing,
  29648. * software distributed under the License is distributed on an
  29649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29650. * KIND, either express or implied. See the License for the
  29651. * specific language governing permissions and limitations
  29652. * under the License.
  29653. */
  29654. var samplers = {
  29655. average: function (frame) {
  29656. var sum = 0;
  29657. var count = 0;
  29658. for (var i = 0; i < frame.length; i++) {
  29659. if (!isNaN(frame[i])) {
  29660. sum += frame[i];
  29661. count++;
  29662. }
  29663. }
  29664. // Return NaN if count is 0
  29665. return count === 0 ? NaN : sum / count;
  29666. },
  29667. sum: function (frame) {
  29668. var sum = 0;
  29669. for (var i = 0; i < frame.length; i++) {
  29670. // Ignore NaN
  29671. sum += frame[i] || 0;
  29672. }
  29673. return sum;
  29674. },
  29675. max: function (frame) {
  29676. var max = -Infinity;
  29677. for (var i = 0; i < frame.length; i++) {
  29678. frame[i] > max && (max = frame[i]);
  29679. }
  29680. // NaN will cause illegal axis extent.
  29681. return isFinite(max) ? max : NaN;
  29682. },
  29683. min: function (frame) {
  29684. var min = Infinity;
  29685. for (var i = 0; i < frame.length; i++) {
  29686. frame[i] < min && (min = frame[i]);
  29687. }
  29688. // NaN will cause illegal axis extent.
  29689. return isFinite(min) ? min : NaN;
  29690. },
  29691. // TODO
  29692. // Median
  29693. nearest: function (frame) {
  29694. return frame[0];
  29695. }
  29696. };
  29697. var indexSampler = function (frame, value) {
  29698. return Math.round(frame.length / 2);
  29699. };
  29700. var dataSample = function (seriesType) {
  29701. return {
  29702. seriesType: seriesType,
  29703. modifyOutputEnd: true,
  29704. reset: function (seriesModel, ecModel, api) {
  29705. var data = seriesModel.getData();
  29706. var sampling = seriesModel.get('sampling');
  29707. var coordSys = seriesModel.coordinateSystem;
  29708. // Only cartesian2d support down sampling
  29709. if (coordSys.type === 'cartesian2d' && sampling) {
  29710. var baseAxis = coordSys.getBaseAxis();
  29711. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29712. var extent = baseAxis.getExtent();
  29713. // Coordinste system has been resized
  29714. var size = extent[1] - extent[0];
  29715. var rate = Math.round(data.count() / size);
  29716. if (rate > 1) {
  29717. var sampler;
  29718. if (typeof sampling === 'string') {
  29719. sampler = samplers[sampling];
  29720. }
  29721. else if (typeof sampling === 'function') {
  29722. sampler = sampling;
  29723. }
  29724. if (sampler) {
  29725. // Only support sample the first dim mapped from value axis.
  29726. seriesModel.setData(data.downSample(
  29727. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  29728. ));
  29729. }
  29730. }
  29731. }
  29732. }
  29733. };
  29734. };
  29735. /*
  29736. * Licensed to the Apache Software Foundation (ASF) under one
  29737. * or more contributor license agreements. See the NOTICE file
  29738. * distributed with this work for additional information
  29739. * regarding copyright ownership. The ASF licenses this file
  29740. * to you under the Apache License, Version 2.0 (the
  29741. * "License"); you may not use this file except in compliance
  29742. * with the License. You may obtain a copy of the License at
  29743. *
  29744. * http://www.apache.org/licenses/LICENSE-2.0
  29745. *
  29746. * Unless required by applicable law or agreed to in writing,
  29747. * software distributed under the License is distributed on an
  29748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29749. * KIND, either express or implied. See the License for the
  29750. * specific language governing permissions and limitations
  29751. * under the License.
  29752. */
  29753. /**
  29754. * // Scale class management
  29755. * @module echarts/scale/Scale
  29756. */
  29757. /**
  29758. * @param {Object} [setting]
  29759. */
  29760. function Scale(setting) {
  29761. this._setting = setting || {};
  29762. /**
  29763. * Extent
  29764. * @type {Array.<number>}
  29765. * @protected
  29766. */
  29767. this._extent = [Infinity, -Infinity];
  29768. /**
  29769. * Step is calculated in adjustExtent
  29770. * @type {Array.<number>}
  29771. * @protected
  29772. */
  29773. this._interval = 0;
  29774. this.init && this.init.apply(this, arguments);
  29775. }
  29776. /**
  29777. * Parse input val to valid inner number.
  29778. * @param {*} val
  29779. * @return {number}
  29780. */
  29781. Scale.prototype.parse = function (val) {
  29782. // Notice: This would be a trap here, If the implementation
  29783. // of this method depends on extent, and this method is used
  29784. // before extent set (like in dataZoom), it would be wrong.
  29785. // Nevertheless, parse does not depend on extent generally.
  29786. return val;
  29787. };
  29788. Scale.prototype.getSetting = function (name) {
  29789. return this._setting[name];
  29790. };
  29791. Scale.prototype.contain = function (val) {
  29792. var extent = this._extent;
  29793. return val >= extent[0] && val <= extent[1];
  29794. };
  29795. /**
  29796. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  29797. * @param {number} val
  29798. * @return {number}
  29799. */
  29800. Scale.prototype.normalize = function (val) {
  29801. var extent = this._extent;
  29802. if (extent[1] === extent[0]) {
  29803. return 0.5;
  29804. }
  29805. return (val - extent[0]) / (extent[1] - extent[0]);
  29806. };
  29807. /**
  29808. * Scale normalized value
  29809. * @param {number} val
  29810. * @return {number}
  29811. */
  29812. Scale.prototype.scale = function (val) {
  29813. var extent = this._extent;
  29814. return val * (extent[1] - extent[0]) + extent[0];
  29815. };
  29816. /**
  29817. * Set extent from data
  29818. * @param {Array.<number>} other
  29819. */
  29820. Scale.prototype.unionExtent = function (other) {
  29821. var extent = this._extent;
  29822. other[0] < extent[0] && (extent[0] = other[0]);
  29823. other[1] > extent[1] && (extent[1] = other[1]);
  29824. // not setExtent because in log axis it may transformed to power
  29825. // this.setExtent(extent[0], extent[1]);
  29826. };
  29827. /**
  29828. * Set extent from data
  29829. * @param {module:echarts/data/List} data
  29830. * @param {string} dim
  29831. */
  29832. Scale.prototype.unionExtentFromData = function (data, dim) {
  29833. this.unionExtent(data.getApproximateExtent(dim));
  29834. };
  29835. /**
  29836. * Get extent
  29837. * @return {Array.<number>}
  29838. */
  29839. Scale.prototype.getExtent = function () {
  29840. return this._extent.slice();
  29841. };
  29842. /**
  29843. * Set extent
  29844. * @param {number} start
  29845. * @param {number} end
  29846. */
  29847. Scale.prototype.setExtent = function (start, end) {
  29848. var thisExtent = this._extent;
  29849. if (!isNaN(start)) {
  29850. thisExtent[0] = start;
  29851. }
  29852. if (!isNaN(end)) {
  29853. thisExtent[1] = end;
  29854. }
  29855. };
  29856. /**
  29857. * When axis extent depends on data and no data exists,
  29858. * axis ticks should not be drawn, which is named 'blank'.
  29859. */
  29860. Scale.prototype.isBlank = function () {
  29861. return this._isBlank;
  29862. },
  29863. /**
  29864. * When axis extent depends on data and no data exists,
  29865. * axis ticks should not be drawn, which is named 'blank'.
  29866. */
  29867. Scale.prototype.setBlank = function (isBlank) {
  29868. this._isBlank = isBlank;
  29869. };
  29870. /**
  29871. * @abstract
  29872. * @param {*} tick
  29873. * @return {string} label of the tick.
  29874. */
  29875. Scale.prototype.getLabel = null;
  29876. enableClassExtend(Scale);
  29877. enableClassManagement(Scale, {
  29878. registerWhenExtend: true
  29879. });
  29880. /*
  29881. * Licensed to the Apache Software Foundation (ASF) under one
  29882. * or more contributor license agreements. See the NOTICE file
  29883. * distributed with this work for additional information
  29884. * regarding copyright ownership. The ASF licenses this file
  29885. * to you under the Apache License, Version 2.0 (the
  29886. * "License"); you may not use this file except in compliance
  29887. * with the License. You may obtain a copy of the License at
  29888. *
  29889. * http://www.apache.org/licenses/LICENSE-2.0
  29890. *
  29891. * Unless required by applicable law or agreed to in writing,
  29892. * software distributed under the License is distributed on an
  29893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29894. * KIND, either express or implied. See the License for the
  29895. * specific language governing permissions and limitations
  29896. * under the License.
  29897. */
  29898. /**
  29899. * @constructor
  29900. * @param {Object} [opt]
  29901. * @param {Object} [opt.categories=[]]
  29902. * @param {Object} [opt.needCollect=false]
  29903. * @param {Object} [opt.deduplication=false]
  29904. */
  29905. function OrdinalMeta(opt) {
  29906. /**
  29907. * @readOnly
  29908. * @type {Array.<string>}
  29909. */
  29910. this.categories = opt.categories || [];
  29911. /**
  29912. * @private
  29913. * @type {boolean}
  29914. */
  29915. this._needCollect = opt.needCollect;
  29916. /**
  29917. * @private
  29918. * @type {boolean}
  29919. */
  29920. this._deduplication = opt.deduplication;
  29921. /**
  29922. * @private
  29923. * @type {boolean}
  29924. */
  29925. this._map;
  29926. }
  29927. /**
  29928. * @param {module:echarts/model/Model} axisModel
  29929. * @return {module:echarts/data/OrdinalMeta}
  29930. */
  29931. OrdinalMeta.createByAxisModel = function (axisModel) {
  29932. var option = axisModel.option;
  29933. var data = option.data;
  29934. var categories = data && map(data, getName);
  29935. return new OrdinalMeta({
  29936. categories: categories,
  29937. needCollect: !categories,
  29938. // deduplication is default in axis.
  29939. deduplication: option.dedplication !== false
  29940. });
  29941. };
  29942. var proto$1 = OrdinalMeta.prototype;
  29943. /**
  29944. * @param {string} category
  29945. * @return {number} ordinal
  29946. */
  29947. proto$1.getOrdinal = function (category) {
  29948. return getOrCreateMap(this).get(category);
  29949. };
  29950. /**
  29951. * @param {*} category
  29952. * @return {number} The ordinal. If not found, return NaN.
  29953. */
  29954. proto$1.parseAndCollect = function (category) {
  29955. var index;
  29956. var needCollect = this._needCollect;
  29957. // The value of category dim can be the index of the given category set.
  29958. // This feature is only supported when !needCollect, because we should
  29959. // consider a common case: a value is 2017, which is a number but is
  29960. // expected to be tread as a category. This case usually happen in dataset,
  29961. // where it happent to be no need of the index feature.
  29962. if (typeof category !== 'string' && !needCollect) {
  29963. return category;
  29964. }
  29965. // Optimize for the scenario:
  29966. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29967. // data has been ensured not duplicate and is large data.
  29968. // Notice, if a dataset dimension provide categroies, usually echarts
  29969. // should remove duplication except user tell echarts dont do that
  29970. // (set axis.deduplication = false), because echarts do not know whether
  29971. // the values in the category dimension has duplication (consider the
  29972. // parallel-aqi example)
  29973. if (needCollect && !this._deduplication) {
  29974. index = this.categories.length;
  29975. this.categories[index] = category;
  29976. return index;
  29977. }
  29978. var map$$1 = getOrCreateMap(this);
  29979. index = map$$1.get(category);
  29980. if (index == null) {
  29981. if (needCollect) {
  29982. index = this.categories.length;
  29983. this.categories[index] = category;
  29984. map$$1.set(category, index);
  29985. }
  29986. else {
  29987. index = NaN;
  29988. }
  29989. }
  29990. return index;
  29991. };
  29992. // Consider big data, do not create map until needed.
  29993. function getOrCreateMap(ordinalMeta) {
  29994. return ordinalMeta._map || (
  29995. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  29996. );
  29997. }
  29998. function getName(obj) {
  29999. if (isObject$1(obj) && obj.value != null) {
  30000. return obj.value;
  30001. }
  30002. else {
  30003. return obj + '';
  30004. }
  30005. }
  30006. /*
  30007. * Licensed to the Apache Software Foundation (ASF) under one
  30008. * or more contributor license agreements. See the NOTICE file
  30009. * distributed with this work for additional information
  30010. * regarding copyright ownership. The ASF licenses this file
  30011. * to you under the Apache License, Version 2.0 (the
  30012. * "License"); you may not use this file except in compliance
  30013. * with the License. You may obtain a copy of the License at
  30014. *
  30015. * http://www.apache.org/licenses/LICENSE-2.0
  30016. *
  30017. * Unless required by applicable law or agreed to in writing,
  30018. * software distributed under the License is distributed on an
  30019. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30020. * KIND, either express or implied. See the License for the
  30021. * specific language governing permissions and limitations
  30022. * under the License.
  30023. */
  30024. /**
  30025. * Linear continuous scale
  30026. * @module echarts/coord/scale/Ordinal
  30027. *
  30028. * http://en.wikipedia.org/wiki/Level_of_measurement
  30029. */
  30030. // FIXME only one data
  30031. var scaleProto = Scale.prototype;
  30032. var OrdinalScale = Scale.extend({
  30033. type: 'ordinal',
  30034. /**
  30035. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  30036. */
  30037. init: function (ordinalMeta, extent) {
  30038. // Caution: Should not use instanceof, consider ec-extensions using
  30039. // import approach to get OrdinalMeta class.
  30040. if (!ordinalMeta || isArray(ordinalMeta)) {
  30041. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  30042. }
  30043. this._ordinalMeta = ordinalMeta;
  30044. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  30045. },
  30046. parse: function (val) {
  30047. return typeof val === 'string'
  30048. ? this._ordinalMeta.getOrdinal(val)
  30049. // val might be float.
  30050. : Math.round(val);
  30051. },
  30052. contain: function (rank) {
  30053. rank = this.parse(rank);
  30054. return scaleProto.contain.call(this, rank)
  30055. && this._ordinalMeta.categories[rank] != null;
  30056. },
  30057. /**
  30058. * Normalize given rank or name to linear [0, 1]
  30059. * @param {number|string} [val]
  30060. * @return {number}
  30061. */
  30062. normalize: function (val) {
  30063. return scaleProto.normalize.call(this, this.parse(val));
  30064. },
  30065. scale: function (val) {
  30066. return Math.round(scaleProto.scale.call(this, val));
  30067. },
  30068. /**
  30069. * @return {Array}
  30070. */
  30071. getTicks: function () {
  30072. var ticks = [];
  30073. var extent = this._extent;
  30074. var rank = extent[0];
  30075. while (rank <= extent[1]) {
  30076. ticks.push(rank);
  30077. rank++;
  30078. }
  30079. return ticks;
  30080. },
  30081. /**
  30082. * Get item on rank n
  30083. * @param {number} n
  30084. * @return {string}
  30085. */
  30086. getLabel: function (n) {
  30087. if (!this.isBlank()) {
  30088. // Note that if no data, ordinalMeta.categories is an empty array.
  30089. return this._ordinalMeta.categories[n];
  30090. }
  30091. },
  30092. /**
  30093. * @return {number}
  30094. */
  30095. count: function () {
  30096. return this._extent[1] - this._extent[0] + 1;
  30097. },
  30098. /**
  30099. * @override
  30100. */
  30101. unionExtentFromData: function (data, dim) {
  30102. this.unionExtent(data.getApproximateExtent(dim));
  30103. },
  30104. getOrdinalMeta: function () {
  30105. return this._ordinalMeta;
  30106. },
  30107. niceTicks: noop,
  30108. niceExtent: noop
  30109. });
  30110. /**
  30111. * @return {module:echarts/scale/Time}
  30112. */
  30113. OrdinalScale.create = function () {
  30114. return new OrdinalScale();
  30115. };
  30116. /*
  30117. * Licensed to the Apache Software Foundation (ASF) under one
  30118. * or more contributor license agreements. See the NOTICE file
  30119. * distributed with this work for additional information
  30120. * regarding copyright ownership. The ASF licenses this file
  30121. * to you under the Apache License, Version 2.0 (the
  30122. * "License"); you may not use this file except in compliance
  30123. * with the License. You may obtain a copy of the License at
  30124. *
  30125. * http://www.apache.org/licenses/LICENSE-2.0
  30126. *
  30127. * Unless required by applicable law or agreed to in writing,
  30128. * software distributed under the License is distributed on an
  30129. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30130. * KIND, either express or implied. See the License for the
  30131. * specific language governing permissions and limitations
  30132. * under the License.
  30133. */
  30134. /**
  30135. * For testable.
  30136. */
  30137. var roundNumber$1 = round$2;
  30138. /**
  30139. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  30140. * Should be extent[0] < extent[1].
  30141. * @param {number} splitNumber splitNumber should be >= 1.
  30142. * @param {number} [minInterval]
  30143. * @param {number} [maxInterval]
  30144. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  30145. */
  30146. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  30147. var result = {};
  30148. var span = extent[1] - extent[0];
  30149. var interval = result.interval = nice(span / splitNumber, true);
  30150. if (minInterval != null && interval < minInterval) {
  30151. interval = result.interval = minInterval;
  30152. }
  30153. if (maxInterval != null && interval > maxInterval) {
  30154. interval = result.interval = maxInterval;
  30155. }
  30156. // Tow more digital for tick.
  30157. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  30158. // Niced extent inside original extent
  30159. var niceTickExtent = result.niceTickExtent = [
  30160. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  30161. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  30162. ];
  30163. fixExtent(niceTickExtent, extent);
  30164. return result;
  30165. }
  30166. /**
  30167. * @param {number} interval
  30168. * @return {number} interval precision
  30169. */
  30170. function getIntervalPrecision(interval) {
  30171. // Tow more digital for tick.
  30172. return getPrecisionSafe(interval) + 2;
  30173. }
  30174. function clamp(niceTickExtent, idx, extent) {
  30175. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30176. }
  30177. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30178. function fixExtent(niceTickExtent, extent) {
  30179. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30180. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30181. clamp(niceTickExtent, 0, extent);
  30182. clamp(niceTickExtent, 1, extent);
  30183. if (niceTickExtent[0] > niceTickExtent[1]) {
  30184. niceTickExtent[0] = niceTickExtent[1];
  30185. }
  30186. }
  30187. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  30188. var ticks = [];
  30189. // If interval is 0, return [];
  30190. if (!interval) {
  30191. return ticks;
  30192. }
  30193. // Consider this case: using dataZoom toolbox, zoom and zoom.
  30194. var safeLimit = 10000;
  30195. if (extent[0] < niceTickExtent[0]) {
  30196. ticks.push(extent[0]);
  30197. }
  30198. var tick = niceTickExtent[0];
  30199. while (tick <= niceTickExtent[1]) {
  30200. ticks.push(tick);
  30201. // Avoid rounding error
  30202. tick = roundNumber$1(tick + interval, intervalPrecision);
  30203. if (tick === ticks[ticks.length - 1]) {
  30204. // Consider out of safe float point, e.g.,
  30205. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30206. break;
  30207. }
  30208. if (ticks.length > safeLimit) {
  30209. return [];
  30210. }
  30211. }
  30212. // Consider this case: the last item of ticks is smaller
  30213. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30214. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  30215. ticks.push(extent[1]);
  30216. }
  30217. return ticks;
  30218. }
  30219. /*
  30220. * Licensed to the Apache Software Foundation (ASF) under one
  30221. * or more contributor license agreements. See the NOTICE file
  30222. * distributed with this work for additional information
  30223. * regarding copyright ownership. The ASF licenses this file
  30224. * to you under the Apache License, Version 2.0 (the
  30225. * "License"); you may not use this file except in compliance
  30226. * with the License. You may obtain a copy of the License at
  30227. *
  30228. * http://www.apache.org/licenses/LICENSE-2.0
  30229. *
  30230. * Unless required by applicable law or agreed to in writing,
  30231. * software distributed under the License is distributed on an
  30232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30233. * KIND, either express or implied. See the License for the
  30234. * specific language governing permissions and limitations
  30235. * under the License.
  30236. */
  30237. /**
  30238. * Interval scale
  30239. * @module echarts/scale/Interval
  30240. */
  30241. var roundNumber = round$2;
  30242. /**
  30243. * @alias module:echarts/coord/scale/Interval
  30244. * @constructor
  30245. */
  30246. var IntervalScale = Scale.extend({
  30247. type: 'interval',
  30248. _interval: 0,
  30249. _intervalPrecision: 2,
  30250. setExtent: function (start, end) {
  30251. var thisExtent = this._extent;
  30252. //start,end may be a Number like '25',so...
  30253. if (!isNaN(start)) {
  30254. thisExtent[0] = parseFloat(start);
  30255. }
  30256. if (!isNaN(end)) {
  30257. thisExtent[1] = parseFloat(end);
  30258. }
  30259. },
  30260. unionExtent: function (other) {
  30261. var extent = this._extent;
  30262. other[0] < extent[0] && (extent[0] = other[0]);
  30263. other[1] > extent[1] && (extent[1] = other[1]);
  30264. // unionExtent may called by it's sub classes
  30265. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  30266. },
  30267. /**
  30268. * Get interval
  30269. */
  30270. getInterval: function () {
  30271. return this._interval;
  30272. },
  30273. /**
  30274. * Set interval
  30275. */
  30276. setInterval: function (interval) {
  30277. this._interval = interval;
  30278. // Dropped auto calculated niceExtent and use user setted extent
  30279. // We assume user wan't to set both interval, min, max to get a better result
  30280. this._niceExtent = this._extent.slice();
  30281. this._intervalPrecision = getIntervalPrecision(interval);
  30282. },
  30283. /**
  30284. * @return {Array.<number>}
  30285. */
  30286. getTicks: function () {
  30287. return intervalScaleGetTicks(
  30288. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  30289. );
  30290. },
  30291. /**
  30292. * @param {number} data
  30293. * @param {Object} [opt]
  30294. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  30295. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  30296. * @return {string}
  30297. */
  30298. getLabel: function (data, opt) {
  30299. if (data == null) {
  30300. return '';
  30301. }
  30302. var precision = opt && opt.precision;
  30303. if (precision == null) {
  30304. precision = getPrecisionSafe(data) || 0;
  30305. }
  30306. else if (precision === 'auto') {
  30307. // Should be more precise then tick.
  30308. precision = this._intervalPrecision;
  30309. }
  30310. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30311. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30312. data = roundNumber(data, precision, true);
  30313. return addCommas(data);
  30314. },
  30315. /**
  30316. * Update interval and extent of intervals for nice ticks
  30317. *
  30318. * @param {number} [splitNumber = 5] Desired number of ticks
  30319. * @param {number} [minInterval]
  30320. * @param {number} [maxInterval]
  30321. */
  30322. niceTicks: function (splitNumber, minInterval, maxInterval) {
  30323. splitNumber = splitNumber || 5;
  30324. var extent = this._extent;
  30325. var span = extent[1] - extent[0];
  30326. if (!isFinite(span)) {
  30327. return;
  30328. }
  30329. // User may set axis min 0 and data are all negative
  30330. // FIXME If it needs to reverse ?
  30331. if (span < 0) {
  30332. span = -span;
  30333. extent.reverse();
  30334. }
  30335. var result = intervalScaleNiceTicks(
  30336. extent, splitNumber, minInterval, maxInterval
  30337. );
  30338. this._intervalPrecision = result.intervalPrecision;
  30339. this._interval = result.interval;
  30340. this._niceExtent = result.niceTickExtent;
  30341. },
  30342. /**
  30343. * Nice extent.
  30344. * @param {Object} opt
  30345. * @param {number} [opt.splitNumber = 5] Given approx tick number
  30346. * @param {boolean} [opt.fixMin=false]
  30347. * @param {boolean} [opt.fixMax=false]
  30348. * @param {boolean} [opt.minInterval]
  30349. * @param {boolean} [opt.maxInterval]
  30350. */
  30351. niceExtent: function (opt) {
  30352. var extent = this._extent;
  30353. // If extent start and end are same, expand them
  30354. if (extent[0] === extent[1]) {
  30355. if (extent[0] !== 0) {
  30356. // Expand extent
  30357. var expandSize = extent[0];
  30358. // In the fowllowing case
  30359. // Axis has been fixed max 100
  30360. // Plus data are all 100 and axis extent are [100, 100].
  30361. // Extend to the both side will cause expanded max is larger than fixed max.
  30362. // So only expand to the smaller side.
  30363. if (!opt.fixMax) {
  30364. extent[1] += expandSize / 2;
  30365. extent[0] -= expandSize / 2;
  30366. }
  30367. else {
  30368. extent[0] -= expandSize / 2;
  30369. }
  30370. }
  30371. else {
  30372. extent[1] = 1;
  30373. }
  30374. }
  30375. var span = extent[1] - extent[0];
  30376. // If there are no data and extent are [Infinity, -Infinity]
  30377. if (!isFinite(span)) {
  30378. extent[0] = 0;
  30379. extent[1] = 1;
  30380. }
  30381. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30382. // var extent = this._extent;
  30383. var interval = this._interval;
  30384. if (!opt.fixMin) {
  30385. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30386. }
  30387. if (!opt.fixMax) {
  30388. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30389. }
  30390. }
  30391. });
  30392. /**
  30393. * @return {module:echarts/scale/Time}
  30394. */
  30395. IntervalScale.create = function () {
  30396. return new IntervalScale();
  30397. };
  30398. /*
  30399. * Licensed to the Apache Software Foundation (ASF) under one
  30400. * or more contributor license agreements. See the NOTICE file
  30401. * distributed with this work for additional information
  30402. * regarding copyright ownership. The ASF licenses this file
  30403. * to you under the Apache License, Version 2.0 (the
  30404. * "License"); you may not use this file except in compliance
  30405. * with the License. You may obtain a copy of the License at
  30406. *
  30407. * http://www.apache.org/licenses/LICENSE-2.0
  30408. *
  30409. * Unless required by applicable law or agreed to in writing,
  30410. * software distributed under the License is distributed on an
  30411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30412. * KIND, either express or implied. See the License for the
  30413. * specific language governing permissions and limitations
  30414. * under the License.
  30415. */
  30416. /* global Float32Array */
  30417. var STACK_PREFIX = '__ec_stack_';
  30418. var LARGE_BAR_MIN_WIDTH = 0.5;
  30419. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  30420. function getSeriesStackId(seriesModel) {
  30421. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30422. }
  30423. function getAxisKey(axis) {
  30424. return axis.dim + axis.index;
  30425. }
  30426. /**
  30427. * @param {Object} opt
  30428. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  30429. * @param {number} opt.count Positive interger.
  30430. * @param {number} [opt.barWidth]
  30431. * @param {number} [opt.barMaxWidth]
  30432. * @param {number} [opt.barGap]
  30433. * @param {number} [opt.barCategoryGap]
  30434. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  30435. */
  30436. function prepareLayoutBarSeries(seriesType, ecModel) {
  30437. var seriesModels = [];
  30438. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30439. // Check series coordinate, do layout for cartesian2d only
  30440. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  30441. seriesModels.push(seriesModel);
  30442. }
  30443. });
  30444. return seriesModels;
  30445. }
  30446. function makeColumnLayout(barSeries) {
  30447. var seriesInfoList = [];
  30448. each$1(barSeries, function (seriesModel) {
  30449. var data = seriesModel.getData();
  30450. var cartesian = seriesModel.coordinateSystem;
  30451. var baseAxis = cartesian.getBaseAxis();
  30452. var axisExtent = baseAxis.getExtent();
  30453. var bandWidth = baseAxis.type === 'category'
  30454. ? baseAxis.getBandWidth()
  30455. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  30456. var barWidth = parsePercent$1(
  30457. seriesModel.get('barWidth'), bandWidth
  30458. );
  30459. var barMaxWidth = parsePercent$1(
  30460. seriesModel.get('barMaxWidth'), bandWidth
  30461. );
  30462. var barGap = seriesModel.get('barGap');
  30463. var barCategoryGap = seriesModel.get('barCategoryGap');
  30464. seriesInfoList.push({
  30465. bandWidth: bandWidth,
  30466. barWidth: barWidth,
  30467. barMaxWidth: barMaxWidth,
  30468. barGap: barGap,
  30469. barCategoryGap: barCategoryGap,
  30470. axisKey: getAxisKey(baseAxis),
  30471. stackId: getSeriesStackId(seriesModel)
  30472. });
  30473. });
  30474. return doCalBarWidthAndOffset(seriesInfoList);
  30475. }
  30476. function doCalBarWidthAndOffset(seriesInfoList) {
  30477. // Columns info on each category axis. Key is cartesian name
  30478. var columnsMap = {};
  30479. each$1(seriesInfoList, function (seriesInfo, idx) {
  30480. var axisKey = seriesInfo.axisKey;
  30481. var bandWidth = seriesInfo.bandWidth;
  30482. var columnsOnAxis = columnsMap[axisKey] || {
  30483. bandWidth: bandWidth,
  30484. remainedWidth: bandWidth,
  30485. autoWidthCount: 0,
  30486. categoryGap: '20%',
  30487. gap: '30%',
  30488. stacks: {}
  30489. };
  30490. var stacks = columnsOnAxis.stacks;
  30491. columnsMap[axisKey] = columnsOnAxis;
  30492. var stackId = seriesInfo.stackId;
  30493. if (!stacks[stackId]) {
  30494. columnsOnAxis.autoWidthCount++;
  30495. }
  30496. stacks[stackId] = stacks[stackId] || {
  30497. width: 0,
  30498. maxWidth: 0
  30499. };
  30500. // Caution: In a single coordinate system, these barGrid attributes
  30501. // will be shared by series. Consider that they have default values,
  30502. // only the attributes set on the last series will work.
  30503. // Do not change this fact unless there will be a break change.
  30504. // TODO
  30505. var barWidth = seriesInfo.barWidth;
  30506. if (barWidth && !stacks[stackId].width) {
  30507. // See #6312, do not restrict width.
  30508. stacks[stackId].width = barWidth;
  30509. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30510. columnsOnAxis.remainedWidth -= barWidth;
  30511. }
  30512. var barMaxWidth = seriesInfo.barMaxWidth;
  30513. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30514. var barGap = seriesInfo.barGap;
  30515. (barGap != null) && (columnsOnAxis.gap = barGap);
  30516. var barCategoryGap = seriesInfo.barCategoryGap;
  30517. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  30518. });
  30519. var result = {};
  30520. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  30521. result[coordSysName] = {};
  30522. var stacks = columnsOnAxis.stacks;
  30523. var bandWidth = columnsOnAxis.bandWidth;
  30524. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  30525. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30526. var remainedWidth = columnsOnAxis.remainedWidth;
  30527. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30528. var autoWidth = (remainedWidth - categoryGap)
  30529. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30530. autoWidth = Math.max(autoWidth, 0);
  30531. // Find if any auto calculated bar exceeded maxBarWidth
  30532. each$1(stacks, function (column, stack) {
  30533. var maxWidth = column.maxWidth;
  30534. if (maxWidth && maxWidth < autoWidth) {
  30535. maxWidth = Math.min(maxWidth, remainedWidth);
  30536. if (column.width) {
  30537. maxWidth = Math.min(maxWidth, column.width);
  30538. }
  30539. remainedWidth -= maxWidth;
  30540. column.width = maxWidth;
  30541. autoWidthCount--;
  30542. }
  30543. });
  30544. // Recalculate width again
  30545. autoWidth = (remainedWidth - categoryGap)
  30546. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30547. autoWidth = Math.max(autoWidth, 0);
  30548. var widthSum = 0;
  30549. var lastColumn;
  30550. each$1(stacks, function (column, idx) {
  30551. if (!column.width) {
  30552. column.width = autoWidth;
  30553. }
  30554. lastColumn = column;
  30555. widthSum += column.width * (1 + barGapPercent);
  30556. });
  30557. if (lastColumn) {
  30558. widthSum -= lastColumn.width * barGapPercent;
  30559. }
  30560. var offset = -widthSum / 2;
  30561. each$1(stacks, function (column, stackId) {
  30562. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30563. offset: offset,
  30564. width: column.width
  30565. };
  30566. offset += column.width * (1 + barGapPercent);
  30567. });
  30568. });
  30569. return result;
  30570. }
  30571. /**
  30572. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  30573. * @param {module:echarts/coord/Axis} axis
  30574. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  30575. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  30576. */
  30577. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30578. if (barWidthAndOffset && axis) {
  30579. var result = barWidthAndOffset[getAxisKey(axis)];
  30580. if (result != null && seriesModel != null) {
  30581. result = result[getSeriesStackId(seriesModel)];
  30582. }
  30583. return result;
  30584. }
  30585. }
  30586. /**
  30587. * @param {string} seriesType
  30588. * @param {module:echarts/model/Global} ecModel
  30589. */
  30590. function layout(seriesType, ecModel) {
  30591. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30592. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30593. var lastStackCoords = {};
  30594. each$1(seriesModels, function (seriesModel) {
  30595. var data = seriesModel.getData();
  30596. var cartesian = seriesModel.coordinateSystem;
  30597. var baseAxis = cartesian.getBaseAxis();
  30598. var stackId = getSeriesStackId(seriesModel);
  30599. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30600. var columnOffset = columnLayoutInfo.offset;
  30601. var columnWidth = columnLayoutInfo.width;
  30602. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30603. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30604. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30605. data.setLayout({
  30606. offset: columnOffset,
  30607. size: columnWidth
  30608. });
  30609. var valueDim = data.mapDimension(valueAxis.dim);
  30610. var baseDim = data.mapDimension(baseAxis.dim);
  30611. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  30612. var isValueAxisH = valueAxis.isHorizontal();
  30613. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  30614. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30615. var value = data.get(valueDim, idx);
  30616. var baseValue = data.get(baseDim, idx);
  30617. if (isNaN(value)) {
  30618. continue;
  30619. }
  30620. var sign = value >= 0 ? 'p' : 'n';
  30621. var baseCoord = valueAxisStart;
  30622. // Because of the barMinHeight, we can not use the value in
  30623. // stackResultDimension directly.
  30624. if (stacked) {
  30625. // Only ordinal axis can be stacked.
  30626. if (!lastStackCoords[stackId][baseValue]) {
  30627. lastStackCoords[stackId][baseValue] = {
  30628. p: valueAxisStart, // Positive stack
  30629. n: valueAxisStart // Negative stack
  30630. };
  30631. }
  30632. // Should also consider #4243
  30633. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30634. }
  30635. var x;
  30636. var y;
  30637. var width;
  30638. var height;
  30639. if (isValueAxisH) {
  30640. var coord = cartesian.dataToPoint([value, baseValue]);
  30641. x = baseCoord;
  30642. y = coord[1] + columnOffset;
  30643. width = coord[0] - valueAxisStart;
  30644. height = columnWidth;
  30645. if (Math.abs(width) < barMinHeight) {
  30646. width = (width < 0 ? -1 : 1) * barMinHeight;
  30647. }
  30648. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30649. }
  30650. else {
  30651. var coord = cartesian.dataToPoint([baseValue, value]);
  30652. x = coord[0] + columnOffset;
  30653. y = baseCoord;
  30654. width = columnWidth;
  30655. height = coord[1] - valueAxisStart;
  30656. if (Math.abs(height) < barMinHeight) {
  30657. // Include zero to has a positive bar
  30658. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30659. }
  30660. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30661. }
  30662. data.setItemLayout(idx, {
  30663. x: x,
  30664. y: y,
  30665. width: width,
  30666. height: height
  30667. });
  30668. }
  30669. }, this);
  30670. }
  30671. // TODO: Do not support stack in large mode yet.
  30672. var largeLayout = {
  30673. seriesType: 'bar',
  30674. plan: createRenderPlanner(),
  30675. reset: function (seriesModel) {
  30676. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30677. return;
  30678. }
  30679. var data = seriesModel.getData();
  30680. var cartesian = seriesModel.coordinateSystem;
  30681. var baseAxis = cartesian.getBaseAxis();
  30682. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30683. var valueDim = data.mapDimension(valueAxis.dim);
  30684. var baseDim = data.mapDimension(baseAxis.dim);
  30685. var valueAxisHorizontal = valueAxis.isHorizontal();
  30686. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30687. var barWidth = retrieveColumnLayout(
  30688. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  30689. ).width;
  30690. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  30691. barWidth = LARGE_BAR_MIN_WIDTH;
  30692. }
  30693. return {progress: progress};
  30694. function progress(params, data) {
  30695. var largePoints = new LargeArr(params.count * 2);
  30696. var dataIndex;
  30697. var coord = [];
  30698. var valuePair = [];
  30699. var offset = 0;
  30700. while ((dataIndex = params.next()) != null) {
  30701. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30702. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30703. coord = cartesian.dataToPoint(valuePair, null, coord);
  30704. largePoints[offset++] = coord[0];
  30705. largePoints[offset++] = coord[1];
  30706. }
  30707. data.setLayout({
  30708. largePoints: largePoints,
  30709. barWidth: barWidth,
  30710. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  30711. valueAxisHorizontal: valueAxisHorizontal
  30712. });
  30713. }
  30714. }
  30715. };
  30716. function isOnCartesian(seriesModel) {
  30717. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30718. }
  30719. function isInLargeMode(seriesModel) {
  30720. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30721. }
  30722. // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30723. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30724. var extent = valueAxis.getGlobalExtent();
  30725. var min;
  30726. var max;
  30727. if (extent[0] > extent[1]) {
  30728. min = extent[1];
  30729. max = extent[0];
  30730. }
  30731. else {
  30732. min = extent[0];
  30733. max = extent[1];
  30734. }
  30735. var valueStart = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  30736. valueStart < min && (valueStart = min);
  30737. valueStart > max && (valueStart = max);
  30738. return valueStart;
  30739. }
  30740. /*
  30741. * Licensed to the Apache Software Foundation (ASF) under one
  30742. * or more contributor license agreements. See the NOTICE file
  30743. * distributed with this work for additional information
  30744. * regarding copyright ownership. The ASF licenses this file
  30745. * to you under the Apache License, Version 2.0 (the
  30746. * "License"); you may not use this file except in compliance
  30747. * with the License. You may obtain a copy of the License at
  30748. *
  30749. * http://www.apache.org/licenses/LICENSE-2.0
  30750. *
  30751. * Unless required by applicable law or agreed to in writing,
  30752. * software distributed under the License is distributed on an
  30753. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30754. * KIND, either express or implied. See the License for the
  30755. * specific language governing permissions and limitations
  30756. * under the License.
  30757. */
  30758. /*
  30759. * A third-party license is embeded for some of the code in this file:
  30760. * The "scaleLevels" was originally copied from "d3.js" with some
  30761. * modifications made for this project.
  30762. * (See more details in the comment on the definition of "scaleLevels" below.)
  30763. * The use of the source code of this file is also subject to the terms
  30764. * and consitions of the license of "d3.js" (BSD-3Clause, see
  30765. * </licenses/LICENSE-d3>).
  30766. */
  30767. // [About UTC and local time zone]:
  30768. // In most cases, `number.parseDate` will treat input data string as local time
  30769. // (except time zone is specified in time string). And `format.formateTime` returns
  30770. // local time by default. option.useUTC is false by default. This design have
  30771. // concidered these common case:
  30772. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  30773. // in local time by default.
  30774. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  30775. // as its original time, without any time difference.
  30776. var intervalScaleProto = IntervalScale.prototype;
  30777. var mathCeil = Math.ceil;
  30778. var mathFloor = Math.floor;
  30779. var ONE_SECOND = 1000;
  30780. var ONE_MINUTE = ONE_SECOND * 60;
  30781. var ONE_HOUR = ONE_MINUTE * 60;
  30782. var ONE_DAY = ONE_HOUR * 24;
  30783. // FIXME 公用?
  30784. var bisect = function (a, x, lo, hi) {
  30785. while (lo < hi) {
  30786. var mid = lo + hi >>> 1;
  30787. if (a[mid][1] < x) {
  30788. lo = mid + 1;
  30789. }
  30790. else {
  30791. hi = mid;
  30792. }
  30793. }
  30794. return lo;
  30795. };
  30796. /**
  30797. * @alias module:echarts/coord/scale/Time
  30798. * @constructor
  30799. */
  30800. var TimeScale = IntervalScale.extend({
  30801. type: 'time',
  30802. /**
  30803. * @override
  30804. */
  30805. getLabel: function (val) {
  30806. var stepLvl = this._stepLvl;
  30807. var date = new Date(val);
  30808. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  30809. },
  30810. /**
  30811. * @override
  30812. */
  30813. niceExtent: function (opt) {
  30814. var extent = this._extent;
  30815. // If extent start and end are same, expand them
  30816. if (extent[0] === extent[1]) {
  30817. // Expand extent
  30818. extent[0] -= ONE_DAY;
  30819. extent[1] += ONE_DAY;
  30820. }
  30821. // If there are no data and extent are [Infinity, -Infinity]
  30822. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30823. var d = new Date();
  30824. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30825. extent[0] = extent[1] - ONE_DAY;
  30826. }
  30827. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30828. // var extent = this._extent;
  30829. var interval = this._interval;
  30830. if (!opt.fixMin) {
  30831. extent[0] = round$2(mathFloor(extent[0] / interval) * interval);
  30832. }
  30833. if (!opt.fixMax) {
  30834. extent[1] = round$2(mathCeil(extent[1] / interval) * interval);
  30835. }
  30836. },
  30837. /**
  30838. * @override
  30839. */
  30840. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  30841. approxTickNum = approxTickNum || 10;
  30842. var extent = this._extent;
  30843. var span = extent[1] - extent[0];
  30844. var approxInterval = span / approxTickNum;
  30845. if (minInterval != null && approxInterval < minInterval) {
  30846. approxInterval = minInterval;
  30847. }
  30848. if (maxInterval != null && approxInterval > maxInterval) {
  30849. approxInterval = maxInterval;
  30850. }
  30851. var scaleLevelsLen = scaleLevels.length;
  30852. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  30853. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  30854. var interval = level[1];
  30855. // Same with interval scale if span is much larger than 1 year
  30856. if (level[0] === 'year') {
  30857. var yearSpan = span / interval;
  30858. // From "Nice Numbers for Graph Labels" of Graphic Gems
  30859. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  30860. var yearStep = nice(yearSpan / approxTickNum, true);
  30861. interval *= yearStep;
  30862. }
  30863. var timezoneOffset = this.getSetting('useUTC')
  30864. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  30865. var niceExtent = [
  30866. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  30867. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  30868. ];
  30869. fixExtent(niceExtent, extent);
  30870. this._stepLvl = level;
  30871. // Interval will be used in getTicks
  30872. this._interval = interval;
  30873. this._niceExtent = niceExtent;
  30874. },
  30875. parse: function (val) {
  30876. // val might be float.
  30877. return +parseDate(val);
  30878. }
  30879. });
  30880. each$1(['contain', 'normalize'], function (methodName) {
  30881. TimeScale.prototype[methodName] = function (val) {
  30882. return intervalScaleProto[methodName].call(this, this.parse(val));
  30883. };
  30884. });
  30885. /**
  30886. * This implementation was originally copied from "d3.js"
  30887. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30888. * with some modifications made for this program.
  30889. * See the license statement at the head of this file.
  30890. */
  30891. var scaleLevels = [
  30892. // Format interval
  30893. ['hh:mm:ss', ONE_SECOND], // 1s
  30894. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  30895. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  30896. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  30897. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  30898. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  30899. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  30900. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  30901. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  30902. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  30903. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  30904. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  30905. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  30906. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  30907. ['MM-dd\nyyyy', ONE_DAY], // 1d
  30908. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  30909. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  30910. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  30911. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  30912. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  30913. ['week', ONE_DAY * 7], // 7d
  30914. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  30915. ['week', ONE_DAY * 14], // 2w
  30916. ['week', ONE_DAY * 21], // 3w
  30917. ['month', ONE_DAY * 31], // 1M
  30918. ['week', ONE_DAY * 42], // 6w
  30919. ['month', ONE_DAY * 62], // 2M
  30920. ['week', ONE_DAY * 70], // 10w
  30921. ['quarter', ONE_DAY * 95], // 3M
  30922. ['month', ONE_DAY * 31 * 4], // 4M
  30923. ['month', ONE_DAY * 31 * 5], // 5M
  30924. ['half-year', ONE_DAY * 380 / 2], // 6M
  30925. ['month', ONE_DAY * 31 * 8], // 8M
  30926. ['month', ONE_DAY * 31 * 10], // 10M
  30927. ['year', ONE_DAY * 380] // 1Y
  30928. ];
  30929. /**
  30930. * @param {module:echarts/model/Model}
  30931. * @return {module:echarts/scale/Time}
  30932. */
  30933. TimeScale.create = function (model) {
  30934. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  30935. };
  30936. /*
  30937. * Licensed to the Apache Software Foundation (ASF) under one
  30938. * or more contributor license agreements. See the NOTICE file
  30939. * distributed with this work for additional information
  30940. * regarding copyright ownership. The ASF licenses this file
  30941. * to you under the Apache License, Version 2.0 (the
  30942. * "License"); you may not use this file except in compliance
  30943. * with the License. You may obtain a copy of the License at
  30944. *
  30945. * http://www.apache.org/licenses/LICENSE-2.0
  30946. *
  30947. * Unless required by applicable law or agreed to in writing,
  30948. * software distributed under the License is distributed on an
  30949. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30950. * KIND, either express or implied. See the License for the
  30951. * specific language governing permissions and limitations
  30952. * under the License.
  30953. */
  30954. /**
  30955. * Log scale
  30956. * @module echarts/scale/Log
  30957. */
  30958. // Use some method of IntervalScale
  30959. var scaleProto$1 = Scale.prototype;
  30960. var intervalScaleProto$1 = IntervalScale.prototype;
  30961. var getPrecisionSafe$1 = getPrecisionSafe;
  30962. var roundingErrorFix = round$2;
  30963. var mathFloor$1 = Math.floor;
  30964. var mathCeil$1 = Math.ceil;
  30965. var mathPow$1 = Math.pow;
  30966. var mathLog = Math.log;
  30967. var LogScale = Scale.extend({
  30968. type: 'log',
  30969. base: 10,
  30970. $constructor: function () {
  30971. Scale.apply(this, arguments);
  30972. this._originalScale = new IntervalScale();
  30973. },
  30974. /**
  30975. * @return {Array.<number>}
  30976. */
  30977. getTicks: function () {
  30978. var originalScale = this._originalScale;
  30979. var extent = this._extent;
  30980. var originalExtent = originalScale.getExtent();
  30981. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  30982. var powVal = round$2(mathPow$1(this.base, val));
  30983. // Fix #4158
  30984. powVal = (val === extent[0] && originalScale.__fixMin)
  30985. ? fixRoundingError(powVal, originalExtent[0])
  30986. : powVal;
  30987. powVal = (val === extent[1] && originalScale.__fixMax)
  30988. ? fixRoundingError(powVal, originalExtent[1])
  30989. : powVal;
  30990. return powVal;
  30991. }, this);
  30992. },
  30993. /**
  30994. * @param {number} val
  30995. * @return {string}
  30996. */
  30997. getLabel: intervalScaleProto$1.getLabel,
  30998. /**
  30999. * @param {number} val
  31000. * @return {number}
  31001. */
  31002. scale: function (val) {
  31003. val = scaleProto$1.scale.call(this, val);
  31004. return mathPow$1(this.base, val);
  31005. },
  31006. /**
  31007. * @param {number} start
  31008. * @param {number} end
  31009. */
  31010. setExtent: function (start, end) {
  31011. var base = this.base;
  31012. start = mathLog(start) / mathLog(base);
  31013. end = mathLog(end) / mathLog(base);
  31014. intervalScaleProto$1.setExtent.call(this, start, end);
  31015. },
  31016. /**
  31017. * @return {number} end
  31018. */
  31019. getExtent: function () {
  31020. var base = this.base;
  31021. var extent = scaleProto$1.getExtent.call(this);
  31022. extent[0] = mathPow$1(base, extent[0]);
  31023. extent[1] = mathPow$1(base, extent[1]);
  31024. // Fix #4158
  31025. var originalScale = this._originalScale;
  31026. var originalExtent = originalScale.getExtent();
  31027. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31028. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31029. return extent;
  31030. },
  31031. /**
  31032. * @param {Array.<number>} extent
  31033. */
  31034. unionExtent: function (extent) {
  31035. this._originalScale.unionExtent(extent);
  31036. var base = this.base;
  31037. extent[0] = mathLog(extent[0]) / mathLog(base);
  31038. extent[1] = mathLog(extent[1]) / mathLog(base);
  31039. scaleProto$1.unionExtent.call(this, extent);
  31040. },
  31041. /**
  31042. * @override
  31043. */
  31044. unionExtentFromData: function (data, dim) {
  31045. // TODO
  31046. // filter value that <= 0
  31047. this.unionExtent(data.getApproximateExtent(dim));
  31048. },
  31049. /**
  31050. * Update interval and extent of intervals for nice ticks
  31051. * @param {number} [approxTickNum = 10] Given approx tick number
  31052. */
  31053. niceTicks: function (approxTickNum) {
  31054. approxTickNum = approxTickNum || 10;
  31055. var extent = this._extent;
  31056. var span = extent[1] - extent[0];
  31057. if (span === Infinity || span <= 0) {
  31058. return;
  31059. }
  31060. var interval = quantity(span);
  31061. var err = approxTickNum / span * interval;
  31062. // Filter ticks to get closer to the desired count.
  31063. if (err <= 0.5) {
  31064. interval *= 10;
  31065. }
  31066. // Interval should be integer
  31067. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31068. interval *= 10;
  31069. }
  31070. var niceExtent = [
  31071. round$2(mathCeil$1(extent[0] / interval) * interval),
  31072. round$2(mathFloor$1(extent[1] / interval) * interval)
  31073. ];
  31074. this._interval = interval;
  31075. this._niceExtent = niceExtent;
  31076. },
  31077. /**
  31078. * Nice extent.
  31079. * @override
  31080. */
  31081. niceExtent: function (opt) {
  31082. intervalScaleProto$1.niceExtent.call(this, opt);
  31083. var originalScale = this._originalScale;
  31084. originalScale.__fixMin = opt.fixMin;
  31085. originalScale.__fixMax = opt.fixMax;
  31086. }
  31087. });
  31088. each$1(['contain', 'normalize'], function (methodName) {
  31089. LogScale.prototype[methodName] = function (val) {
  31090. val = mathLog(val) / mathLog(this.base);
  31091. return scaleProto$1[methodName].call(this, val);
  31092. };
  31093. });
  31094. LogScale.create = function () {
  31095. return new LogScale();
  31096. };
  31097. function fixRoundingError(val, originalVal) {
  31098. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  31099. }
  31100. /*
  31101. * Licensed to the Apache Software Foundation (ASF) under one
  31102. * or more contributor license agreements. See the NOTICE file
  31103. * distributed with this work for additional information
  31104. * regarding copyright ownership. The ASF licenses this file
  31105. * to you under the Apache License, Version 2.0 (the
  31106. * "License"); you may not use this file except in compliance
  31107. * with the License. You may obtain a copy of the License at
  31108. *
  31109. * http://www.apache.org/licenses/LICENSE-2.0
  31110. *
  31111. * Unless required by applicable law or agreed to in writing,
  31112. * software distributed under the License is distributed on an
  31113. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31114. * KIND, either express or implied. See the License for the
  31115. * specific language governing permissions and limitations
  31116. * under the License.
  31117. */
  31118. /**
  31119. * Get axis scale extent before niced.
  31120. * Item of returned array can only be number (including Infinity and NaN).
  31121. */
  31122. function getScaleExtent(scale, model) {
  31123. var scaleType = scale.type;
  31124. var min = model.getMin();
  31125. var max = model.getMax();
  31126. var fixMin = min != null;
  31127. var fixMax = max != null;
  31128. var originalExtent = scale.getExtent();
  31129. var axisDataLen;
  31130. var boundaryGap;
  31131. var span;
  31132. if (scaleType === 'ordinal') {
  31133. axisDataLen = model.getCategories().length;
  31134. }
  31135. else {
  31136. boundaryGap = model.get('boundaryGap');
  31137. if (!isArray(boundaryGap)) {
  31138. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  31139. }
  31140. if (typeof boundaryGap[0] === 'boolean') {
  31141. if (__DEV__) {
  31142. console.warn('Boolean type for boundaryGap is only '
  31143. + 'allowed for ordinal axis. Please use string in '
  31144. + 'percentage instead, e.g., "20%". Currently, '
  31145. + 'boundaryGap is set to be 0.');
  31146. }
  31147. boundaryGap = [0, 0];
  31148. }
  31149. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  31150. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  31151. span = (originalExtent[1] - originalExtent[0])
  31152. || Math.abs(originalExtent[0]);
  31153. }
  31154. // Notice: When min/max is not set (that is, when there are null/undefined,
  31155. // which is the most common case), these cases should be ensured:
  31156. // (1) For 'ordinal', show all axis.data.
  31157. // (2) For others:
  31158. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31159. // disabled).
  31160. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31161. // be the result that originalExtent enlarged by boundaryGap.
  31162. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31163. // FIXME
  31164. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  31165. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  31166. // that the results processed by boundaryGap are positive/negative?
  31167. if (min == null) {
  31168. min = scaleType === 'ordinal'
  31169. ? (axisDataLen ? 0 : NaN)
  31170. : originalExtent[0] - boundaryGap[0] * span;
  31171. }
  31172. if (max == null) {
  31173. max = scaleType === 'ordinal'
  31174. ? (axisDataLen ? axisDataLen - 1 : NaN)
  31175. : originalExtent[1] + boundaryGap[1] * span;
  31176. }
  31177. if (min === 'dataMin') {
  31178. min = originalExtent[0];
  31179. }
  31180. else if (typeof min === 'function') {
  31181. min = min({
  31182. min: originalExtent[0],
  31183. max: originalExtent[1]
  31184. });
  31185. }
  31186. if (max === 'dataMax') {
  31187. max = originalExtent[1];
  31188. }
  31189. else if (typeof max === 'function') {
  31190. max = max({
  31191. min: originalExtent[0],
  31192. max: originalExtent[1]
  31193. });
  31194. }
  31195. (min == null || !isFinite(min)) && (min = NaN);
  31196. (max == null || !isFinite(max)) && (max = NaN);
  31197. scale.setBlank(
  31198. eqNaN(min)
  31199. || eqNaN(max)
  31200. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  31201. );
  31202. // Evaluate if axis needs cross zero
  31203. if (model.getNeedCrossZero()) {
  31204. // Axis is over zero and min is not set
  31205. if (min > 0 && max > 0 && !fixMin) {
  31206. min = 0;
  31207. }
  31208. // Axis is under zero and max is not set
  31209. if (min < 0 && max < 0 && !fixMax) {
  31210. max = 0;
  31211. }
  31212. }
  31213. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  31214. // is base axis
  31215. // FIXME
  31216. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31217. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31218. // Should not depend on series type `bar`?
  31219. // (3) Fix that might overlap when using dataZoom.
  31220. // (4) Consider other chart types using `barGrid`?
  31221. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31222. var ecModel = model.ecModel;
  31223. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  31224. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31225. var isBaseAxisAndHasBarSeries;
  31226. each$1(barSeriesModels, function (seriesModel) {
  31227. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  31228. });
  31229. if (isBaseAxisAndHasBarSeries) {
  31230. // Calculate placement of bars on axis
  31231. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  31232. // Adjust axis min and max to account for overflow
  31233. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31234. min = adjustedScale.min;
  31235. max = adjustedScale.max;
  31236. }
  31237. }
  31238. return [min, max];
  31239. }
  31240. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  31241. // Get Axis Length
  31242. var axisExtent = model.axis.getExtent();
  31243. var axisLength = axisExtent[1] - axisExtent[0];
  31244. // Get bars on current base axis and calculate min and max overflow
  31245. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31246. if (barsOnCurrentAxis === undefined) {
  31247. return {min: min, max: max};
  31248. }
  31249. var minOverflow = Infinity;
  31250. each$1(barsOnCurrentAxis, function (item) {
  31251. minOverflow = Math.min(item.offset, minOverflow);
  31252. });
  31253. var maxOverflow = -Infinity;
  31254. each$1(barsOnCurrentAxis, function (item) {
  31255. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31256. });
  31257. minOverflow = Math.abs(minOverflow);
  31258. maxOverflow = Math.abs(maxOverflow);
  31259. var totalOverFlow = minOverflow + maxOverflow;
  31260. // Calulate required buffer based on old range and overflow
  31261. var oldRange = max - min;
  31262. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  31263. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  31264. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31265. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31266. return {min: min, max: max};
  31267. }
  31268. function niceScaleExtent(scale, model) {
  31269. var extent = getScaleExtent(scale, model);
  31270. var fixMin = model.getMin() != null;
  31271. var fixMax = model.getMax() != null;
  31272. var splitNumber = model.get('splitNumber');
  31273. if (scale.type === 'log') {
  31274. scale.base = model.get('logBase');
  31275. }
  31276. var scaleType = scale.type;
  31277. scale.setExtent(extent[0], extent[1]);
  31278. scale.niceExtent({
  31279. splitNumber: splitNumber,
  31280. fixMin: fixMin,
  31281. fixMax: fixMax,
  31282. minInterval: (scaleType === 'interval' || scaleType === 'time')
  31283. ? model.get('minInterval') : null,
  31284. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  31285. ? model.get('maxInterval') : null
  31286. });
  31287. // If some one specified the min, max. And the default calculated interval
  31288. // is not good enough. He can specify the interval. It is often appeared
  31289. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31290. // to be 60.
  31291. // FIXME
  31292. var interval = model.get('interval');
  31293. if (interval != null) {
  31294. scale.setInterval && scale.setInterval(interval);
  31295. }
  31296. }
  31297. /**
  31298. * @param {module:echarts/model/Model} model
  31299. * @param {string} [axisType] Default retrieve from model.type
  31300. * @return {module:echarts/scale/*}
  31301. */
  31302. function createScaleByModel(model, axisType) {
  31303. axisType = axisType || model.get('type');
  31304. if (axisType) {
  31305. switch (axisType) {
  31306. // Buildin scale
  31307. case 'category':
  31308. return new OrdinalScale(
  31309. model.getOrdinalMeta
  31310. ? model.getOrdinalMeta()
  31311. : model.getCategories(),
  31312. [Infinity, -Infinity]
  31313. );
  31314. case 'value':
  31315. return new IntervalScale();
  31316. // Extended scale, like time and log
  31317. default:
  31318. return (Scale.getClass(axisType) || IntervalScale).create(model);
  31319. }
  31320. }
  31321. }
  31322. /**
  31323. * Check if the axis corss 0
  31324. */
  31325. function ifAxisCrossZero(axis) {
  31326. var dataExtent = axis.scale.getExtent();
  31327. var min = dataExtent[0];
  31328. var max = dataExtent[1];
  31329. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  31330. }
  31331. /**
  31332. * @param {module:echarts/coord/Axis} axis
  31333. * @return {Function} Label formatter function.
  31334. * param: {number} tickValue,
  31335. * param: {number} idx, the index in all ticks.
  31336. * If category axis, this param is not requied.
  31337. * return: {string} label string.
  31338. */
  31339. function makeLabelFormatter(axis) {
  31340. var labelFormatter = axis.getLabelModel().get('formatter');
  31341. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31342. if (typeof labelFormatter === 'string') {
  31343. labelFormatter = (function (tpl) {
  31344. return function (val) {
  31345. // For category axis, get raw value; for numeric axis,
  31346. // get foramtted label like '1,333,444'.
  31347. val = axis.scale.getLabel(val);
  31348. return tpl.replace('{value}', val != null ? val : '');
  31349. };
  31350. })(labelFormatter);
  31351. // Consider empty array
  31352. return labelFormatter;
  31353. }
  31354. else if (typeof labelFormatter === 'function') {
  31355. return function (tickValue, idx) {
  31356. // The original intention of `idx` is "the index of the tick in all ticks".
  31357. // But the previous implementation of category axis do not consider the
  31358. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31359. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31360. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31361. // the definition here for back compatibility.
  31362. if (categoryTickStart != null) {
  31363. idx = tickValue - categoryTickStart;
  31364. }
  31365. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  31366. };
  31367. }
  31368. else {
  31369. return function (tick) {
  31370. return axis.scale.getLabel(tick);
  31371. };
  31372. }
  31373. }
  31374. function getAxisRawValue(axis, value) {
  31375. // In category axis with data zoom, tick is not the original
  31376. // index of axis.data. So tick should not be exposed to user
  31377. // in category axis.
  31378. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  31379. }
  31380. /**
  31381. * @param {module:echarts/coord/Axis} axis
  31382. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  31383. */
  31384. function estimateLabelUnionRect(axis) {
  31385. var axisModel = axis.model;
  31386. var scale = axis.scale;
  31387. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  31388. return;
  31389. }
  31390. var isCategory = axis.type === 'category';
  31391. var realNumberScaleTicks;
  31392. var tickCount;
  31393. var categoryScaleExtent = scale.getExtent();
  31394. // Optimize for large category data, avoid call `getTicks()`.
  31395. if (isCategory) {
  31396. tickCount = scale.count();
  31397. }
  31398. else {
  31399. realNumberScaleTicks = scale.getTicks();
  31400. tickCount = realNumberScaleTicks.length;
  31401. }
  31402. var axisLabelModel = axis.getLabelModel();
  31403. var labelFormatter = makeLabelFormatter(axis);
  31404. var rect;
  31405. var step = 1;
  31406. // Simple optimization for large amount of labels
  31407. if (tickCount > 40) {
  31408. step = Math.ceil(tickCount / 40);
  31409. }
  31410. for (var i = 0; i < tickCount; i += step) {
  31411. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  31412. var label = labelFormatter(tickValue);
  31413. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31414. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31415. rect ? rect.union(singleRect) : (rect = singleRect);
  31416. }
  31417. return rect;
  31418. }
  31419. function rotateTextRect(textRect, rotate) {
  31420. var rotateRadians = rotate * Math.PI / 180;
  31421. var boundingBox = textRect.plain();
  31422. var beforeWidth = boundingBox.width;
  31423. var beforeHeight = boundingBox.height;
  31424. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  31425. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  31426. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  31427. return rotatedRect;
  31428. }
  31429. /**
  31430. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  31431. * @return {number|String} Can be null|'auto'|number|function
  31432. */
  31433. function getOptionCategoryInterval(model) {
  31434. var interval = model.get('interval');
  31435. return interval == null ? 'auto' : interval;
  31436. }
  31437. /**
  31438. * Set `categoryInterval` as 0 implicitly indicates that
  31439. * show all labels reguardless of overlap.
  31440. * @param {Object} axis axisModel.axis
  31441. * @return {boolean}
  31442. */
  31443. function shouldShowAllLabels(axis) {
  31444. return axis.type === 'category'
  31445. && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31446. }
  31447. /*
  31448. * Licensed to the Apache Software Foundation (ASF) under one
  31449. * or more contributor license agreements. See the NOTICE file
  31450. * distributed with this work for additional information
  31451. * regarding copyright ownership. The ASF licenses this file
  31452. * to you under the Apache License, Version 2.0 (the
  31453. * "License"); you may not use this file except in compliance
  31454. * with the License. You may obtain a copy of the License at
  31455. *
  31456. * http://www.apache.org/licenses/LICENSE-2.0
  31457. *
  31458. * Unless required by applicable law or agreed to in writing,
  31459. * software distributed under the License is distributed on an
  31460. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31461. * KIND, either express or implied. See the License for the
  31462. * specific language governing permissions and limitations
  31463. * under the License.
  31464. */
  31465. /**
  31466. * Cartesian coordinate system
  31467. * @module echarts/coord/Cartesian
  31468. *
  31469. */
  31470. function dimAxisMapper(dim) {
  31471. return this._axes[dim];
  31472. }
  31473. /**
  31474. * @alias module:echarts/coord/Cartesian
  31475. * @constructor
  31476. */
  31477. var Cartesian = function (name) {
  31478. this._axes = {};
  31479. this._dimList = [];
  31480. /**
  31481. * @type {string}
  31482. */
  31483. this.name = name || '';
  31484. };
  31485. Cartesian.prototype = {
  31486. constructor: Cartesian,
  31487. type: 'cartesian',
  31488. /**
  31489. * Get axis
  31490. * @param {number|string} dim
  31491. * @return {module:echarts/coord/Cartesian~Axis}
  31492. */
  31493. getAxis: function (dim) {
  31494. return this._axes[dim];
  31495. },
  31496. /**
  31497. * Get axes list
  31498. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  31499. */
  31500. getAxes: function () {
  31501. return map(this._dimList, dimAxisMapper, this);
  31502. },
  31503. /**
  31504. * Get axes list by given scale type
  31505. */
  31506. getAxesByScale: function (scaleType) {
  31507. scaleType = scaleType.toLowerCase();
  31508. return filter(
  31509. this.getAxes(),
  31510. function (axis) {
  31511. return axis.scale.type === scaleType;
  31512. }
  31513. );
  31514. },
  31515. /**
  31516. * Add axis
  31517. * @param {module:echarts/coord/Cartesian.Axis}
  31518. */
  31519. addAxis: function (axis) {
  31520. var dim = axis.dim;
  31521. this._axes[dim] = axis;
  31522. this._dimList.push(dim);
  31523. },
  31524. /**
  31525. * Convert data to coord in nd space
  31526. * @param {Array.<number>|Object.<string, number>} val
  31527. * @return {Array.<number>|Object.<string, number>}
  31528. */
  31529. dataToCoord: function (val) {
  31530. return this._dataCoordConvert(val, 'dataToCoord');
  31531. },
  31532. /**
  31533. * Convert coord in nd space to data
  31534. * @param {Array.<number>|Object.<string, number>} val
  31535. * @return {Array.<number>|Object.<string, number>}
  31536. */
  31537. coordToData: function (val) {
  31538. return this._dataCoordConvert(val, 'coordToData');
  31539. },
  31540. _dataCoordConvert: function (input, method) {
  31541. var dimList = this._dimList;
  31542. var output = input instanceof Array ? [] : {};
  31543. for (var i = 0; i < dimList.length; i++) {
  31544. var dim = dimList[i];
  31545. var axis = this._axes[dim];
  31546. output[dim] = axis[method](input[dim]);
  31547. }
  31548. return output;
  31549. }
  31550. };
  31551. /*
  31552. * Licensed to the Apache Software Foundation (ASF) under one
  31553. * or more contributor license agreements. See the NOTICE file
  31554. * distributed with this work for additional information
  31555. * regarding copyright ownership. The ASF licenses this file
  31556. * to you under the Apache License, Version 2.0 (the
  31557. * "License"); you may not use this file except in compliance
  31558. * with the License. You may obtain a copy of the License at
  31559. *
  31560. * http://www.apache.org/licenses/LICENSE-2.0
  31561. *
  31562. * Unless required by applicable law or agreed to in writing,
  31563. * software distributed under the License is distributed on an
  31564. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31565. * KIND, either express or implied. See the License for the
  31566. * specific language governing permissions and limitations
  31567. * under the License.
  31568. */
  31569. function Cartesian2D(name) {
  31570. Cartesian.call(this, name);
  31571. }
  31572. Cartesian2D.prototype = {
  31573. constructor: Cartesian2D,
  31574. type: 'cartesian2d',
  31575. /**
  31576. * @type {Array.<string>}
  31577. * @readOnly
  31578. */
  31579. dimensions: ['x', 'y'],
  31580. /**
  31581. * Base axis will be used on stacking.
  31582. *
  31583. * @return {module:echarts/coord/cartesian/Axis2D}
  31584. */
  31585. getBaseAxis: function () {
  31586. return this.getAxesByScale('ordinal')[0]
  31587. || this.getAxesByScale('time')[0]
  31588. || this.getAxis('x');
  31589. },
  31590. /**
  31591. * If contain point
  31592. * @param {Array.<number>} point
  31593. * @return {boolean}
  31594. */
  31595. containPoint: function (point) {
  31596. var axisX = this.getAxis('x');
  31597. var axisY = this.getAxis('y');
  31598. return axisX.contain(axisX.toLocalCoord(point[0]))
  31599. && axisY.contain(axisY.toLocalCoord(point[1]));
  31600. },
  31601. /**
  31602. * If contain data
  31603. * @param {Array.<number>} data
  31604. * @return {boolean}
  31605. */
  31606. containData: function (data) {
  31607. return this.getAxis('x').containData(data[0])
  31608. && this.getAxis('y').containData(data[1]);
  31609. },
  31610. /**
  31611. * @param {Array.<number>} data
  31612. * @param {Array.<number>} out
  31613. * @return {Array.<number>}
  31614. */
  31615. dataToPoint: function (data, reserved, out) {
  31616. var xAxis = this.getAxis('x');
  31617. var yAxis = this.getAxis('y');
  31618. out = out || [];
  31619. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  31620. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  31621. return out;
  31622. },
  31623. /**
  31624. * @param {Array.<number>} data
  31625. * @param {Array.<number>} out
  31626. * @return {Array.<number>}
  31627. */
  31628. clampData: function (data, out) {
  31629. var xScale = this.getAxis('x').scale;
  31630. var yScale = this.getAxis('y').scale;
  31631. var xAxisExtent = xScale.getExtent();
  31632. var yAxisExtent = yScale.getExtent();
  31633. var x = xScale.parse(data[0]);
  31634. var y = yScale.parse(data[1]);
  31635. out = out || [];
  31636. out[0] = Math.min(
  31637. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  31638. Math.max(xAxisExtent[0], xAxisExtent[1])
  31639. );
  31640. out[1] = Math.min(
  31641. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  31642. Math.max(yAxisExtent[0], yAxisExtent[1])
  31643. );
  31644. return out;
  31645. },
  31646. /**
  31647. * @param {Array.<number>} point
  31648. * @param {Array.<number>} out
  31649. * @return {Array.<number>}
  31650. */
  31651. pointToData: function (point, out) {
  31652. var xAxis = this.getAxis('x');
  31653. var yAxis = this.getAxis('y');
  31654. out = out || [];
  31655. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  31656. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  31657. return out;
  31658. },
  31659. /**
  31660. * Get other axis
  31661. * @param {module:echarts/coord/cartesian/Axis2D} axis
  31662. */
  31663. getOtherAxis: function (axis) {
  31664. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  31665. }
  31666. };
  31667. inherits(Cartesian2D, Cartesian);
  31668. /*
  31669. * Licensed to the Apache Software Foundation (ASF) under one
  31670. * or more contributor license agreements. See the NOTICE file
  31671. * distributed with this work for additional information
  31672. * regarding copyright ownership. The ASF licenses this file
  31673. * to you under the Apache License, Version 2.0 (the
  31674. * "License"); you may not use this file except in compliance
  31675. * with the License. You may obtain a copy of the License at
  31676. *
  31677. * http://www.apache.org/licenses/LICENSE-2.0
  31678. *
  31679. * Unless required by applicable law or agreed to in writing,
  31680. * software distributed under the License is distributed on an
  31681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31682. * KIND, either express or implied. See the License for the
  31683. * specific language governing permissions and limitations
  31684. * under the License.
  31685. */
  31686. var inner$6 = makeInner();
  31687. /**
  31688. * @param {module:echats/coord/Axis} axis
  31689. * @return {Object} {
  31690. * labels: [{
  31691. * formattedLabel: string,
  31692. * rawLabel: string,
  31693. * tickValue: number
  31694. * }, ...],
  31695. * labelCategoryInterval: number
  31696. * }
  31697. */
  31698. function createAxisLabels(axis) {
  31699. // Only ordinal scale support tick interval
  31700. return axis.type === 'category'
  31701. ? makeCategoryLabels(axis)
  31702. : makeRealNumberLabels(axis);
  31703. }
  31704. /**
  31705. * @param {module:echats/coord/Axis} axis
  31706. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31707. * @return {Object} {
  31708. * ticks: Array.<number>
  31709. * tickCategoryInterval: number
  31710. * }
  31711. */
  31712. function createAxisTicks(axis, tickModel) {
  31713. // Only ordinal scale support tick interval
  31714. return axis.type === 'category'
  31715. ? makeCategoryTicks(axis, tickModel)
  31716. : {ticks: axis.scale.getTicks()};
  31717. }
  31718. function makeCategoryLabels(axis) {
  31719. var labelModel = axis.getLabelModel();
  31720. var result = makeCategoryLabelsActually(axis, labelModel);
  31721. return (!labelModel.get('show') || axis.scale.isBlank())
  31722. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  31723. : result;
  31724. }
  31725. function makeCategoryLabelsActually(axis, labelModel) {
  31726. var labelsCache = getListCache(axis, 'labels');
  31727. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31728. var result = listCacheGet(labelsCache, optionLabelInterval);
  31729. if (result) {
  31730. return result;
  31731. }
  31732. var labels;
  31733. var numericLabelInterval;
  31734. if (isFunction$1(optionLabelInterval)) {
  31735. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31736. }
  31737. else {
  31738. numericLabelInterval = optionLabelInterval === 'auto'
  31739. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31740. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31741. }
  31742. // Cache to avoid calling interval function repeatly.
  31743. return listCacheSet(labelsCache, optionLabelInterval, {
  31744. labels: labels, labelCategoryInterval: numericLabelInterval
  31745. });
  31746. }
  31747. function makeCategoryTicks(axis, tickModel) {
  31748. var ticksCache = getListCache(axis, 'ticks');
  31749. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31750. var result = listCacheGet(ticksCache, optionTickInterval);
  31751. if (result) {
  31752. return result;
  31753. }
  31754. var ticks;
  31755. var tickCategoryInterval;
  31756. // Optimize for the case that large category data and no label displayed,
  31757. // we should not return all ticks.
  31758. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31759. ticks = [];
  31760. }
  31761. if (isFunction$1(optionTickInterval)) {
  31762. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31763. }
  31764. // Always use label interval by default despite label show. Consider this
  31765. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31766. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31767. else if (optionTickInterval === 'auto') {
  31768. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31769. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31770. ticks = map(labelsResult.labels, function (labelItem) {
  31771. return labelItem.tickValue;
  31772. });
  31773. }
  31774. else {
  31775. tickCategoryInterval = optionTickInterval;
  31776. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31777. }
  31778. // Cache to avoid calling interval function repeatly.
  31779. return listCacheSet(ticksCache, optionTickInterval, {
  31780. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  31781. });
  31782. }
  31783. function makeRealNumberLabels(axis) {
  31784. var ticks = axis.scale.getTicks();
  31785. var labelFormatter = makeLabelFormatter(axis);
  31786. return {
  31787. labels: map(ticks, function (tickValue, idx) {
  31788. return {
  31789. formattedLabel: labelFormatter(tickValue, idx),
  31790. rawLabel: axis.scale.getLabel(tickValue),
  31791. tickValue: tickValue
  31792. };
  31793. })
  31794. };
  31795. }
  31796. // Large category data calculation is performence sensitive, and ticks and label
  31797. // probably be fetched by multiple times. So we cache the result.
  31798. // axis is created each time during a ec process, so we do not need to clear cache.
  31799. function getListCache(axis, prop) {
  31800. // Because key can be funciton, and cache size always be small, we use array cache.
  31801. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  31802. }
  31803. function listCacheGet(cache, key) {
  31804. for (var i = 0; i < cache.length; i++) {
  31805. if (cache[i].key === key) {
  31806. return cache[i].value;
  31807. }
  31808. }
  31809. }
  31810. function listCacheSet(cache, key, value) {
  31811. cache.push({key: key, value: value});
  31812. return value;
  31813. }
  31814. function makeAutoCategoryInterval(axis) {
  31815. var result = inner$6(axis).autoInterval;
  31816. return result != null
  31817. ? result
  31818. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  31819. }
  31820. /**
  31821. * Calculate interval for category axis ticks and labels.
  31822. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31823. * should be implemented in axis.
  31824. */
  31825. function calculateCategoryInterval(axis) {
  31826. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31827. var labelFormatter = makeLabelFormatter(axis);
  31828. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31829. var ordinalScale = axis.scale;
  31830. var ordinalExtent = ordinalScale.getExtent();
  31831. // Providing this method is for optimization:
  31832. // avoid generating a long array by `getTicks`
  31833. // in large category data case.
  31834. var tickCount = ordinalScale.count();
  31835. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31836. return 0;
  31837. }
  31838. var step = 1;
  31839. // Simple optimization. Empirical value: tick count should less than 40.
  31840. if (tickCount > 40) {
  31841. step = Math.max(1, Math.floor(tickCount / 40));
  31842. }
  31843. var tickValue = ordinalExtent[0];
  31844. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31845. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31846. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31847. var maxW = 0;
  31848. var maxH = 0;
  31849. // Caution: Performance sensitive for large category data.
  31850. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31851. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31852. var width = 0;
  31853. var height = 0;
  31854. // Not precise, do not consider align and vertical align
  31855. // and each distance from axis line yet.
  31856. var rect = getBoundingRect(
  31857. labelFormatter(tickValue), params.font, 'center', 'top'
  31858. );
  31859. // Magic number
  31860. width = rect.width * 1.3;
  31861. height = rect.height * 1.3;
  31862. // Min size, void long loop.
  31863. maxW = Math.max(maxW, width, 7);
  31864. maxH = Math.max(maxH, height, 7);
  31865. }
  31866. var dw = maxW / unitW;
  31867. var dh = maxH / unitH;
  31868. // 0/0 is NaN, 1/0 is Infinity.
  31869. isNaN(dw) && (dw = Infinity);
  31870. isNaN(dh) && (dh = Infinity);
  31871. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31872. var cache = inner$6(axis.model);
  31873. var lastAutoInterval = cache.lastAutoInterval;
  31874. var lastTickCount = cache.lastTickCount;
  31875. // Use cache to keep interval stable while moving zoom window,
  31876. // otherwise the calculated interval might jitter when the zoom
  31877. // window size is close to the interval-changing size.
  31878. if (lastAutoInterval != null
  31879. && lastTickCount != null
  31880. && Math.abs(lastAutoInterval - interval) <= 1
  31881. && Math.abs(lastTickCount - tickCount) <= 1
  31882. // Always choose the bigger one, otherwise the critical
  31883. // point is not the same when zooming in or zooming out.
  31884. && lastAutoInterval > interval
  31885. ) {
  31886. interval = lastAutoInterval;
  31887. }
  31888. // Only update cache if cache not used, otherwise the
  31889. // changing of interval is too insensitive.
  31890. else {
  31891. cache.lastTickCount = tickCount;
  31892. cache.lastAutoInterval = interval;
  31893. }
  31894. return interval;
  31895. }
  31896. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31897. var labelModel = axis.getLabelModel();
  31898. return {
  31899. axisRotate: axis.getRotate
  31900. ? axis.getRotate()
  31901. : (axis.isHorizontal && !axis.isHorizontal())
  31902. ? 90
  31903. : 0,
  31904. labelRotate: labelModel.get('rotate') || 0,
  31905. font: labelModel.getFont()
  31906. };
  31907. }
  31908. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  31909. var labelFormatter = makeLabelFormatter(axis);
  31910. var ordinalScale = axis.scale;
  31911. var ordinalExtent = ordinalScale.getExtent();
  31912. var labelModel = axis.getLabelModel();
  31913. var result = [];
  31914. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  31915. var step = Math.max((categoryInterval || 0) + 1, 1);
  31916. var startTick = ordinalExtent[0];
  31917. var tickCount = ordinalScale.count();
  31918. // Calculate start tick based on zero if possible to keep label consistent
  31919. // while zooming and moving while interval > 0. Otherwise the selection
  31920. // of displayable ticks and symbols probably keep changing.
  31921. // 3 is empirical value.
  31922. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  31923. startTick = Math.round(Math.ceil(startTick / step) * step);
  31924. }
  31925. // (1) Only add min max label here but leave overlap checking
  31926. // to render stage, which also ensure the returned list
  31927. // suitable for splitLine and splitArea rendering.
  31928. // (2) Scales except category always contain min max label so
  31929. // do not need to perform this process.
  31930. var showAllLabel = shouldShowAllLabels(axis);
  31931. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  31932. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  31933. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  31934. addItem(ordinalExtent[0]);
  31935. }
  31936. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  31937. var tickValue = startTick;
  31938. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31939. addItem(tickValue);
  31940. }
  31941. if (includeMaxLabel && tickValue !== ordinalExtent[1]) {
  31942. addItem(ordinalExtent[1]);
  31943. }
  31944. function addItem(tVal) {
  31945. result.push(onlyTick
  31946. ? tVal
  31947. : {
  31948. formattedLabel: labelFormatter(tVal),
  31949. rawLabel: ordinalScale.getLabel(tVal),
  31950. tickValue: tVal
  31951. }
  31952. );
  31953. }
  31954. return result;
  31955. }
  31956. // When interval is function, the result `false` means ignore the tick.
  31957. // It is time consuming for large category data.
  31958. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  31959. var ordinalScale = axis.scale;
  31960. var labelFormatter = makeLabelFormatter(axis);
  31961. var result = [];
  31962. each$1(ordinalScale.getTicks(), function (tickValue) {
  31963. var rawLabel = ordinalScale.getLabel(tickValue);
  31964. if (categoryInterval(tickValue, rawLabel)) {
  31965. result.push(onlyTick
  31966. ? tickValue
  31967. : {
  31968. formattedLabel: labelFormatter(tickValue),
  31969. rawLabel: rawLabel,
  31970. tickValue: tickValue
  31971. }
  31972. );
  31973. }
  31974. });
  31975. return result;
  31976. }
  31977. /*
  31978. * Licensed to the Apache Software Foundation (ASF) under one
  31979. * or more contributor license agreements. See the NOTICE file
  31980. * distributed with this work for additional information
  31981. * regarding copyright ownership. The ASF licenses this file
  31982. * to you under the Apache License, Version 2.0 (the
  31983. * "License"); you may not use this file except in compliance
  31984. * with the License. You may obtain a copy of the License at
  31985. *
  31986. * http://www.apache.org/licenses/LICENSE-2.0
  31987. *
  31988. * Unless required by applicable law or agreed to in writing,
  31989. * software distributed under the License is distributed on an
  31990. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31991. * KIND, either express or implied. See the License for the
  31992. * specific language governing permissions and limitations
  31993. * under the License.
  31994. */
  31995. var NORMALIZED_EXTENT = [0, 1];
  31996. /**
  31997. * Base class of Axis.
  31998. * @constructor
  31999. */
  32000. var Axis = function (dim, scale, extent) {
  32001. /**
  32002. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  32003. * @type {string}
  32004. */
  32005. this.dim = dim;
  32006. /**
  32007. * Axis scale
  32008. * @type {module:echarts/coord/scale/*}
  32009. */
  32010. this.scale = scale;
  32011. /**
  32012. * @type {Array.<number>}
  32013. * @private
  32014. */
  32015. this._extent = extent || [0, 0];
  32016. /**
  32017. * @type {boolean}
  32018. */
  32019. this.inverse = false;
  32020. /**
  32021. * Usually true when axis has a ordinal scale
  32022. * @type {boolean}
  32023. */
  32024. this.onBand = false;
  32025. };
  32026. Axis.prototype = {
  32027. constructor: Axis,
  32028. /**
  32029. * If axis extent contain given coord
  32030. * @param {number} coord
  32031. * @return {boolean}
  32032. */
  32033. contain: function (coord) {
  32034. var extent = this._extent;
  32035. var min = Math.min(extent[0], extent[1]);
  32036. var max = Math.max(extent[0], extent[1]);
  32037. return coord >= min && coord <= max;
  32038. },
  32039. /**
  32040. * If axis extent contain given data
  32041. * @param {number} data
  32042. * @return {boolean}
  32043. */
  32044. containData: function (data) {
  32045. return this.contain(this.dataToCoord(data));
  32046. },
  32047. /**
  32048. * Get coord extent.
  32049. * @return {Array.<number>}
  32050. */
  32051. getExtent: function () {
  32052. return this._extent.slice();
  32053. },
  32054. /**
  32055. * Get precision used for formatting
  32056. * @param {Array.<number>} [dataExtent]
  32057. * @return {number}
  32058. */
  32059. getPixelPrecision: function (dataExtent) {
  32060. return getPixelPrecision(
  32061. dataExtent || this.scale.getExtent(),
  32062. this._extent
  32063. );
  32064. },
  32065. /**
  32066. * Set coord extent
  32067. * @param {number} start
  32068. * @param {number} end
  32069. */
  32070. setExtent: function (start, end) {
  32071. var extent = this._extent;
  32072. extent[0] = start;
  32073. extent[1] = end;
  32074. },
  32075. /**
  32076. * Convert data to coord. Data is the rank if it has an ordinal scale
  32077. * @param {number} data
  32078. * @param {boolean} clamp
  32079. * @return {number}
  32080. */
  32081. dataToCoord: function (data, clamp) {
  32082. var extent = this._extent;
  32083. var scale = this.scale;
  32084. data = scale.normalize(data);
  32085. if (this.onBand && scale.type === 'ordinal') {
  32086. extent = extent.slice();
  32087. fixExtentWithBands(extent, scale.count());
  32088. }
  32089. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32090. },
  32091. /**
  32092. * Convert coord to data. Data is the rank if it has an ordinal scale
  32093. * @param {number} coord
  32094. * @param {boolean} clamp
  32095. * @return {number}
  32096. */
  32097. coordToData: function (coord, clamp) {
  32098. var extent = this._extent;
  32099. var scale = this.scale;
  32100. if (this.onBand && scale.type === 'ordinal') {
  32101. extent = extent.slice();
  32102. fixExtentWithBands(extent, scale.count());
  32103. }
  32104. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32105. return this.scale.scale(t);
  32106. },
  32107. /**
  32108. * Convert pixel point to data in axis
  32109. * @param {Array.<number>} point
  32110. * @param {boolean} clamp
  32111. * @return {number} data
  32112. */
  32113. pointToData: function (point, clamp) {
  32114. // Should be implemented in derived class if necessary.
  32115. },
  32116. /**
  32117. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32118. * `axis.getTicksCoords` considers `onBand`, which is used by
  32119. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32120. * @param {Object} [opt]
  32121. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  32122. * @param {boolean} [opt.clamp] If `true`, the first and the last
  32123. * tick must be at the axis end points. Otherwise, clip ticks
  32124. * that outside the axis extent.
  32125. * @return {Array.<Object>} [{
  32126. * coord: ...,
  32127. * tickValue: ...
  32128. * }, ...]
  32129. */
  32130. getTicksCoords: function (opt) {
  32131. opt = opt || {};
  32132. var tickModel = opt.tickModel || this.getTickModel();
  32133. var result = createAxisTicks(this, tickModel);
  32134. var ticks = result.ticks;
  32135. var ticksCoords = map(ticks, function (tickValue) {
  32136. return {
  32137. coord: this.dataToCoord(tickValue),
  32138. tickValue: tickValue
  32139. };
  32140. }, this);
  32141. var alignWithLabel = tickModel.get('alignWithLabel');
  32142. fixOnBandTicksCoords(
  32143. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  32144. );
  32145. return ticksCoords;
  32146. },
  32147. /**
  32148. * @return {Array.<Object>} [{
  32149. * formattedLabel: string,
  32150. * rawLabel: axis.scale.getLabel(tickValue)
  32151. * tickValue: number
  32152. * }, ...]
  32153. */
  32154. getViewLabels: function () {
  32155. return createAxisLabels(this).labels;
  32156. },
  32157. /**
  32158. * @return {module:echarts/coord/model/Model}
  32159. */
  32160. getLabelModel: function () {
  32161. return this.model.getModel('axisLabel');
  32162. },
  32163. /**
  32164. * Notice here we only get the default tick model. For splitLine
  32165. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32166. * manually when calling `getTicksCoords`.
  32167. * In GL, this method may be overrided to:
  32168. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32169. * @return {module:echarts/coord/model/Model}
  32170. */
  32171. getTickModel: function () {
  32172. return this.model.getModel('axisTick');
  32173. },
  32174. /**
  32175. * Get width of band
  32176. * @return {number}
  32177. */
  32178. getBandWidth: function () {
  32179. var axisExtent = this._extent;
  32180. var dataExtent = this.scale.getExtent();
  32181. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  32182. // Fix #2728, avoid NaN when only one data.
  32183. len === 0 && (len = 1);
  32184. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32185. return Math.abs(size) / len;
  32186. },
  32187. /**
  32188. * @abstract
  32189. * @return {boolean} Is horizontal
  32190. */
  32191. isHorizontal: null,
  32192. /**
  32193. * @abstract
  32194. * @return {number} Get axis rotate, by degree.
  32195. */
  32196. getRotate: null,
  32197. /**
  32198. * Only be called in category axis.
  32199. * Can be overrided, consider other axes like in 3D.
  32200. * @return {number} Auto interval for cateogry axis tick and label
  32201. */
  32202. calculateCategoryInterval: function () {
  32203. return calculateCategoryInterval(this);
  32204. }
  32205. };
  32206. function fixExtentWithBands(extent, nTick) {
  32207. var size = extent[1] - extent[0];
  32208. var len = nTick;
  32209. var margin = size / len / 2;
  32210. extent[0] += margin;
  32211. extent[1] -= margin;
  32212. }
  32213. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32214. // |---1---|---2---|---3---|---4---|.
  32215. // So the displayed ticks and splitLine/splitArea should between
  32216. // each data item, otherwise cause misleading (e.g., split tow bars
  32217. // of a single data item when there are two bar series).
  32218. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32219. // splitLine/spliteArea should layout appropriately corresponding
  32220. // to displayed labels. (So we should not use `getBandWidth` in this
  32221. // case).
  32222. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  32223. var ticksLen = ticksCoords.length;
  32224. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32225. return;
  32226. }
  32227. var axisExtent = axis.getExtent();
  32228. var last;
  32229. if (ticksLen === 1) {
  32230. ticksCoords[0].coord = axisExtent[0];
  32231. last = ticksCoords[1] = {coord: axisExtent[0]};
  32232. }
  32233. else {
  32234. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  32235. each$1(ticksCoords, function (ticksItem) {
  32236. ticksItem.coord -= shift / 2;
  32237. var tickCategoryInterval = tickCategoryInterval || 0;
  32238. // Avoid split a single data item when odd interval.
  32239. if (tickCategoryInterval % 2 > 0) {
  32240. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  32241. }
  32242. });
  32243. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  32244. ticksCoords.push(last);
  32245. }
  32246. var inverse = axisExtent[0] > axisExtent[1];
  32247. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32248. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  32249. }
  32250. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32251. ticksCoords.unshift({coord: axisExtent[0]});
  32252. }
  32253. if (littleThan(axisExtent[1], last.coord)) {
  32254. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  32255. }
  32256. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32257. ticksCoords.push({coord: axisExtent[1]});
  32258. }
  32259. function littleThan(a, b) {
  32260. return inverse ? a > b : a < b;
  32261. }
  32262. }
  32263. /*
  32264. * Licensed to the Apache Software Foundation (ASF) under one
  32265. * or more contributor license agreements. See the NOTICE file
  32266. * distributed with this work for additional information
  32267. * regarding copyright ownership. The ASF licenses this file
  32268. * to you under the Apache License, Version 2.0 (the
  32269. * "License"); you may not use this file except in compliance
  32270. * with the License. You may obtain a copy of the License at
  32271. *
  32272. * http://www.apache.org/licenses/LICENSE-2.0
  32273. *
  32274. * Unless required by applicable law or agreed to in writing,
  32275. * software distributed under the License is distributed on an
  32276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32277. * KIND, either express or implied. See the License for the
  32278. * specific language governing permissions and limitations
  32279. * under the License.
  32280. */
  32281. /**
  32282. * Extend axis 2d
  32283. * @constructor module:echarts/coord/cartesian/Axis2D
  32284. * @extends {module:echarts/coord/cartesian/Axis}
  32285. * @param {string} dim
  32286. * @param {*} scale
  32287. * @param {Array.<number>} coordExtent
  32288. * @param {string} axisType
  32289. * @param {string} position
  32290. */
  32291. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  32292. Axis.call(this, dim, scale, coordExtent);
  32293. /**
  32294. * Axis type
  32295. * - 'category'
  32296. * - 'value'
  32297. * - 'time'
  32298. * - 'log'
  32299. * @type {string}
  32300. */
  32301. this.type = axisType || 'value';
  32302. /**
  32303. * Axis position
  32304. * - 'top'
  32305. * - 'bottom'
  32306. * - 'left'
  32307. * - 'right'
  32308. */
  32309. this.position = position || 'bottom';
  32310. };
  32311. Axis2D.prototype = {
  32312. constructor: Axis2D,
  32313. /**
  32314. * Index of axis, can be used as key
  32315. */
  32316. index: 0,
  32317. /**
  32318. * Implemented in <module:echarts/coord/cartesian/Grid>.
  32319. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  32320. * If not on zero of other axis, return null/undefined.
  32321. * If no axes, return an empty array.
  32322. */
  32323. getAxesOnZeroOf: null,
  32324. /**
  32325. * Axis model
  32326. * @param {module:echarts/coord/cartesian/AxisModel}
  32327. */
  32328. model: null,
  32329. isHorizontal: function () {
  32330. var position = this.position;
  32331. return position === 'top' || position === 'bottom';
  32332. },
  32333. /**
  32334. * Each item cooresponds to this.getExtent(), which
  32335. * means globalExtent[0] may greater than globalExtent[1],
  32336. * unless `asc` is input.
  32337. *
  32338. * @param {boolean} [asc]
  32339. * @return {Array.<number>}
  32340. */
  32341. getGlobalExtent: function (asc) {
  32342. var ret = this.getExtent();
  32343. ret[0] = this.toGlobalCoord(ret[0]);
  32344. ret[1] = this.toGlobalCoord(ret[1]);
  32345. asc && ret[0] > ret[1] && ret.reverse();
  32346. return ret;
  32347. },
  32348. getOtherAxis: function () {
  32349. this.grid.getOtherAxis();
  32350. },
  32351. /**
  32352. * @override
  32353. */
  32354. pointToData: function (point, clamp) {
  32355. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  32356. },
  32357. /**
  32358. * Transform global coord to local coord,
  32359. * i.e. var localCoord = axis.toLocalCoord(80);
  32360. * designate by module:echarts/coord/cartesian/Grid.
  32361. * @type {Function}
  32362. */
  32363. toLocalCoord: null,
  32364. /**
  32365. * Transform global coord to local coord,
  32366. * i.e. var globalCoord = axis.toLocalCoord(40);
  32367. * designate by module:echarts/coord/cartesian/Grid.
  32368. * @type {Function}
  32369. */
  32370. toGlobalCoord: null
  32371. };
  32372. inherits(Axis2D, Axis);
  32373. /*
  32374. * Licensed to the Apache Software Foundation (ASF) under one
  32375. * or more contributor license agreements. See the NOTICE file
  32376. * distributed with this work for additional information
  32377. * regarding copyright ownership. The ASF licenses this file
  32378. * to you under the Apache License, Version 2.0 (the
  32379. * "License"); you may not use this file except in compliance
  32380. * with the License. You may obtain a copy of the License at
  32381. *
  32382. * http://www.apache.org/licenses/LICENSE-2.0
  32383. *
  32384. * Unless required by applicable law or agreed to in writing,
  32385. * software distributed under the License is distributed on an
  32386. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32387. * KIND, either express or implied. See the License for the
  32388. * specific language governing permissions and limitations
  32389. * under the License.
  32390. */
  32391. var defaultOption = {
  32392. show: true,
  32393. zlevel: 0,
  32394. z: 0,
  32395. // Inverse the axis.
  32396. inverse: false,
  32397. // Axis name displayed.
  32398. name: '',
  32399. // 'start' | 'middle' | 'end'
  32400. nameLocation: 'end',
  32401. // By degree. By defualt auto rotate by nameLocation.
  32402. nameRotate: null,
  32403. nameTruncate: {
  32404. maxWidth: null,
  32405. ellipsis: '...',
  32406. placeholder: '.'
  32407. },
  32408. // Use global text style by default.
  32409. nameTextStyle: {},
  32410. // The gap between axisName and axisLine.
  32411. nameGap: 15,
  32412. // Default `false` to support tooltip.
  32413. silent: false,
  32414. // Default `false` to avoid legacy user event listener fail.
  32415. triggerEvent: false,
  32416. tooltip: {
  32417. show: false
  32418. },
  32419. axisPointer: {},
  32420. axisLine: {
  32421. show: true,
  32422. onZero: true,
  32423. onZeroAxisIndex: null,
  32424. lineStyle: {
  32425. color: '#333',
  32426. width: 1,
  32427. type: 'solid'
  32428. },
  32429. // The arrow at both ends the the axis.
  32430. symbol: ['none', 'none'],
  32431. symbolSize: [10, 15]
  32432. },
  32433. axisTick: {
  32434. show: true,
  32435. // Whether axisTick is inside the grid or outside the grid.
  32436. inside: false,
  32437. // The length of axisTick.
  32438. length: 5,
  32439. lineStyle: {
  32440. width: 1
  32441. }
  32442. },
  32443. axisLabel: {
  32444. show: true,
  32445. // Whether axisLabel is inside the grid or outside the grid.
  32446. inside: false,
  32447. rotate: 0,
  32448. // true | false | null/undefined (auto)
  32449. showMinLabel: null,
  32450. // true | false | null/undefined (auto)
  32451. showMaxLabel: null,
  32452. margin: 8,
  32453. // formatter: null,
  32454. fontSize: 12
  32455. },
  32456. splitLine: {
  32457. show: true,
  32458. lineStyle: {
  32459. color: ['#ccc'],
  32460. width: 1,
  32461. type: 'solid'
  32462. }
  32463. },
  32464. splitArea: {
  32465. show: false,
  32466. areaStyle: {
  32467. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  32468. }
  32469. }
  32470. };
  32471. var axisDefault = {};
  32472. axisDefault.categoryAxis = merge({
  32473. // The gap at both ends of the axis. For categoryAxis, boolean.
  32474. boundaryGap: true,
  32475. // Set false to faster category collection.
  32476. // Only usefull in the case like: category is
  32477. // ['2012-01-01', '2012-01-02', ...], where the input
  32478. // data has been ensured not duplicate and is large data.
  32479. // null means "auto":
  32480. // if axis.data provided, do not deduplication,
  32481. // else do deduplication.
  32482. deduplication: null,
  32483. // splitArea: {
  32484. // show: false
  32485. // },
  32486. splitLine: {
  32487. show: false
  32488. },
  32489. axisTick: {
  32490. // If tick is align with label when boundaryGap is true
  32491. alignWithLabel: false,
  32492. interval: 'auto'
  32493. },
  32494. axisLabel: {
  32495. interval: 'auto'
  32496. }
  32497. }, defaultOption);
  32498. axisDefault.valueAxis = merge({
  32499. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  32500. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  32501. boundaryGap: [0, 0],
  32502. // TODO
  32503. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  32504. // Min value of the axis. can be:
  32505. // + a number
  32506. // + 'dataMin': use the min value in data.
  32507. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  32508. // min: null,
  32509. // Max value of the axis. can be:
  32510. // + a number
  32511. // + 'dataMax': use the max value in data.
  32512. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  32513. // max: null,
  32514. // Readonly prop, specifies start value of the range when using data zoom.
  32515. // rangeStart: null
  32516. // Readonly prop, specifies end value of the range when using data zoom.
  32517. // rangeEnd: null
  32518. // Optional value can be:
  32519. // + `false`: always include value 0.
  32520. // + `true`: the extent do not consider value 0.
  32521. // scale: false,
  32522. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  32523. splitNumber: 5
  32524. // Interval specifies the span of the ticks is mandatorily.
  32525. // interval: null
  32526. // Specify min interval when auto calculate tick interval.
  32527. // minInterval: null
  32528. // Specify max interval when auto calculate tick interval.
  32529. // maxInterval: null
  32530. }, defaultOption);
  32531. axisDefault.timeAxis = defaults({
  32532. scale: true,
  32533. min: 'dataMin',
  32534. max: 'dataMax'
  32535. }, axisDefault.valueAxis);
  32536. axisDefault.logAxis = defaults({
  32537. scale: true,
  32538. logBase: 10
  32539. }, axisDefault.valueAxis);
  32540. /*
  32541. * Licensed to the Apache Software Foundation (ASF) under one
  32542. * or more contributor license agreements. See the NOTICE file
  32543. * distributed with this work for additional information
  32544. * regarding copyright ownership. The ASF licenses this file
  32545. * to you under the Apache License, Version 2.0 (the
  32546. * "License"); you may not use this file except in compliance
  32547. * with the License. You may obtain a copy of the License at
  32548. *
  32549. * http://www.apache.org/licenses/LICENSE-2.0
  32550. *
  32551. * Unless required by applicable law or agreed to in writing,
  32552. * software distributed under the License is distributed on an
  32553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32554. * KIND, either express or implied. See the License for the
  32555. * specific language governing permissions and limitations
  32556. * under the License.
  32557. */
  32558. // FIXME axisType is fixed ?
  32559. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  32560. /**
  32561. * Generate sub axis model class
  32562. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  32563. * @param {module:echarts/model/Component} BaseAxisModelClass
  32564. * @param {Function} axisTypeDefaulter
  32565. * @param {Object} [extraDefaultOption]
  32566. */
  32567. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  32568. each$1(AXIS_TYPES, function (axisType) {
  32569. BaseAxisModelClass.extend({
  32570. /**
  32571. * @readOnly
  32572. */
  32573. type: axisName + 'Axis.' + axisType,
  32574. mergeDefaultAndTheme: function (option, ecModel) {
  32575. var layoutMode = this.layoutMode;
  32576. var inputPositionParams = layoutMode
  32577. ? getLayoutParams(option) : {};
  32578. var themeModel = ecModel.getTheme();
  32579. merge(option, themeModel.get(axisType + 'Axis'));
  32580. merge(option, this.getDefaultOption());
  32581. option.type = axisTypeDefaulter(axisName, option);
  32582. if (layoutMode) {
  32583. mergeLayoutParam(option, inputPositionParams, layoutMode);
  32584. }
  32585. },
  32586. /**
  32587. * @override
  32588. */
  32589. optionUpdated: function () {
  32590. var thisOption = this.option;
  32591. if (thisOption.type === 'category') {
  32592. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  32593. }
  32594. },
  32595. /**
  32596. * Should not be called before all of 'getInitailData' finished.
  32597. * Because categories are collected during initializing data.
  32598. */
  32599. getCategories: function (rawData) {
  32600. var option = this.option;
  32601. // FIXME
  32602. // warning if called before all of 'getInitailData' finished.
  32603. if (option.type === 'category') {
  32604. if (rawData) {
  32605. return option.data;
  32606. }
  32607. return this.__ordinalMeta.categories;
  32608. }
  32609. },
  32610. getOrdinalMeta: function () {
  32611. return this.__ordinalMeta;
  32612. },
  32613. defaultOption: mergeAll(
  32614. [
  32615. {},
  32616. axisDefault[axisType + 'Axis'],
  32617. extraDefaultOption
  32618. ],
  32619. true
  32620. )
  32621. });
  32622. });
  32623. ComponentModel.registerSubTypeDefaulter(
  32624. axisName + 'Axis',
  32625. curry(axisTypeDefaulter, axisName)
  32626. );
  32627. };
  32628. /*
  32629. * Licensed to the Apache Software Foundation (ASF) under one
  32630. * or more contributor license agreements. See the NOTICE file
  32631. * distributed with this work for additional information
  32632. * regarding copyright ownership. The ASF licenses this file
  32633. * to you under the Apache License, Version 2.0 (the
  32634. * "License"); you may not use this file except in compliance
  32635. * with the License. You may obtain a copy of the License at
  32636. *
  32637. * http://www.apache.org/licenses/LICENSE-2.0
  32638. *
  32639. * Unless required by applicable law or agreed to in writing,
  32640. * software distributed under the License is distributed on an
  32641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32642. * KIND, either express or implied. See the License for the
  32643. * specific language governing permissions and limitations
  32644. * under the License.
  32645. */
  32646. // import * as axisHelper from './axisHelper';
  32647. var axisModelCommonMixin = {
  32648. /**
  32649. * @param {boolean} origin
  32650. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  32651. */
  32652. getMin: function (origin) {
  32653. var option = this.option;
  32654. var min = (!origin && option.rangeStart != null)
  32655. ? option.rangeStart : option.min;
  32656. if (this.axis
  32657. && min != null
  32658. && min !== 'dataMin'
  32659. && typeof min !== 'function'
  32660. && !eqNaN(min)
  32661. ) {
  32662. min = this.axis.scale.parse(min);
  32663. }
  32664. return min;
  32665. },
  32666. /**
  32667. * @param {boolean} origin
  32668. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  32669. */
  32670. getMax: function (origin) {
  32671. var option = this.option;
  32672. var max = (!origin && option.rangeEnd != null)
  32673. ? option.rangeEnd : option.max;
  32674. if (this.axis
  32675. && max != null
  32676. && max !== 'dataMax'
  32677. && typeof max !== 'function'
  32678. && !eqNaN(max)
  32679. ) {
  32680. max = this.axis.scale.parse(max);
  32681. }
  32682. return max;
  32683. },
  32684. /**
  32685. * @return {boolean}
  32686. */
  32687. getNeedCrossZero: function () {
  32688. var option = this.option;
  32689. return (option.rangeStart != null || option.rangeEnd != null)
  32690. ? false : !option.scale;
  32691. },
  32692. /**
  32693. * Should be implemented by each axis model if necessary.
  32694. * @return {module:echarts/model/Component} coordinate system model
  32695. */
  32696. getCoordSysModel: noop,
  32697. /**
  32698. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  32699. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  32700. */
  32701. setRange: function (rangeStart, rangeEnd) {
  32702. this.option.rangeStart = rangeStart;
  32703. this.option.rangeEnd = rangeEnd;
  32704. },
  32705. /**
  32706. * Reset range
  32707. */
  32708. resetRange: function () {
  32709. // rangeStart and rangeEnd is readonly.
  32710. this.option.rangeStart = this.option.rangeEnd = null;
  32711. }
  32712. };
  32713. /*
  32714. * Licensed to the Apache Software Foundation (ASF) under one
  32715. * or more contributor license agreements. See the NOTICE file
  32716. * distributed with this work for additional information
  32717. * regarding copyright ownership. The ASF licenses this file
  32718. * to you under the Apache License, Version 2.0 (the
  32719. * "License"); you may not use this file except in compliance
  32720. * with the License. You may obtain a copy of the License at
  32721. *
  32722. * http://www.apache.org/licenses/LICENSE-2.0
  32723. *
  32724. * Unless required by applicable law or agreed to in writing,
  32725. * software distributed under the License is distributed on an
  32726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32727. * KIND, either express or implied. See the License for the
  32728. * specific language governing permissions and limitations
  32729. * under the License.
  32730. */
  32731. var AxisModel = ComponentModel.extend({
  32732. type: 'cartesian2dAxis',
  32733. /**
  32734. * @type {module:echarts/coord/cartesian/Axis2D}
  32735. */
  32736. axis: null,
  32737. /**
  32738. * @override
  32739. */
  32740. init: function () {
  32741. AxisModel.superApply(this, 'init', arguments);
  32742. this.resetRange();
  32743. },
  32744. /**
  32745. * @override
  32746. */
  32747. mergeOption: function () {
  32748. AxisModel.superApply(this, 'mergeOption', arguments);
  32749. this.resetRange();
  32750. },
  32751. /**
  32752. * @override
  32753. */
  32754. restoreData: function () {
  32755. AxisModel.superApply(this, 'restoreData', arguments);
  32756. this.resetRange();
  32757. },
  32758. /**
  32759. * @override
  32760. * @return {module:echarts/model/Component}
  32761. */
  32762. getCoordSysModel: function () {
  32763. return this.ecModel.queryComponents({
  32764. mainType: 'grid',
  32765. index: this.option.gridIndex,
  32766. id: this.option.gridId
  32767. })[0];
  32768. }
  32769. });
  32770. function getAxisType(axisDim, option) {
  32771. // Default axis with data is category axis
  32772. return option.type || (option.data ? 'category' : 'value');
  32773. }
  32774. merge(AxisModel.prototype, axisModelCommonMixin);
  32775. var extraOption = {
  32776. // gridIndex: 0,
  32777. // gridId: '',
  32778. // Offset is for multiple axis on the same position
  32779. offset: 0
  32780. };
  32781. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  32782. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  32783. /*
  32784. * Licensed to the Apache Software Foundation (ASF) under one
  32785. * or more contributor license agreements. See the NOTICE file
  32786. * distributed with this work for additional information
  32787. * regarding copyright ownership. The ASF licenses this file
  32788. * to you under the Apache License, Version 2.0 (the
  32789. * "License"); you may not use this file except in compliance
  32790. * with the License. You may obtain a copy of the License at
  32791. *
  32792. * http://www.apache.org/licenses/LICENSE-2.0
  32793. *
  32794. * Unless required by applicable law or agreed to in writing,
  32795. * software distributed under the License is distributed on an
  32796. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32797. * KIND, either express or implied. See the License for the
  32798. * specific language governing permissions and limitations
  32799. * under the License.
  32800. */
  32801. // Grid 是在有直角坐标系的时候必须要存在的
  32802. // 所以这里也要被 Cartesian2D 依赖
  32803. ComponentModel.extend({
  32804. type: 'grid',
  32805. dependencies: ['xAxis', 'yAxis'],
  32806. layoutMode: 'box',
  32807. /**
  32808. * @type {module:echarts/coord/cartesian/Grid}
  32809. */
  32810. coordinateSystem: null,
  32811. defaultOption: {
  32812. show: false,
  32813. zlevel: 0,
  32814. z: 0,
  32815. left: '10%',
  32816. top: 60,
  32817. right: '10%',
  32818. bottom: 60,
  32819. // If grid size contain label
  32820. containLabel: false,
  32821. // width: {totalWidth} - left - right,
  32822. // height: {totalHeight} - top - bottom,
  32823. backgroundColor: 'rgba(0,0,0,0)',
  32824. borderWidth: 1,
  32825. borderColor: '#ccc'
  32826. }
  32827. });
  32828. /*
  32829. * Licensed to the Apache Software Foundation (ASF) under one
  32830. * or more contributor license agreements. See the NOTICE file
  32831. * distributed with this work for additional information
  32832. * regarding copyright ownership. The ASF licenses this file
  32833. * to you under the Apache License, Version 2.0 (the
  32834. * "License"); you may not use this file except in compliance
  32835. * with the License. You may obtain a copy of the License at
  32836. *
  32837. * http://www.apache.org/licenses/LICENSE-2.0
  32838. *
  32839. * Unless required by applicable law or agreed to in writing,
  32840. * software distributed under the License is distributed on an
  32841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32842. * KIND, either express or implied. See the License for the
  32843. * specific language governing permissions and limitations
  32844. * under the License.
  32845. */
  32846. /**
  32847. * Grid is a region which contains at most 4 cartesian systems
  32848. *
  32849. * TODO Default cartesian
  32850. */
  32851. // Depends on GridModel, AxisModel, which performs preprocess.
  32852. /**
  32853. * Check if the axis is used in the specified grid
  32854. * @inner
  32855. */
  32856. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  32857. return axisModel.getCoordSysModel() === gridModel;
  32858. }
  32859. function Grid(gridModel, ecModel, api) {
  32860. /**
  32861. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  32862. * @private
  32863. */
  32864. this._coordsMap = {};
  32865. /**
  32866. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  32867. * @private
  32868. */
  32869. this._coordsList = [];
  32870. /**
  32871. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  32872. * @private
  32873. */
  32874. this._axesMap = {};
  32875. /**
  32876. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  32877. * @private
  32878. */
  32879. this._axesList = [];
  32880. this._initCartesian(gridModel, ecModel, api);
  32881. this.model = gridModel;
  32882. }
  32883. var gridProto = Grid.prototype;
  32884. gridProto.type = 'grid';
  32885. gridProto.axisPointerEnabled = true;
  32886. gridProto.getRect = function () {
  32887. return this._rect;
  32888. };
  32889. gridProto.update = function (ecModel, api) {
  32890. var axesMap = this._axesMap;
  32891. this._updateScale(ecModel, this.model);
  32892. each$1(axesMap.x, function (xAxis) {
  32893. niceScaleExtent(xAxis.scale, xAxis.model);
  32894. });
  32895. each$1(axesMap.y, function (yAxis) {
  32896. niceScaleExtent(yAxis.scale, yAxis.model);
  32897. });
  32898. // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  32899. var onZeroRecords = {};
  32900. each$1(axesMap.x, function (xAxis) {
  32901. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  32902. });
  32903. each$1(axesMap.y, function (yAxis) {
  32904. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  32905. });
  32906. // Resize again if containLabel is enabled
  32907. // FIXME It may cause getting wrong grid size in data processing stage
  32908. this.resize(this.model, api);
  32909. };
  32910. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  32911. axis.getAxesOnZeroOf = function () {
  32912. // TODO: onZero of multiple axes.
  32913. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  32914. };
  32915. // onZero can not be enabled in these two situations:
  32916. // 1. When any other axis is a category axis.
  32917. // 2. When no axis is cross 0 point.
  32918. var otherAxes = axesMap[otherAxisDim];
  32919. var otherAxisOnZeroOf;
  32920. var axisModel = axis.model;
  32921. var onZero = axisModel.get('axisLine.onZero');
  32922. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  32923. if (!onZero) {
  32924. return;
  32925. }
  32926. // If target axis is specified.
  32927. if (onZeroAxisIndex != null) {
  32928. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  32929. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  32930. }
  32931. }
  32932. else {
  32933. // Find the first available other axis.
  32934. for (var idx in otherAxes) {
  32935. if (otherAxes.hasOwnProperty(idx)
  32936. && canOnZeroToAxis(otherAxes[idx])
  32937. // Consider that two Y axes on one value axis,
  32938. // if both onZero, the two Y axes overlap.
  32939. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]
  32940. ) {
  32941. otherAxisOnZeroOf = otherAxes[idx];
  32942. break;
  32943. }
  32944. }
  32945. }
  32946. if (otherAxisOnZeroOf) {
  32947. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  32948. }
  32949. function getOnZeroRecordKey(axis) {
  32950. return axis.dim + '_' + axis.index;
  32951. }
  32952. }
  32953. function canOnZeroToAxis(axis) {
  32954. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  32955. }
  32956. /**
  32957. * Resize the grid
  32958. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  32959. * @param {module:echarts/ExtensionAPI} api
  32960. */
  32961. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  32962. var gridRect = getLayoutRect(
  32963. gridModel.getBoxLayoutParams(), {
  32964. width: api.getWidth(),
  32965. height: api.getHeight()
  32966. });
  32967. this._rect = gridRect;
  32968. var axesList = this._axesList;
  32969. adjustAxes();
  32970. // Minus label size
  32971. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  32972. each$1(axesList, function (axis) {
  32973. if (!axis.model.get('axisLabel.inside')) {
  32974. var labelUnionRect = estimateLabelUnionRect(axis);
  32975. if (labelUnionRect) {
  32976. var dim = axis.isHorizontal() ? 'height' : 'width';
  32977. var margin = axis.model.get('axisLabel.margin');
  32978. gridRect[dim] -= labelUnionRect[dim] + margin;
  32979. if (axis.position === 'top') {
  32980. gridRect.y += labelUnionRect.height + margin;
  32981. }
  32982. else if (axis.position === 'left') {
  32983. gridRect.x += labelUnionRect.width + margin;
  32984. }
  32985. }
  32986. }
  32987. });
  32988. adjustAxes();
  32989. }
  32990. function adjustAxes() {
  32991. each$1(axesList, function (axis) {
  32992. var isHorizontal = axis.isHorizontal();
  32993. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  32994. var idx = axis.inverse ? 1 : 0;
  32995. axis.setExtent(extent[idx], extent[1 - idx]);
  32996. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  32997. });
  32998. }
  32999. };
  33000. /**
  33001. * @param {string} axisType
  33002. * @param {number} [axisIndex]
  33003. */
  33004. gridProto.getAxis = function (axisType, axisIndex) {
  33005. var axesMapOnDim = this._axesMap[axisType];
  33006. if (axesMapOnDim != null) {
  33007. if (axisIndex == null) {
  33008. // Find first axis
  33009. for (var name in axesMapOnDim) {
  33010. if (axesMapOnDim.hasOwnProperty(name)) {
  33011. return axesMapOnDim[name];
  33012. }
  33013. }
  33014. }
  33015. return axesMapOnDim[axisIndex];
  33016. }
  33017. };
  33018. /**
  33019. * @return {Array.<module:echarts/coord/Axis>}
  33020. */
  33021. gridProto.getAxes = function () {
  33022. return this._axesList.slice();
  33023. };
  33024. /**
  33025. * Usage:
  33026. * grid.getCartesian(xAxisIndex, yAxisIndex);
  33027. * grid.getCartesian(xAxisIndex);
  33028. * grid.getCartesian(null, yAxisIndex);
  33029. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  33030. *
  33031. * @param {number|Object} [xAxisIndex]
  33032. * @param {number} [yAxisIndex]
  33033. */
  33034. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  33035. if (xAxisIndex != null && yAxisIndex != null) {
  33036. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  33037. return this._coordsMap[key];
  33038. }
  33039. if (isObject$1(xAxisIndex)) {
  33040. yAxisIndex = xAxisIndex.yAxisIndex;
  33041. xAxisIndex = xAxisIndex.xAxisIndex;
  33042. }
  33043. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  33044. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  33045. if (coordList[i].getAxis('x').index === xAxisIndex
  33046. || coordList[i].getAxis('y').index === yAxisIndex
  33047. ) {
  33048. return coordList[i];
  33049. }
  33050. }
  33051. };
  33052. gridProto.getCartesians = function () {
  33053. return this._coordsList.slice();
  33054. };
  33055. /**
  33056. * @implements
  33057. * see {module:echarts/CoodinateSystem}
  33058. */
  33059. gridProto.convertToPixel = function (ecModel, finder, value) {
  33060. var target = this._findConvertTarget(ecModel, finder);
  33061. return target.cartesian
  33062. ? target.cartesian.dataToPoint(value)
  33063. : target.axis
  33064. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  33065. : null;
  33066. };
  33067. /**
  33068. * @implements
  33069. * see {module:echarts/CoodinateSystem}
  33070. */
  33071. gridProto.convertFromPixel = function (ecModel, finder, value) {
  33072. var target = this._findConvertTarget(ecModel, finder);
  33073. return target.cartesian
  33074. ? target.cartesian.pointToData(value)
  33075. : target.axis
  33076. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  33077. : null;
  33078. };
  33079. /**
  33080. * @inner
  33081. */
  33082. gridProto._findConvertTarget = function (ecModel, finder) {
  33083. var seriesModel = finder.seriesModel;
  33084. var xAxisModel = finder.xAxisModel
  33085. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  33086. var yAxisModel = finder.yAxisModel
  33087. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  33088. var gridModel = finder.gridModel;
  33089. var coordsList = this._coordsList;
  33090. var cartesian;
  33091. var axis;
  33092. if (seriesModel) {
  33093. cartesian = seriesModel.coordinateSystem;
  33094. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  33095. }
  33096. else if (xAxisModel && yAxisModel) {
  33097. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  33098. }
  33099. else if (xAxisModel) {
  33100. axis = this.getAxis('x', xAxisModel.componentIndex);
  33101. }
  33102. else if (yAxisModel) {
  33103. axis = this.getAxis('y', yAxisModel.componentIndex);
  33104. }
  33105. // Lowest priority.
  33106. else if (gridModel) {
  33107. var grid = gridModel.coordinateSystem;
  33108. if (grid === this) {
  33109. cartesian = this._coordsList[0];
  33110. }
  33111. }
  33112. return {cartesian: cartesian, axis: axis};
  33113. };
  33114. /**
  33115. * @implements
  33116. * see {module:echarts/CoodinateSystem}
  33117. */
  33118. gridProto.containPoint = function (point) {
  33119. var coord = this._coordsList[0];
  33120. if (coord) {
  33121. return coord.containPoint(point);
  33122. }
  33123. };
  33124. /**
  33125. * Initialize cartesian coordinate systems
  33126. * @private
  33127. */
  33128. gridProto._initCartesian = function (gridModel, ecModel, api) {
  33129. var axisPositionUsed = {
  33130. left: false,
  33131. right: false,
  33132. top: false,
  33133. bottom: false
  33134. };
  33135. var axesMap = {
  33136. x: {},
  33137. y: {}
  33138. };
  33139. var axesCount = {
  33140. x: 0,
  33141. y: 0
  33142. };
  33143. /// Create axis
  33144. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  33145. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  33146. if (!axesCount.x || !axesCount.y) {
  33147. // Roll back when there no either x or y axis
  33148. this._axesMap = {};
  33149. this._axesList = [];
  33150. return;
  33151. }
  33152. this._axesMap = axesMap;
  33153. /// Create cartesian2d
  33154. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  33155. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  33156. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  33157. var cartesian = new Cartesian2D(key);
  33158. cartesian.grid = this;
  33159. cartesian.model = gridModel;
  33160. this._coordsMap[key] = cartesian;
  33161. this._coordsList.push(cartesian);
  33162. cartesian.addAxis(xAxis);
  33163. cartesian.addAxis(yAxis);
  33164. }, this);
  33165. }, this);
  33166. function createAxisCreator(axisType) {
  33167. return function (axisModel, idx) {
  33168. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  33169. return;
  33170. }
  33171. var axisPosition = axisModel.get('position');
  33172. if (axisType === 'x') {
  33173. // Fix position
  33174. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  33175. // Default bottom of X
  33176. axisPosition = 'bottom';
  33177. if (axisPositionUsed[axisPosition]) {
  33178. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  33179. }
  33180. }
  33181. }
  33182. else {
  33183. // Fix position
  33184. if (axisPosition !== 'left' && axisPosition !== 'right') {
  33185. // Default left of Y
  33186. axisPosition = 'left';
  33187. if (axisPositionUsed[axisPosition]) {
  33188. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  33189. }
  33190. }
  33191. }
  33192. axisPositionUsed[axisPosition] = true;
  33193. var axis = new Axis2D(
  33194. axisType, createScaleByModel(axisModel),
  33195. [0, 0],
  33196. axisModel.get('type'),
  33197. axisPosition
  33198. );
  33199. var isCategory = axis.type === 'category';
  33200. axis.onBand = isCategory && axisModel.get('boundaryGap');
  33201. axis.inverse = axisModel.get('inverse');
  33202. // Inject axis into axisModel
  33203. axisModel.axis = axis;
  33204. // Inject axisModel into axis
  33205. axis.model = axisModel;
  33206. // Inject grid info axis
  33207. axis.grid = this;
  33208. // Index of axis, can be used as key
  33209. axis.index = idx;
  33210. this._axesList.push(axis);
  33211. axesMap[axisType][idx] = axis;
  33212. axesCount[axisType]++;
  33213. };
  33214. }
  33215. };
  33216. /**
  33217. * Update cartesian properties from series
  33218. * @param {module:echarts/model/Option} option
  33219. * @private
  33220. */
  33221. gridProto._updateScale = function (ecModel, gridModel) {
  33222. // Reset scale
  33223. each$1(this._axesList, function (axis) {
  33224. axis.scale.setExtent(Infinity, -Infinity);
  33225. });
  33226. ecModel.eachSeries(function (seriesModel) {
  33227. if (isCartesian2D(seriesModel)) {
  33228. var axesModels = findAxesModels(seriesModel, ecModel);
  33229. var xAxisModel = axesModels[0];
  33230. var yAxisModel = axesModels[1];
  33231. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  33232. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  33233. ) {
  33234. return;
  33235. }
  33236. var cartesian = this.getCartesian(
  33237. xAxisModel.componentIndex, yAxisModel.componentIndex
  33238. );
  33239. var data = seriesModel.getData();
  33240. var xAxis = cartesian.getAxis('x');
  33241. var yAxis = cartesian.getAxis('y');
  33242. if (data.type === 'list') {
  33243. unionExtent(data, xAxis, seriesModel);
  33244. unionExtent(data, yAxis, seriesModel);
  33245. }
  33246. }
  33247. }, this);
  33248. function unionExtent(data, axis, seriesModel) {
  33249. each$1(data.mapDimension(axis.dim, true), function (dim) {
  33250. axis.scale.unionExtentFromData(
  33251. // For example, the extent of the orginal dimension
  33252. // is [0.1, 0.5], the extent of the `stackResultDimension`
  33253. // is [7, 9], the final extent should not include [0.1, 0.5].
  33254. data, getStackedDimension(data, dim)
  33255. );
  33256. });
  33257. }
  33258. };
  33259. /**
  33260. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  33261. * @return {Object} {baseAxes: [], otherAxes: []}
  33262. */
  33263. gridProto.getTooltipAxes = function (dim) {
  33264. var baseAxes = [];
  33265. var otherAxes = [];
  33266. each$1(this.getCartesians(), function (cartesian) {
  33267. var baseAxis = (dim != null && dim !== 'auto')
  33268. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  33269. var otherAxis = cartesian.getOtherAxis(baseAxis);
  33270. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  33271. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  33272. });
  33273. return {baseAxes: baseAxes, otherAxes: otherAxes};
  33274. };
  33275. /**
  33276. * @inner
  33277. */
  33278. function updateAxisTransform(axis, coordBase) {
  33279. var axisExtent = axis.getExtent();
  33280. var axisExtentSum = axisExtent[0] + axisExtent[1];
  33281. // Fast transform
  33282. axis.toGlobalCoord = axis.dim === 'x'
  33283. ? function (coord) {
  33284. return coord + coordBase;
  33285. }
  33286. : function (coord) {
  33287. return axisExtentSum - coord + coordBase;
  33288. };
  33289. axis.toLocalCoord = axis.dim === 'x'
  33290. ? function (coord) {
  33291. return coord - coordBase;
  33292. }
  33293. : function (coord) {
  33294. return axisExtentSum - coord + coordBase;
  33295. };
  33296. }
  33297. var axesTypes = ['xAxis', 'yAxis'];
  33298. /**
  33299. * @inner
  33300. */
  33301. function findAxesModels(seriesModel, ecModel) {
  33302. return map(axesTypes, function (axisType) {
  33303. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  33304. if (__DEV__) {
  33305. if (!axisModel) {
  33306. throw new Error(axisType + ' "' + retrieve(
  33307. seriesModel.get(axisType + 'Index'),
  33308. seriesModel.get(axisType + 'Id'),
  33309. 0
  33310. ) + '" not found');
  33311. }
  33312. }
  33313. return axisModel;
  33314. });
  33315. }
  33316. /**
  33317. * @inner
  33318. */
  33319. function isCartesian2D(seriesModel) {
  33320. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  33321. }
  33322. Grid.create = function (ecModel, api) {
  33323. var grids = [];
  33324. ecModel.eachComponent('grid', function (gridModel, idx) {
  33325. var grid = new Grid(gridModel, ecModel, api);
  33326. grid.name = 'grid_' + idx;
  33327. // dataSampling requires axis extent, so resize
  33328. // should be performed in create stage.
  33329. grid.resize(gridModel, api, true);
  33330. gridModel.coordinateSystem = grid;
  33331. grids.push(grid);
  33332. });
  33333. // Inject the coordinateSystems into seriesModel
  33334. ecModel.eachSeries(function (seriesModel) {
  33335. if (!isCartesian2D(seriesModel)) {
  33336. return;
  33337. }
  33338. var axesModels = findAxesModels(seriesModel, ecModel);
  33339. var xAxisModel = axesModels[0];
  33340. var yAxisModel = axesModels[1];
  33341. var gridModel = xAxisModel.getCoordSysModel();
  33342. if (__DEV__) {
  33343. if (!gridModel) {
  33344. throw new Error(
  33345. 'Grid "' + retrieve(
  33346. xAxisModel.get('gridIndex'),
  33347. xAxisModel.get('gridId'),
  33348. 0
  33349. ) + '" not found'
  33350. );
  33351. }
  33352. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  33353. throw new Error('xAxis and yAxis must use the same grid');
  33354. }
  33355. }
  33356. var grid = gridModel.coordinateSystem;
  33357. seriesModel.coordinateSystem = grid.getCartesian(
  33358. xAxisModel.componentIndex, yAxisModel.componentIndex
  33359. );
  33360. });
  33361. return grids;
  33362. };
  33363. // For deciding which dimensions to use when creating list data
  33364. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  33365. CoordinateSystemManager.register('cartesian2d', Grid);
  33366. /*
  33367. * Licensed to the Apache Software Foundation (ASF) under one
  33368. * or more contributor license agreements. See the NOTICE file
  33369. * distributed with this work for additional information
  33370. * regarding copyright ownership. The ASF licenses this file
  33371. * to you under the Apache License, Version 2.0 (the
  33372. * "License"); you may not use this file except in compliance
  33373. * with the License. You may obtain a copy of the License at
  33374. *
  33375. * http://www.apache.org/licenses/LICENSE-2.0
  33376. *
  33377. * Unless required by applicable law or agreed to in writing,
  33378. * software distributed under the License is distributed on an
  33379. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33380. * KIND, either express or implied. See the License for the
  33381. * specific language governing permissions and limitations
  33382. * under the License.
  33383. */
  33384. var PI$2 = Math.PI;
  33385. function makeAxisEventDataBase(axisModel) {
  33386. var eventData = {
  33387. componentType: axisModel.mainType,
  33388. componentIndex: axisModel.componentIndex
  33389. };
  33390. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  33391. return eventData;
  33392. }
  33393. /**
  33394. * A final axis is translated and rotated from a "standard axis".
  33395. * So opt.position and opt.rotation is required.
  33396. *
  33397. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  33398. * for example: (0, 0) ------------> (0, 50)
  33399. *
  33400. * nameDirection or tickDirection or labelDirection is 1 means tick
  33401. * or label is below the standard axis, whereas is -1 means above
  33402. * the standard axis. labelOffset means offset between label and axis,
  33403. * which is useful when 'onZero', where axisLabel is in the grid and
  33404. * label in outside grid.
  33405. *
  33406. * Tips: like always,
  33407. * positive rotation represents anticlockwise, and negative rotation
  33408. * represents clockwise.
  33409. * The direction of position coordinate is the same as the direction
  33410. * of screen coordinate.
  33411. *
  33412. * Do not need to consider axis 'inverse', which is auto processed by
  33413. * axis extent.
  33414. *
  33415. * @param {module:zrender/container/Group} group
  33416. * @param {Object} axisModel
  33417. * @param {Object} opt Standard axis parameters.
  33418. * @param {Array.<number>} opt.position [x, y]
  33419. * @param {number} opt.rotation by radian
  33420. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  33421. * @param {number} [opt.tickDirection=1] 1 or -1
  33422. * @param {number} [opt.labelDirection=1] 1 or -1
  33423. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  33424. * @param {string} [opt.axisLabelShow] default get from axisModel.
  33425. * @param {string} [opt.axisName] default get from axisModel.
  33426. * @param {number} [opt.axisNameAvailableWidth]
  33427. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  33428. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  33429. * @param {number} [opt.nameTruncateMaxWidth]
  33430. */
  33431. var AxisBuilder = function (axisModel, opt) {
  33432. /**
  33433. * @readOnly
  33434. */
  33435. this.opt = opt;
  33436. /**
  33437. * @readOnly
  33438. */
  33439. this.axisModel = axisModel;
  33440. // Default value
  33441. defaults(
  33442. opt,
  33443. {
  33444. labelOffset: 0,
  33445. nameDirection: 1,
  33446. tickDirection: 1,
  33447. labelDirection: 1,
  33448. silent: true
  33449. }
  33450. );
  33451. /**
  33452. * @readOnly
  33453. */
  33454. this.group = new Group();
  33455. // FIXME Not use a seperate text group?
  33456. var dumbGroup = new Group({
  33457. position: opt.position.slice(),
  33458. rotation: opt.rotation
  33459. });
  33460. // this.group.add(dumbGroup);
  33461. // this._dumbGroup = dumbGroup;
  33462. dumbGroup.updateTransform();
  33463. this._transform = dumbGroup.transform;
  33464. this._dumbGroup = dumbGroup;
  33465. };
  33466. AxisBuilder.prototype = {
  33467. constructor: AxisBuilder,
  33468. hasBuilder: function (name) {
  33469. return !!builders[name];
  33470. },
  33471. add: function (name) {
  33472. builders[name].call(this);
  33473. },
  33474. getGroup: function () {
  33475. return this.group;
  33476. }
  33477. };
  33478. var builders = {
  33479. /**
  33480. * @private
  33481. */
  33482. axisLine: function () {
  33483. var opt = this.opt;
  33484. var axisModel = this.axisModel;
  33485. if (!axisModel.get('axisLine.show')) {
  33486. return;
  33487. }
  33488. var extent = this.axisModel.axis.getExtent();
  33489. var matrix = this._transform;
  33490. var pt1 = [extent[0], 0];
  33491. var pt2 = [extent[1], 0];
  33492. if (matrix) {
  33493. applyTransform(pt1, pt1, matrix);
  33494. applyTransform(pt2, pt2, matrix);
  33495. }
  33496. var lineStyle = extend(
  33497. {
  33498. lineCap: 'round'
  33499. },
  33500. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  33501. );
  33502. this.group.add(new Line(subPixelOptimizeLine({
  33503. // Id for animation
  33504. anid: 'line',
  33505. shape: {
  33506. x1: pt1[0],
  33507. y1: pt1[1],
  33508. x2: pt2[0],
  33509. y2: pt2[1]
  33510. },
  33511. style: lineStyle,
  33512. strokeContainThreshold: opt.strokeContainThreshold || 5,
  33513. silent: true,
  33514. z2: 1
  33515. })));
  33516. var arrows = axisModel.get('axisLine.symbol');
  33517. var arrowSize = axisModel.get('axisLine.symbolSize');
  33518. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  33519. if (typeof arrowOffset === 'number') {
  33520. arrowOffset = [arrowOffset, arrowOffset];
  33521. }
  33522. if (arrows != null) {
  33523. if (typeof arrows === 'string') {
  33524. // Use the same arrow for start and end point
  33525. arrows = [arrows, arrows];
  33526. }
  33527. if (typeof arrowSize === 'string'
  33528. || typeof arrowSize === 'number'
  33529. ) {
  33530. // Use the same size for width and height
  33531. arrowSize = [arrowSize, arrowSize];
  33532. }
  33533. var symbolWidth = arrowSize[0];
  33534. var symbolHeight = arrowSize[1];
  33535. each$1([{
  33536. rotate: opt.rotation + Math.PI / 2,
  33537. offset: arrowOffset[0],
  33538. r: 0
  33539. }, {
  33540. rotate: opt.rotation - Math.PI / 2,
  33541. offset: arrowOffset[1],
  33542. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  33543. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  33544. }], function (point, index) {
  33545. if (arrows[index] !== 'none' && arrows[index] != null) {
  33546. var symbol = createSymbol(
  33547. arrows[index],
  33548. -symbolWidth / 2,
  33549. -symbolHeight / 2,
  33550. symbolWidth,
  33551. symbolHeight,
  33552. lineStyle.stroke,
  33553. true
  33554. );
  33555. // Calculate arrow position with offset
  33556. var r = point.r + point.offset;
  33557. var pos = [
  33558. pt1[0] + r * Math.cos(opt.rotation),
  33559. pt1[1] - r * Math.sin(opt.rotation)
  33560. ];
  33561. symbol.attr({
  33562. rotation: point.rotate,
  33563. position: pos,
  33564. silent: true,
  33565. z2: 11
  33566. });
  33567. this.group.add(symbol);
  33568. }
  33569. }, this);
  33570. }
  33571. },
  33572. /**
  33573. * @private
  33574. */
  33575. axisTickLabel: function () {
  33576. var axisModel = this.axisModel;
  33577. var opt = this.opt;
  33578. var tickEls = buildAxisTick(this, axisModel, opt);
  33579. var labelEls = buildAxisLabel(this, axisModel, opt);
  33580. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  33581. },
  33582. /**
  33583. * @private
  33584. */
  33585. axisName: function () {
  33586. var opt = this.opt;
  33587. var axisModel = this.axisModel;
  33588. var name = retrieve(opt.axisName, axisModel.get('name'));
  33589. if (!name) {
  33590. return;
  33591. }
  33592. var nameLocation = axisModel.get('nameLocation');
  33593. var nameDirection = opt.nameDirection;
  33594. var textStyleModel = axisModel.getModel('nameTextStyle');
  33595. var gap = axisModel.get('nameGap') || 0;
  33596. var extent = this.axisModel.axis.getExtent();
  33597. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  33598. var pos = [
  33599. nameLocation === 'start'
  33600. ? extent[0] - gapSignal * gap
  33601. : nameLocation === 'end'
  33602. ? extent[1] + gapSignal * gap
  33603. : (extent[0] + extent[1]) / 2, // 'middle'
  33604. // Reuse labelOffset.
  33605. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  33606. ];
  33607. var labelLayout;
  33608. var nameRotation = axisModel.get('nameRotate');
  33609. if (nameRotation != null) {
  33610. nameRotation = nameRotation * PI$2 / 180; // To radian.
  33611. }
  33612. var axisNameAvailableWidth;
  33613. if (isNameLocationCenter(nameLocation)) {
  33614. labelLayout = innerTextLayout(
  33615. opt.rotation,
  33616. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  33617. nameDirection
  33618. );
  33619. }
  33620. else {
  33621. labelLayout = endTextLayout(
  33622. opt, nameLocation, nameRotation || 0, extent
  33623. );
  33624. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  33625. if (axisNameAvailableWidth != null) {
  33626. axisNameAvailableWidth = Math.abs(
  33627. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  33628. );
  33629. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  33630. }
  33631. }
  33632. var textFont = textStyleModel.getFont();
  33633. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  33634. var ellipsis = truncateOpt.ellipsis;
  33635. var maxWidth = retrieve(
  33636. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  33637. );
  33638. // FIXME
  33639. // truncate rich text? (consider performance)
  33640. var truncatedText = (ellipsis != null && maxWidth != null)
  33641. ? truncateText$1(
  33642. name, maxWidth, textFont, ellipsis,
  33643. {minChar: 2, placeholder: truncateOpt.placeholder}
  33644. )
  33645. : name;
  33646. var tooltipOpt = axisModel.get('tooltip', true);
  33647. var mainType = axisModel.mainType;
  33648. var formatterParams = {
  33649. componentType: mainType,
  33650. name: name,
  33651. $vars: ['name']
  33652. };
  33653. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  33654. var textEl = new Text({
  33655. // Id for animation
  33656. anid: 'name',
  33657. __fullText: name,
  33658. __truncatedText: truncatedText,
  33659. position: pos,
  33660. rotation: labelLayout.rotation,
  33661. silent: isSilent(axisModel),
  33662. z2: 1,
  33663. tooltip: (tooltipOpt && tooltipOpt.show)
  33664. ? extend({
  33665. content: name,
  33666. formatter: function () {
  33667. return name;
  33668. },
  33669. formatterParams: formatterParams
  33670. }, tooltipOpt)
  33671. : null
  33672. });
  33673. setTextStyle(textEl.style, textStyleModel, {
  33674. text: truncatedText,
  33675. textFont: textFont,
  33676. textFill: textStyleModel.getTextColor()
  33677. || axisModel.get('axisLine.lineStyle.color'),
  33678. textAlign: labelLayout.textAlign,
  33679. textVerticalAlign: labelLayout.textVerticalAlign
  33680. });
  33681. if (axisModel.get('triggerEvent')) {
  33682. textEl.eventData = makeAxisEventDataBase(axisModel);
  33683. textEl.eventData.targetType = 'axisName';
  33684. textEl.eventData.name = name;
  33685. }
  33686. // FIXME
  33687. this._dumbGroup.add(textEl);
  33688. textEl.updateTransform();
  33689. this.group.add(textEl);
  33690. textEl.decomposeTransform();
  33691. }
  33692. };
  33693. /**
  33694. * @public
  33695. * @static
  33696. * @param {Object} opt
  33697. * @param {number} axisRotation in radian
  33698. * @param {number} textRotation in radian
  33699. * @param {number} direction
  33700. * @return {Object} {
  33701. * rotation, // according to axis
  33702. * textAlign,
  33703. * textVerticalAlign
  33704. * }
  33705. */
  33706. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  33707. var rotationDiff = remRadian(textRotation - axisRotation);
  33708. var textAlign;
  33709. var textVerticalAlign;
  33710. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  33711. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  33712. textAlign = 'center';
  33713. }
  33714. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  33715. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  33716. textAlign = 'center';
  33717. }
  33718. else {
  33719. textVerticalAlign = 'middle';
  33720. if (rotationDiff > 0 && rotationDiff < PI$2) {
  33721. textAlign = direction > 0 ? 'right' : 'left';
  33722. }
  33723. else {
  33724. textAlign = direction > 0 ? 'left' : 'right';
  33725. }
  33726. }
  33727. return {
  33728. rotation: rotationDiff,
  33729. textAlign: textAlign,
  33730. textVerticalAlign: textVerticalAlign
  33731. };
  33732. };
  33733. function endTextLayout(opt, textPosition, textRotate, extent) {
  33734. var rotationDiff = remRadian(textRotate - opt.rotation);
  33735. var textAlign;
  33736. var textVerticalAlign;
  33737. var inverse = extent[0] > extent[1];
  33738. var onLeft = (textPosition === 'start' && !inverse)
  33739. || (textPosition !== 'start' && inverse);
  33740. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  33741. textVerticalAlign = onLeft ? 'bottom' : 'top';
  33742. textAlign = 'center';
  33743. }
  33744. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  33745. textVerticalAlign = onLeft ? 'top' : 'bottom';
  33746. textAlign = 'center';
  33747. }
  33748. else {
  33749. textVerticalAlign = 'middle';
  33750. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  33751. textAlign = onLeft ? 'left' : 'right';
  33752. }
  33753. else {
  33754. textAlign = onLeft ? 'right' : 'left';
  33755. }
  33756. }
  33757. return {
  33758. rotation: rotationDiff,
  33759. textAlign: textAlign,
  33760. textVerticalAlign: textVerticalAlign
  33761. };
  33762. }
  33763. function isSilent(axisModel) {
  33764. var tooltipOpt = axisModel.get('tooltip');
  33765. return axisModel.get('silent')
  33766. // Consider mouse cursor, add these restrictions.
  33767. || !(
  33768. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  33769. );
  33770. }
  33771. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  33772. if (shouldShowAllLabels(axisModel.axis)) {
  33773. return;
  33774. }
  33775. // If min or max are user set, we need to check
  33776. // If the tick on min(max) are overlap on their neighbour tick
  33777. // If they are overlapped, we need to hide the min(max) tick label
  33778. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  33779. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  33780. // FIXME
  33781. // Have not consider onBand yet, where tick els is more than label els.
  33782. labelEls = labelEls || [];
  33783. tickEls = tickEls || [];
  33784. var firstLabel = labelEls[0];
  33785. var nextLabel = labelEls[1];
  33786. var lastLabel = labelEls[labelEls.length - 1];
  33787. var prevLabel = labelEls[labelEls.length - 2];
  33788. var firstTick = tickEls[0];
  33789. var nextTick = tickEls[1];
  33790. var lastTick = tickEls[tickEls.length - 1];
  33791. var prevTick = tickEls[tickEls.length - 2];
  33792. if (showMinLabel === false) {
  33793. ignoreEl(firstLabel);
  33794. ignoreEl(firstTick);
  33795. }
  33796. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  33797. if (showMinLabel) {
  33798. ignoreEl(nextLabel);
  33799. ignoreEl(nextTick);
  33800. }
  33801. else {
  33802. ignoreEl(firstLabel);
  33803. ignoreEl(firstTick);
  33804. }
  33805. }
  33806. if (showMaxLabel === false) {
  33807. ignoreEl(lastLabel);
  33808. ignoreEl(lastTick);
  33809. }
  33810. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  33811. if (showMaxLabel) {
  33812. ignoreEl(prevLabel);
  33813. ignoreEl(prevTick);
  33814. }
  33815. else {
  33816. ignoreEl(lastLabel);
  33817. ignoreEl(lastTick);
  33818. }
  33819. }
  33820. }
  33821. function ignoreEl(el) {
  33822. el && (el.ignore = true);
  33823. }
  33824. function isTwoLabelOverlapped(current, next, labelLayout) {
  33825. // current and next has the same rotation.
  33826. var firstRect = current && current.getBoundingRect().clone();
  33827. var nextRect = next && next.getBoundingRect().clone();
  33828. if (!firstRect || !nextRect) {
  33829. return;
  33830. }
  33831. // When checking intersect of two rotated labels, we use mRotationBack
  33832. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  33833. var mRotationBack = identity([]);
  33834. rotate(mRotationBack, mRotationBack, -current.rotation);
  33835. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  33836. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  33837. return firstRect.intersect(nextRect);
  33838. }
  33839. function isNameLocationCenter(nameLocation) {
  33840. return nameLocation === 'middle' || nameLocation === 'center';
  33841. }
  33842. function buildAxisTick(axisBuilder, axisModel, opt) {
  33843. var axis = axisModel.axis;
  33844. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  33845. return;
  33846. }
  33847. var tickModel = axisModel.getModel('axisTick');
  33848. var lineStyleModel = tickModel.getModel('lineStyle');
  33849. var tickLen = tickModel.get('length');
  33850. var ticksCoords = axis.getTicksCoords();
  33851. var pt1 = [];
  33852. var pt2 = [];
  33853. var matrix = axisBuilder._transform;
  33854. var tickEls = [];
  33855. for (var i = 0; i < ticksCoords.length; i++) {
  33856. var tickCoord = ticksCoords[i].coord;
  33857. pt1[0] = tickCoord;
  33858. pt1[1] = 0;
  33859. pt2[0] = tickCoord;
  33860. pt2[1] = opt.tickDirection * tickLen;
  33861. if (matrix) {
  33862. applyTransform(pt1, pt1, matrix);
  33863. applyTransform(pt2, pt2, matrix);
  33864. }
  33865. // Tick line, Not use group transform to have better line draw
  33866. var tickEl = new Line(subPixelOptimizeLine({
  33867. // Id for animation
  33868. anid: 'tick_' + ticksCoords[i].tickValue,
  33869. shape: {
  33870. x1: pt1[0],
  33871. y1: pt1[1],
  33872. x2: pt2[0],
  33873. y2: pt2[1]
  33874. },
  33875. style: defaults(
  33876. lineStyleModel.getLineStyle(),
  33877. {
  33878. stroke: axisModel.get('axisLine.lineStyle.color')
  33879. }
  33880. ),
  33881. z2: 2,
  33882. silent: true
  33883. }));
  33884. axisBuilder.group.add(tickEl);
  33885. tickEls.push(tickEl);
  33886. }
  33887. return tickEls;
  33888. }
  33889. function buildAxisLabel(axisBuilder, axisModel, opt) {
  33890. var axis = axisModel.axis;
  33891. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  33892. if (!show || axis.scale.isBlank()) {
  33893. return;
  33894. }
  33895. var labelModel = axisModel.getModel('axisLabel');
  33896. var labelMargin = labelModel.get('margin');
  33897. var labels = axis.getViewLabels();
  33898. // Special label rotate.
  33899. var labelRotation = (
  33900. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  33901. ) * PI$2 / 180;
  33902. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  33903. var rawCategoryData = axisModel.getCategories(true);
  33904. var labelEls = [];
  33905. var silent = isSilent(axisModel);
  33906. var triggerEvent = axisModel.get('triggerEvent');
  33907. each$1(labels, function (labelItem, index) {
  33908. var tickValue = labelItem.tickValue;
  33909. var formattedLabel = labelItem.formattedLabel;
  33910. var rawLabel = labelItem.rawLabel;
  33911. var itemLabelModel = labelModel;
  33912. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  33913. itemLabelModel = new Model(
  33914. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  33915. );
  33916. }
  33917. var textColor = itemLabelModel.getTextColor()
  33918. || axisModel.get('axisLine.lineStyle.color');
  33919. var tickCoord = axis.dataToCoord(tickValue);
  33920. var pos = [
  33921. tickCoord,
  33922. opt.labelOffset + opt.labelDirection * labelMargin
  33923. ];
  33924. var textEl = new Text({
  33925. // Id for animation
  33926. anid: 'label_' + tickValue,
  33927. position: pos,
  33928. rotation: labelLayout.rotation,
  33929. silent: silent,
  33930. z2: 10
  33931. });
  33932. setTextStyle(textEl.style, itemLabelModel, {
  33933. text: formattedLabel,
  33934. textAlign: itemLabelModel.getShallow('align', true)
  33935. || labelLayout.textAlign,
  33936. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  33937. || itemLabelModel.getShallow('baseline', true)
  33938. || labelLayout.textVerticalAlign,
  33939. textFill: typeof textColor === 'function'
  33940. ? textColor(
  33941. // (1) In category axis with data zoom, tick is not the original
  33942. // index of axis.data. So tick should not be exposed to user
  33943. // in category axis.
  33944. // (2) Compatible with previous version, which always use formatted label as
  33945. // input. But in interval scale the formatted label is like '223,445', which
  33946. // maked user repalce ','. So we modify it to return original val but remain
  33947. // it as 'string' to avoid error in replacing.
  33948. axis.type === 'category'
  33949. ? rawLabel
  33950. : axis.type === 'value'
  33951. ? tickValue + ''
  33952. : tickValue,
  33953. index
  33954. )
  33955. : textColor
  33956. });
  33957. // Pack data for mouse event
  33958. if (triggerEvent) {
  33959. textEl.eventData = makeAxisEventDataBase(axisModel);
  33960. textEl.eventData.targetType = 'axisLabel';
  33961. textEl.eventData.value = rawLabel;
  33962. }
  33963. // FIXME
  33964. axisBuilder._dumbGroup.add(textEl);
  33965. textEl.updateTransform();
  33966. labelEls.push(textEl);
  33967. axisBuilder.group.add(textEl);
  33968. textEl.decomposeTransform();
  33969. });
  33970. return labelEls;
  33971. }
  33972. /*
  33973. * Licensed to the Apache Software Foundation (ASF) under one
  33974. * or more contributor license agreements. See the NOTICE file
  33975. * distributed with this work for additional information
  33976. * regarding copyright ownership. The ASF licenses this file
  33977. * to you under the Apache License, Version 2.0 (the
  33978. * "License"); you may not use this file except in compliance
  33979. * with the License. You may obtain a copy of the License at
  33980. *
  33981. * http://www.apache.org/licenses/LICENSE-2.0
  33982. *
  33983. * Unless required by applicable law or agreed to in writing,
  33984. * software distributed under the License is distributed on an
  33985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33986. * KIND, either express or implied. See the License for the
  33987. * specific language governing permissions and limitations
  33988. * under the License.
  33989. */
  33990. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  33991. // allAxesInfo should be updated when setOption performed.
  33992. function fixValue(axisModel) {
  33993. var axisInfo = getAxisInfo(axisModel);
  33994. if (!axisInfo) {
  33995. return;
  33996. }
  33997. var axisPointerModel = axisInfo.axisPointerModel;
  33998. var scale = axisInfo.axis.scale;
  33999. var option = axisPointerModel.option;
  34000. var status = axisPointerModel.get('status');
  34001. var value = axisPointerModel.get('value');
  34002. // Parse init value for category and time axis.
  34003. if (value != null) {
  34004. value = scale.parse(value);
  34005. }
  34006. var useHandle = isHandleTrigger(axisPointerModel);
  34007. // If `handle` used, `axisPointer` will always be displayed, so value
  34008. // and status should be initialized.
  34009. if (status == null) {
  34010. option.status = useHandle ? 'show' : 'hide';
  34011. }
  34012. var extent = scale.getExtent().slice();
  34013. extent[0] > extent[1] && extent.reverse();
  34014. if (// Pick a value on axis when initializing.
  34015. value == null
  34016. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  34017. // where we should re-pick a value to keep `handle` displaying normally.
  34018. || value > extent[1]
  34019. ) {
  34020. // Make handle displayed on the end of the axis when init, which looks better.
  34021. value = extent[1];
  34022. }
  34023. if (value < extent[0]) {
  34024. value = extent[0];
  34025. }
  34026. option.value = value;
  34027. if (useHandle) {
  34028. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  34029. }
  34030. }
  34031. function getAxisInfo(axisModel) {
  34032. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  34033. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  34034. }
  34035. function getAxisPointerModel(axisModel) {
  34036. var axisInfo = getAxisInfo(axisModel);
  34037. return axisInfo && axisInfo.axisPointerModel;
  34038. }
  34039. function isHandleTrigger(axisPointerModel) {
  34040. return !!axisPointerModel.get('handle.show');
  34041. }
  34042. /**
  34043. * @param {module:echarts/model/Model} model
  34044. * @return {string} unique key
  34045. */
  34046. function makeKey(model) {
  34047. return model.type + '||' + model.id;
  34048. }
  34049. /*
  34050. * Licensed to the Apache Software Foundation (ASF) under one
  34051. * or more contributor license agreements. See the NOTICE file
  34052. * distributed with this work for additional information
  34053. * regarding copyright ownership. The ASF licenses this file
  34054. * to you under the Apache License, Version 2.0 (the
  34055. * "License"); you may not use this file except in compliance
  34056. * with the License. You may obtain a copy of the License at
  34057. *
  34058. * http://www.apache.org/licenses/LICENSE-2.0
  34059. *
  34060. * Unless required by applicable law or agreed to in writing,
  34061. * software distributed under the License is distributed on an
  34062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34063. * KIND, either express or implied. See the License for the
  34064. * specific language governing permissions and limitations
  34065. * under the License.
  34066. */
  34067. /**
  34068. * Base class of AxisView.
  34069. */
  34070. var AxisView = extendComponentView({
  34071. type: 'axis',
  34072. /**
  34073. * @private
  34074. */
  34075. _axisPointer: null,
  34076. /**
  34077. * @protected
  34078. * @type {string}
  34079. */
  34080. axisPointerClass: null,
  34081. /**
  34082. * @override
  34083. */
  34084. render: function (axisModel, ecModel, api, payload) {
  34085. // FIXME
  34086. // This process should proformed after coordinate systems updated
  34087. // (axis scale updated), and should be performed each time update.
  34088. // So put it here temporarily, although it is not appropriate to
  34089. // put a model-writing procedure in `view`.
  34090. this.axisPointerClass && fixValue(axisModel);
  34091. AxisView.superApply(this, 'render', arguments);
  34092. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  34093. },
  34094. /**
  34095. * Action handler.
  34096. * @public
  34097. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34098. * @param {module:echarts/model/Global} ecModel
  34099. * @param {module:echarts/ExtensionAPI} api
  34100. * @param {Object} payload
  34101. */
  34102. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  34103. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  34104. },
  34105. /**
  34106. * @override
  34107. */
  34108. remove: function (ecModel, api) {
  34109. var axisPointer = this._axisPointer;
  34110. axisPointer && axisPointer.remove(api);
  34111. AxisView.superApply(this, 'remove', arguments);
  34112. },
  34113. /**
  34114. * @override
  34115. */
  34116. dispose: function (ecModel, api) {
  34117. disposeAxisPointer(this, api);
  34118. AxisView.superApply(this, 'dispose', arguments);
  34119. }
  34120. });
  34121. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  34122. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  34123. if (!Clazz) {
  34124. return;
  34125. }
  34126. var axisPointerModel = getAxisPointerModel(axisModel);
  34127. axisPointerModel
  34128. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  34129. .render(axisModel, axisPointerModel, api, forceRender)
  34130. : disposeAxisPointer(axisView, api);
  34131. }
  34132. function disposeAxisPointer(axisView, ecModel, api) {
  34133. var axisPointer = axisView._axisPointer;
  34134. axisPointer && axisPointer.dispose(ecModel, api);
  34135. axisView._axisPointer = null;
  34136. }
  34137. var axisPointerClazz = [];
  34138. AxisView.registerAxisPointerClass = function (type, clazz) {
  34139. if (__DEV__) {
  34140. if (axisPointerClazz[type]) {
  34141. throw new Error('axisPointer ' + type + ' exists');
  34142. }
  34143. }
  34144. axisPointerClazz[type] = clazz;
  34145. };
  34146. AxisView.getAxisPointerClass = function (type) {
  34147. return type && axisPointerClazz[type];
  34148. };
  34149. /*
  34150. * Licensed to the Apache Software Foundation (ASF) under one
  34151. * or more contributor license agreements. See the NOTICE file
  34152. * distributed with this work for additional information
  34153. * regarding copyright ownership. The ASF licenses this file
  34154. * to you under the Apache License, Version 2.0 (the
  34155. * "License"); you may not use this file except in compliance
  34156. * with the License. You may obtain a copy of the License at
  34157. *
  34158. * http://www.apache.org/licenses/LICENSE-2.0
  34159. *
  34160. * Unless required by applicable law or agreed to in writing,
  34161. * software distributed under the License is distributed on an
  34162. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34163. * KIND, either express or implied. See the License for the
  34164. * specific language governing permissions and limitations
  34165. * under the License.
  34166. */
  34167. /**
  34168. * Can only be called after coordinate system creation stage.
  34169. * (Can be called before coordinate system update stage).
  34170. *
  34171. * @param {Object} opt {labelInside}
  34172. * @return {Object} {
  34173. * position, rotation, labelDirection, labelOffset,
  34174. * tickDirection, labelRotate, z2
  34175. * }
  34176. */
  34177. function layout$1(gridModel, axisModel, opt) {
  34178. opt = opt || {};
  34179. var grid = gridModel.coordinateSystem;
  34180. var axis = axisModel.axis;
  34181. var layout = {};
  34182. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  34183. var rawAxisPosition = axis.position;
  34184. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  34185. var axisDim = axis.dim;
  34186. var rect = grid.getRect();
  34187. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  34188. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  34189. var axisOffset = axisModel.get('offset') || 0;
  34190. var posBound = axisDim === 'x'
  34191. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  34192. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  34193. if (otherAxisOnZeroOf) {
  34194. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  34195. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  34196. }
  34197. // Axis position
  34198. layout.position = [
  34199. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  34200. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  34201. ];
  34202. // Axis rotation
  34203. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  34204. // Tick and label direction, x y is axisDim
  34205. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  34206. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  34207. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  34208. if (axisModel.get('axisTick.inside')) {
  34209. layout.tickDirection = -layout.tickDirection;
  34210. }
  34211. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  34212. layout.labelDirection = -layout.labelDirection;
  34213. }
  34214. // Special label rotation
  34215. var labelRotate = axisModel.get('axisLabel.rotate');
  34216. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  34217. // Over splitLine and splitArea
  34218. layout.z2 = 1;
  34219. return layout;
  34220. }
  34221. /*
  34222. * Licensed to the Apache Software Foundation (ASF) under one
  34223. * or more contributor license agreements. See the NOTICE file
  34224. * distributed with this work for additional information
  34225. * regarding copyright ownership. The ASF licenses this file
  34226. * to you under the Apache License, Version 2.0 (the
  34227. * "License"); you may not use this file except in compliance
  34228. * with the License. You may obtain a copy of the License at
  34229. *
  34230. * http://www.apache.org/licenses/LICENSE-2.0
  34231. *
  34232. * Unless required by applicable law or agreed to in writing,
  34233. * software distributed under the License is distributed on an
  34234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34235. * KIND, either express or implied. See the License for the
  34236. * specific language governing permissions and limitations
  34237. * under the License.
  34238. */
  34239. var axisBuilderAttrs = [
  34240. 'axisLine', 'axisTickLabel', 'axisName'
  34241. ];
  34242. var selfBuilderAttrs = [
  34243. 'splitArea', 'splitLine'
  34244. ];
  34245. // function getAlignWithLabel(model, axisModel) {
  34246. // var alignWithLabel = model.get('alignWithLabel');
  34247. // if (alignWithLabel === 'auto') {
  34248. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  34249. // }
  34250. // return alignWithLabel;
  34251. // }
  34252. var CartesianAxisView = AxisView.extend({
  34253. type: 'cartesianAxis',
  34254. axisPointerClass: 'CartesianAxisPointer',
  34255. /**
  34256. * @override
  34257. */
  34258. render: function (axisModel, ecModel, api, payload) {
  34259. this.group.removeAll();
  34260. var oldAxisGroup = this._axisGroup;
  34261. this._axisGroup = new Group();
  34262. this.group.add(this._axisGroup);
  34263. if (!axisModel.get('show')) {
  34264. return;
  34265. }
  34266. var gridModel = axisModel.getCoordSysModel();
  34267. var layout = layout$1(gridModel, axisModel);
  34268. var axisBuilder = new AxisBuilder(axisModel, layout);
  34269. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  34270. this._axisGroup.add(axisBuilder.getGroup());
  34271. each$1(selfBuilderAttrs, function (name) {
  34272. if (axisModel.get(name + '.show')) {
  34273. this['_' + name](axisModel, gridModel);
  34274. }
  34275. }, this);
  34276. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  34277. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  34278. },
  34279. remove: function () {
  34280. this._splitAreaColors = null;
  34281. },
  34282. /**
  34283. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34284. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34285. * @private
  34286. */
  34287. _splitLine: function (axisModel, gridModel) {
  34288. var axis = axisModel.axis;
  34289. if (axis.scale.isBlank()) {
  34290. return;
  34291. }
  34292. var splitLineModel = axisModel.getModel('splitLine');
  34293. var lineStyleModel = splitLineModel.getModel('lineStyle');
  34294. var lineColors = lineStyleModel.get('color');
  34295. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  34296. var gridRect = gridModel.coordinateSystem.getRect();
  34297. var isHorizontal = axis.isHorizontal();
  34298. var lineCount = 0;
  34299. var ticksCoords = axis.getTicksCoords({
  34300. tickModel: splitLineModel
  34301. });
  34302. var p1 = [];
  34303. var p2 = [];
  34304. // Simple optimization
  34305. // Batching the lines if color are the same
  34306. var lineStyle = lineStyleModel.getLineStyle();
  34307. for (var i = 0; i < ticksCoords.length; i++) {
  34308. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  34309. if (isHorizontal) {
  34310. p1[0] = tickCoord;
  34311. p1[1] = gridRect.y;
  34312. p2[0] = tickCoord;
  34313. p2[1] = gridRect.y + gridRect.height;
  34314. }
  34315. else {
  34316. p1[0] = gridRect.x;
  34317. p1[1] = tickCoord;
  34318. p2[0] = gridRect.x + gridRect.width;
  34319. p2[1] = tickCoord;
  34320. }
  34321. var colorIndex = (lineCount++) % lineColors.length;
  34322. var tickValue = ticksCoords[i].tickValue;
  34323. this._axisGroup.add(new Line(subPixelOptimizeLine({
  34324. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  34325. shape: {
  34326. x1: p1[0],
  34327. y1: p1[1],
  34328. x2: p2[0],
  34329. y2: p2[1]
  34330. },
  34331. style: defaults({
  34332. stroke: lineColors[colorIndex]
  34333. }, lineStyle),
  34334. silent: true
  34335. })));
  34336. }
  34337. },
  34338. /**
  34339. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  34340. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  34341. * @private
  34342. */
  34343. _splitArea: function (axisModel, gridModel) {
  34344. var axis = axisModel.axis;
  34345. if (axis.scale.isBlank()) {
  34346. return;
  34347. }
  34348. var splitAreaModel = axisModel.getModel('splitArea');
  34349. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  34350. var areaColors = areaStyleModel.get('color');
  34351. var gridRect = gridModel.coordinateSystem.getRect();
  34352. var ticksCoords = axis.getTicksCoords({
  34353. tickModel: splitAreaModel,
  34354. clamp: true
  34355. });
  34356. if (!ticksCoords.length) {
  34357. return;
  34358. }
  34359. // For Making appropriate splitArea animation, the color and anid
  34360. // should be corresponding to previous one if possible.
  34361. var areaColorsLen = areaColors.length;
  34362. var lastSplitAreaColors = this._splitAreaColors;
  34363. var newSplitAreaColors = createHashMap();
  34364. var colorIndex = 0;
  34365. if (lastSplitAreaColors) {
  34366. for (var i = 0; i < ticksCoords.length; i++) {
  34367. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  34368. if (cIndex != null) {
  34369. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  34370. break;
  34371. }
  34372. }
  34373. }
  34374. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  34375. var areaStyle = areaStyleModel.getAreaStyle();
  34376. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  34377. for (var i = 1; i < ticksCoords.length; i++) {
  34378. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  34379. var x;
  34380. var y;
  34381. var width;
  34382. var height;
  34383. if (axis.isHorizontal()) {
  34384. x = prev;
  34385. y = gridRect.y;
  34386. width = tickCoord - x;
  34387. height = gridRect.height;
  34388. prev = x + width;
  34389. }
  34390. else {
  34391. x = gridRect.x;
  34392. y = prev;
  34393. width = gridRect.width;
  34394. height = tickCoord - y;
  34395. prev = y + height;
  34396. }
  34397. var tickValue = ticksCoords[i - 1].tickValue;
  34398. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  34399. this._axisGroup.add(new Rect({
  34400. anid: tickValue != null ? 'area_' + tickValue : null,
  34401. shape: {
  34402. x: x,
  34403. y: y,
  34404. width: width,
  34405. height: height
  34406. },
  34407. style: defaults({
  34408. fill: areaColors[colorIndex]
  34409. }, areaStyle),
  34410. silent: true
  34411. }));
  34412. colorIndex = (colorIndex + 1) % areaColorsLen;
  34413. }
  34414. this._splitAreaColors = newSplitAreaColors;
  34415. }
  34416. });
  34417. CartesianAxisView.extend({
  34418. type: 'xAxis'
  34419. });
  34420. CartesianAxisView.extend({
  34421. type: 'yAxis'
  34422. });
  34423. /*
  34424. * Licensed to the Apache Software Foundation (ASF) under one
  34425. * or more contributor license agreements. See the NOTICE file
  34426. * distributed with this work for additional information
  34427. * regarding copyright ownership. The ASF licenses this file
  34428. * to you under the Apache License, Version 2.0 (the
  34429. * "License"); you may not use this file except in compliance
  34430. * with the License. You may obtain a copy of the License at
  34431. *
  34432. * http://www.apache.org/licenses/LICENSE-2.0
  34433. *
  34434. * Unless required by applicable law or agreed to in writing,
  34435. * software distributed under the License is distributed on an
  34436. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34437. * KIND, either express or implied. See the License for the
  34438. * specific language governing permissions and limitations
  34439. * under the License.
  34440. */
  34441. /*
  34442. * Licensed to the Apache Software Foundation (ASF) under one
  34443. * or more contributor license agreements. See the NOTICE file
  34444. * distributed with this work for additional information
  34445. * regarding copyright ownership. The ASF licenses this file
  34446. * to you under the Apache License, Version 2.0 (the
  34447. * "License"); you may not use this file except in compliance
  34448. * with the License. You may obtain a copy of the License at
  34449. *
  34450. * http://www.apache.org/licenses/LICENSE-2.0
  34451. *
  34452. * Unless required by applicable law or agreed to in writing,
  34453. * software distributed under the License is distributed on an
  34454. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34455. * KIND, either express or implied. See the License for the
  34456. * specific language governing permissions and limitations
  34457. * under the License.
  34458. */
  34459. // Grid view
  34460. extendComponentView({
  34461. type: 'grid',
  34462. render: function (gridModel, ecModel) {
  34463. this.group.removeAll();
  34464. if (gridModel.get('show')) {
  34465. this.group.add(new Rect({
  34466. shape: gridModel.coordinateSystem.getRect(),
  34467. style: defaults({
  34468. fill: gridModel.get('backgroundColor')
  34469. }, gridModel.getItemStyle()),
  34470. silent: true,
  34471. z2: -1
  34472. }));
  34473. }
  34474. }
  34475. });
  34476. registerPreprocessor(function (option) {
  34477. // Only create grid when need
  34478. if (option.xAxis && option.yAxis && !option.grid) {
  34479. option.grid = {};
  34480. }
  34481. });
  34482. /*
  34483. * Licensed to the Apache Software Foundation (ASF) under one
  34484. * or more contributor license agreements. See the NOTICE file
  34485. * distributed with this work for additional information
  34486. * regarding copyright ownership. The ASF licenses this file
  34487. * to you under the Apache License, Version 2.0 (the
  34488. * "License"); you may not use this file except in compliance
  34489. * with the License. You may obtain a copy of the License at
  34490. *
  34491. * http://www.apache.org/licenses/LICENSE-2.0
  34492. *
  34493. * Unless required by applicable law or agreed to in writing,
  34494. * software distributed under the License is distributed on an
  34495. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34496. * KIND, either express or implied. See the License for the
  34497. * specific language governing permissions and limitations
  34498. * under the License.
  34499. */
  34500. // In case developer forget to include grid component
  34501. registerVisual(visualSymbol('line', 'circle', 'line'));
  34502. registerLayout(layoutPoints('line'));
  34503. // Down sample after filter
  34504. registerProcessor(
  34505. PRIORITY.PROCESSOR.STATISTIC,
  34506. dataSample('line')
  34507. );
  34508. /*
  34509. * Licensed to the Apache Software Foundation (ASF) under one
  34510. * or more contributor license agreements. See the NOTICE file
  34511. * distributed with this work for additional information
  34512. * regarding copyright ownership. The ASF licenses this file
  34513. * to you under the Apache License, Version 2.0 (the
  34514. * "License"); you may not use this file except in compliance
  34515. * with the License. You may obtain a copy of the License at
  34516. *
  34517. * http://www.apache.org/licenses/LICENSE-2.0
  34518. *
  34519. * Unless required by applicable law or agreed to in writing,
  34520. * software distributed under the License is distributed on an
  34521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34522. * KIND, either express or implied. See the License for the
  34523. * specific language governing permissions and limitations
  34524. * under the License.
  34525. */
  34526. var BaseBarSeries = SeriesModel.extend({
  34527. type: 'series.__base_bar__',
  34528. getInitialData: function (option, ecModel) {
  34529. return createListFromArray(this.getSource(), this);
  34530. },
  34531. getMarkerPosition: function (value) {
  34532. var coordSys = this.coordinateSystem;
  34533. if (coordSys) {
  34534. // PENDING if clamp ?
  34535. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  34536. var data = this.getData();
  34537. var offset = data.getLayout('offset');
  34538. var size = data.getLayout('size');
  34539. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  34540. pt[offsetIndex] += offset + size / 2;
  34541. return pt;
  34542. }
  34543. return [NaN, NaN];
  34544. },
  34545. defaultOption: {
  34546. zlevel: 0, // 一级层叠
  34547. z: 2, // 二级层叠
  34548. coordinateSystem: 'cartesian2d',
  34549. legendHoverLink: true,
  34550. // stack: null
  34551. // Cartesian coordinate system
  34552. // xAxisIndex: 0,
  34553. // yAxisIndex: 0,
  34554. // 最小高度改为0
  34555. barMinHeight: 0,
  34556. // 最小角度为0,仅对极坐标系下的柱状图有效
  34557. barMinAngle: 0,
  34558. // cursor: null,
  34559. large: false,
  34560. largeThreshold: 400,
  34561. progressive: 3e3,
  34562. progressiveChunkMode: 'mod',
  34563. // barMaxWidth: null,
  34564. // 默认自适应
  34565. // barWidth: null,
  34566. // 柱间距离,默认为柱形宽度的30%,可设固定值
  34567. // barGap: '30%',
  34568. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  34569. // barCategoryGap: '20%',
  34570. // label: {
  34571. // show: false
  34572. // },
  34573. itemStyle: {},
  34574. emphasis: {}
  34575. }
  34576. });
  34577. /*
  34578. * Licensed to the Apache Software Foundation (ASF) under one
  34579. * or more contributor license agreements. See the NOTICE file
  34580. * distributed with this work for additional information
  34581. * regarding copyright ownership. The ASF licenses this file
  34582. * to you under the Apache License, Version 2.0 (the
  34583. * "License"); you may not use this file except in compliance
  34584. * with the License. You may obtain a copy of the License at
  34585. *
  34586. * http://www.apache.org/licenses/LICENSE-2.0
  34587. *
  34588. * Unless required by applicable law or agreed to in writing,
  34589. * software distributed under the License is distributed on an
  34590. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34591. * KIND, either express or implied. See the License for the
  34592. * specific language governing permissions and limitations
  34593. * under the License.
  34594. */
  34595. BaseBarSeries.extend({
  34596. type: 'series.bar',
  34597. dependencies: ['grid', 'polar'],
  34598. brushSelector: 'rect',
  34599. /**
  34600. * @override
  34601. */
  34602. getProgressive: function () {
  34603. // Do not support progressive in normal mode.
  34604. return this.get('large')
  34605. ? this.get('progressive')
  34606. : false;
  34607. },
  34608. /**
  34609. * @override
  34610. */
  34611. getProgressiveThreshold: function () {
  34612. // Do not support progressive in normal mode.
  34613. var progressiveThreshold = this.get('progressiveThreshold');
  34614. var largeThreshold = this.get('largeThreshold');
  34615. if (largeThreshold > progressiveThreshold) {
  34616. progressiveThreshold = largeThreshold;
  34617. }
  34618. return progressiveThreshold;
  34619. }
  34620. });
  34621. /*
  34622. * Licensed to the Apache Software Foundation (ASF) under one
  34623. * or more contributor license agreements. See the NOTICE file
  34624. * distributed with this work for additional information
  34625. * regarding copyright ownership. The ASF licenses this file
  34626. * to you under the Apache License, Version 2.0 (the
  34627. * "License"); you may not use this file except in compliance
  34628. * with the License. You may obtain a copy of the License at
  34629. *
  34630. * http://www.apache.org/licenses/LICENSE-2.0
  34631. *
  34632. * Unless required by applicable law or agreed to in writing,
  34633. * software distributed under the License is distributed on an
  34634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34635. * KIND, either express or implied. See the License for the
  34636. * specific language governing permissions and limitations
  34637. * under the License.
  34638. */
  34639. function setLabel(
  34640. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  34641. ) {
  34642. var labelModel = itemModel.getModel('label');
  34643. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34644. setLabelStyle(
  34645. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  34646. {
  34647. labelFetcher: seriesModel,
  34648. labelDataIndex: dataIndex,
  34649. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  34650. isRectText: true,
  34651. autoColor: color
  34652. }
  34653. );
  34654. fixPosition(normalStyle);
  34655. fixPosition(hoverStyle);
  34656. }
  34657. function fixPosition(style, labelPositionOutside) {
  34658. if (style.textPosition === 'outside') {
  34659. style.textPosition = labelPositionOutside;
  34660. }
  34661. }
  34662. /*
  34663. * Licensed to the Apache Software Foundation (ASF) under one
  34664. * or more contributor license agreements. See the NOTICE file
  34665. * distributed with this work for additional information
  34666. * regarding copyright ownership. The ASF licenses this file
  34667. * to you under the Apache License, Version 2.0 (the
  34668. * "License"); you may not use this file except in compliance
  34669. * with the License. You may obtain a copy of the License at
  34670. *
  34671. * http://www.apache.org/licenses/LICENSE-2.0
  34672. *
  34673. * Unless required by applicable law or agreed to in writing,
  34674. * software distributed under the License is distributed on an
  34675. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34676. * KIND, either express or implied. See the License for the
  34677. * specific language governing permissions and limitations
  34678. * under the License.
  34679. */
  34680. var getBarItemStyle = makeStyleMapper(
  34681. [
  34682. ['fill', 'color'],
  34683. ['stroke', 'borderColor'],
  34684. ['lineWidth', 'borderWidth'],
  34685. // Compatitable with 2
  34686. ['stroke', 'barBorderColor'],
  34687. ['lineWidth', 'barBorderWidth'],
  34688. ['opacity'],
  34689. ['shadowBlur'],
  34690. ['shadowOffsetX'],
  34691. ['shadowOffsetY'],
  34692. ['shadowColor']
  34693. ]
  34694. );
  34695. var barItemStyle = {
  34696. getBarItemStyle: function (excludes) {
  34697. var style = getBarItemStyle(this, excludes);
  34698. if (this.getBorderLineDash) {
  34699. var lineDash = this.getBorderLineDash();
  34700. lineDash && (style.lineDash = lineDash);
  34701. }
  34702. return style;
  34703. }
  34704. };
  34705. /*
  34706. * Licensed to the Apache Software Foundation (ASF) under one
  34707. * or more contributor license agreements. See the NOTICE file
  34708. * distributed with this work for additional information
  34709. * regarding copyright ownership. The ASF licenses this file
  34710. * to you under the Apache License, Version 2.0 (the
  34711. * "License"); you may not use this file except in compliance
  34712. * with the License. You may obtain a copy of the License at
  34713. *
  34714. * http://www.apache.org/licenses/LICENSE-2.0
  34715. *
  34716. * Unless required by applicable law or agreed to in writing,
  34717. * software distributed under the License is distributed on an
  34718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34719. * KIND, either express or implied. See the License for the
  34720. * specific language governing permissions and limitations
  34721. * under the License.
  34722. */
  34723. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  34724. // FIXME
  34725. // Just for compatible with ec2.
  34726. extend(Model.prototype, barItemStyle);
  34727. extendChartView({
  34728. type: 'bar',
  34729. render: function (seriesModel, ecModel, api) {
  34730. this._updateDrawMode(seriesModel);
  34731. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34732. if (coordinateSystemType === 'cartesian2d'
  34733. || coordinateSystemType === 'polar'
  34734. ) {
  34735. this._isLargeDraw
  34736. ? this._renderLarge(seriesModel, ecModel, api)
  34737. : this._renderNormal(seriesModel, ecModel, api);
  34738. }
  34739. else if (__DEV__) {
  34740. console.warn('Only cartesian2d and polar supported for bar.');
  34741. }
  34742. return this.group;
  34743. },
  34744. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  34745. this._clear();
  34746. this._updateDrawMode(seriesModel);
  34747. },
  34748. incrementalRender: function (params, seriesModel, ecModel, api) {
  34749. // Do not support progressive in normal mode.
  34750. this._incrementalRenderLarge(params, seriesModel);
  34751. },
  34752. _updateDrawMode: function (seriesModel) {
  34753. var isLargeDraw = seriesModel.pipelineContext.large;
  34754. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  34755. this._isLargeDraw = isLargeDraw;
  34756. this._clear();
  34757. }
  34758. },
  34759. _renderNormal: function (seriesModel, ecModel, api) {
  34760. var group = this.group;
  34761. var data = seriesModel.getData();
  34762. var oldData = this._data;
  34763. var coord = seriesModel.coordinateSystem;
  34764. var baseAxis = coord.getBaseAxis();
  34765. var isHorizontalOrRadial;
  34766. if (coord.type === 'cartesian2d') {
  34767. isHorizontalOrRadial = baseAxis.isHorizontal();
  34768. }
  34769. else if (coord.type === 'polar') {
  34770. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34771. }
  34772. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34773. data.diff(oldData)
  34774. .add(function (dataIndex) {
  34775. if (!data.hasValue(dataIndex)) {
  34776. return;
  34777. }
  34778. var itemModel = data.getItemModel(dataIndex);
  34779. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34780. var el = elementCreator[coord.type](
  34781. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  34782. );
  34783. data.setItemGraphicEl(dataIndex, el);
  34784. group.add(el);
  34785. updateStyle(
  34786. el, data, dataIndex, itemModel, layout,
  34787. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34788. );
  34789. })
  34790. .update(function (newIndex, oldIndex) {
  34791. var el = oldData.getItemGraphicEl(oldIndex);
  34792. if (!data.hasValue(newIndex)) {
  34793. group.remove(el);
  34794. return;
  34795. }
  34796. var itemModel = data.getItemModel(newIndex);
  34797. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34798. if (el) {
  34799. updateProps(el, {shape: layout}, animationModel, newIndex);
  34800. }
  34801. else {
  34802. el = elementCreator[coord.type](
  34803. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  34804. );
  34805. }
  34806. data.setItemGraphicEl(newIndex, el);
  34807. // Add back
  34808. group.add(el);
  34809. updateStyle(
  34810. el, data, newIndex, itemModel, layout,
  34811. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34812. );
  34813. })
  34814. .remove(function (dataIndex) {
  34815. var el = oldData.getItemGraphicEl(dataIndex);
  34816. if (coord.type === 'cartesian2d') {
  34817. el && removeRect(dataIndex, animationModel, el);
  34818. }
  34819. else {
  34820. el && removeSector(dataIndex, animationModel, el);
  34821. }
  34822. })
  34823. .execute();
  34824. this._data = data;
  34825. },
  34826. _renderLarge: function (seriesModel, ecModel, api) {
  34827. this._clear();
  34828. createLarge(seriesModel, this.group);
  34829. },
  34830. _incrementalRenderLarge: function (params, seriesModel) {
  34831. createLarge(seriesModel, this.group, true);
  34832. },
  34833. dispose: noop,
  34834. remove: function (ecModel) {
  34835. this._clear(ecModel);
  34836. },
  34837. _clear: function (ecModel) {
  34838. var group = this.group;
  34839. var data = this._data;
  34840. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  34841. data.eachItemGraphicEl(function (el) {
  34842. if (el.type === 'sector') {
  34843. removeSector(el.dataIndex, ecModel, el);
  34844. }
  34845. else {
  34846. removeRect(el.dataIndex, ecModel, el);
  34847. }
  34848. });
  34849. }
  34850. else {
  34851. group.removeAll();
  34852. }
  34853. this._data = null;
  34854. }
  34855. });
  34856. var elementCreator = {
  34857. cartesian2d: function (
  34858. data, dataIndex, itemModel, layout, isHorizontal,
  34859. animationModel, isUpdate
  34860. ) {
  34861. var rect = new Rect({shape: extend({}, layout)});
  34862. // Animation
  34863. if (animationModel) {
  34864. var rectShape = rect.shape;
  34865. var animateProperty = isHorizontal ? 'height' : 'width';
  34866. var animateTarget = {};
  34867. rectShape[animateProperty] = 0;
  34868. animateTarget[animateProperty] = layout[animateProperty];
  34869. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  34870. shape: animateTarget
  34871. }, animationModel, dataIndex);
  34872. }
  34873. return rect;
  34874. },
  34875. polar: function (
  34876. data, dataIndex, itemModel, layout, isRadial,
  34877. animationModel, isUpdate
  34878. ) {
  34879. // Keep the same logic with bar in catesion: use end value to control
  34880. // direction. Notice that if clockwise is true (by default), the sector
  34881. // will always draw clockwisely, no matter whether endAngle is greater
  34882. // or less than startAngle.
  34883. var clockwise = layout.startAngle < layout.endAngle;
  34884. var sector = new Sector({
  34885. shape: defaults({clockwise: clockwise}, layout)
  34886. });
  34887. // Animation
  34888. if (animationModel) {
  34889. var sectorShape = sector.shape;
  34890. var animateProperty = isRadial ? 'r' : 'endAngle';
  34891. var animateTarget = {};
  34892. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  34893. animateTarget[animateProperty] = layout[animateProperty];
  34894. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  34895. shape: animateTarget
  34896. }, animationModel, dataIndex);
  34897. }
  34898. return sector;
  34899. }
  34900. };
  34901. function removeRect(dataIndex, animationModel, el) {
  34902. // Not show text when animating
  34903. el.style.text = null;
  34904. updateProps(el, {
  34905. shape: {
  34906. width: 0
  34907. }
  34908. }, animationModel, dataIndex, function () {
  34909. el.parent && el.parent.remove(el);
  34910. });
  34911. }
  34912. function removeSector(dataIndex, animationModel, el) {
  34913. // Not show text when animating
  34914. el.style.text = null;
  34915. updateProps(el, {
  34916. shape: {
  34917. r: el.shape.r0
  34918. }
  34919. }, animationModel, dataIndex, function () {
  34920. el.parent && el.parent.remove(el);
  34921. });
  34922. }
  34923. var getLayout = {
  34924. cartesian2d: function (data, dataIndex, itemModel) {
  34925. var layout = data.getItemLayout(dataIndex);
  34926. var fixedLineWidth = getLineWidth(itemModel, layout);
  34927. // fix layout with lineWidth
  34928. var signX = layout.width > 0 ? 1 : -1;
  34929. var signY = layout.height > 0 ? 1 : -1;
  34930. return {
  34931. x: layout.x + signX * fixedLineWidth / 2,
  34932. y: layout.y + signY * fixedLineWidth / 2,
  34933. width: layout.width - signX * fixedLineWidth,
  34934. height: layout.height - signY * fixedLineWidth
  34935. };
  34936. },
  34937. polar: function (data, dataIndex, itemModel) {
  34938. var layout = data.getItemLayout(dataIndex);
  34939. return {
  34940. cx: layout.cx,
  34941. cy: layout.cy,
  34942. r0: layout.r0,
  34943. r: layout.r,
  34944. startAngle: layout.startAngle,
  34945. endAngle: layout.endAngle
  34946. };
  34947. }
  34948. };
  34949. function updateStyle(
  34950. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  34951. ) {
  34952. var color = data.getItemVisual(dataIndex, 'color');
  34953. var opacity = data.getItemVisual(dataIndex, 'opacity');
  34954. var itemStyleModel = itemModel.getModel('itemStyle');
  34955. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  34956. if (!isPolar) {
  34957. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  34958. }
  34959. el.useStyle(defaults(
  34960. {
  34961. fill: color,
  34962. opacity: opacity
  34963. },
  34964. itemStyleModel.getBarItemStyle()
  34965. ));
  34966. var cursorStyle = itemModel.getShallow('cursor');
  34967. cursorStyle && el.attr('cursor', cursorStyle);
  34968. var labelPositionOutside = isHorizontal
  34969. ? (layout.height > 0 ? 'bottom' : 'top')
  34970. : (layout.width > 0 ? 'left' : 'right');
  34971. if (!isPolar) {
  34972. setLabel(
  34973. el.style, hoverStyle, itemModel, color,
  34974. seriesModel, dataIndex, labelPositionOutside
  34975. );
  34976. }
  34977. setHoverStyle(el, hoverStyle);
  34978. }
  34979. // In case width or height are too small.
  34980. function getLineWidth(itemModel, rawLayout) {
  34981. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  34982. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  34983. }
  34984. var LargePath = Path.extend({
  34985. type: 'largeBar',
  34986. shape: {points: []},
  34987. buildPath: function (ctx, shape) {
  34988. // Drawing lines is more efficient than drawing
  34989. // a whole line or drawing rects.
  34990. var points = shape.points;
  34991. var startPoint = this.__startPoint;
  34992. var valueIdx = this.__valueIdx;
  34993. for (var i = 0; i < points.length; i += 2) {
  34994. startPoint[this.__valueIdx] = points[i + valueIdx];
  34995. ctx.moveTo(startPoint[0], startPoint[1]);
  34996. ctx.lineTo(points[i], points[i + 1]);
  34997. }
  34998. }
  34999. });
  35000. function createLarge(seriesModel, group, incremental) {
  35001. // TODO support polar
  35002. var data = seriesModel.getData();
  35003. var startPoint = [];
  35004. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  35005. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  35006. var el = new LargePath({
  35007. shape: {points: data.getLayout('largePoints')},
  35008. incremental: !!incremental,
  35009. __startPoint: startPoint,
  35010. __valueIdx: valueIdx
  35011. });
  35012. group.add(el);
  35013. setLargeStyle(el, seriesModel, data);
  35014. }
  35015. function setLargeStyle(el, seriesModel, data) {
  35016. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  35017. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  35018. el.useStyle(itemStyle);
  35019. el.style.fill = null;
  35020. el.style.stroke = borderColor;
  35021. el.style.lineWidth = data.getLayout('barWidth');
  35022. }
  35023. /*
  35024. * Licensed to the Apache Software Foundation (ASF) under one
  35025. * or more contributor license agreements. See the NOTICE file
  35026. * distributed with this work for additional information
  35027. * regarding copyright ownership. The ASF licenses this file
  35028. * to you under the Apache License, Version 2.0 (the
  35029. * "License"); you may not use this file except in compliance
  35030. * with the License. You may obtain a copy of the License at
  35031. *
  35032. * http://www.apache.org/licenses/LICENSE-2.0
  35033. *
  35034. * Unless required by applicable law or agreed to in writing,
  35035. * software distributed under the License is distributed on an
  35036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35037. * KIND, either express or implied. See the License for the
  35038. * specific language governing permissions and limitations
  35039. * under the License.
  35040. */
  35041. // In case developer forget to include grid component
  35042. registerLayout(curry(layout, 'bar'));
  35043. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  35044. registerLayout(largeLayout);
  35045. registerVisual({
  35046. seriesType: 'bar',
  35047. reset: function (seriesModel) {
  35048. // Visual coding for legend
  35049. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  35050. }
  35051. });
  35052. /*
  35053. * Licensed to the Apache Software Foundation (ASF) under one
  35054. * or more contributor license agreements. See the NOTICE file
  35055. * distributed with this work for additional information
  35056. * regarding copyright ownership. The ASF licenses this file
  35057. * to you under the Apache License, Version 2.0 (the
  35058. * "License"); you may not use this file except in compliance
  35059. * with the License. You may obtain a copy of the License at
  35060. *
  35061. * http://www.apache.org/licenses/LICENSE-2.0
  35062. *
  35063. * Unless required by applicable law or agreed to in writing,
  35064. * software distributed under the License is distributed on an
  35065. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35066. * KIND, either express or implied. See the License for the
  35067. * specific language governing permissions and limitations
  35068. * under the License.
  35069. */
  35070. /**
  35071. * [Usage]:
  35072. * (1)
  35073. * createListSimply(seriesModel, ['value']);
  35074. * (2)
  35075. * createListSimply(seriesModel, {
  35076. * coordDimensions: ['value'],
  35077. * dimensionsCount: 5
  35078. * });
  35079. *
  35080. * @param {module:echarts/model/Series} seriesModel
  35081. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  35082. * The options in opt, see `echarts/data/helper/createDimensions`
  35083. * @param {Array.<string>} [nameList]
  35084. * @return {module:echarts/data/List}
  35085. */
  35086. var createListSimply = function (seriesModel, opt, nameList) {
  35087. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  35088. var source = seriesModel.getSource();
  35089. var dimensionsInfo = createDimensions(source, opt);
  35090. var list = new List(dimensionsInfo, seriesModel);
  35091. list.initData(source, nameList);
  35092. return list;
  35093. };
  35094. /*
  35095. * Licensed to the Apache Software Foundation (ASF) under one
  35096. * or more contributor license agreements. See the NOTICE file
  35097. * distributed with this work for additional information
  35098. * regarding copyright ownership. The ASF licenses this file
  35099. * to you under the Apache License, Version 2.0 (the
  35100. * "License"); you may not use this file except in compliance
  35101. * with the License. You may obtain a copy of the License at
  35102. *
  35103. * http://www.apache.org/licenses/LICENSE-2.0
  35104. *
  35105. * Unless required by applicable law or agreed to in writing,
  35106. * software distributed under the License is distributed on an
  35107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35108. * KIND, either express or implied. See the License for the
  35109. * specific language governing permissions and limitations
  35110. * under the License.
  35111. */
  35112. /**
  35113. * Data selectable mixin for chart series.
  35114. * To eanble data select, option of series must have `selectedMode`.
  35115. * And each data item will use `selected` to toggle itself selected status
  35116. */
  35117. var dataSelectableMixin = {
  35118. /**
  35119. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  35120. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  35121. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  35122. */
  35123. updateSelectedMap: function (targetList) {
  35124. this._targetList = isArray(targetList) ? targetList.slice() : [];
  35125. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  35126. targetMap.set(target.name, target);
  35127. return targetMap;
  35128. }, createHashMap());
  35129. },
  35130. /**
  35131. * Either name or id should be passed as input here.
  35132. * If both of them are defined, id is used.
  35133. *
  35134. * @param {string|undefined} name name of data
  35135. * @param {number|undefined} id dataIndex of data
  35136. */
  35137. // PENGING If selectedMode is null ?
  35138. select: function (name, id) {
  35139. var target = id != null
  35140. ? this._targetList[id]
  35141. : this._selectTargetMap.get(name);
  35142. var selectedMode = this.get('selectedMode');
  35143. if (selectedMode === 'single') {
  35144. this._selectTargetMap.each(function (target) {
  35145. target.selected = false;
  35146. });
  35147. }
  35148. target && (target.selected = true);
  35149. },
  35150. /**
  35151. * Either name or id should be passed as input here.
  35152. * If both of them are defined, id is used.
  35153. *
  35154. * @param {string|undefined} name name of data
  35155. * @param {number|undefined} id dataIndex of data
  35156. */
  35157. unSelect: function (name, id) {
  35158. var target = id != null
  35159. ? this._targetList[id]
  35160. : this._selectTargetMap.get(name);
  35161. // var selectedMode = this.get('selectedMode');
  35162. // selectedMode !== 'single' && target && (target.selected = false);
  35163. target && (target.selected = false);
  35164. },
  35165. /**
  35166. * Either name or id should be passed as input here.
  35167. * If both of them are defined, id is used.
  35168. *
  35169. * @param {string|undefined} name name of data
  35170. * @param {number|undefined} id dataIndex of data
  35171. */
  35172. toggleSelected: function (name, id) {
  35173. var target = id != null
  35174. ? this._targetList[id]
  35175. : this._selectTargetMap.get(name);
  35176. if (target != null) {
  35177. this[target.selected ? 'unSelect' : 'select'](name, id);
  35178. return target.selected;
  35179. }
  35180. },
  35181. /**
  35182. * Either name or id should be passed as input here.
  35183. * If both of them are defined, id is used.
  35184. *
  35185. * @param {string|undefined} name name of data
  35186. * @param {number|undefined} id dataIndex of data
  35187. */
  35188. isSelected: function (name, id) {
  35189. var target = id != null
  35190. ? this._targetList[id]
  35191. : this._selectTargetMap.get(name);
  35192. return target && target.selected;
  35193. }
  35194. };
  35195. /*
  35196. * Licensed to the Apache Software Foundation (ASF) under one
  35197. * or more contributor license agreements. See the NOTICE file
  35198. * distributed with this work for additional information
  35199. * regarding copyright ownership. The ASF licenses this file
  35200. * to you under the Apache License, Version 2.0 (the
  35201. * "License"); you may not use this file except in compliance
  35202. * with the License. You may obtain a copy of the License at
  35203. *
  35204. * http://www.apache.org/licenses/LICENSE-2.0
  35205. *
  35206. * Unless required by applicable law or agreed to in writing,
  35207. * software distributed under the License is distributed on an
  35208. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35209. * KIND, either express or implied. See the License for the
  35210. * specific language governing permissions and limitations
  35211. * under the License.
  35212. */
  35213. var PieSeries = extendSeriesModel({
  35214. type: 'series.pie',
  35215. // Overwrite
  35216. init: function (option) {
  35217. PieSeries.superApply(this, 'init', arguments);
  35218. // Enable legend selection for each data item
  35219. // Use a function instead of direct access because data reference may changed
  35220. this.legendDataProvider = function () {
  35221. return this.getRawData();
  35222. };
  35223. this.updateSelectedMap(this._createSelectableList());
  35224. this._defaultLabelLine(option);
  35225. },
  35226. // Overwrite
  35227. mergeOption: function (newOption) {
  35228. PieSeries.superCall(this, 'mergeOption', newOption);
  35229. this.updateSelectedMap(this._createSelectableList());
  35230. },
  35231. getInitialData: function (option, ecModel) {
  35232. return createListSimply(this, ['value']);
  35233. },
  35234. _createSelectableList: function () {
  35235. var data = this.getRawData();
  35236. var valueDim = data.mapDimension('value');
  35237. var targetList = [];
  35238. for (var i = 0, len = data.count(); i < len; i++) {
  35239. targetList.push({
  35240. name: data.getName(i),
  35241. value: data.get(valueDim, i),
  35242. selected: retrieveRawAttr(data, i, 'selected')
  35243. });
  35244. }
  35245. return targetList;
  35246. },
  35247. // Overwrite
  35248. getDataParams: function (dataIndex) {
  35249. var data = this.getData();
  35250. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  35251. // FIXME toFixed?
  35252. var valueList = [];
  35253. data.each(data.mapDimension('value'), function (value) {
  35254. valueList.push(value);
  35255. });
  35256. params.percent = getPercentWithPrecision(
  35257. valueList,
  35258. dataIndex,
  35259. data.hostModel.get('percentPrecision')
  35260. );
  35261. params.$vars.push('percent');
  35262. return params;
  35263. },
  35264. _defaultLabelLine: function (option) {
  35265. // Extend labelLine emphasis
  35266. defaultEmphasis(option, 'labelLine', ['show']);
  35267. var labelLineNormalOpt = option.labelLine;
  35268. var labelLineEmphasisOpt = option.emphasis.labelLine;
  35269. // Not show label line if `label.normal.show = false`
  35270. labelLineNormalOpt.show = labelLineNormalOpt.show
  35271. && option.label.show;
  35272. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  35273. && option.emphasis.label.show;
  35274. },
  35275. defaultOption: {
  35276. zlevel: 0,
  35277. z: 2,
  35278. legendHoverLink: true,
  35279. hoverAnimation: true,
  35280. // 默认全局居中
  35281. center: ['50%', '50%'],
  35282. radius: [0, '75%'],
  35283. // 默认顺时针
  35284. clockwise: true,
  35285. startAngle: 90,
  35286. // 最小角度改为0
  35287. minAngle: 0,
  35288. // 选中时扇区偏移量
  35289. selectedOffset: 10,
  35290. // 高亮扇区偏移量
  35291. hoverOffset: 10,
  35292. // If use strategy to avoid label overlapping
  35293. avoidLabelOverlap: true,
  35294. // 选择模式,默认关闭,可选single,multiple
  35295. // selectedMode: false,
  35296. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  35297. // roseType: null,
  35298. percentPrecision: 2,
  35299. // If still show when all data zero.
  35300. stillShowZeroSum: true,
  35301. // cursor: null,
  35302. label: {
  35303. // If rotate around circle
  35304. rotate: false,
  35305. show: true,
  35306. // 'outer', 'inside', 'center'
  35307. position: 'outer'
  35308. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35309. // 默认使用全局文本样式,详见TEXTSTYLE
  35310. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  35311. },
  35312. // Enabled when label.normal.position is 'outer'
  35313. labelLine: {
  35314. show: true,
  35315. // 引导线两段中的第一段长度
  35316. length: 15,
  35317. // 引导线两段中的第二段长度
  35318. length2: 15,
  35319. smooth: false,
  35320. lineStyle: {
  35321. // color: 各异,
  35322. width: 1,
  35323. type: 'solid'
  35324. }
  35325. },
  35326. itemStyle: {
  35327. borderWidth: 1
  35328. },
  35329. // Animation type canbe expansion, scale
  35330. animationType: 'expansion',
  35331. animationEasing: 'cubicOut'
  35332. }
  35333. });
  35334. mixin(PieSeries, dataSelectableMixin);
  35335. /*
  35336. * Licensed to the Apache Software Foundation (ASF) under one
  35337. * or more contributor license agreements. See the NOTICE file
  35338. * distributed with this work for additional information
  35339. * regarding copyright ownership. The ASF licenses this file
  35340. * to you under the Apache License, Version 2.0 (the
  35341. * "License"); you may not use this file except in compliance
  35342. * with the License. You may obtain a copy of the License at
  35343. *
  35344. * http://www.apache.org/licenses/LICENSE-2.0
  35345. *
  35346. * Unless required by applicable law or agreed to in writing,
  35347. * software distributed under the License is distributed on an
  35348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35349. * KIND, either express or implied. See the License for the
  35350. * specific language governing permissions and limitations
  35351. * under the License.
  35352. */
  35353. /**
  35354. * @param {module:echarts/model/Series} seriesModel
  35355. * @param {boolean} hasAnimation
  35356. * @inner
  35357. */
  35358. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  35359. var data = seriesModel.getData();
  35360. var dataIndex = this.dataIndex;
  35361. var name = data.getName(dataIndex);
  35362. var selectedOffset = seriesModel.get('selectedOffset');
  35363. api.dispatchAction({
  35364. type: 'pieToggleSelect',
  35365. from: uid,
  35366. name: name,
  35367. seriesId: seriesModel.id
  35368. });
  35369. data.each(function (idx) {
  35370. toggleItemSelected(
  35371. data.getItemGraphicEl(idx),
  35372. data.getItemLayout(idx),
  35373. seriesModel.isSelected(data.getName(idx)),
  35374. selectedOffset,
  35375. hasAnimation
  35376. );
  35377. });
  35378. }
  35379. /**
  35380. * @param {module:zrender/graphic/Sector} el
  35381. * @param {Object} layout
  35382. * @param {boolean} isSelected
  35383. * @param {number} selectedOffset
  35384. * @param {boolean} hasAnimation
  35385. * @inner
  35386. */
  35387. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  35388. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35389. var dx = Math.cos(midAngle);
  35390. var dy = Math.sin(midAngle);
  35391. var offset = isSelected ? selectedOffset : 0;
  35392. var position = [dx * offset, dy * offset];
  35393. hasAnimation
  35394. // animateTo will stop revious animation like update transition
  35395. ? el.animate()
  35396. .when(200, {
  35397. position: position
  35398. })
  35399. .start('bounceOut')
  35400. : el.attr('position', position);
  35401. }
  35402. /**
  35403. * Piece of pie including Sector, Label, LabelLine
  35404. * @constructor
  35405. * @extends {module:zrender/graphic/Group}
  35406. */
  35407. function PiePiece(data, idx) {
  35408. Group.call(this);
  35409. var sector = new Sector({
  35410. z2: 2
  35411. });
  35412. var polyline = new Polyline();
  35413. var text = new Text();
  35414. this.add(sector);
  35415. this.add(polyline);
  35416. this.add(text);
  35417. this.updateData(data, idx, true);
  35418. // Hover to change label and labelLine
  35419. function onEmphasis() {
  35420. polyline.ignore = polyline.hoverIgnore;
  35421. text.ignore = text.hoverIgnore;
  35422. }
  35423. function onNormal() {
  35424. polyline.ignore = polyline.normalIgnore;
  35425. text.ignore = text.normalIgnore;
  35426. }
  35427. this.on('emphasis', onEmphasis)
  35428. .on('normal', onNormal)
  35429. .on('mouseover', onEmphasis)
  35430. .on('mouseout', onNormal);
  35431. }
  35432. var piePieceProto = PiePiece.prototype;
  35433. piePieceProto.updateData = function (data, idx, firstCreate) {
  35434. var sector = this.childAt(0);
  35435. var seriesModel = data.hostModel;
  35436. var itemModel = data.getItemModel(idx);
  35437. var layout = data.getItemLayout(idx);
  35438. var sectorShape = extend({}, layout);
  35439. sectorShape.label = null;
  35440. if (firstCreate) {
  35441. sector.setShape(sectorShape);
  35442. var animationType = seriesModel.getShallow('animationType');
  35443. if (animationType === 'scale') {
  35444. sector.shape.r = layout.r0;
  35445. initProps(sector, {
  35446. shape: {
  35447. r: layout.r
  35448. }
  35449. }, seriesModel, idx);
  35450. }
  35451. // Expansion
  35452. else {
  35453. sector.shape.endAngle = layout.startAngle;
  35454. updateProps(sector, {
  35455. shape: {
  35456. endAngle: layout.endAngle
  35457. }
  35458. }, seriesModel, idx);
  35459. }
  35460. }
  35461. else {
  35462. updateProps(sector, {
  35463. shape: sectorShape
  35464. }, seriesModel, idx);
  35465. }
  35466. // Update common style
  35467. var visualColor = data.getItemVisual(idx, 'color');
  35468. sector.useStyle(
  35469. defaults(
  35470. {
  35471. lineJoin: 'bevel',
  35472. fill: visualColor
  35473. },
  35474. itemModel.getModel('itemStyle').getItemStyle()
  35475. )
  35476. );
  35477. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  35478. var cursorStyle = itemModel.getShallow('cursor');
  35479. cursorStyle && sector.attr('cursor', cursorStyle);
  35480. // Toggle selected
  35481. toggleItemSelected(
  35482. this,
  35483. data.getItemLayout(idx),
  35484. seriesModel.isSelected(null, idx),
  35485. seriesModel.get('selectedOffset'),
  35486. seriesModel.get('animation')
  35487. );
  35488. function onEmphasis() {
  35489. // Sector may has animation of updating data. Force to move to the last frame
  35490. // Or it may stopped on the wrong shape
  35491. sector.stopAnimation(true);
  35492. sector.animateTo({
  35493. shape: {
  35494. r: layout.r + seriesModel.get('hoverOffset')
  35495. }
  35496. }, 300, 'elasticOut');
  35497. }
  35498. function onNormal() {
  35499. sector.stopAnimation(true);
  35500. sector.animateTo({
  35501. shape: {
  35502. r: layout.r
  35503. }
  35504. }, 300, 'elasticOut');
  35505. }
  35506. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  35507. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  35508. sector
  35509. .on('mouseover', onEmphasis)
  35510. .on('mouseout', onNormal)
  35511. .on('emphasis', onEmphasis)
  35512. .on('normal', onNormal);
  35513. }
  35514. this._updateLabel(data, idx);
  35515. setHoverStyle(this);
  35516. };
  35517. piePieceProto._updateLabel = function (data, idx) {
  35518. var labelLine = this.childAt(1);
  35519. var labelText = this.childAt(2);
  35520. var seriesModel = data.hostModel;
  35521. var itemModel = data.getItemModel(idx);
  35522. var layout = data.getItemLayout(idx);
  35523. var labelLayout = layout.label;
  35524. var visualColor = data.getItemVisual(idx, 'color');
  35525. updateProps(labelLine, {
  35526. shape: {
  35527. points: labelLayout.linePoints || [
  35528. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  35529. ]
  35530. }
  35531. }, seriesModel, idx);
  35532. updateProps(labelText, {
  35533. style: {
  35534. x: labelLayout.x,
  35535. y: labelLayout.y
  35536. }
  35537. }, seriesModel, idx);
  35538. labelText.attr({
  35539. rotation: labelLayout.rotation,
  35540. origin: [labelLayout.x, labelLayout.y],
  35541. z2: 10
  35542. });
  35543. var labelModel = itemModel.getModel('label');
  35544. var labelHoverModel = itemModel.getModel('emphasis.label');
  35545. var labelLineModel = itemModel.getModel('labelLine');
  35546. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35547. var visualColor = data.getItemVisual(idx, 'color');
  35548. setLabelStyle(
  35549. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  35550. {
  35551. labelFetcher: data.hostModel,
  35552. labelDataIndex: idx,
  35553. defaultText: data.getName(idx),
  35554. autoColor: visualColor,
  35555. useInsideStyle: !!labelLayout.inside
  35556. },
  35557. {
  35558. textAlign: labelLayout.textAlign,
  35559. textVerticalAlign: labelLayout.verticalAlign,
  35560. opacity: data.getItemVisual(idx, 'opacity')
  35561. }
  35562. );
  35563. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35564. labelText.hoverIgnore = !labelHoverModel.get('show');
  35565. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35566. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  35567. // Default use item visual color
  35568. labelLine.setStyle({
  35569. stroke: visualColor,
  35570. opacity: data.getItemVisual(idx, 'opacity')
  35571. });
  35572. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35573. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35574. var smooth = labelLineModel.get('smooth');
  35575. if (smooth && smooth === true) {
  35576. smooth = 0.4;
  35577. }
  35578. labelLine.setShape({
  35579. smooth: smooth
  35580. });
  35581. };
  35582. inherits(PiePiece, Group);
  35583. // Pie view
  35584. var PieView = Chart.extend({
  35585. type: 'pie',
  35586. init: function () {
  35587. var sectorGroup = new Group();
  35588. this._sectorGroup = sectorGroup;
  35589. },
  35590. render: function (seriesModel, ecModel, api, payload) {
  35591. if (payload && (payload.from === this.uid)) {
  35592. return;
  35593. }
  35594. var data = seriesModel.getData();
  35595. var oldData = this._data;
  35596. var group = this.group;
  35597. var hasAnimation = ecModel.get('animation');
  35598. var isFirstRender = !oldData;
  35599. var animationType = seriesModel.get('animationType');
  35600. var onSectorClick = curry(
  35601. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  35602. );
  35603. var selectedMode = seriesModel.get('selectedMode');
  35604. data.diff(oldData)
  35605. .add(function (idx) {
  35606. var piePiece = new PiePiece(data, idx);
  35607. // Default expansion animation
  35608. if (isFirstRender && animationType !== 'scale') {
  35609. piePiece.eachChild(function (child) {
  35610. child.stopAnimation(true);
  35611. });
  35612. }
  35613. selectedMode && piePiece.on('click', onSectorClick);
  35614. data.setItemGraphicEl(idx, piePiece);
  35615. group.add(piePiece);
  35616. })
  35617. .update(function (newIdx, oldIdx) {
  35618. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35619. piePiece.updateData(data, newIdx);
  35620. piePiece.off('click');
  35621. selectedMode && piePiece.on('click', onSectorClick);
  35622. group.add(piePiece);
  35623. data.setItemGraphicEl(newIdx, piePiece);
  35624. })
  35625. .remove(function (idx) {
  35626. var piePiece = oldData.getItemGraphicEl(idx);
  35627. group.remove(piePiece);
  35628. })
  35629. .execute();
  35630. if (
  35631. hasAnimation && isFirstRender && data.count() > 0
  35632. // Default expansion animation
  35633. && animationType !== 'scale'
  35634. ) {
  35635. var shape = data.getItemLayout(0);
  35636. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35637. var removeClipPath = bind(group.removeClipPath, group);
  35638. group.setClipPath(this._createClipPath(
  35639. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  35640. ));
  35641. }
  35642. else {
  35643. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  35644. group.removeClipPath();
  35645. }
  35646. this._data = data;
  35647. },
  35648. dispose: function () {},
  35649. _createClipPath: function (
  35650. cx, cy, r, startAngle, clockwise, cb, seriesModel
  35651. ) {
  35652. var clipPath = new Sector({
  35653. shape: {
  35654. cx: cx,
  35655. cy: cy,
  35656. r0: 0,
  35657. r: r,
  35658. startAngle: startAngle,
  35659. endAngle: startAngle,
  35660. clockwise: clockwise
  35661. }
  35662. });
  35663. initProps(clipPath, {
  35664. shape: {
  35665. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35666. }
  35667. }, seriesModel, cb);
  35668. return clipPath;
  35669. },
  35670. /**
  35671. * @implement
  35672. */
  35673. containPoint: function (point, seriesModel) {
  35674. var data = seriesModel.getData();
  35675. var itemLayout = data.getItemLayout(0);
  35676. if (itemLayout) {
  35677. var dx = point[0] - itemLayout.cx;
  35678. var dy = point[1] - itemLayout.cy;
  35679. var radius = Math.sqrt(dx * dx + dy * dy);
  35680. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35681. }
  35682. }
  35683. });
  35684. /*
  35685. * Licensed to the Apache Software Foundation (ASF) under one
  35686. * or more contributor license agreements. See the NOTICE file
  35687. * distributed with this work for additional information
  35688. * regarding copyright ownership. The ASF licenses this file
  35689. * to you under the Apache License, Version 2.0 (the
  35690. * "License"); you may not use this file except in compliance
  35691. * with the License. You may obtain a copy of the License at
  35692. *
  35693. * http://www.apache.org/licenses/LICENSE-2.0
  35694. *
  35695. * Unless required by applicable law or agreed to in writing,
  35696. * software distributed under the License is distributed on an
  35697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35698. * KIND, either express or implied. See the License for the
  35699. * specific language governing permissions and limitations
  35700. * under the License.
  35701. */
  35702. var createDataSelectAction = function (seriesType, actionInfos) {
  35703. each$1(actionInfos, function (actionInfo) {
  35704. actionInfo.update = 'updateView';
  35705. /**
  35706. * @payload
  35707. * @property {string} seriesName
  35708. * @property {string} name
  35709. */
  35710. registerAction(actionInfo, function (payload, ecModel) {
  35711. var selected = {};
  35712. ecModel.eachComponent(
  35713. {mainType: 'series', subType: seriesType, query: payload},
  35714. function (seriesModel) {
  35715. if (seriesModel[actionInfo.method]) {
  35716. seriesModel[actionInfo.method](
  35717. payload.name,
  35718. payload.dataIndex
  35719. );
  35720. }
  35721. var data = seriesModel.getData();
  35722. // Create selected map
  35723. data.each(function (idx) {
  35724. var name = data.getName(idx);
  35725. selected[name] = seriesModel.isSelected(name)
  35726. || false;
  35727. });
  35728. }
  35729. );
  35730. return {
  35731. name: payload.name,
  35732. selected: selected
  35733. };
  35734. });
  35735. });
  35736. };
  35737. /*
  35738. * Licensed to the Apache Software Foundation (ASF) under one
  35739. * or more contributor license agreements. See the NOTICE file
  35740. * distributed with this work for additional information
  35741. * regarding copyright ownership. The ASF licenses this file
  35742. * to you under the Apache License, Version 2.0 (the
  35743. * "License"); you may not use this file except in compliance
  35744. * with the License. You may obtain a copy of the License at
  35745. *
  35746. * http://www.apache.org/licenses/LICENSE-2.0
  35747. *
  35748. * Unless required by applicable law or agreed to in writing,
  35749. * software distributed under the License is distributed on an
  35750. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35751. * KIND, either express or implied. See the License for the
  35752. * specific language governing permissions and limitations
  35753. * under the License.
  35754. */
  35755. // Pick color from palette for each data item.
  35756. // Applicable for charts that require applying color palette
  35757. // in data level (like pie, funnel, chord).
  35758. var dataColor = function (seriesType) {
  35759. return {
  35760. getTargetSeries: function (ecModel) {
  35761. // Pie and funnel may use diferrent scope
  35762. var paletteScope = {};
  35763. var seiresModelMap = createHashMap();
  35764. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35765. seriesModel.__paletteScope = paletteScope;
  35766. seiresModelMap.set(seriesModel.uid, seriesModel);
  35767. });
  35768. return seiresModelMap;
  35769. },
  35770. reset: function (seriesModel, ecModel) {
  35771. var dataAll = seriesModel.getRawData();
  35772. var idxMap = {};
  35773. var data = seriesModel.getData();
  35774. data.each(function (idx) {
  35775. var rawIdx = data.getRawIndex(idx);
  35776. idxMap[rawIdx] = idx;
  35777. });
  35778. dataAll.each(function (rawIdx) {
  35779. var filteredIdx = idxMap[rawIdx];
  35780. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35781. var singleDataColor = filteredIdx != null
  35782. && data.getItemVisual(filteredIdx, 'color', true);
  35783. if (!singleDataColor) {
  35784. // FIXME Performance
  35785. var itemModel = dataAll.getItemModel(rawIdx);
  35786. var color = itemModel.get('itemStyle.color')
  35787. || seriesModel.getColorFromPalette(
  35788. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  35789. dataAll.count()
  35790. );
  35791. // Legend may use the visual info in data before processed
  35792. dataAll.setItemVisual(rawIdx, 'color', color);
  35793. // Data is not filtered
  35794. if (filteredIdx != null) {
  35795. data.setItemVisual(filteredIdx, 'color', color);
  35796. }
  35797. }
  35798. else {
  35799. // Set data all color for legend
  35800. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  35801. }
  35802. });
  35803. }
  35804. };
  35805. };
  35806. /*
  35807. * Licensed to the Apache Software Foundation (ASF) under one
  35808. * or more contributor license agreements. See the NOTICE file
  35809. * distributed with this work for additional information
  35810. * regarding copyright ownership. The ASF licenses this file
  35811. * to you under the Apache License, Version 2.0 (the
  35812. * "License"); you may not use this file except in compliance
  35813. * with the License. You may obtain a copy of the License at
  35814. *
  35815. * http://www.apache.org/licenses/LICENSE-2.0
  35816. *
  35817. * Unless required by applicable law or agreed to in writing,
  35818. * software distributed under the License is distributed on an
  35819. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35820. * KIND, either express or implied. See the License for the
  35821. * specific language governing permissions and limitations
  35822. * under the License.
  35823. */
  35824. // FIXME emphasis label position is not same with normal label position
  35825. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  35826. list.sort(function (a, b) {
  35827. return a.y - b.y;
  35828. });
  35829. function shiftDown(start, end, delta, dir) {
  35830. for (var j = start; j < end; j++) {
  35831. list[j].y += delta;
  35832. if (j > start
  35833. && j + 1 < end
  35834. && list[j + 1].y > list[j].y + list[j].height
  35835. ) {
  35836. shiftUp(j, delta / 2);
  35837. return;
  35838. }
  35839. }
  35840. shiftUp(end - 1, delta / 2);
  35841. }
  35842. function shiftUp(end, delta) {
  35843. for (var j = end; j >= 0; j--) {
  35844. list[j].y -= delta;
  35845. if (j > 0
  35846. && list[j].y > list[j - 1].y + list[j - 1].height
  35847. ) {
  35848. break;
  35849. }
  35850. }
  35851. }
  35852. function changeX(list, isDownList, cx, cy, r, dir) {
  35853. var lastDeltaX = dir > 0
  35854. ? isDownList // right-side
  35855. ? Number.MAX_VALUE // down
  35856. : 0 // up
  35857. : isDownList // left-side
  35858. ? Number.MAX_VALUE // down
  35859. : 0; // up
  35860. for (var i = 0, l = list.length; i < l; i++) {
  35861. var deltaY = Math.abs(list[i].y - cy);
  35862. var length = list[i].len;
  35863. var length2 = list[i].len2;
  35864. var deltaX = (deltaY < r + length)
  35865. ? Math.sqrt(
  35866. (r + length + length2) * (r + length + length2)
  35867. - deltaY * deltaY
  35868. )
  35869. : Math.abs(list[i].x - cx);
  35870. if (isDownList && deltaX >= lastDeltaX) {
  35871. // right-down, left-down
  35872. deltaX = lastDeltaX - 10;
  35873. }
  35874. if (!isDownList && deltaX <= lastDeltaX) {
  35875. // right-up, left-up
  35876. deltaX = lastDeltaX + 10;
  35877. }
  35878. list[i].x = cx + deltaX * dir;
  35879. lastDeltaX = deltaX;
  35880. }
  35881. }
  35882. var lastY = 0;
  35883. var delta;
  35884. var len = list.length;
  35885. var upList = [];
  35886. var downList = [];
  35887. for (var i = 0; i < len; i++) {
  35888. delta = list[i].y - lastY;
  35889. if (delta < 0) {
  35890. shiftDown(i, len, -delta, dir);
  35891. }
  35892. lastY = list[i].y + list[i].height;
  35893. }
  35894. if (viewHeight - lastY < 0) {
  35895. shiftUp(len - 1, lastY - viewHeight);
  35896. }
  35897. for (var i = 0; i < len; i++) {
  35898. if (list[i].y >= cy) {
  35899. downList.push(list[i]);
  35900. }
  35901. else {
  35902. upList.push(list[i]);
  35903. }
  35904. }
  35905. changeX(upList, false, cx, cy, r, dir);
  35906. changeX(downList, true, cx, cy, r, dir);
  35907. }
  35908. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  35909. var leftList = [];
  35910. var rightList = [];
  35911. for (var i = 0; i < labelLayoutList.length; i++) {
  35912. if (isPositionCenter(labelLayoutList[i])) {
  35913. continue;
  35914. }
  35915. if (labelLayoutList[i].x < cx) {
  35916. leftList.push(labelLayoutList[i]);
  35917. }
  35918. else {
  35919. rightList.push(labelLayoutList[i]);
  35920. }
  35921. }
  35922. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  35923. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  35924. for (var i = 0; i < labelLayoutList.length; i++) {
  35925. if (isPositionCenter(labelLayoutList[i])) {
  35926. continue;
  35927. }
  35928. var linePoints = labelLayoutList[i].linePoints;
  35929. if (linePoints) {
  35930. var dist = linePoints[1][0] - linePoints[2][0];
  35931. if (labelLayoutList[i].x < cx) {
  35932. linePoints[2][0] = labelLayoutList[i].x + 3;
  35933. }
  35934. else {
  35935. linePoints[2][0] = labelLayoutList[i].x - 3;
  35936. }
  35937. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  35938. linePoints[1][0] = linePoints[2][0] + dist;
  35939. }
  35940. }
  35941. }
  35942. function isPositionCenter(layout) {
  35943. // Not change x for center label
  35944. return layout.position === 'center';
  35945. }
  35946. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  35947. var data = seriesModel.getData();
  35948. var labelLayoutList = [];
  35949. var cx;
  35950. var cy;
  35951. var hasLabelRotate = false;
  35952. data.each(function (idx) {
  35953. var layout = data.getItemLayout(idx);
  35954. var itemModel = data.getItemModel(idx);
  35955. var labelModel = itemModel.getModel('label');
  35956. // Use position in normal or emphasis
  35957. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  35958. var labelLineModel = itemModel.getModel('labelLine');
  35959. var labelLineLen = labelLineModel.get('length');
  35960. var labelLineLen2 = labelLineModel.get('length2');
  35961. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35962. var dx = Math.cos(midAngle);
  35963. var dy = Math.sin(midAngle);
  35964. var textX;
  35965. var textY;
  35966. var linePoints;
  35967. var textAlign;
  35968. cx = layout.cx;
  35969. cy = layout.cy;
  35970. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35971. if (labelPosition === 'center') {
  35972. textX = layout.cx;
  35973. textY = layout.cy;
  35974. textAlign = 'center';
  35975. }
  35976. else {
  35977. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  35978. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  35979. textX = x1 + dx * 3;
  35980. textY = y1 + dy * 3;
  35981. if (!isLabelInside) {
  35982. // For roseType
  35983. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  35984. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  35985. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  35986. var y3 = y2;
  35987. textX = x3 + (dx < 0 ? -5 : 5);
  35988. textY = y3;
  35989. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35990. }
  35991. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  35992. }
  35993. var font = labelModel.getFont();
  35994. var labelRotate = labelModel.get('rotate')
  35995. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  35996. var text = seriesModel.getFormattedLabel(idx, 'normal')
  35997. || data.getName(idx);
  35998. var textRect = getBoundingRect(
  35999. text, font, textAlign, 'top'
  36000. );
  36001. hasLabelRotate = !!labelRotate;
  36002. layout.label = {
  36003. x: textX,
  36004. y: textY,
  36005. position: labelPosition,
  36006. height: textRect.height,
  36007. len: labelLineLen,
  36008. len2: labelLineLen2,
  36009. linePoints: linePoints,
  36010. textAlign: textAlign,
  36011. verticalAlign: 'middle',
  36012. rotation: labelRotate,
  36013. inside: isLabelInside
  36014. };
  36015. // Not layout the inside label
  36016. if (!isLabelInside) {
  36017. labelLayoutList.push(layout.label);
  36018. }
  36019. });
  36020. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  36021. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  36022. }
  36023. };
  36024. /*
  36025. * Licensed to the Apache Software Foundation (ASF) under one
  36026. * or more contributor license agreements. See the NOTICE file
  36027. * distributed with this work for additional information
  36028. * regarding copyright ownership. The ASF licenses this file
  36029. * to you under the Apache License, Version 2.0 (the
  36030. * "License"); you may not use this file except in compliance
  36031. * with the License. You may obtain a copy of the License at
  36032. *
  36033. * http://www.apache.org/licenses/LICENSE-2.0
  36034. *
  36035. * Unless required by applicable law or agreed to in writing,
  36036. * software distributed under the License is distributed on an
  36037. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36038. * KIND, either express or implied. See the License for the
  36039. * specific language governing permissions and limitations
  36040. * under the License.
  36041. */
  36042. var PI2$4 = Math.PI * 2;
  36043. var RADIAN = Math.PI / 180;
  36044. var pieLayout = function (seriesType, ecModel, api, payload) {
  36045. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36046. var data = seriesModel.getData();
  36047. var valueDim = data.mapDimension('value');
  36048. var center = seriesModel.get('center');
  36049. var radius = seriesModel.get('radius');
  36050. if (!isArray(radius)) {
  36051. radius = [0, radius];
  36052. }
  36053. if (!isArray(center)) {
  36054. center = [center, center];
  36055. }
  36056. var width = api.getWidth();
  36057. var height = api.getHeight();
  36058. var size = Math.min(width, height);
  36059. var cx = parsePercent$1(center[0], width);
  36060. var cy = parsePercent$1(center[1], height);
  36061. var r0 = parsePercent$1(radius[0], size / 2);
  36062. var r = parsePercent$1(radius[1], size / 2);
  36063. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36064. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36065. var validDataCount = 0;
  36066. data.each(valueDim, function (value) {
  36067. !isNaN(value) && validDataCount++;
  36068. });
  36069. var sum = data.getSum(valueDim);
  36070. // Sum may be 0
  36071. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36072. var clockwise = seriesModel.get('clockwise');
  36073. var roseType = seriesModel.get('roseType');
  36074. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  36075. // [0...max]
  36076. var extent = data.getDataExtent(valueDim);
  36077. extent[0] = 0;
  36078. // In the case some sector angle is smaller than minAngle
  36079. var restAngle = PI2$4;
  36080. var valueSumLargerThanMinAngle = 0;
  36081. var currentAngle = startAngle;
  36082. var dir = clockwise ? 1 : -1;
  36083. data.each(valueDim, function (value, idx) {
  36084. var angle;
  36085. if (isNaN(value)) {
  36086. data.setItemLayout(idx, {
  36087. angle: NaN,
  36088. startAngle: NaN,
  36089. endAngle: NaN,
  36090. clockwise: clockwise,
  36091. cx: cx,
  36092. cy: cy,
  36093. r0: r0,
  36094. r: roseType
  36095. ? NaN
  36096. : r
  36097. });
  36098. return;
  36099. }
  36100. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36101. if (roseType !== 'area') {
  36102. angle = (sum === 0 && stillShowZeroSum)
  36103. ? unitRadian : (value * unitRadian);
  36104. }
  36105. else {
  36106. angle = PI2$4 / validDataCount;
  36107. }
  36108. if (angle < minAngle) {
  36109. angle = minAngle;
  36110. restAngle -= minAngle;
  36111. }
  36112. else {
  36113. valueSumLargerThanMinAngle += value;
  36114. }
  36115. var endAngle = currentAngle + dir * angle;
  36116. data.setItemLayout(idx, {
  36117. angle: angle,
  36118. startAngle: currentAngle,
  36119. endAngle: endAngle,
  36120. clockwise: clockwise,
  36121. cx: cx,
  36122. cy: cy,
  36123. r0: r0,
  36124. r: roseType
  36125. ? linearMap(value, extent, [r0, r])
  36126. : r
  36127. });
  36128. currentAngle = endAngle;
  36129. });
  36130. // Some sector is constrained by minAngle
  36131. // Rest sectors needs recalculate angle
  36132. if (restAngle < PI2$4 && validDataCount) {
  36133. // Average the angle if rest angle is not enough after all angles is
  36134. // Constrained by minAngle
  36135. if (restAngle <= 1e-3) {
  36136. var angle = PI2$4 / validDataCount;
  36137. data.each(valueDim, function (value, idx) {
  36138. if (!isNaN(value)) {
  36139. var layout = data.getItemLayout(idx);
  36140. layout.angle = angle;
  36141. layout.startAngle = startAngle + dir * idx * angle;
  36142. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  36143. }
  36144. });
  36145. }
  36146. else {
  36147. unitRadian = restAngle / valueSumLargerThanMinAngle;
  36148. currentAngle = startAngle;
  36149. data.each(valueDim, function (value, idx) {
  36150. if (!isNaN(value)) {
  36151. var layout = data.getItemLayout(idx);
  36152. var angle = layout.angle === minAngle
  36153. ? minAngle : value * unitRadian;
  36154. layout.startAngle = currentAngle;
  36155. layout.endAngle = currentAngle + dir * angle;
  36156. currentAngle += dir * angle;
  36157. }
  36158. });
  36159. }
  36160. }
  36161. labelLayout(seriesModel, r, width, height);
  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 dataFilter = function (seriesType) {
  36183. return {
  36184. seriesType: seriesType,
  36185. reset: function (seriesModel, ecModel) {
  36186. var legendModels = ecModel.findComponents({
  36187. mainType: 'legend'
  36188. });
  36189. if (!legendModels || !legendModels.length) {
  36190. return;
  36191. }
  36192. var data = seriesModel.getData();
  36193. data.filterSelf(function (idx) {
  36194. var name = data.getName(idx);
  36195. // If in any legend component the status is not selected.
  36196. for (var i = 0; i < legendModels.length; i++) {
  36197. if (!legendModels[i].isSelected(name)) {
  36198. return false;
  36199. }
  36200. }
  36201. return true;
  36202. });
  36203. }
  36204. };
  36205. };
  36206. /*
  36207. * Licensed to the Apache Software Foundation (ASF) under one
  36208. * or more contributor license agreements. See the NOTICE file
  36209. * distributed with this work for additional information
  36210. * regarding copyright ownership. The ASF licenses this file
  36211. * to you under the Apache License, Version 2.0 (the
  36212. * "License"); you may not use this file except in compliance
  36213. * with the License. You may obtain a copy of the License at
  36214. *
  36215. * http://www.apache.org/licenses/LICENSE-2.0
  36216. *
  36217. * Unless required by applicable law or agreed to in writing,
  36218. * software distributed under the License is distributed on an
  36219. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36220. * KIND, either express or implied. See the License for the
  36221. * specific language governing permissions and limitations
  36222. * under the License.
  36223. */
  36224. createDataSelectAction('pie', [{
  36225. type: 'pieToggleSelect',
  36226. event: 'pieselectchanged',
  36227. method: 'toggleSelected'
  36228. }, {
  36229. type: 'pieSelect',
  36230. event: 'pieselected',
  36231. method: 'select'
  36232. }, {
  36233. type: 'pieUnSelect',
  36234. event: 'pieunselected',
  36235. method: 'unSelect'
  36236. }]);
  36237. registerVisual(dataColor('pie'));
  36238. registerLayout(curry(pieLayout, 'pie'));
  36239. registerProcessor(dataFilter('pie'));
  36240. /*
  36241. * Licensed to the Apache Software Foundation (ASF) under one
  36242. * or more contributor license agreements. See the NOTICE file
  36243. * distributed with this work for additional information
  36244. * regarding copyright ownership. The ASF licenses this file
  36245. * to you under the Apache License, Version 2.0 (the
  36246. * "License"); you may not use this file except in compliance
  36247. * with the License. You may obtain a copy of the License at
  36248. *
  36249. * http://www.apache.org/licenses/LICENSE-2.0
  36250. *
  36251. * Unless required by applicable law or agreed to in writing,
  36252. * software distributed under the License is distributed on an
  36253. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36254. * KIND, either express or implied. See the License for the
  36255. * specific language governing permissions and limitations
  36256. * under the License.
  36257. */
  36258. exports.version = version;
  36259. exports.dependencies = dependencies;
  36260. exports.PRIORITY = PRIORITY;
  36261. exports.init = init;
  36262. exports.connect = connect;
  36263. exports.disConnect = disConnect;
  36264. exports.disconnect = disconnect;
  36265. exports.dispose = dispose;
  36266. exports.getInstanceByDom = getInstanceByDom;
  36267. exports.getInstanceById = getInstanceById;
  36268. exports.registerTheme = registerTheme;
  36269. exports.registerPreprocessor = registerPreprocessor;
  36270. exports.registerProcessor = registerProcessor;
  36271. exports.registerPostUpdate = registerPostUpdate;
  36272. exports.registerAction = registerAction;
  36273. exports.registerCoordinateSystem = registerCoordinateSystem;
  36274. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  36275. exports.registerLayout = registerLayout;
  36276. exports.registerVisual = registerVisual;
  36277. exports.registerLoading = registerLoading;
  36278. exports.extendComponentModel = extendComponentModel;
  36279. exports.extendComponentView = extendComponentView;
  36280. exports.extendSeriesModel = extendSeriesModel;
  36281. exports.extendChartView = extendChartView;
  36282. exports.setCanvasCreator = setCanvasCreator;
  36283. exports.registerMap = registerMap;
  36284. exports.getMap = getMap;
  36285. exports.dataTool = dataTool;
  36286. })));